Skip to main content

Path2D

Struct Path2D 

Source
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

Source

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

Source

pub fn from_rect(bounds: Rect) -> Result<Self, ValidationError>

Builds a closed rectangle, rejecting invalid bounds before any mutation.

Source

pub fn polyline( points: impl IntoIterator<Item = Point>, ) -> Result<Self, ValidationError>

Builds a bounded polyline, rejecting nonfinite points and verb overflow.

Source

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

Source

pub fn cubic_breakpoints(&self) -> Result<Vec<f64>, ValidationError>

Returns normalized arc-length boundaries for curve morphing.

Source

pub fn cubic_intervals( &self, fractions: &[f64], ) -> Result<Vec<[Point; 4]>, ValidationError>

Extracts cubic representations of checked normalized arc-length intervals.

Source

pub fn length(&self) -> f64

Returns cached total contour length, including explicit closing edges. Panics if integration overflows or exhausts its bounded precision/work.

Source

pub fn try_length(&self) -> Result<f64, ValidationError>

Checked arc length with bounded adaptive eight-point Gaussian integration.

Source

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.

Source

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.

Source

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.

Source

pub fn try_trim(&self, start: f64, end: f64) -> Result<Self, ValidationError>

Checked de Casteljau extraction. Full range preserves all original verbs.

Source

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

Source

pub fn new() -> Self

Creates an empty path without paint.

Source

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.

Source

pub fn verbs(&self) -> &[PathVerb]

Returns the immutable absolute f64 verbs.

Source

pub fn bounding_box(&self) -> Rect

Returns cached f64 geometric bounds, retaining zero-area geometry.

Source

pub fn transformed( &self, transform: &Transform, ) -> Result<Self, ValidationError>

Maps all endpoints and controls without flattening or modifying this path.

Source

pub fn shared_verbs(&self) -> Arc<Vec<PathVerb>> ⓘ

Shares only the immutable verb snapshot, without retaining metric caches. Arc::make_mut on a returned handle cannot edit this path’s snapshot.

Source

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.

Source

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.

Trait Implementations§

Source§

impl Clone for Path2D

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Path2D

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Path2D

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Path2D> for PathClip

Source§

fn from(path: Path2D) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Path2D

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Shape for Path2D

Source§

fn path(&self) -> Result<Path2D, ValidationError>

Returns a checked path snapshot without f32 narrowing.
Source§

fn bounding_box(&self) -> Result<Rect, ValidationError>

Geometric bounds; defaults to the path’s cached curve bounds.
Source§

fn as_rect(&self) -> Option<Rect>

Exact rectangle equivalent, when available, for a rule-independent fast path.
Source§

fn fill(self, paint: impl Into<Paint>) -> Styled<Self>
where Self: Sized,

Adds floating fill paint, using the nonzero rule by default.
Source§

fn stroke(self, width: f64, paint: impl Into<Paint>) -> Styled<Self>
where Self: Sized,

Adds a bounded curve/path stroke without an implicit fill.

Auto Trait Implementations§

§

impl Forget for Path2D

§

impl Freeze for Path2D

§

impl Move for Path2D

§

impl RefUnwindSafe for Path2D

§

impl Send for Path2D

§

impl Sync for Path2D

§

impl Unpin for Path2D

§

impl UnsafeUnpin for Path2D

§

impl UnwindSafe for Path2D

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<Geometry> IntoShapeClip for Geometry
where Geometry: Shape,

Source§

fn into_shape_clip(self) -> Result<ShapeClip, ValidationError>

Captures the clip geometry, reporting invalid shapes.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.