Bezier-rs: Add Euclidean parameterization to Bezier::evaluate (#828)

* Add enum to evaluate for differenciating compute type

* Add euclidean parameterization and update styling in the UI

Co-authored-by: Rob Nadal <robnadal44@gmail.com>

* Update usage of evaluate in graphite

* Add description

* Code review changes

* Update tests

* Improve ComputeType ergonomics

* Large code review/cleanup pass

Co-authored-by: Rob Nadal <robnadal44@gmail.com>
Co-authored-by: Keavon Chambers <keavon@keavon.com>
This commit is contained in:
Hannah Li
2022-11-18 20:37:52 -08:00
committed by Keavon Chambers
co-authored by Rob Nadal Keavon Chambers
parent a220bfa759
commit 01a9724389
15 changed files with 341 additions and 276 deletions
@@ -1,5 +1,6 @@
use crate::messages::prelude::*; use crate::messages::prelude::*;
use bezier_rs::ComputeType;
use graphene::layers::vector::consts::ManipulatorType; use graphene::layers::vector::consts::ManipulatorType;
use graphene::layers::vector::manipulator_group::ManipulatorGroup; use graphene::layers::vector::manipulator_group::ManipulatorGroup;
use graphene::layers::vector::manipulator_point::ManipulatorPoint; use graphene::layers::vector::manipulator_point::ManipulatorPoint;
@@ -277,7 +278,7 @@ impl ShapeEditor {
for bezier_id in document.layer(layer_path).ok()?.as_subpath()?.bezier_iter() { for bezier_id in document.layer(layer_path).ok()?.as_subpath()?.bezier_iter() {
let bezier = bezier_id.internal; let bezier = bezier_id.internal;
let t = bezier.project(layer_pos, projection_options); let t = bezier.project(layer_pos, projection_options);
let layerspace = bezier.evaluate(t); let layerspace = bezier.evaluate(ComputeType::Parametric(t));
let screenspace = transform.transform_point2(layerspace); let screenspace = transform.transform_point2(layerspace);
let distance_squared = screenspace.distance_squared(position); let distance_squared = screenspace.distance_squared(position);
+8 -6
View File
@@ -203,6 +203,8 @@ impl Bezier {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::utils::ComputeType;
use super::compare::compare_points; use super::compare::compare_points;
use super::*; use super::*;
@@ -213,13 +215,13 @@ mod tests {
let p3 = DVec2::new(160., 170.); let p3 = DVec2::new(160., 170.);
let bezier1 = Bezier::quadratic_through_points(p1, p2, p3, None); let bezier1 = Bezier::quadratic_through_points(p1, p2, p3, None);
assert!(compare_points(bezier1.evaluate(0.5), p2)); assert!(compare_points(bezier1.evaluate(ComputeType::Parametric(0.5)), p2));
let bezier2 = Bezier::quadratic_through_points(p1, p2, p3, Some(0.8)); let bezier2 = Bezier::quadratic_through_points(p1, p2, p3, Some(0.8));
assert!(compare_points(bezier2.evaluate(0.8), p2)); assert!(compare_points(bezier2.evaluate(ComputeType::Parametric(0.8)), p2));
let bezier3 = Bezier::quadratic_through_points(p1, p2, p3, Some(0.)); let bezier3 = Bezier::quadratic_through_points(p1, p2, p3, Some(0.));
assert!(compare_points(bezier3.evaluate(0.), p2)); assert!(compare_points(bezier3.evaluate(ComputeType::Parametric(0.)), p2));
} }
#[test] #[test]
@@ -229,12 +231,12 @@ mod tests {
let p3 = DVec2::new(160., 160.); let p3 = DVec2::new(160., 160.);
let bezier1 = Bezier::cubic_through_points(p1, p2, p3, Some(0.3), Some(10.)); let bezier1 = Bezier::cubic_through_points(p1, p2, p3, Some(0.3), Some(10.));
assert!(compare_points(bezier1.evaluate(0.3), p2)); assert!(compare_points(bezier1.evaluate(ComputeType::Parametric(0.3)), p2));
let bezier2 = Bezier::cubic_through_points(p1, p2, p3, Some(0.8), Some(91.7)); let bezier2 = Bezier::cubic_through_points(p1, p2, p3, Some(0.8), Some(91.7));
assert!(compare_points(bezier2.evaluate(0.8), p2)); assert!(compare_points(bezier2.evaluate(ComputeType::Parametric(0.8)), p2));
let bezier3 = Bezier::cubic_through_points(p1, p2, p3, Some(0.), Some(91.7)); let bezier3 = Bezier::cubic_through_points(p1, p2, p3, Some(0.), Some(91.7));
assert!(compare_points(bezier3.evaluate(0.), p2)); assert!(compare_points(bezier3.evaluate(ComputeType::Parametric(0.)), p2));
} }
} }
+55 -10
View File
@@ -1,9 +1,11 @@
use crate::utils::{f64_compare, ComputeType};
use super::*; use super::*;
/// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`. /// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`.
impl Bezier { impl Bezier {
/// Calculate the point on the curve based on the `t`-value provided. /// Calculate the point on the curve based on the `t`-value provided.
pub(crate) fn unrestricted_evaluate(&self, t: f64) -> DVec2 { pub(crate) fn unrestricted_parametric_evaluate(&self, t: f64) -> DVec2 {
// Basis code based off of pseudocode found here: <https://pomax.github.io/bezierinfo/#explanation>. // Basis code based off of pseudocode found here: <https://pomax.github.io/bezierinfo/#explanation>.
let t_squared = t * t; let t_squared = t * t;
@@ -21,11 +23,48 @@ impl Bezier {
} }
} }
/// Calculate the point along the curve that is a factor of `d` away from the start.
pub(crate) fn unrestricted_euclidean_evaluate(&self, d: f64, error: f64) -> DVec2 {
if let BezierHandles::Linear = self.handles {
return self.unrestricted_parametric_evaluate(d);
}
let mut low = 0.;
let mut mid = 0.;
let mut high = 1.;
let total_length = self.length(None);
while low < high {
mid = (low + high) / 2.;
let test_d = self.trim(0., mid).length(None) / total_length;
if f64_compare(test_d, d, error) {
break;
} else if test_d < d {
low = mid;
} else {
high = mid;
}
}
self.unrestricted_parametric_evaluate(mid)
}
/// Calculate the point on the curve based on the `t`-value provided. /// Calculate the point on the curve based on the `t`-value provided.
/// Expects `t` to be within the inclusive range `[0, 1]`. /// Expects `t` to be within the inclusive range `[0, 1]`.
pub fn evaluate(&self, t: f64) -> DVec2 { pub fn evaluate(&self, t: ComputeType) -> DVec2 {
assert!((0.0..=1.).contains(&t)); match t {
self.unrestricted_evaluate(t) ComputeType::Parametric(t) => {
assert!((0.0..=1.).contains(&t));
self.unrestricted_parametric_evaluate(t)
}
ComputeType::Euclidean(t) => {
assert!((0.0..=1.).contains(&t));
self.unrestricted_euclidean_evaluate(t, 0.0001)
}
ComputeType::EuclideanWithinError { t, epsilon } => {
assert!((0.0..=1.).contains(&t));
self.unrestricted_euclidean_evaluate(t, epsilon)
}
}
} }
/// Return a selection of equidistant points on the bezier curve. /// Return a selection of equidistant points on the bezier curve.
@@ -36,7 +75,7 @@ impl Bezier {
let mut steps_array = Vec::with_capacity(steps_unwrapped + 1); let mut steps_array = Vec::with_capacity(steps_unwrapped + 1);
for t in 0..steps_unwrapped + 1 { for t in 0..steps_unwrapped + 1 {
steps_array.push(self.evaluate(f64::from(t as i32) * ratio)) steps_array.push(self.evaluate(ComputeType::Parametric(f64::from(t as i32) * ratio)))
} }
steps_array steps_array
@@ -123,7 +162,7 @@ impl Bezier {
if step_index == 0 { if step_index == 0 {
distance = *table_distance; distance = *table_distance;
} else { } else {
distance = point.distance(self.evaluate(iterator_t)); distance = point.distance(self.evaluate(ComputeType::Parametric(iterator_t)));
*table_distance = distance; *table_distance = distance;
} }
if distance < new_minimum_distance { if distance < new_minimum_distance {
@@ -173,23 +212,29 @@ mod tests {
let p4 = DVec2::new(30., 21.); let p4 = DVec2::new(30., 21.);
let bezier1 = Bezier::from_quadratic_dvec2(p1, p2, p3); let bezier1 = Bezier::from_quadratic_dvec2(p1, p2, p3);
assert_eq!(bezier1.evaluate(0.5), DVec2::new(12.5, 6.25)); assert_eq!(bezier1.evaluate(ComputeType::Parametric(0.5)), DVec2::new(12.5, 6.25));
let bezier2 = Bezier::from_cubic_dvec2(p1, p2, p3, p4); let bezier2 = Bezier::from_cubic_dvec2(p1, p2, p3, p4);
assert_eq!(bezier2.evaluate(0.5), DVec2::new(16.5, 9.625)); assert_eq!(bezier2.evaluate(ComputeType::Parametric(0.5)), DVec2::new(16.5, 9.625));
} }
#[test] #[test]
fn test_compute_lookup_table() { fn test_compute_lookup_table() {
let bezier1 = Bezier::from_quadratic_coordinates(10., 10., 30., 30., 50., 10.); let bezier1 = Bezier::from_quadratic_coordinates(10., 10., 30., 30., 50., 10.);
let lookup_table1 = bezier1.compute_lookup_table(Some(2)); let lookup_table1 = bezier1.compute_lookup_table(Some(2));
assert_eq!(lookup_table1, vec![bezier1.start(), bezier1.evaluate(0.5), bezier1.end()]); assert_eq!(lookup_table1, vec![bezier1.start(), bezier1.evaluate(ComputeType::Parametric(0.5)), bezier1.end()]);
let bezier2 = Bezier::from_cubic_coordinates(10., 10., 30., 30., 70., 70., 90., 10.); let bezier2 = Bezier::from_cubic_coordinates(10., 10., 30., 30., 70., 70., 90., 10.);
let lookup_table2 = bezier2.compute_lookup_table(Some(4)); let lookup_table2 = bezier2.compute_lookup_table(Some(4));
assert_eq!( assert_eq!(
lookup_table2, lookup_table2,
vec![bezier2.start(), bezier2.evaluate(0.25), bezier2.evaluate(0.5), bezier2.evaluate(0.75), bezier2.end()] vec![
bezier2.start(),
bezier2.evaluate(ComputeType::Parametric(0.25)),
bezier2.evaluate(ComputeType::Parametric(0.50)),
bezier2.evaluate(ComputeType::Parametric(0.75)),
bezier2.end()
]
); );
} }
+18 -17
View File
@@ -1,4 +1,5 @@
use super::*; use super::*;
use crate::utils::ComputeType;
use glam::DMat2; use glam::DMat2;
use std::ops::Range; use std::ops::Range;
@@ -52,7 +53,7 @@ impl Bezier {
pub fn tangent(&self, t: f64) -> DVec2 { pub fn tangent(&self, t: f64) -> DVec2 {
match self.handles { match self.handles {
BezierHandles::Linear => self.end - self.start, BezierHandles::Linear => self.end - self.start,
_ => self.derivative().unwrap().evaluate(t), _ => self.derivative().unwrap().evaluate(ComputeType::Parametric(t)),
} }
.normalize() .normalize()
} }
@@ -67,8 +68,8 @@ impl Bezier {
pub fn curvature(&self, t: f64) -> f64 { pub fn curvature(&self, t: f64) -> f64 {
let (d, dd) = match &self.derivative() { let (d, dd) = match &self.derivative() {
Some(first_derivative) => match first_derivative.derivative() { Some(first_derivative) => match first_derivative.derivative() {
Some(second_derivative) => (first_derivative.evaluate(t), second_derivative.evaluate(t)), Some(second_derivative) => (first_derivative.evaluate(ComputeType::Parametric(t)), second_derivative.evaluate(ComputeType::Parametric(t))),
None => (first_derivative.evaluate(t), first_derivative.end - first_derivative.start), None => (first_derivative.evaluate(ComputeType::Parametric(t)), first_derivative.end - first_derivative.start),
}, },
None => (self.end - self.start, DVec2::new(0., 0.)), None => (self.end - self.start, DVec2::new(0., 0.)),
}; };
@@ -128,7 +129,7 @@ impl Bezier {
let extrema = self.local_extrema(); let extrema = self.local_extrema();
for t_values in extrema { for t_values in extrema {
for t in t_values { for t in t_values {
let point = self.evaluate(t); let point = self.evaluate(ComputeType::Parametric(t));
// Update bounding box if new min/max is found. // Update bounding box if new min/max is found.
endpoints_min = endpoints_min.min(point); endpoints_min = endpoints_min.min(point);
endpoints_max = endpoints_max.max(point); endpoints_max = endpoints_max.max(point);
@@ -276,7 +277,7 @@ impl Bezier {
// Accept the t value if it is approximately in [0, 1] and if the corresponding coordinates are within the range of the linear line // Accept the t value if it is approximately in [0, 1] and if the corresponding coordinates are within the range of the linear line
.filter(|&t| { .filter(|&t| {
utils::f64_approximately_in_range(t, 0., 1., MAX_ABSOLUTE_DIFFERENCE) utils::f64_approximately_in_range(t, 0., 1., MAX_ABSOLUTE_DIFFERENCE)
&& utils::dvec2_approximately_in_range(self.unrestricted_evaluate(t), min, max, MAX_ABSOLUTE_DIFFERENCE).all() && utils::dvec2_approximately_in_range(self.unrestricted_parametric_evaluate(t), min, max, MAX_ABSOLUTE_DIFFERENCE).all()
}) })
// Ensure the returned value is within the correct range // Ensure the returned value is within the correct range
.map(|t| t.clamp(0., 1.)) .map(|t| t.clamp(0., 1.))
@@ -348,7 +349,7 @@ mod tests {
]; ];
assert_eq!(&de_casteljau_points, &expected_de_casteljau_points); assert_eq!(&de_casteljau_points, &expected_de_casteljau_points);
assert_eq!(expected_de_casteljau_points[3][0], bezier.evaluate(0.5)); assert_eq!(expected_de_casteljau_points[3][0], bezier.evaluate(ComputeType::Parametric(0.5)));
} }
#[test] #[test]
@@ -564,12 +565,12 @@ mod tests {
let line1 = Bezier::from_linear_coordinates(20., 60., 70., 60.); let line1 = Bezier::from_linear_coordinates(20., 60., 70., 60.);
let intersections1 = bezier.intersections(&line1, None); let intersections1 = bezier.intersections(&line1, None);
assert!(intersections1.len() == 1); assert!(intersections1.len() == 1);
assert!(compare_points(bezier.evaluate(intersections1[0]), DVec2::new(30., 60.))); assert!(compare_points(bezier.evaluate(ComputeType::Parametric(intersections1[0])), DVec2::new(30., 60.)));
// Intersection in the middle of curve // Intersection in the middle of curve
let line2 = Bezier::from_linear_coordinates(150., 150., 30., 30.); let line2 = Bezier::from_linear_coordinates(150., 150., 30., 30.);
let intersections2 = bezier.intersections(&line2, None); let intersections2 = bezier.intersections(&line2, None);
assert!(compare_points(bezier.evaluate(intersections2[0]), DVec2::new(96., 96.))); assert!(compare_points(bezier.evaluate(ComputeType::Parametric(intersections2[0])), DVec2::new(96., 96.)));
} }
#[test] #[test]
@@ -583,12 +584,12 @@ mod tests {
let line1 = Bezier::from_linear_coordinates(20., 50., 40., 50.); let line1 = Bezier::from_linear_coordinates(20., 50., 40., 50.);
let intersections1 = bezier.intersections(&line1, None); let intersections1 = bezier.intersections(&line1, None);
assert!(intersections1.len() == 1); assert!(intersections1.len() == 1);
assert!(compare_points(bezier.evaluate(intersections1[0]), p1)); assert!(compare_points(bezier.evaluate(ComputeType::Parametric(intersections1[0])), p1));
// Intersection in the middle of curve // Intersection in the middle of curve
let line2 = Bezier::from_linear_coordinates(150., 150., 30., 30.); let line2 = Bezier::from_linear_coordinates(150., 150., 30., 30.);
let intersections2 = bezier.intersections(&line2, None); let intersections2 = bezier.intersections(&line2, None);
assert!(compare_points(bezier.evaluate(intersections2[0]), DVec2::new(47.77355, 47.77354))); assert!(compare_points(bezier.evaluate(ComputeType::Parametric(intersections2[0])), DVec2::new(47.77355, 47.77354)));
} }
#[test] #[test]
@@ -603,14 +604,14 @@ mod tests {
let line1 = Bezier::from_linear_coordinates(20., 30., 40., 30.); let line1 = Bezier::from_linear_coordinates(20., 30., 40., 30.);
let intersections1 = bezier.intersections(&line1, None); let intersections1 = bezier.intersections(&line1, None);
assert!(intersections1.len() == 1); assert!(intersections1.len() == 1);
assert!(compare_points(bezier.evaluate(intersections1[0]), p1)); assert!(compare_points(bezier.evaluate(ComputeType::Parametric(intersections1[0])), p1));
// Intersection at edge and in middle of curve, Discriminant < 0 // Intersection at edge and in middle of curve, Discriminant < 0
let line2 = Bezier::from_linear_coordinates(150., 150., 30., 30.); let line2 = Bezier::from_linear_coordinates(150., 150., 30., 30.);
let intersections2 = bezier.intersections(&line2, None); let intersections2 = bezier.intersections(&line2, None);
assert!(intersections2.len() == 2); assert!(intersections2.len() == 2);
assert!(compare_points(bezier.evaluate(intersections2[0]), p1)); assert!(compare_points(bezier.evaluate(ComputeType::Parametric(intersections2[0])), p1));
assert!(compare_points(bezier.evaluate(intersections2[1]), DVec2::new(85.84, 85.84))); assert!(compare_points(bezier.evaluate(ComputeType::Parametric(intersections2[1])), DVec2::new(85.84, 85.84)));
} }
#[test] #[test]
@@ -621,8 +622,8 @@ mod tests {
let intersections = bezier1.intersections(&bezier2, None); let intersections = bezier1.intersections(&bezier2, None);
let intersections2 = bezier2.intersections(&bezier1, None); let intersections2 = bezier2.intersections(&bezier1, None);
assert!(compare_vec_of_points( assert!(compare_vec_of_points(
intersections.iter().map(|&t| bezier1.evaluate(t)).collect(), intersections.iter().map(|&t| bezier1.evaluate(ComputeType::Parametric(t))).collect(),
intersections2.iter().map(|&t| bezier2.evaluate(t)).collect(), intersections2.iter().map(|&t| bezier2.evaluate(ComputeType::Parametric(t))).collect(),
2. 2.
)); ));
} }
@@ -632,8 +633,8 @@ mod tests {
let bezier = Bezier::from_cubic_coordinates(160., 180., 170., 10., 30., 90., 180., 140.); let bezier = Bezier::from_cubic_coordinates(160., 180., 170., 10., 30., 90., 180., 140.);
let intersections = bezier.self_intersections(Some(0.5)); let intersections = bezier.self_intersections(Some(0.5));
assert!(compare_vec_of_points( assert!(compare_vec_of_points(
intersections.iter().map(|&t| bezier.evaluate(t[0])).collect(), intersections.iter().map(|&t| bezier.evaluate(ComputeType::Parametric(t[0]))).collect(),
intersections.iter().map(|&t| bezier.evaluate(t[1])).collect(), intersections.iter().map(|&t| bezier.evaluate(ComputeType::Parametric(t[1]))).collect(),
2. 2.
)); ));
assert!(Bezier::from_linear_coordinates(160., 180., 170., 10.).self_intersections(None).is_empty()); assert!(Bezier::from_linear_coordinates(160., 180., 170., 10.).self_intersections(None).is_empty());
+58 -36
View File
@@ -1,5 +1,5 @@
use super::*; use super::*;
use crate::utils::f64_compare; use crate::utils::{f64_compare, ComputeType};
use glam::DMat2; use glam::DMat2;
use std::f64::consts::PI; use std::f64::consts::PI;
@@ -8,7 +8,7 @@ use std::f64::consts::PI;
impl Bezier { impl Bezier {
/// Returns the pair of Bezier curves that result from splitting the original curve at the point corresponding to `t`. /// Returns the pair of Bezier curves that result from splitting the original curve at the point corresponding to `t`.
pub fn split(&self, t: f64) -> [Bezier; 2] { pub fn split(&self, t: f64) -> [Bezier; 2] {
let split_point = self.evaluate(t); let split_point = self.evaluate(ComputeType::Parametric(t));
match self.handles { match self.handles {
BezierHandles::Linear => [Bezier::from_linear_dvec2(self.start, split_point), Bezier::from_linear_dvec2(split_point, self.end)], BezierHandles::Linear => [Bezier::from_linear_dvec2(self.start, split_point), Bezier::from_linear_dvec2(split_point, self.end)],
@@ -53,7 +53,7 @@ impl Bezier {
pub fn trim(&self, t1: f64, t2: f64) -> Bezier { pub fn trim(&self, t1: f64, t2: f64) -> Bezier {
// If t1 is equal to t2, return a bezier comprised entirely of the same point // If t1 is equal to t2, return a bezier comprised entirely of the same point
if f64_compare(t1, t2, MAX_ABSOLUTE_DIFFERENCE) { if f64_compare(t1, t2, MAX_ABSOLUTE_DIFFERENCE) {
let point = self.evaluate(t1); let point = self.evaluate(ComputeType::Parametric(t1));
return match self.handles { return match self.handles {
BezierHandles::Linear => Bezier::from_linear_dvec2(point, point), BezierHandles::Linear => Bezier::from_linear_dvec2(point, point),
BezierHandles::Quadratic { handle: _ } => Bezier::from_quadratic_dvec2(point, point, point), BezierHandles::Quadratic { handle: _ } => Bezier::from_quadratic_dvec2(point, point, point),
@@ -444,9 +444,9 @@ impl Bezier {
// Inner loop to find the next maximal segment of the curve that can be approximated with a circular arc // Inner loop to find the next maximal segment of the curve that can be approximated with a circular arc
while iterations <= max_iterations { while iterations <= max_iterations {
iterations += 1; iterations += 1;
let p1 = self.evaluate(low); let p1 = self.evaluate(ComputeType::Parametric(low));
let p2 = self.evaluate(middle); let p2 = self.evaluate(ComputeType::Parametric(middle));
let p3 = self.evaluate(high); let p3 = self.evaluate(ComputeType::Parametric(high));
let wrapped_center = utils::compute_circle_center_from_points(p1, p2, p3); let wrapped_center = utils::compute_circle_center_from_points(p1, p2, p3);
// If the segment is linear, move on to next segment // If the segment is linear, move on to next segment
@@ -486,8 +486,8 @@ impl Bezier {
}; };
// Use points in between low, middle, and high to evaluate how well the arc approximates the curve // Use points in between low, middle, and high to evaluate how well the arc approximates the curve
let e1 = self.evaluate((low + middle) / 2.); let e1 = self.evaluate(ComputeType::Parametric((low + middle) / 2.));
let e2 = self.evaluate((middle + high) / 2.); let e2 = self.evaluate(ComputeType::Parametric((middle + high) / 2.));
// Iterate until we find the largest good approximation such that the next iteration is not a good approximation with an arc // Iterate until we find the largest good approximation such that the next iteration is not a good approximation with an arc
if utils::f64_compare(radius, e1.distance(center), error) && utils::f64_compare(radius, e2.distance(center), error) { if utils::f64_compare(radius, e1.distance(center), error) && utils::f64_compare(radius, e2.distance(center), error) {
@@ -537,6 +537,8 @@ impl Bezier {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::utils::ComputeType;
use super::compare::{compare_arcs, compare_vector_of_beziers}; use super::compare::{compare_arcs, compare_vector_of_beziers};
use super::*; use super::*;
@@ -546,34 +548,34 @@ mod tests {
let [part1, part2] = line.split(0.5); let [part1, part2] = line.split(0.5);
assert_eq!(part1.start(), line.start()); assert_eq!(part1.start(), line.start());
assert_eq!(part1.end(), line.evaluate(0.5)); assert_eq!(part1.end(), line.evaluate(ComputeType::Parametric(0.5)));
assert_eq!(part1.evaluate(0.5), line.evaluate(0.25)); assert_eq!(part1.evaluate(ComputeType::Parametric(0.5)), line.evaluate(ComputeType::Parametric(0.25)));
assert_eq!(part2.start(), line.evaluate(0.5)); assert_eq!(part2.start(), line.evaluate(ComputeType::Parametric(0.5)));
assert_eq!(part2.end(), line.end()); assert_eq!(part2.end(), line.end());
assert_eq!(part2.evaluate(0.5), line.evaluate(0.75)); assert_eq!(part2.evaluate(ComputeType::Parametric(0.5)), line.evaluate(ComputeType::Parametric(0.75)));
let quad_bezier = Bezier::from_quadratic_coordinates(10., 10., 50., 50., 90., 10.); let quad_bezier = Bezier::from_quadratic_coordinates(10., 10., 50., 50., 90., 10.);
let [part3, part4] = quad_bezier.split(0.5); let [part3, part4] = quad_bezier.split(0.5);
assert_eq!(part3.start(), quad_bezier.start()); assert_eq!(part3.start(), quad_bezier.start());
assert_eq!(part3.end(), quad_bezier.evaluate(0.5)); assert_eq!(part3.end(), quad_bezier.evaluate(ComputeType::Parametric(0.5)));
assert_eq!(part3.evaluate(0.5), quad_bezier.evaluate(0.25)); assert_eq!(part3.evaluate(ComputeType::Parametric(0.5)), quad_bezier.evaluate(ComputeType::Parametric(0.25)));
assert_eq!(part4.start(), quad_bezier.evaluate(0.5)); assert_eq!(part4.start(), quad_bezier.evaluate(ComputeType::Parametric(0.5)));
assert_eq!(part4.end(), quad_bezier.end()); assert_eq!(part4.end(), quad_bezier.end());
assert_eq!(part4.evaluate(0.5), quad_bezier.evaluate(0.75)); assert_eq!(part4.evaluate(ComputeType::Parametric(0.5)), quad_bezier.evaluate(ComputeType::Parametric(0.75)));
let cubic_bezier = Bezier::from_cubic_coordinates(10., 10., 50., 50., 90., 10., 40., 50.); let cubic_bezier = Bezier::from_cubic_coordinates(10., 10., 50., 50., 90., 10., 40., 50.);
let [part5, part6] = cubic_bezier.split(0.5); let [part5, part6] = cubic_bezier.split(0.5);
assert_eq!(part5.start(), cubic_bezier.start()); assert_eq!(part5.start(), cubic_bezier.start());
assert_eq!(part5.end(), cubic_bezier.evaluate(0.5)); assert_eq!(part5.end(), cubic_bezier.evaluate(ComputeType::Parametric(0.5)));
assert_eq!(part5.evaluate(0.5), cubic_bezier.evaluate(0.25)); assert_eq!(part5.evaluate(ComputeType::Parametric(0.5)), cubic_bezier.evaluate(ComputeType::Parametric(0.25)));
assert_eq!(part6.start(), cubic_bezier.evaluate(0.5)); assert_eq!(part6.start(), cubic_bezier.evaluate(ComputeType::Parametric(0.5)));
assert_eq!(part6.end(), cubic_bezier.end()); assert_eq!(part6.end(), cubic_bezier.end());
assert_eq!(part6.evaluate(0.5), cubic_bezier.evaluate(0.75)); assert_eq!(part6.evaluate(ComputeType::Parametric(0.5)), cubic_bezier.evaluate(ComputeType::Parametric(0.75)));
} }
#[test] #[test]
@@ -611,23 +613,23 @@ mod tests {
let line = Bezier::from_linear_coordinates(80., 80., 40., 40.); let line = Bezier::from_linear_coordinates(80., 80., 40., 40.);
let trimmed1 = line.trim(0.25, 0.75); let trimmed1 = line.trim(0.25, 0.75);
assert_eq!(trimmed1.start(), line.evaluate(0.25)); assert_eq!(trimmed1.start(), line.evaluate(ComputeType::Parametric(0.25)));
assert_eq!(trimmed1.end(), line.evaluate(0.75)); assert_eq!(trimmed1.end(), line.evaluate(ComputeType::Parametric(0.75)));
assert_eq!(trimmed1.evaluate(0.5), line.evaluate(0.5)); assert_eq!(trimmed1.evaluate(ComputeType::Parametric(0.5)), line.evaluate(ComputeType::Parametric(0.5)));
let quadratic_bezier = Bezier::from_quadratic_coordinates(80., 80., 40., 40., 70., 70.); let quadratic_bezier = Bezier::from_quadratic_coordinates(80., 80., 40., 40., 70., 70.);
let trimmed2 = quadratic_bezier.trim(0.25, 0.75); let trimmed2 = quadratic_bezier.trim(0.25, 0.75);
assert_eq!(trimmed2.start(), quadratic_bezier.evaluate(0.25)); assert_eq!(trimmed2.start(), quadratic_bezier.evaluate(ComputeType::Parametric(0.25)));
assert_eq!(trimmed2.end(), quadratic_bezier.evaluate(0.75)); assert_eq!(trimmed2.end(), quadratic_bezier.evaluate(ComputeType::Parametric(0.75)));
assert_eq!(trimmed2.evaluate(0.5), quadratic_bezier.evaluate(0.5)); assert_eq!(trimmed2.evaluate(ComputeType::Parametric(0.5)), quadratic_bezier.evaluate(ComputeType::Parametric(0.5)));
let cubic_bezier = Bezier::from_cubic_coordinates(80., 80., 40., 40., 70., 70., 150., 150.); let cubic_bezier = Bezier::from_cubic_coordinates(80., 80., 40., 40., 70., 70., 150., 150.);
let trimmed3 = cubic_bezier.trim(0.25, 0.75); let trimmed3 = cubic_bezier.trim(0.25, 0.75);
assert_eq!(trimmed3.start(), cubic_bezier.evaluate(0.25)); assert_eq!(trimmed3.start(), cubic_bezier.evaluate(ComputeType::Parametric(0.25)));
assert_eq!(trimmed3.end(), cubic_bezier.evaluate(0.75)); assert_eq!(trimmed3.end(), cubic_bezier.evaluate(ComputeType::Parametric(0.75)));
assert_eq!(trimmed3.evaluate(0.5), cubic_bezier.evaluate(0.5)); assert_eq!(trimmed3.evaluate(ComputeType::Parametric(0.5)), cubic_bezier.evaluate(ComputeType::Parametric(0.5)));
} }
#[test] #[test]
@@ -741,16 +743,24 @@ mod tests {
assert_eq!(outline.len(), 4); assert_eq!(outline.len(), 4);
// Assert the first length-wise piece of the outline is 10 units from the line // Assert the first length-wise piece of the outline is 10 units from the line
assert!(f64_compare(outline[0].evaluate(0.25).distance(line.evaluate(0.25)), 10., MAX_ABSOLUTE_DIFFERENCE)); // f64 assert!(f64_compare(
outline[0].evaluate(ComputeType::Parametric(0.25)).distance(line.evaluate(ComputeType::Parametric(0.25))),
10.,
MAX_ABSOLUTE_DIFFERENCE
)); // f64
// Assert the first cap touches the line end point at the halfway point // Assert the first cap touches the line end point at the halfway point
assert!(outline[1].evaluate(0.5).abs_diff_eq(line.end(), MAX_ABSOLUTE_DIFFERENCE)); assert!(outline[1].evaluate(ComputeType::Parametric(0.5)).abs_diff_eq(line.end(), MAX_ABSOLUTE_DIFFERENCE));
// Assert the second length-wise piece of the outline is 10 units from the line // Assert the second length-wise piece of the outline is 10 units from the line
assert!(f64_compare(outline[2].evaluate(0.25).distance(line.evaluate(0.75)), 10., MAX_ABSOLUTE_DIFFERENCE)); // f64 assert!(f64_compare(
outline[2].evaluate(ComputeType::Parametric(0.25)).distance(line.evaluate(ComputeType::Parametric(0.75))),
10.,
MAX_ABSOLUTE_DIFFERENCE
)); // f64
// Assert the second cap touches the line start point at the halfway point // Assert the second cap touches the line start point at the halfway point
assert!(outline[3].evaluate(0.5).abs_diff_eq(line.start(), MAX_ABSOLUTE_DIFFERENCE)); assert!(outline[3].evaluate(ComputeType::Parametric(0.5)).abs_diff_eq(line.start(), MAX_ABSOLUTE_DIFFERENCE));
} }
#[test] #[test]
@@ -767,9 +777,21 @@ mod tests {
dbg!(scaled_bezier); dbg!(scaled_bezier);
// Assert the scaled bezier is 30 units from the line // Assert the scaled bezier is 30 units from the line
assert!(f64_compare(scaled_bezier.evaluate(0.).distance(bezier.evaluate(0.)), 30., MAX_ABSOLUTE_DIFFERENCE)); assert!(f64_compare(
assert!(f64_compare(scaled_bezier.evaluate(1.).distance(bezier.evaluate(1.)), 30., MAX_ABSOLUTE_DIFFERENCE)); scaled_bezier.evaluate(ComputeType::Parametric(0.)).distance(bezier.evaluate(ComputeType::Parametric(0.))),
assert!(f64_compare(scaled_bezier.evaluate(0.5).distance(bezier.evaluate(0.5)), 30., MAX_ABSOLUTE_DIFFERENCE)); 30.,
MAX_ABSOLUTE_DIFFERENCE
));
assert!(f64_compare(
scaled_bezier.evaluate(ComputeType::Parametric(1.)).distance(bezier.evaluate(ComputeType::Parametric(1.))),
30.,
MAX_ABSOLUTE_DIFFERENCE
));
assert!(f64_compare(
scaled_bezier.evaluate(ComputeType::Parametric(0.5)).distance(bezier.evaluate(ComputeType::Parametric(0.5))),
30.,
MAX_ABSOLUTE_DIFFERENCE
));
} }
#[test] #[test]
+1
View File
@@ -7,3 +7,4 @@ mod utils;
pub use bezier::*; pub use bezier::*;
pub use subpath::*; pub use subpath::*;
pub use utils::ComputeType;
+7
View File
@@ -3,6 +3,13 @@ use crate::consts::{MAX_ABSOLUTE_DIFFERENCE, STRICT_MAX_ABSOLUTE_DIFFERENCE};
use glam::{BVec2, DMat2, DVec2}; use glam::{BVec2, DMat2, DVec2};
use std::f64::consts::PI; use std::f64::consts::PI;
#[derive(Copy, Clone, PartialEq)]
pub enum ComputeType {
Parametric(f64),
Euclidean(f64),
EuclideanWithinError { t: f64, epsilon: f64 },
}
/// Helper to perform the computation of a and c, where b is the provided point on the curve. /// Helper to perform the computation of a and c, where b is the provided point on the curve.
/// Given the correct power of `t` and `(1-t)`, the computation is the same for quadratic and cubic cases. /// Given the correct power of `t` and `(1-t)`, the computation is the same for quadratic and cubic cases.
/// Relevant derivation and the definitions of a, b, and c can be found in [the projection identity section](https://pomax.github.io/bezierinfo/#abc) of Pomax's bezier curve primer. /// Relevant derivation and the definitions of a, b, and c can be found in [the projection identity section](https://pomax.github.io/bezierinfo/#abc) of Pomax's bezier curve primer.
+91 -53
View File
@@ -1,23 +1,69 @@
<template> <template>
<div class="App"> <h1>Bezier-rs Interactive Documentation</h1>
<h1>Bezier-rs Interactive Documentation</h1> <p>This is the interactive documentation for the <b>bezier-rs</b> library. Click and drag on the endpoints of the example curves to visualize the various Bezier utilities and functions.</p>
<p>This is the interactive documentation for the <b>bezier-rs</b> library. Click and drag on the endpoints of the example curves to visualize the various Bezier utilities and functions.</p> <h2>Beziers</h2>
<h2>Beziers</h2> <div v-for="(feature, index) in bezierFeatures" :key="index">
<div v-for="(feature, index) in bezierFeatures" :key="index"> <BezierExamplePane
<BezierExamplePane :name="feature.name" :callback="feature.callback" :exampleOptions="feature.exampleOptions" :triggerOnMouseMove="feature.triggerOnMouseMove" /> :name="feature.name"
</div> :callback="feature.callback"
<h2>Subpaths</h2> :exampleOptions="feature.exampleOptions"
<div v-for="(feature, index) in subpathFeatures" :key="index"> :triggerOnMouseMove="feature.triggerOnMouseMove"
<SubpathExamplePane :name="feature.name" :callback="feature.callback" /> :chooseComputeType="feature.chooseComputeType"
</div> />
</div>
<h2>Subpaths</h2>
<div v-for="(feature, index) in subpathFeatures" :key="index">
<SubpathExamplePane :name="feature.name" :callback="feature.callback" />
</div> </div>
</template> </template>
<style>
#app {
font-family: Arial, sans-serif;
text-align: center;
margin: 40px 0;
}
/* Example Pane styles */
.example-row {
display: flex;
flex-direction: row;
justify-content: center;
}
.compute-type-choice {
margin-top: 20px;
}
.example-pane-header {
margin-top: 2em;
margin-bottom: 0;
}
.example-pane-container {
position: relative;
width: fit-content;
margin: auto;
}
/* Example styles */
.example-header {
margin: 20px 0;
}
.example-figure {
width: 200px;
height: 200px;
margin-bottom: 20px;
border: solid 1px black;
}
</style>
<script lang="ts"> <script lang="ts">
import { defineComponent } from "vue"; import { defineComponent } from "vue";
import { WasmBezier } from "@/../wasm/pkg"; import { WasmBezier } from "@/../wasm/pkg";
import { BezierCurveType, ExampleOptions, WasmBezierInstance, WasmSubpathInstance } from "@/utils/types"; import { ComputeType, ExampleOptions, WasmBezierInstance, WasmSubpathInstance } from "@/utils/types";
import BezierExamplePane from "@/components/BezierExamplePane.vue"; import BezierExamplePane from "@/components/BezierExamplePane.vue";
import SubpathExamplePane from "@/components/SubpathExamplePane.vue"; import SubpathExamplePane from "@/components/SubpathExamplePane.vue";
@@ -56,10 +102,10 @@ export default defineComponent({
return WasmBezier.cubic_through_points(points, options.t, options["midpoint separation"]); return WasmBezier.cubic_through_points(points, options.t, options["midpoint separation"]);
}, },
exampleOptions: { exampleOptions: {
[BezierCurveType.Linear]: { Linear: {
disabled: true, disabled: true,
}, },
[BezierCurveType.Quadratic]: { Quadratic: {
customPoints: [ customPoints: [
[30, 50], [30, 50],
[120, 70], [120, 70],
@@ -75,7 +121,7 @@ export default defineComponent({
}, },
], ],
}, },
[BezierCurveType.Cubic]: { Cubic: {
customPoints: [ customPoints: [
[30, 50], [30, 50],
[120, 70], [120, 70],
@@ -106,18 +152,19 @@ export default defineComponent({
}, },
{ {
name: "Evaluate", name: "Evaluate",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.evaluate(options.t), callback: (bezier: WasmBezierInstance, options: Record<string, number>, _: undefined, computeType: ComputeType): string => bezier.evaluate(options.computeArgument, computeType),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tSliderOptions], sliderOptions: [{ ...tSliderOptions, variable: "computeArgument" }],
}, },
}, },
chooseComputeType: true,
}, },
{ {
name: "Lookup Table", name: "Lookup Table",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.compute_lookup_table(options.steps), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.compute_lookup_table(options.steps),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [ sliderOptions: [
{ {
min: 2, min: 2,
@@ -134,17 +181,17 @@ export default defineComponent({
name: "Derivative", name: "Derivative",
callback: (bezier: WasmBezierInstance, _: Record<string, number>): string => bezier.derivative(), callback: (bezier: WasmBezierInstance, _: Record<string, number>): string => bezier.derivative(),
exampleOptions: { exampleOptions: {
[BezierCurveType.Linear]: { Linear: {
disabled: true, disabled: true,
}, },
[BezierCurveType.Quadratic]: { Quadratic: {
customPoints: [ customPoints: [
[30, 40], [30, 40],
[110, 50], [110, 50],
[120, 130], [120, 130],
], ],
}, },
[BezierCurveType.Cubic]: { Cubic: {
customPoints: [ customPoints: [
[50, 50], [50, 50],
[60, 100], [60, 100],
@@ -158,7 +205,7 @@ export default defineComponent({
name: "Tangent", name: "Tangent",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.tangent(options.t), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.tangent(options.t),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tSliderOptions], sliderOptions: [tSliderOptions],
}, },
}, },
@@ -168,7 +215,7 @@ export default defineComponent({
name: "Normal", name: "Normal",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.normal(options.t), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.normal(options.t),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tSliderOptions], sliderOptions: [tSliderOptions],
}, },
}, },
@@ -177,10 +224,10 @@ export default defineComponent({
name: "Curvature", name: "Curvature",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.curvature(options.t), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.curvature(options.t),
exampleOptions: { exampleOptions: {
[BezierCurveType.Linear]: { Linear: {
disabled: true, disabled: true,
}, },
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tSliderOptions], sliderOptions: [tSliderOptions],
}, },
}, },
@@ -189,7 +236,7 @@ export default defineComponent({
name: "Split", name: "Split",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.split(options.t), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.split(options.t),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tSliderOptions], sliderOptions: [tSliderOptions],
}, },
}, },
@@ -198,7 +245,7 @@ export default defineComponent({
name: "Trim", name: "Trim",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.trim(options.t1, options.t2), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.trim(options.t1, options.t2),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [ sliderOptions: [
{ {
variable: "t1", variable: "t1",
@@ -228,14 +275,14 @@ export default defineComponent({
name: "Local Extrema", name: "Local Extrema",
callback: (bezier: WasmBezierInstance, _: Record<string, number>): string => bezier.local_extrema(), callback: (bezier: WasmBezierInstance, _: Record<string, number>): string => bezier.local_extrema(),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
customPoints: [ customPoints: [
[40, 40], [40, 40],
[160, 30], [160, 30],
[110, 150], [110, 150],
], ],
}, },
[BezierCurveType.Cubic]: { Cubic: {
customPoints: [ customPoints: [
[160, 180], [160, 180],
[170, 10], [170, 10],
@@ -253,10 +300,10 @@ export default defineComponent({
name: "Inflections", name: "Inflections",
callback: (bezier: WasmBezierInstance, _: Record<string, number>): string => bezier.inflections(), callback: (bezier: WasmBezierInstance, _: Record<string, number>): string => bezier.inflections(),
exampleOptions: { exampleOptions: {
[BezierCurveType.Linear]: { Linear: {
disabled: true, disabled: true,
}, },
[BezierCurveType.Quadratic]: { Quadratic: {
disabled: true, disabled: true,
}, },
}, },
@@ -269,7 +316,7 @@ export default defineComponent({
name: "Offset", name: "Offset",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.offset(options.distance), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.offset(options.distance),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [ sliderOptions: [
{ {
variable: "distance", variable: "distance",
@@ -286,7 +333,7 @@ export default defineComponent({
name: "Outline", name: "Outline",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.outline(options.distance), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.outline(options.distance),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [ sliderOptions: [
{ {
variable: "distance", variable: "distance",
@@ -303,7 +350,7 @@ export default defineComponent({
name: "Graduated Outline", name: "Graduated Outline",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.graduated_outline(options.start_distance, options.end_distance), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.graduated_outline(options.start_distance, options.end_distance),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [ sliderOptions: [
{ {
variable: "start_distance", variable: "start_distance",
@@ -328,7 +375,7 @@ export default defineComponent({
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => callback: (bezier: WasmBezierInstance, options: Record<string, number>): string =>
bezier.skewed_outline(options.distance1, options.distance2, options.distance3, options.distance4), bezier.skewed_outline(options.distance1, options.distance2, options.distance3, options.distance4),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [ sliderOptions: [
{ {
variable: "distance1", variable: "distance1",
@@ -392,7 +439,7 @@ export default defineComponent({
]; ];
return { return {
[BezierCurveType.Quadratic]: { Quadratic: {
customPoints: [ customPoints: [
[50, 50], [50, 50],
[85, 65], [85, 65],
@@ -401,7 +448,7 @@ export default defineComponent({
sliderOptions, sliderOptions,
disabled: false, disabled: false,
}, },
[BezierCurveType.Cubic]: { Cubic: {
customPoints: [ customPoints: [
[160, 180], [160, 180],
[170, 10], [170, 10],
@@ -435,7 +482,7 @@ export default defineComponent({
return bezier.intersect_quadratic_segment(quadratic, options.error); return bezier.intersect_quadratic_segment(quadratic, options.error);
}, },
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tErrorOptions], sliderOptions: [tErrorOptions],
}, },
}, },
@@ -452,7 +499,7 @@ export default defineComponent({
return bezier.intersect_cubic_segment(cubic, options.error); return bezier.intersect_cubic_segment(cubic, options.error);
}, },
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tErrorOptions], sliderOptions: [tErrorOptions],
}, },
}, },
@@ -461,10 +508,10 @@ export default defineComponent({
name: "Intersect (Self)", name: "Intersect (Self)",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.intersect_self(options.error), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.intersect_self(options.error),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tErrorOptions], sliderOptions: [tErrorOptions],
}, },
[BezierCurveType.Cubic]: { Cubic: {
customPoints: [ customPoints: [
[160, 180], [160, 180],
[170, 10], [170, 10],
@@ -478,7 +525,7 @@ export default defineComponent({
name: "Rotate", name: "Rotate",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.rotate(options.angle * Math.PI, 100, 100), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.rotate(options.angle * Math.PI, 100, 100),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [ sliderOptions: [
{ {
variable: "angle", variable: "angle",
@@ -496,7 +543,7 @@ export default defineComponent({
name: "De Casteljau Points", name: "De Casteljau Points",
callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.de_casteljau_points(options.t), callback: (bezier: WasmBezierInstance, options: Record<string, number>): string => bezier.de_casteljau_points(options.t),
exampleOptions: { exampleOptions: {
[BezierCurveType.Quadratic]: { Quadratic: {
sliderOptions: [tSliderOptions], sliderOptions: [tSliderOptions],
}, },
}, },
@@ -520,12 +567,3 @@ export default defineComponent({
}, },
}); });
</script> </script>
<style>
#app {
font-family: Arial, sans-serif;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
@@ -9,42 +9,31 @@
</div> </div>
</template> </template>
<style></style>
<script lang="ts"> <script lang="ts">
import { defineComponent, PropType } from "vue"; import { defineComponent, PropType } from "vue";
import { WasmBezier } from "@/../wasm/pkg"; import { WasmBezier } from "@/../wasm/pkg";
import { getConstructorKey, getCurveType } from "@/utils/helpers"; import { getConstructorKey, getCurveType, BezierCallback, BezierCurveType, WasmBezierManipulatorKey, SliderOption, ComputeType } from "@/utils/types";
import { BezierCallback, BezierCurveType, WasmBezierManipulatorKey, SliderOption } from "@/utils/types";
const SELECTABLE_RANGE = 10; const SELECTABLE_RANGE = 10;
// Given the number of points in the curve, map the index of a point to the correct manipulator key // Given the number of points in the curve, map the index of a point to the correct manipulator key
const MANIPULATOR_KEYS_FROM_BEZIER_TYPE: { [key in BezierCurveType]: WasmBezierManipulatorKey[] } = { const MANIPULATOR_KEYS_FROM_BEZIER_TYPE: { [key in BezierCurveType]: WasmBezierManipulatorKey[] } = {
[BezierCurveType.Linear]: ["set_start", "set_end"], Linear: ["set_start", "set_end"],
[BezierCurveType.Quadratic]: ["set_start", "set_handle_start", "set_end"], Quadratic: ["set_start", "set_handle_start", "set_end"],
[BezierCurveType.Cubic]: ["set_start", "set_handle_start", "set_handle_end", "set_end"], Cubic: ["set_start", "set_handle_start", "set_handle_end", "set_end"],
}; };
export default defineComponent({ export default defineComponent({
props: { props: {
title: String, title: { type: String as PropType<string>, required: true },
points: { points: { type: Array as PropType<Array<Array<number>>>, required: true, mutable: true },
type: Array as PropType<Array<Array<number>>>, callback: { type: Function as PropType<BezierCallback>, required: true },
required: true, sliderOptions: { type: Object as PropType<Array<SliderOption>>, default: () => ({}) },
mutable: true, triggerOnMouseMove: { type: Boolean as PropType<boolean>, default: false },
}, computeType: { type: String as PropType<ComputeType>, default: "Parametric" },
callback: {
type: Function as PropType<BezierCallback>,
required: true,
},
sliderOptions: {
type: Object as PropType<Array<SliderOption>>,
default: () => ({}),
},
triggerOnMouseMove: {
type: Boolean,
default: false,
},
}, },
data() { data() {
const curveType = getCurveType(this.points.length); const curveType = getCurveType(this.points.length);
@@ -55,7 +44,7 @@ export default defineComponent({
return { return {
bezier, bezier,
bezierSVG: this.callback(bezier, sliderData), bezierSVG: this.callback(bezier, sliderData, undefined, "Euclidean"),
manipulatorKeys, manipulatorKeys,
activeIndex: undefined as number | undefined, activeIndex: undefined as number | undefined,
mutablePoints: JSON.parse(JSON.stringify(this.points)), mutablePoints: JSON.parse(JSON.stringify(this.points)),
@@ -84,9 +73,9 @@ export default defineComponent({
if (this.activeIndex !== undefined) { if (this.activeIndex !== undefined) {
this.bezier[this.manipulatorKeys[this.activeIndex]](mx, my); this.bezier[this.manipulatorKeys[this.activeIndex]](mx, my);
this.mutablePoints[this.activeIndex] = [mx, my]; this.mutablePoints[this.activeIndex] = [mx, my];
this.bezierSVG = this.callback(this.bezier, this.sliderData); this.bezierSVG = this.callback(this.bezier, this.sliderData, undefined, this.computeType);
} else if (this.triggerOnMouseMove) { } else if (this.triggerOnMouseMove) {
this.bezierSVG = this.callback(this.bezier, this.sliderData, [mx, my]); this.bezierSVG = this.callback(this.bezier, this.sliderData, [mx, my], this.computeType);
} }
}, },
getSliderValue: (sliderValue: number, sliderUnit?: string | string[]) => (Array.isArray(sliderUnit) ? sliderUnit[sliderValue] : sliderUnit), getSliderValue: (sliderValue: number, sliderUnit?: string | string[]) => (Array.isArray(sliderUnit) ? sliderUnit[sliderValue] : sliderUnit),
@@ -94,18 +83,15 @@ export default defineComponent({
watch: { watch: {
sliderData: { sliderData: {
handler() { handler() {
this.bezierSVG = this.callback(this.bezier, this.sliderData); this.bezierSVG = this.callback(this.bezier, this.sliderData, undefined, this.computeType);
}, },
deep: true, deep: true,
}, },
computeType: {
handler() {
this.bezierSVG = this.callback(this.bezier, this.sliderData, undefined, this.computeType);
},
},
}, },
}); });
</script> </script>
<style scoped>
.example-figure {
border: solid 1px black;
width: 200px;
height: 200px;
}
</style>
@@ -1,6 +1,15 @@
<template> <template>
<div> <div class="example-pane-container">
<h3 class="example-pane-header">{{ name }}</h3> <h3 class="example-pane-header">{{ name }}</h3>
<div v-if="chooseComputeType" class="compute-type-choice">
<strong>ComputeType:</strong>
<input type="radio" :id="`${id}-parametric`" value="Parametric" v-model="computeTypeChoice" />
<label :for="`${id}-parametric`">Parametric</label>
<input type="radio" :id="`${id}-euclidean`" value="Euclidean" v-model="computeTypeChoice" />
<label :for="`${id}-euclidean`">Euclidean</label>
</div>
<div class="example-row"> <div class="example-row">
<div v-for="(example, index) in examples" :key="index"> <div v-for="(example, index) in examples" :key="index">
<BezierExample <BezierExample
@@ -10,51 +19,46 @@
:callback="callback" :callback="callback"
:sliderOptions="example.sliderOptions" :sliderOptions="example.sliderOptions"
:triggerOnMouseMove="triggerOnMouseMove" :triggerOnMouseMove="triggerOnMouseMove"
:computeType="computeTypeChoice"
/> />
</div> </div>
</div> </div>
</div> </div>
</template> </template>
<style></style>
<script lang="ts"> <script lang="ts">
import { defineComponent, PropType } from "vue"; import { defineComponent, PropType } from "vue";
import { BezierCallback, BezierCurveType, ExampleOptions, SliderOption } from "@/utils/types"; import { BezierCallback, BezierCurveType, BEZIER_CURVE_TYPE, ComputeType, ExampleOptions, SliderOption } from "@/utils/types";
import BezierExample from "@/components/BezierExample.vue"; import BezierExample from "@/components/BezierExample.vue";
export default defineComponent({ export default defineComponent({
props: { props: {
name: String, name: { type: String as PropType<string>, required: true },
callback: { callback: { type: Function as PropType<BezierCallback>, required: true },
type: Function as PropType<BezierCallback>, exampleOptions: { type: Object as PropType<ExampleOptions>, default: () => ({}) },
required: true, triggerOnMouseMove: { type: Boolean as PropType<boolean>, default: false },
}, chooseComputeType: { type: Boolean as PropType<boolean>, default: false },
exampleOptions: {
type: Object as PropType<ExampleOptions>,
default: () => ({}),
},
triggerOnMouseMove: {
type: Boolean,
default: false,
},
}, },
data() { data() {
const exampleDefaults = { const exampleDefaults = {
[BezierCurveType.Linear]: { Linear: {
points: [ points: [
[30, 60], [30, 60],
[140, 120], [140, 120],
], ],
}, },
[BezierCurveType.Quadratic]: { Quadratic: {
points: [ points: [
[30, 50], [30, 50],
[140, 30], [140, 30],
[160, 170], [160, 170],
], ],
}, },
[BezierCurveType.Cubic]: { Cubic: {
points: [ points: [
[30, 30], [30, 30],
[60, 140], [60, 140],
@@ -65,10 +69,10 @@ export default defineComponent({
}; };
// Use quadratic slider options as a default if sliders are not provided for the other curve types. // Use quadratic slider options as a default if sliders are not provided for the other curve types.
const defaultSliderOptions: SliderOption[] = this.exampleOptions[BezierCurveType.Quadratic]?.sliderOptions || []; const defaultSliderOptions: SliderOption[] = this.exampleOptions.Quadratic?.sliderOptions || [];
return { return {
examples: Object.values(BezierCurveType).map((curveType: BezierCurveType) => { examples: BEZIER_CURVE_TYPE.map((curveType: BezierCurveType) => {
const givenData = this.exampleOptions[curveType]; const givenData = this.exampleOptions[curveType];
const defaultData = exampleDefaults[curveType]; const defaultData = exampleDefaults[curveType];
return { return {
@@ -78,6 +82,8 @@ export default defineComponent({
sliderOptions: givenData?.sliderOptions || defaultSliderOptions, sliderOptions: givenData?.sliderOptions || defaultSliderOptions,
}; };
}), }),
id: `${Math.random()}`.substring(2),
computeTypeChoice: "Parametric" as ComputeType,
}; };
}, },
components: { components: {
@@ -85,15 +91,3 @@ export default defineComponent({
}, },
}); });
</script> </script>
<style scoped>
.example-row {
display: flex;
flex-direction: row;
justify-content: center;
}
.example-pane-header {
margin-bottom: 0;
}
</style>
@@ -5,6 +5,8 @@
</div> </div>
</template> </template>
<style></style>
<script lang="ts"> <script lang="ts">
import { defineComponent, PropType } from "vue"; import { defineComponent, PropType } from "vue";
@@ -16,20 +18,10 @@ const POINT_INDEX_TO_MANIPULATOR: WasmSubpathManipulatorKey[] = ["set_anchor", "
export default defineComponent({ export default defineComponent({
props: { props: {
title: String, title: { type: String as PropType<string>, required: true },
triples: { triples: { type: Array as PropType<Array<Array<number[] | undefined>>>, mutable: true, required: true },
type: Array as PropType<Array<Array<number[] | undefined>>>, closed: { type: Boolean as PropType<boolean>, default: false },
required: true, callback: { type: Function as PropType<SubpathCallback>, required: true },
mutable: true,
},
closed: {
type: Boolean as PropType<boolean>,
default: false,
},
callback: {
type: Function as PropType<SubpathCallback>,
required: true,
},
}, },
data() { data() {
const subpath = WasmSubpath.from_triples(this.triples, this.closed) as WasmSubpathInstance; const subpath = WasmSubpath.from_triples(this.triples, this.closed) as WasmSubpathInstance;
@@ -69,11 +61,3 @@ export default defineComponent({
}, },
}); });
</script> </script>
<style scoped>
.example-figure {
border: solid 1px black;
width: 200px;
height: 200px;
}
</style>
@@ -9,6 +9,8 @@
</div> </div>
</template> </template>
<style></style>
<script lang="ts"> <script lang="ts">
import { defineComponent, PropType } from "vue"; import { defineComponent, PropType } from "vue";
@@ -18,11 +20,8 @@ import SubpathExample from "@/components/SubpathExample.vue";
export default defineComponent({ export default defineComponent({
props: { props: {
name: String, name: { type: String as PropType<string>, required: true },
callback: { callback: { type: Function as PropType<SubpathCallback>, required: true },
type: Function as PropType<SubpathCallback>,
required: true,
},
}, },
data() { data() {
return { return {
@@ -58,15 +57,3 @@ export default defineComponent({
}, },
}); });
</script> </script>
<style scoped>
.example-row {
display: flex;
flex-direction: row;
justify-content: center;
}
.example-pane-header {
margin-bottom: 0;
}
</style>
@@ -1,27 +0,0 @@
import { BezierCurveType, WasmBezierConstructorKey } from "@/utils/types";
export function getCurveType(numPoints: number): BezierCurveType {
switch (numPoints) {
case 2:
return BezierCurveType.Linear;
case 3:
return BezierCurveType.Quadratic;
case 4:
return BezierCurveType.Cubic;
default:
throw new Error("Invalid number of points for a bezier");
}
}
export function getConstructorKey(bezierCurveType: BezierCurveType): WasmBezierConstructorKey {
switch (bezierCurveType) {
case BezierCurveType.Linear:
return "new_linear";
case BezierCurveType.Quadratic:
return "new_quadratic";
case BezierCurveType.Cubic:
return "new_cubic";
default:
throw new Error("Invalid value for a BezierCurveType");
}
}
@@ -8,13 +8,12 @@ export type WasmBezierManipulatorKey = "set_start" | "set_handle_start" | "set_h
export type WasmSubpathInstance = InstanceType<WasmRawInstance["WasmSubpath"]>; export type WasmSubpathInstance = InstanceType<WasmRawInstance["WasmSubpath"]>;
export type WasmSubpathManipulatorKey = "set_anchor" | "set_in_handle" | "set_out_handle"; export type WasmSubpathManipulatorKey = "set_anchor" | "set_in_handle" | "set_out_handle";
export enum BezierCurveType { export const BEZIER_CURVE_TYPE = ["Linear", "Quadratic", "Cubic"] as const;
Linear = "Linear", export type BezierCurveType = typeof BEZIER_CURVE_TYPE[number];
Quadratic = "Quadratic",
Cubic = "Cubic",
}
export type BezierCallback = (bezier: WasmBezierInstance, options: Record<string, number>, mouseLocation?: [number, number]) => string; export type ComputeType = "Euclidean" | "Parametric";
export type BezierCallback = (bezier: WasmBezierInstance, options: Record<string, number>, mouseLocation?: [number, number], computeType?: ComputeType) => string;
export type SubpathCallback = (subpath: WasmSubpathInstance) => string; export type SubpathCallback = (subpath: WasmSubpathInstance) => string;
export type ExampleOptions = { export type ExampleOptions = {
@@ -33,3 +32,24 @@ export type SliderOption = {
variable: string; variable: string;
unit?: string | string[]; unit?: string | string[];
}; };
export function getCurveType(numPoints: number): BezierCurveType {
const mapping: Record<number, BezierCurveType> = {
2: "Linear",
3: "Quadratic",
4: "Cubic",
};
if (!(numPoints in mapping)) throw new Error("Invalid number of points for a bezier");
return mapping[numPoints];
}
export function getConstructorKey(bezierCurveType: BezierCurveType): WasmBezierConstructorKey {
const mapping: Record<BezierCurveType, WasmBezierConstructorKey> = {
Linear: "new_linear",
Quadratic: "new_quadratic",
Cubic: "new_cubic",
};
return mapping[bezierCurveType];
}
@@ -1,5 +1,5 @@
use crate::svg_drawing::*; use crate::svg_drawing::*;
use bezier_rs::{ArcStrategy, ArcsOptions, Bezier, ProjectionOptions}; use bezier_rs::{ArcStrategy, ArcsOptions, Bezier, ComputeType, ProjectionOptions};
use glam::DVec2; use glam::DVec2;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
@@ -132,10 +132,14 @@ impl WasmBezier {
wrap_svg_tag(format!("{bezier}{}", draw_text(format!("Length: {:.2}", self.0.length(None)), TEXT_OFFSET_X, TEXT_OFFSET_Y, BLACK))) wrap_svg_tag(format!("{bezier}{}", draw_text(format!("Length: {:.2}", self.0.length(None)), TEXT_OFFSET_X, TEXT_OFFSET_Y, BLACK)))
} }
pub fn evaluate(&self, t: f64) -> String { pub fn evaluate(&self, t: f64, compute_type: String) -> String {
let bezier = self.get_bezier_path(); let bezier = self.get_bezier_path();
let point = &self.0.evaluate(t); let point = match compute_type.as_str() {
let content = format!("{bezier}{}", draw_circle(*point, 4., RED, 1.5, WHITE)); "Euclidean" => self.0.evaluate(ComputeType::Euclidean(t)),
"Parametric" => self.0.evaluate(ComputeType::Parametric(t)),
_ => panic!("Unexpected ComputeType string: '{}'", compute_type),
};
let content = format!("{bezier}{}", draw_circle(point, 4., RED, 1.5, WHITE));
wrap_svg_tag(content) wrap_svg_tag(content)
} }
@@ -173,7 +177,7 @@ impl WasmBezier {
let bezier = self.get_bezier_path(); let bezier = self.get_bezier_path();
let tangent_point = self.0.tangent(t); let tangent_point = self.0.tangent(t);
let intersection_point = self.0.evaluate(t); let intersection_point = self.0.evaluate(ComputeType::Parametric(t));
let tangent_end = intersection_point + tangent_point * SCALE_UNIT_VECTOR_FACTOR; let tangent_end = intersection_point + tangent_point * SCALE_UNIT_VECTOR_FACTOR;
let content = format!( let content = format!(
@@ -189,7 +193,7 @@ impl WasmBezier {
let bezier = self.get_bezier_path(); let bezier = self.get_bezier_path();
let normal_point = self.0.normal(t); let normal_point = self.0.normal(t);
let intersection_point = self.0.evaluate(t); let intersection_point = self.0.evaluate(ComputeType::Parametric(t));
let normal_end = intersection_point + normal_point * SCALE_UNIT_VECTOR_FACTOR; let normal_end = intersection_point + normal_point * SCALE_UNIT_VECTOR_FACTOR;
let content = format!( let content = format!(
@@ -205,7 +209,7 @@ impl WasmBezier {
let bezier = self.get_bezier_path(); let bezier = self.get_bezier_path();
let radius = 1. / self.0.curvature(t); let radius = 1. / self.0.curvature(t);
let normal_point = self.0.normal(t); let normal_point = self.0.normal(t);
let intersection_point = self.0.evaluate(t); let intersection_point = self.0.evaluate(ComputeType::Parametric(t));
let curvature_center = intersection_point + normal_point * radius; let curvature_center = intersection_point + normal_point * radius;
@@ -269,7 +273,7 @@ impl WasmBezier {
pub fn project(&self, x: f64, y: f64) -> String { pub fn project(&self, x: f64, y: f64) -> String {
let projected_t_value = self.0.project(DVec2::new(x, y), ProjectionOptions::default()); let projected_t_value = self.0.project(DVec2::new(x, y), ProjectionOptions::default());
let projected_point = self.0.evaluate(projected_t_value); let projected_point = self.0.evaluate(ComputeType::Parametric(projected_t_value));
let bezier = self.get_bezier_path(); let bezier = self.get_bezier_path();
let content = format!("{bezier}{}", draw_line(projected_point.x, projected_point.y, x, y, RED, 1.),); let content = format!("{bezier}{}", draw_line(projected_point.x, projected_point.y, x, y, RED, 1.),);
@@ -285,7 +289,7 @@ impl WasmBezier {
.zip([RED, GREEN]) .zip([RED, GREEN])
.flat_map(|(t_value_list, color)| { .flat_map(|(t_value_list, color)| {
t_value_list.iter().map(|&t_value| { t_value_list.iter().map(|&t_value| {
let point = self.0.evaluate(t_value); let point = self.0.evaluate(ComputeType::Parametric(t_value));
draw_circle(point, 3., color, 1.5, WHITE) draw_circle(point, 3., color, 1.5, WHITE)
}) })
}) })
@@ -320,7 +324,7 @@ impl WasmBezier {
let circles: String = inflections let circles: String = inflections
.iter() .iter()
.map(|&t_value| { .map(|&t_value| {
let point = self.0.evaluate(t_value); let point = self.0.evaluate(ComputeType::Parametric(t_value));
draw_circle(point, 3., RED, 1.5, WHITE) draw_circle(point, 3., RED, 1.5, WHITE)
}) })
.fold("".to_string(), |acc, circle| acc + &circle); .fold("".to_string(), |acc, circle| acc + &circle);
@@ -413,7 +417,7 @@ impl WasmBezier {
.intersect(&line, None) .intersect(&line, None)
.iter() .iter()
.map(|intersection_t| { .map(|intersection_t| {
let point = &self.0.evaluate(*intersection_t); let point = &self.0.evaluate(ComputeType::Parametric(*intersection_t));
draw_circle(*point, 4., RED, 1.5, WHITE) draw_circle(*point, 4., RED, 1.5, WHITE)
}) })
.fold(String::new(), |acc, item| format!("{acc}{item}")); .fold(String::new(), |acc, item| format!("{acc}{item}"));
@@ -433,7 +437,7 @@ impl WasmBezier {
.intersect(&quadratic, Some(error)) .intersect(&quadratic, Some(error))
.iter() .iter()
.map(|intersection_t| { .map(|intersection_t| {
let point = &self.0.evaluate(*intersection_t); let point = &self.0.evaluate(ComputeType::Parametric(*intersection_t));
draw_circle(*point, 4., RED, 1.5, WHITE) draw_circle(*point, 4., RED, 1.5, WHITE)
}) })
.fold(String::new(), |acc, item| format!("{acc}{item}")); .fold(String::new(), |acc, item| format!("{acc}{item}"));
@@ -453,7 +457,7 @@ impl WasmBezier {
.intersect(&cubic, Some(error)) .intersect(&cubic, Some(error))
.iter() .iter()
.map(|intersection_t| { .map(|intersection_t| {
let point = &self.0.evaluate(*intersection_t); let point = &self.0.evaluate(ComputeType::Parametric(*intersection_t));
draw_circle(*point, 4., RED, 1.5, WHITE) draw_circle(*point, 4., RED, 1.5, WHITE)
}) })
.fold(String::new(), |acc, item| format!("{acc}{item}")); .fold(String::new(), |acc, item| format!("{acc}{item}"));
@@ -469,7 +473,7 @@ impl WasmBezier {
.self_intersections(Some(error)) .self_intersections(Some(error))
.iter() .iter()
.map(|intersection_t| { .map(|intersection_t| {
let point = &self.0.evaluate(intersection_t[0]); let point = &self.0.evaluate(ComputeType::Parametric(intersection_t[0]));
draw_circle(*point, 4., RED, 1.5, WHITE) draw_circle(*point, 4., RED, 1.5, WHITE)
}) })
.fold(bezier_curve_svg, |acc, item| format!("{acc}{item}")); .fold(bezier_curve_svg, |acc, item| format!("{acc}{item}"));