pub struct Path2D { /* private fields */ }Expand description
A cheaply cloned, checked f64 path with lazily cached geometric bounds.
A path is always valid: the try_ methods return failures immediately and
leave the snapshot unchanged, and PathBuilder reports its first failure
from PathBuilder::build.
Bounds include move positions and curve extrema, not the curve control hull.
Empty paths have zero bounds at the origin. SVG path data imports through
Self::parse_svg. Arc lengths use cached bounded Gaussian integration;
partial curves retain their Bezier representation rather than flattening.
crate::Shape::stroke expands bounded curves into fill outlines;
Styled trim/dash share the same arc-length parameterization.
use motion_core::prelude::*;
use motion_core::{
DisplayList, RasterLimits, ResourceStore, ValidatedDisplayList, MAX_PATH_VERBS,
MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
};
let path = Path2D::builder()
.move_to(Point::ORIGIN)
.quadratic_to(Point::new(10.0, 20.0), Point::new(20.0, 0.0))
.close()
.build()?;
assert_eq!(path.bounding_box(), Rect::new(0.0, 0.0, 20.0, 10.0));
let node = path
.fill(Color::from_hex(0x24a49b))
.fill_rule(FillRule::EvenOdd)
.at(Point::new(100.0, 80.0));
assert_eq!(
node.measure(ValidationLimits::default())?,
Rect::new(90.0, 75.0, 110.0, 85.0)
);
let list = node.compile(
Size::new(200.0, 160.0),
PixelSize::new(200, 160),
ValidationLimits::default(),
)?;
assert_eq!(list.commands.len(), 1);
assert!(matches!(
list.commands[0],
DrawCommand::Fill {
rule: FillRule::EvenOdd,
..
}
));Implementations§
Source§impl Path2D
impl Path2D
Sourcepub fn boolean(
&self,
other: &Self,
op: PathBooleanOp,
options: PathBooleanOptions,
) -> Result<Self, ValidationError>
pub fn boolean( &self, other: &Self, op: PathBooleanOp, options: PathBooleanOptions, ) -> Result<Self, ValidationError>
Combines two filled paths into a new path of closed line-only contours.
Curves are flattened to options.tolerance first, so the result is polygonal.
Each result contour keeps the covered area on its left (counter-clockwise in
y-up coordinates) and is meant to be filled with FillRule::NonZero. Open
subpaths are implicitly closed. Empty or zero-area results are empty paths.
The result depends only on the inputs, and degenerate or self-intersecting
operands are interpreted through options.fill_rule.
§Errors
Fails for a non-finite or non-positive tolerance, more than
MAX_BOOLEAN_EDGES flattened edges, or exceeded options.limits.
use motion_core::{Path2D, PathBooleanOp, PathBooleanOptions, Rect};
let left = Path2D::from_rect(Rect::new(0.0, 0.0, 10.0, 10.0))?;
let right = Path2D::from_rect(Rect::new(5.0, 0.0, 15.0, 10.0))?;
let overlap = left.boolean(&right, PathBooleanOp::Intersection, PathBooleanOptions::default())?;
assert_eq!(overlap.bounding_box(), Rect::new(5.0, 0.0, 10.0, 10.0));Source§impl Path2D
impl Path2D
Sourcepub fn from_rect(bounds: Rect) -> Result<Self, ValidationError>
pub fn from_rect(bounds: Rect) -> Result<Self, ValidationError>
Builds a closed rectangle, rejecting invalid bounds before any mutation.
Sourcepub fn polyline(
points: impl IntoIterator<Item = Point>,
) -> Result<Self, ValidationError>
pub fn polyline( points: impl IntoIterator<Item = Point>, ) -> Result<Self, ValidationError>
Builds a bounded polyline, rejecting nonfinite points and verb overflow.
Sourcepub fn parse_svg(path_data: &str) -> Result<Self, ValidationError>
pub fn parse_svg(path_data: &str) -> Result<Self, ValidationError>
Imports SVG path data, not an XML document, without rasterizing geometry.
Supports absolute/relative M/L/H/V/C/S/Q/T/A/Z, including repeated argument groups and reflected smooth controls. Empty data produces an empty path. A/a arcs become bounded cubic segments; zero radii become lines and coincident endpoints emit nothing. Syntax, nonfinite arithmetic and overflowing control extents return InvalidValue; input beyond MAX_SVG_PATH_BYTES or MAX_PATH_VERBS returns StructuralLimit. Parsed commands and expanded verbs have independent MAX_PATH_VERBS caps. Errors discard the entire result; there is no partial-path recovery, I/O or cache.
use motion_core::prelude::*;
use motion_core::{
DisplayList, RasterLimits, ResourceStore, ValidatedDisplayList, MAX_PATH_VERBS,
MAX_STROKE_VERBS, MAX_SVG_PATH_BYTES, sample_offsets,
};
let path = Path2D::parse_svg("M1 1h6v6H1z")?;
assert_eq!(path, Path2D::from_rect(Rect::new(1.0, 1.0, 7.0, 7.0))?);
let frame = Node::from(path.fill(Color::WHITE)).compile(
Size::new(8.0, 8.0),
PixelSize::new(8, 8),
ValidationLimits::default(),
)?;Source§impl Path2D
impl Path2D
Sourcepub fn cubic_breakpoints(&self) -> Result<Vec<f64>, ValidationError>
pub fn cubic_breakpoints(&self) -> Result<Vec<f64>, ValidationError>
Returns normalized arc-length boundaries for curve morphing.
Sourcepub fn cubic_intervals(
&self,
fractions: &[f64],
) -> Result<Vec<[Point; 4]>, ValidationError>
pub fn cubic_intervals( &self, fractions: &[f64], ) -> Result<Vec<[Point; 4]>, ValidationError>
Extracts cubic representations of checked normalized arc-length intervals.
Sourcepub fn length(&self) -> f64
pub fn length(&self) -> f64
Returns cached total contour length, including explicit closing edges. Panics if integration overflows or exhausts its bounded precision/work.
Sourcepub fn try_length(&self) -> Result<f64, ValidationError>
pub fn try_length(&self) -> Result<f64, ValidationError>
Checked arc length with bounded adaptive eight-point Gaussian integration.
Sourcepub fn point_at(&self, progress: f64) -> (Point, Vector2)
pub fn point_at(&self, progress: f64) -> (Point, Vector2)
Samples normalized arc distance and its unit forward tangent. Progress clamps to 0..=1; nonfinite inputs or metric failures panic.
Sourcepub fn try_point_at(
&self,
progress: f64,
) -> Result<(Point, Vector2), ValidationError>
pub fn try_point_at( &self, progress: f64, ) -> Result<(Point, Vector2), ValidationError>
Checked sampling. Empty/move-only paths have a zero tangent. At a cusp, uses the forward one-sided direction, or backward direction at the end.
Sourcepub fn trim(&self, start: f64, end: f64) -> Self
pub fn trim(&self, start: f64, end: f64) -> Self
Extracts a normalized arc-length interval, preserving Bezier segments. Clamps finite endpoints; empty/reversed intervals produce an empty path. Panics on invalid inputs or numerical/resource failure; see try_trim.
Sourcepub fn try_trim(&self, start: f64, end: f64) -> Result<Self, ValidationError>
pub fn try_trim(&self, start: f64, end: f64) -> Result<Self, ValidationError>
Checked de Casteljau extraction. Full range preserves all original verbs.
Sourcepub fn dashed(
&self,
pattern: &[f64],
offset: f64,
) -> Result<Self, ValidationError>
pub fn dashed( &self, pattern: &[f64], offset: f64, ) -> Result<Self, ValidationError>
Cuts positive finite dash/gap lengths in logical units. Odd patterns repeat twice; phase restarts per contour and positive offsets advance it. Empty patterns retain the path. At most 256 entries and 8192 visible intervals per contour are admitted; generated verbs remain bounded.
Source§impl Path2D
impl Path2D
Sourcepub fn builder() -> PathBuilder
pub fn builder() -> PathBuilder
Starts a chainable builder that reports its first error from build.
This is the public way to author paths. The in-place try_* appenders on Path2D
are hidden from the documentation and exist for content crates that grow a path in a loop.
Sourcepub fn bounding_box(&self) -> Rect
pub fn bounding_box(&self) -> Rect
Returns cached f64 geometric bounds, retaining zero-area geometry.
Sourcepub fn transformed(
&self,
transform: &Transform,
) -> Result<Self, ValidationError>
pub fn transformed( &self, transform: &Transform, ) -> Result<Self, ValidationError>
Maps all endpoints and controls without flattening or modifying this path.
Shares only the immutable verb snapshot, without retaining metric caches. Arc::make_mut on a returned handle cannot edit this path’s snapshot.
Sourcepub fn axis_aligned_rectangle(&self) -> Option<Rect>
pub fn axis_aligned_rectangle(&self) -> Option<Rect>
Bounds of a single nondegenerate four-edge axis-aligned closed contour. Curves, extra contours, retraced edges and nonrectangular paths return None.
Sourcepub fn fingerprint(&self) -> u64
pub fn fingerprint(&self) -> u64
Stable content fingerprint shared by clones and invalidated by successful edits. This is a lookup hint, not a collision-free geometry identity.