kurbo/
lib.rs

1// Copyright 2018 the Kurbo Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! 2D geometry, with a focus on curves.
5//!
6//! The kurbo library contains data structures and algorithms for curves and
7//! vector paths. It was designed to serve the needs of 2D graphics applications,
8//! but it is intended to be general enough to be useful for other applications.
9//! It can be used as "vocabulary types" for representing curves and paths, and
10//! also contains a number of computational geometry methods.
11//!
12//! # Examples
13//!
14//! Basic UI-style geometry:
15//! ```
16//! use kurbo::{Insets, Point, Rect, Size, Vec2};
17//!
18//! let pt = Point::new(10.0, 10.0);
19//! let vector = Vec2::new(5.0, -5.0);
20//! let pt2 = pt + vector;
21//! assert_eq!(pt2, Point::new(15.0, 5.0));
22//!
23//! let rect = Rect::from_points(pt, pt2);
24//! assert_eq!(rect, Rect::from_origin_size((10.0, 5.0), (5.0, 5.0)));
25//!
26//! let insets = Insets::uniform(1.0);
27//! let inset_rect = rect - insets;
28//! assert_eq!(inset_rect.size(), Size::new(3.0, 3.0));
29//! ```
30//!
31//! Finding the closest position on a [`Shape`]'s perimeter to a [`Point`]:
32//!
33//! ```
34//! use kurbo::{Circle, ParamCurve, ParamCurveNearest, Point, Shape};
35//!
36//! const DESIRED_ACCURACY: f64 = 0.1;
37//!
38//! /// Given a shape and a point, returns the closest position on the shape's
39//! /// perimeter, or `None` if the shape is malformed.
40//! fn closest_perimeter_point(shape: impl Shape, pt: Point) -> Option<Point> {
41//!     let mut best: Option<(Point, f64)> = None;
42//!     for segment in shape.path_segments(DESIRED_ACCURACY) {
43//!         let nearest = segment.nearest(pt, DESIRED_ACCURACY);
44//!         if best.map(|(_, best_d)| nearest.distance_sq < best_d).unwrap_or(true) {
45//!             best = Some((segment.eval(nearest.t), nearest.distance_sq))
46//!         }
47//!     }
48//!     best.map(|(point, _)| point)
49//! }
50//!
51//! let circle = Circle::new((5.0, 5.0), 5.0);
52//! let hit_point = Point::new(5.0, -2.0);
53//! let expectation = Point::new(5.0, 0.0);
54//! let hit = closest_perimeter_point(circle, hit_point).unwrap();
55//! assert!(hit.distance(expectation) <= DESIRED_ACCURACY);
56//! ```
57//!
58//! # Feature Flags
59//!
60//! The following crate [feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features) are available:
61//!
62//! - `std` (enabled by default): Get floating point functions from the standard library
63//!   (likely using your target's libc).
64//! - `libm`: Use floating point implementations from [libm][].
65//!   This is useful for `no_std` environments.
66//!   However, note that the `libm` crate is not as efficient as the standard library.
67//! - `mint`: Enable `From`/`Into` conversion of Kurbo and [mint][] types, enabling interoperability
68//!   with other graphics libraries.
69//! - `euclid`: Enable `From`/`Into` conversion of Kurbo and [euclid][] types.
70//!   Note that if you're using both Kurbo and euclid at the same time, you *must*
71//!   also enable one of euclid's `std` or `libm` features.
72//! - `serde`: Implement `serde::Deserialize` and `serde::Serialize` on various types.
73//! - `schemars`: Add best-effort support for using Kurbo types in JSON schemas using [schemars][].
74//!
75//! At least one of `std` and `libm` is required; `std` overrides `libm`.
76//! Note that Kurbo does require that an allocator is available (i.e. it uses [alloc]).
77
78// LINEBENDER LINT SET - lib.rs - v4
79// See https://linebender.org/wiki/canonical-lints/
80// These lints shouldn't apply to examples or tests.
81#![cfg_attr(not(test), warn(unused_crate_dependencies))]
82// These lints shouldn't apply to examples.
83#![warn(clippy::print_stdout, clippy::print_stderr)]
84// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit.
85#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))]
86// END LINEBENDER LINT SET
87#![cfg_attr(docsrs, feature(doc_cfg))]
88#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
89#![allow(
90    clippy::unreadable_literal,
91    clippy::many_single_char_names,
92    clippy::excessive_precision,
93    clippy::bool_to_int_with_if
94)]
95// The following lints are part of the Linebender standard set,
96// but resolving them has been deferred for now.
97// Feel free to send a PR that solves one or more of these.
98#![allow(
99    missing_debug_implementations,
100    elided_lifetimes_in_paths,
101    trivial_numeric_casts,
102    unnameable_types,
103    clippy::use_self,
104    clippy::cast_possible_truncation,
105    clippy::missing_assert_message,
106    clippy::unseparated_literal_suffix,
107    clippy::duplicated_attributes,
108    clippy::allow_attributes_without_reason
109)]
110
111#[cfg(not(any(feature = "std", feature = "libm")))]
112compile_error!("kurbo requires either the `std` or `libm` feature");
113
114// Suppress the unused_crate_dependencies lint when both std and libm are specified.
115#[cfg(all(feature = "std", feature = "libm"))]
116use libm as _;
117
118extern crate alloc;
119
120mod affine;
121mod arc;
122mod axis;
123mod bezpath;
124mod circle;
125pub mod common;
126mod cubicbez;
127mod ellipse;
128mod fit;
129mod insets;
130mod line;
131mod mindist;
132mod moments;
133pub mod offset;
134mod param_curve;
135mod point;
136mod quadbez;
137mod quadspline;
138mod rect;
139mod rounded_rect;
140mod rounded_rect_radii;
141mod shape;
142pub mod simplify;
143mod size;
144mod stroke;
145mod svg;
146mod translate_scale;
147mod triangle;
148mod vec2;
149
150#[cfg(feature = "euclid")]
151mod interop_euclid;
152
153pub use crate::affine::Affine;
154pub use crate::arc::{Arc, ArcAppendIter};
155pub use crate::axis::Axis;
156pub use crate::bezpath::{
157    flatten, segments, BezPath, LineIntersection, MinDistance, PathEl, PathSeg, PathSegIter,
158    Segments,
159};
160pub use crate::circle::{Circle, CirclePathIter, CircleSegment};
161pub use crate::cubicbez::{cubics_to_quadratic_splines, CubicBez, CubicBezIter, CuspType};
162pub use crate::ellipse::Ellipse;
163pub use crate::fit::{
164    fit_to_bezpath, fit_to_bezpath_opt, fit_to_cubic, CurveFitSample, ParamCurveFit,
165};
166pub use crate::insets::Insets;
167pub use crate::line::{ConstPoint, Line, LinePathIter};
168pub use crate::moments::{Moments, ParamCurveMoments};
169pub use crate::param_curve::{
170    Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, ParamCurveDeriv,
171    ParamCurveExtrema, ParamCurveNearest, DEFAULT_ACCURACY, MAX_EXTREMA,
172};
173pub use crate::point::Point;
174pub use crate::quadbez::{QuadBez, QuadBezIter};
175pub use crate::quadspline::QuadSpline;
176pub use crate::rect::{Rect, RectPathIter};
177pub use crate::rounded_rect::{RoundedRect, RoundedRectPathIter};
178pub use crate::rounded_rect_radii::RoundedRectRadii;
179pub use crate::shape::Shape;
180pub use crate::size::Size;
181pub use crate::stroke::{
182    dash, stroke, stroke_with, Cap, Dashes, Join, Stroke, StrokeCtx, StrokeOptLevel, StrokeOpts,
183};
184pub use crate::svg::{SvgArc, SvgParseError};
185pub use crate::translate_scale::TranslateScale;
186pub use crate::triangle::{Triangle, TrianglePathIter};
187pub use crate::vec2::Vec2;