diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 55ff91d455..009f7f7119 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -27,6 +27,7 @@ author, source and license. Library code and original assets are under the repos | `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 | | Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT | | Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 | +| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) | | `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | | `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) | | `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) | diff --git a/Cargo.lock b/Cargo.lock index 0e7d6730c1..07c3fd7ab8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1865,6 +1865,7 @@ dependencies = [ "craft-media-source", "craft-menu", "craft-mesh", + "craft-mesh-ops", "craft-metadata", "craft-metafile", "craft-midi", @@ -3445,6 +3446,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mesh-ops" +version = "0.1.0" +dependencies = [ + "glam 0.30.10", + "mikktspace", + "rayon", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -3607,6 +3619,9 @@ version = "0.1.0" name = "craft-pbr" version = "0.1.0" dependencies = [ + "craft-materialx", + "craft-mesh", + "craft-pbr", "craft-texture", "glam 0.30.10", "naga", @@ -4330,10 +4345,13 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "libc", + "png 0.18.1", "rustix 1.1.6", "serde_json", "sha2 0.10.9", "skrifa 0.47.0", + "tempfile", + "toml", ] [[package]] @@ -4367,8 +4385,12 @@ name = "craft-texture" version = "0.1.0" dependencies = [ "bytemuck", + "craft-exr", + "craft-hdr", + "craft-image-codecs", "dds", "half", + "png 0.18.1", "rayon", "thiserror 2.0.21", ] @@ -4970,10 +4992,14 @@ name = "craft-xtask" version = "0.1.0" dependencies = [ "craft-atomic", + "flate2", "libc", "serde_json", + "sha2 0.10.9", + "tar", "tempfile", "toml_edit", + "unicode-normalization", ] [[package]] @@ -6847,6 +6873,12 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glam" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b" + [[package]] name = "glam" version = "0.25.0" @@ -6858,6 +6890,9 @@ name = "glam" version = "0.30.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9" +dependencies = [ + "serde_core", +] [[package]] name = "glifo" @@ -8386,8 +8421,6 @@ dependencies = [ [[package]] name = "kurbo" version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" dependencies = [ "arrayvec", "euclid", @@ -8703,6 +8736,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74" +[[package]] +name = "mikktspace" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d0b56b403871a8f992ca626d52cc0a690d4841baea8955dc4af6304ac62f8b0" +dependencies = [ + "glam 0.15.2", +] + [[package]] name = "mime" version = "0.3.17" diff --git a/Cargo.toml b/Cargo.toml index fe766a6848..136df2be6f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" members = ["crates/*"] -exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"] +exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"] [workspace.package] version = "0.1.0" @@ -136,6 +136,7 @@ craft-gcode = { path = "crates/gcode" } craft-gif = { path = "crates/gif" } craft-hdr = { path = "crates/hdr" } craft-mesh = { path = "crates/mesh" } +craft-mesh-ops = { path = "crates/mesh-ops" } craft-html = { path = "crates/html" } craft-ipp = { path = "crates/ipp" } craft-heif = { path = "crates/heif" } @@ -324,6 +325,7 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } +kurbo = { path = "vendor/kurbo" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } diff --git a/NOTICE b/NOTICE index 4a2d1084e4..baa994eb47 100644 --- a/NOTICE +++ b/NOTICE @@ -63,6 +63,10 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops, + is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C + MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or + altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full. crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer. crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists) 2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/. @@ -229,6 +233,17 @@ The colour management module in crates/cms is extracted from: Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain (CC0-1.0); see ATTRIBUTION.md. +The mesh operations in crates/mesh-ops are moved from: +- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs, + camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2. + https://github.com/storytold/texturecraft + Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. +- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision + 3133062968b8a1566eda12a357cb06062db16687. + https://github.com/storytold/materialcraft + Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. + All licensed MIT OR Apache-2.0. + The image-based lighting in crates/pbr (craft-pbr) is adapted from: - TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc, copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs. @@ -288,11 +303,18 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs, -src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its -manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman +as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local -patches and the files left out. +changes and the files left out. + +kurbo + +kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR +Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to +src/stroke.rs. Its source files carry "Copyright the Kurbo Authors" lines (2018 to 2026), +and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and +vendor/kurbo/SOURCE.json for provenance and the local patches. Platform lifecycle source provenance diff --git a/README.md b/README.md index fb17f85974..8169bedf9a 100644 --- a/README.md +++ b/README.md @@ -329,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY, glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft. +- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals, + MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a + BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft. - [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and 2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per quarter note. From SoundCraft. @@ -432,7 +435,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the test when the variable the caller names is `1`. Any other value of that variable except empty fails the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder - against a pinned SHA-256 list. Not published. + against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures + under `target/fixtures` and publishes each one under a lock. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and @@ -440,8 +444,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit (ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find` (regex) are features. - [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with - nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are - bounded by `Limits`. From MaterialCraft. + nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and + (optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float + samples. Sizes are bounded by `Limits`. From MaterialCraft. - [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates, timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE, CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel, diff --git a/crates/affinity/src/synth.rs b/crates/affinity/src/synth.rs index 5b75ca0bff..a25cba792b 100644 --- a/crates/affinity/src/synth.rs +++ b/crates/affinity/src/synth.rs @@ -257,3 +257,11 @@ pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]> } out } + +/// What `f` gives, and how many paragraph ends the reader looked up on this thread while it ran +/// to give each character run its paragraph's format. +pub fn count_paragraph_lookups(f: impl FnOnce() -> T) -> (T, usize) { + crate::text::MATCH_READS.with(|reads| reads.set(0)); + let value = f(); + (value, crate::text::MATCH_READS.with(std::cell::Cell::get)) +} diff --git a/crates/affinity/src/text.rs b/crates/affinity/src/text.rs index c74dc287f6..f645d66857 100644 --- a/crates/affinity/src/text.rs +++ b/crates/affinity/src/text.rs @@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect(); cuts.dedup(); let push = |r: &mut Reader, runs: &mut Vec, attrs: Option, from: usize, to: usize, budget: &mut Option| { // Split at paragraph ends so every run has one paragraph format. - let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default(); + let first = cuts.partition_point(|c| { + count_match_read(); + *c <= from + }); + let past = cuts.partition_point(|c| { + count_match_read(); + *c < to + }); + let inside = cuts.get(first..past).unwrap_or_default(); let mut a = from; for &c in inside.iter().chain(std::iter::once(&to)) { push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a)); @@ -282,6 +296,18 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn count_match_read() { + #[cfg(any(test, feature = "synth"))] + MATCH_READS.with(|reads| reads.set(reads.get().saturating_add(1))); +} + fn characters(chars: &[char], start: usize, end: usize) -> String { chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect() } diff --git a/crates/affinity/tests/it/import_limits.rs b/crates/affinity/tests/it/import_limits.rs index f08c044298..9924125d9d 100644 --- a/crates/affinity/tests/it/import_limits.rs +++ b/crates/affinity/tests/it/import_limits.rs @@ -111,25 +111,32 @@ fn a_shared_story_is_read_within_the_characters_of_one_document() { #[test] fn many_paragraphs_and_runs_are_matched_in_about_linear_time() { - // 200 000 paragraphs, each with its own run and format. - let n = 200_000; - let text = "a\u{2029}".repeat(n); - let fmt = - |end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]; - let blk = F::Obj( - tag(b"StBl"), - vec![ - (tag(b"Glyp"), utf8(&text)), - (tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])), - (tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])), - ], - ); - let started = std::time::Instant::now(); - let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]); - let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") }; - assert_eq!(t.runs.len(), n); - // (About half a second; quadratic matching took over half a minute on the same machine.) - assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); + // `n` paragraphs, each with its own run and format, and how many paragraph ends matching + // them looks up. + let lookups = |n: usize| { + let text = "a\u{2029}".repeat(n); + let fmt = |end: usize| { + vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))] + }; + let blk = F::Obj( + tag(b"StBl"), + vec![ + (tag(b"Glyp"), utf8(&text)), + (tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])), + (tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])), + ], + ); + let story = artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))])); + let (d, lookups) = synth::count_paragraph_lookups(|| open(vec![story])); + let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") }; + assert_eq!(t.runs.len(), n); + lookups + }; + // Four times the paragraphs and runs: a few binary searches each, so about four times the + // lookups (a little more for the longer searches), where matching each run against every + // paragraph is sixteen times. + let (quarter, full) = (lookups(50_000), lookups(200_000)); + assert!(full <= 5 * quarter, "{quarter} lookups for 50,000 paragraphs, {full} for 200,000"); } /// A shape node of `size` px. diff --git a/crates/behavior/src/frame_step.rs b/crates/behavior/src/frame_step.rs index a293d5a1ff..225cc70b4c 100644 --- a/crates/behavior/src/frame_step.rs +++ b/crates/behavior/src/frame_step.rs @@ -3,8 +3,9 @@ /// The longest step motion integrates, in seconds, so a stalled pass never jumps the view. pub const FRAME_STEP_MAX: f64 = 0.1; -/// The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the -/// caller's pass clock: `dt` within `0..=FRAME_STEP_MAX`, and 0 where it is not a number. +/// The step of a pass that came `dt` seconds after the previous one, kept within `0..=FRAME_STEP_MAX`. +/// +/// `dt` is the time between two readings of the caller's pass clock; where it is not a number, the step is 0. pub fn frame_step(dt: f64) -> f64 { if dt.is_finite() { dt.clamp(0.0, FRAME_STEP_MAX) } else { 0.0 } } diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md index 772f915350..e29d443fea 100644 --- a/crates/cdr/PROVENANCE.md +++ b/crates/cdr/PROVENANCE.md @@ -155,14 +155,13 @@ file is committed. | R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) | | R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) | | R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample | -| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | +| R77 | The index of a file with 32-bit coordinates, which the reader does not read. `cont` bytes 84, 88 and 92 hold the u32 file offsets of the master index `ixmr`, of `LIST INFO` and of the picture of the drawing (`DISP`), 0xFFFFFFFF for one the file does not hold. Each offset here names where a chunk's id starts. `cont` bytes 96 to 112 hold four i32 edges, the same bytes as the edges in the page's begin-page record, and bytes 112 to 116 a u32, the page's instruction count as begin page holds it. `LIST indx` holds a layer table `ixlr`, then `ixtl`, `ixpg` and `ixmr`. `ixmr`: the u16 values 1 and 24, a u16 count, then a u16 id and a u32 offset for each entry: 1 `ixmr` itself, 2 `ixpg`, 3 `ixtl`, 15 `rotl`, 16 `rott`, 17 `rota`, 18 `rscr`, 19 `rpen`, 20 `rdot`, 21 `rclr`, 22 `ccmm`; a table the file does not hold has no entry. `ixpg`: a u16 count, then for each page a u16 record size of 16 and four u32: the page chunk, its layer table, its picture (0xFFFFFFFF for none) and its reference list `rlst`. `ixtl`: a u16 count, a u16 record size of 4, the u16 type 3 (layer tables), then the u32 offset of each layer table. `ixlr`: a u16 count of the page's layers and the u16 value 1, then for each layer in file order a u16 size (8 plus the name's length), the u32 offset of its begin-layer instruction, its name as a u16 count and 8-bit characters, and 0xFFFFFFFF after the size. `rlst`: a u16 count of the page's layers, then the u16 values 2 and 9 and the layer's number for each. Begin page's field 1 ends with the u32 offset of the end-page instruction, a u16 count of the page's layers and a u32 count of its instructions, begin and end page included; begin layer's field 1 holds a u32 count of the layer's instructions, begin and end layer included, at bytes 8 to 12; begin group's field 1 holds the left, top, right and bottom edges of its curves (i32), a u16 count of the groups directly inside it, a u32 count of its instructions, begin and end group included, and the u32 offset of the instruction after its end | LC `CMXParser.cpp` L260-L286 (the three offsets, 0xFFFFFFFF for none; four coordinates after them, read only for a debug message), L1011-L1019 (the four coordinates of a box), L346-L413 (`ixmr`: two u16, the count, the id and offset pairs), L545-L590 (begin group: the edges, a u16, the command count and the end address), L1974-L2019 (`ixtl`: the count, the record size, the type), L2060-L2096 (`ixpg`: the count, the record size and four offsets for each page), `CMXParser.h` L24-L41 (the ids); S: every CX file with 32-bit coordinates holds these chunks in this order, its `ixmr` entries name these chunks with these ids, the values 1 and 24 and `ixtl` type 3, its `ixpg` names its one page, the one `ixlr` and the `rlst`, its `ixlr` names its layers' begin-layer instructions with their names and the value 1, its `rlst` holds 2, 9 and the number of each of its layers, and the counts and offsets in its 9 pages, 33 layers and 12 groups match the instructions; in each of the 9 files, `cont` bytes 96 to 116 match its one page's edges and instruction count; 8 of the 12 groups hold the edges of their curves' points | sample (the order, `ixlr`, `rlst`, the values 1 and 24, the counts and offsets in the records, the header's edges and instruction count), public-reader (the header's offsets, the `ixmr` ids, `ixpg`, `ixtl` and the order of begin group's fields; the samples agree), unconfirmed (the group count counting only the groups directly inside, as no sample nests groups two deep; the value 1 in a layer table of a page after the first) | ## Written fields `src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table lists every field it sets. `own` marks a value the reader does not read, which the writer sets as -the synthetic test files of `src/synth_cmx.rs` set it. The header's bounds and instruction count -at bytes 96 to 116 are not written. +the synthetic test files of `src/synth_cmx.rs` set it. | Field written | Rows | Status | |---|---|---| @@ -170,6 +169,7 @@ at bytes 96 to 116 are not written. | Chunk order: `cont`, each `page` chunk followed by its `rlst`, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr`, then `LIST indx` | R53, R77 | sample (`page`, `rlst`, the tables, `LIST indx`), own (the order of the tables; the `rlst` of a page after the first) | | `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample | | `cont`: the offset of `ixmr` at bytes 84 to 88, 0xFFFFFFFF for the information list and the picture at bytes 88 to 96 | R77 | public-reader, sample (the picture), own (no information list) | +| `cont`: the first page's edges at bytes 96 to 112 and its instruction count at bytes 112 to 116, as its begin-page record holds them; zeros for a file with no page | R77 | sample (one page), the writer's choice (the first page of several, and zeros) | | `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own | | `LIST indx`: a layer table `ixlr` for each page, `ixtl` listing them, `ixpg` with each page, and `ixmr` with itself, `ixpg`, `ixtl` and the seven tables | R77 | sample (one page), own (a layer table for each page, `ixtl` listing each, and the page number after the count) | | `rlst` for each page: its layers' numbers | R77 | sample | diff --git a/crates/cdr/README.md b/crates/cdr/README.md index e86a8aa393..0bf2c8e8f8 100644 --- a/crates/cdr/README.md +++ b/crates/cdr/README.md @@ -131,7 +131,7 @@ by their chunk ids, opens it: the header gives where the master index starts, th layer and group records give their instruction counts. A page's record also gives where its end-page instruction starts, and a group's record gives where the instruction after its end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of its curves, or -of the page when it has none. The header's bounds and instruction count are not written. +of the page when it has none. The header repeats the first page's edges and instruction count. `PROVENANCE.md`'s "Written fields" table lists every field the `.cmx` writer sets. ## Writing diff --git a/crates/cdr/src/cmx_write.rs b/crates/cdr/src/cmx_write.rs index 53d0ec8664..a5c6e00058 100644 --- a/crates/cdr/src/cmx_write.rs +++ b/crates/cdr/src/cmx_write.rs @@ -131,20 +131,20 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result Ok(()) }; // The header's index offset is set once the index is placed. - add(chunk(b"cont", &cont(0))?)?; + add(chunk(b"cont", &cont(0, PageHead::default()))?)?; // Each page chunk and its reference list, with where they start in the file and the start and // name of each of the page's layers. let mut pages = Vec::new(); let mut page = |w: &mut Writer, n: usize, size: Option<(f64, f64)>, layers: &[Layer]| -> Result<(), Error> { let at = w.file_bytes; - let (c, written) = w.page(n, size, layers)?; + let (c, written, head) = w.page(n, size, layers)?; add(c)?; let refs = w.file_bytes; let r = chunk(b"rlst", &reference_list(written.len()))?; w.check_bytes(r.len())?; w.file_bytes += r.len(); add(r)?; - pages.push(PageAt { at, refs, layers: written }); + pages.push(PageAt { at, refs, layers: written, head }); Ok(()) }; for (n, p) in drawing.pages.iter().enumerate() { @@ -181,7 +181,7 @@ pub fn write(drawing: &Drawing, limits: crate::Limits) -> Result if total > w.limits.input { return Err(Error::Limit("input size")); } - children[0] = chunk(b"cont", &cont(ixmr))?; + children[0] = chunk(b"cont", &cont(ixmr, pages.first().map(|p| p.head).unwrap_or_default()))?; let mut bytes = Vec::new(); bytes.try_reserve_exact(total).map_err(|_| Error::Limit("file size"))?; bytes.extend(b"RIFF"); @@ -222,8 +222,9 @@ fn chunk(id: &[u8; 4], body: &[u8]) -> Result, Error> { /// The header (R54): the coordinate size digit `4` at byte 52 and the unit in meters at bytes 64 /// to 72. Bytes 48 and 54 hold the digit `2`, as in the sample files. Bytes 84 to 96 hold the file /// offset of the master index `ixmr`, then 0xFFFFFFFF for the information list and for the -/// picture of the drawing, which the file does not hold (R77); the rest are zeros. -fn cont(ixmr: u32) -> Vec { +/// picture of the drawing, which the file does not hold (R77). Bytes 96 to 116 hold the edges and +/// the instruction count of `first`, the first page's begin-page record (R77); the rest are zeros. +fn cont(ixmr: u32, first: PageHead) -> Vec { let mut c = vec![0u8; 180]; c[48] = b'2'; c[52] = b'4'; @@ -231,9 +232,21 @@ fn cont(ixmr: u32) -> Vec { c[64..72].copy_from_slice(&UNIT_METERS.to_le_bytes()); c[84..88].copy_from_slice(&ixmr.to_le_bytes()); c[88..96].fill(0xFF); + for (i, v) in first.edges.iter().enumerate() { + c[96 + 4 * i..100 + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + c[112..116].copy_from_slice(&first.instructions.to_le_bytes()); c } +/// What a page's begin-page record holds that the header repeats: its left, top, right and bottom +/// edges and its instruction count, begin and end page included. +#[derive(Clone, Copy, Default)] +struct PageHead { + edges: [i32; 4], + instructions: u32, +} + /// Where a layer's begin-layer instruction starts in the file, and the layer's 8-bit name. type LayerAt = (usize, Vec); @@ -243,6 +256,8 @@ struct PageAt { /// The page's reference list `rlst`. refs: usize, layers: Vec, + /// What the header repeats of its begin-page record. + head: PageHead, } /// A page's reference list (R77): a u16 count of its layers, then for each layer from 1 the u16 @@ -733,9 +748,10 @@ impl Writer { } /// A `page` chunk: begin page `n` (from 0), its shown layers back to front, end the page (R60), - /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name. - /// The chunk starts at the file offset [`Writer::file_bytes`] gives. - fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec), Error> { + /// with the file offset of each layer's begin-layer instruction and the layer's 8-bit name, and + /// what the header repeats of the begin-page record. The chunk starts at the file offset + /// [`Writer::file_bytes`] gives. + fn page(&mut self, n: usize, size: Option<(f64, f64)>, layers: &[Layer]) -> Result<(Vec, Vec, PageHead), Error> { let mut out = Vec::new(); self.bounds = None; self.instructions = 1; @@ -803,7 +819,7 @@ impl Writer { self.check_bytes(c.len())?; let layers = starts.into_iter().map(|(at, name)| (base.saturating_add(at), name)).collect(); self.file_bytes += c.len(); - Ok((c, layers)) + Ok((c, layers, PageHead { edges: page_edges(size, bounds)?, instructions: tail.instructions })) } /// An [`Error::Limit`] when the file would be longer than the input size of the limits with @@ -1164,29 +1180,15 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail let mut d = number.to_le_bytes().to_vec(); d.extend(0u32.to_le_bytes()); let mut list = Vec::new(); - let mut size_field = None; - let mut edges = [0i32; 4]; - if let Some((w, h)) = size { - // A negative or NaN side counts as 0. - let (wu, hu) = (width_units(w)?, width_units(h)?); - // A side that rounds to nothing would make the reader drop the page's whole size. - if wu == 0 || hu == 0 { - return Err(Error::Limit("page size")); + let edges = page_edges(size, bounds)?; + let size_field = match size { + Some((w, h)) => { + let mut s = width_units(w)?.to_le_bytes().to_vec(); + s.extend(width_units(h)?.to_le_bytes()); + Some(s) } - edges = match bounds { - Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], - None => { - // The page around its center; an odd size keeps its extra unit on the left and - // bottom, where the edge reaches -2^31. - let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); - let (w, h) = (i64::from(wu), i64::from(hu)); - [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] - } - }; - let mut s = wu.to_le_bytes().to_vec(); - s.extend(hu.to_le_bytes()); - size_field = Some(s); - } + None => None, + }; for v in edges { d.extend(v.to_le_bytes()); } @@ -1200,6 +1202,28 @@ fn begin_page(n: usize, size: Option<(f64, f64)>, bounds: Option<[i32; 4]>, tail Ok(instr(BEGIN_PAGE, &fields(&list))) } +/// The left, top, right and bottom edges begin page holds for a page of `size` whose art reaches +/// `bounds`, as [`begin_page`] describes. A page side that rounds to 0 is an [`Error::Limit`]. +fn page_edges(size: Option<(f64, f64)>, bounds: Option<[i32; 4]>) -> Result<[i32; 4], Error> { + let Some((w, h)) = size else { return Ok([0; 4]) }; + // A negative or NaN side counts as 0. + let (wu, hu) = (width_units(w)?, width_units(h)?); + // A side that rounds to nothing would make the reader drop the page's whole size. + if wu == 0 || hu == 0 { + return Err(Error::Limit("page size")); + } + Ok(match bounds { + Some([x0, y0, x1, y1]) => [x0, y1, x1, y0], + None => { + // The page around its center; an odd size keeps its extra unit on the left and + // bottom, where the edge reaches -2^31. + let edge = |v: i64| i32::try_from(v).map_err(|_| Error::Limit("page size")); + let (w, h) = (i64::from(wu), i64::from(hu)); + [edge(w / 2 - w)?, edge(h / 2)?, edge(w / 2)?, edge(h / 2 - h)?] + } + }) +} + /// `c` as a Windows-1252 byte, or `?` when the code page has no byte for it. fn windows_1252_byte(c: char) -> u8 { match u8::try_from(u32::from(c)) { diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs index 4c9ee11bb7..b18029fb25 100644 --- a/crates/cdr/src/lib.rs +++ b/crates/cdr/src/lib.rs @@ -153,8 +153,8 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { /// page, layer and group records give their instruction counts. A page's record also gives where /// its end-page instruction starts, and a group's record gives where the instruction after its /// end-group instruction starts and the edges of its curves. The record of a page with a size holds the edges of -/// its curves, or of the page when it has none. The header's bounds and instruction count are not -/// written. +/// its curves, or of the page when it has none. The header repeats the first page's edges and +/// instruction count. pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result { cmx_write::write(drawing, limits) } diff --git a/crates/cdr/tests/it/cmx_write.rs b/crates/cdr/tests/it/cmx_write.rs index f25ed11fe2..989205e635 100644 --- a/crates/cdr/tests/it/cmx_write.rs +++ b/crates/cdr/tests/it/cmx_write.rs @@ -1078,6 +1078,35 @@ fn the_index_and_the_records_give_where_everything_is() { assert_eq!(groups, [(0, 3), (1, 7)]); } +#[test] +fn the_header_repeats_the_first_pages_edges_and_instruction_count() { + let plain = |x: f64| Object::Shape(Box::new(Shape::new(square(x, 0.0, 10.0), Matrix::IDENTITY, Some(Color::Gray(0.5)), None))); + let pages = vec![ + Page { size: Some((200.0, 100.0)), layers: vec![layer("Front", vec![plain(0.0), plain(20.0)]), layer("Back", vec![plain(5.0)])] }, + Page { size: Some((300.0, 100.0)), layers: vec![layer("Only", vec![plain(1.0)])] }, + ]; + let b = write_cmx(&drawing(pages)).unwrap().bytes; + let cont = 12 + 8; + let chunk = page_index(&b)[0][0]; + let page = chunk + 8; + // Begin page's field 1: the page number, the flags, the edges, the end offset, the layer count + // and the instruction count. + let fields = field_starts(&b, page + 4, page + instruction_size(&b, page, page + u32_at(&b, chunk + 4))); + assert_eq!(fields[0].0, 1); + let f1 = fields[0].1; + assert_eq!(&b[cont + 96..cont + 112], &b[f1 + 6..f1 + 22]); + // The curves of the first page reach from 0 to 30 pt across and 0 to 10 pt down. + let edges: Vec = (0..4).map(|i| i32::from_le_bytes(b[cont + 96 + 4 * i..cont + 100 + 4 * i].try_into().unwrap())).collect(); + let unit = |pt: f64| (pt * 0.0254 / 72.0 / 1e-7).round() as i32; + assert_eq!(edges, [0, unit(10.0), unit(30.0), 0]); + // Begin and end page, two begin and end layers and three curves. + assert_eq!(u32_at(&b, cont + 112), 9); + assert_eq!(u32_at(&b, f1 + 28), 9); + // A drawing without pages leaves them 0. + let b = write_cmx(&drawing(Vec::new())).unwrap().bytes; + assert!(b[cont + 96..cont + 116].iter().all(|v| *v == 0)); +} + /// The page index of a written file of two pages, each entry's page chunk, layer table, picture /// and reference list, checked through the header and the master index. fn page_index(b: &[u8]) -> Vec<[usize; 4]> { diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index 8494bd029a..f1df948d43 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -361,17 +361,35 @@ fn edge_index(t: &[f32], start: bool) -> f32 { if start { let v = t[0]; // The first value that differs, given they do so from there on. - let first_other = t.partition_point(|x| (*x - v).abs() <= 1e-7); + let first_other = t.partition_point(|x| { + count_edge_read(); + (*x - v).abs() <= 1e-7 + }); let i = if first_other >= n { n - 1 } else { first_other.saturating_sub(1) }; i as f32 / (n - 1) as f32 } else { let v = t[n - 1]; // The start of the trailing run equal to the last value. - let i = t.partition_point(|x| (*x - v).abs() > 1e-7); + let i = t.partition_point(|x| { + count_edge_read(); + (*x - v).abs() > 1e-7 + }); i as f32 / (n - 1) as f32 } } +// Each table entry `edge_index` reads on this thread. +#[cfg(test)] +std::thread_local! { + static EDGE_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[inline] +fn count_edge_read() { + #[cfg(test)] + EDGE_READS.with(|reads| reads.set(reads.get().saturating_add(1))); +} + #[cfg(test)] mod tests { use super::*; @@ -381,13 +399,18 @@ mod tests { // Four million zeros and a one: a scan per call would be 8·10¹¹ steps for these calls. let mut t = vec![0.0f32; 4_000_000]; t.push(1.0); + // Bisection reads one entry per halving of the table, and a scan reads the whole run. + let per_call = t.len().ilog2() as usize + 2; let c = Curve::Table(t); - let started = std::time::Instant::now(); - let mut last = 0.0; - for _ in 0..200_000 { + EDGE_READS.with(|reads| reads.set(0)); + let mut last = c.eval_inverse(0.0); + let one_call = EDGE_READS.with(std::cell::Cell::get); + assert!(one_call <= per_call, "one inversion read {one_call} entries"); + for _ in 1..200_000 { last = c.eval_inverse(0.0); } assert!(last > 0.99, "the flat start ends at the last zero: {last}"); - assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); + let total = EDGE_READS.with(std::cell::Cell::get); + assert!(total <= 200_000 * per_call, "200,000 inversions read {total} entries"); } } diff --git a/crates/color-ui/src/ui/hud.rs b/crates/color-ui/src/ui/hud.rs index f8a15f453a..0d6b4e3660 100644 --- a/crates/color-ui/src/ui/hud.rs +++ b/crates/color-ui/src/ui/hud.rs @@ -6,7 +6,7 @@ use crate::AreaMode; use craft_behavior::{EditEvent, EditEvents, Metrics, PartKey, Sense}; use craft_theme::Srgba; use craft_ui::contract::{ - Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPUP_PAD, PaintUi, PartsCx, + Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, POPOVER_PAD, PaintUi, PartsCx, Pattern, Props as _, Role, Show as _, ShowContainer as _, pad_of, }; use craft_ui::popover::Popover; @@ -77,7 +77,7 @@ fn start_point(geometry: Geometry, start: Option) -> Pos2 { /// The popover's top left, so that the start colour's point in the area sits at `at`. fn origin(tokens: &UiTokens, at: Pos2, start: Option) -> Pos2 { let point = start_point(Geometry::of(tokens), start); - let pad = pad_of(tokens, POPUP_PAD); + let pad = pad_of(tokens, POPOVER_PAD); pos2(at.x - pad - point.x, at.y - pad - point.y) } diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index 54fb837833..c075c29095 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -68,14 +68,14 @@ pub use paint_chip::{ PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords, }; pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well}; -pub use palette::{SwatchPalette, SwatchPaletteOutput}; +pub use palette::{PaletteCell, SwatchPalette, SwatchPaletteOutput}; pub use panel::{ ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow, }; pub use picker::{ - ChannelRow, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor, - ScreenPickGesture, TrackRamp, + ChannelRow, ChannelRowOutput, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, + PickedColor, ScreenPickGesture, TrackRamp, }; pub use picker_dialog::{ ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary, diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index b5d35ac5c0..7da075f1aa 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -38,6 +38,18 @@ pub struct SwatchPaletteOutput { /// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour. /// The recent row and the Other… cell do not report a swatch index. pub picked_swatch: Option, + /// The cell `picked` came from, so a host can tell apart cells that show the same color. + pub cell: Option, +} + +/// A cell of a [`SwatchPalette`] by its place in the host's lists. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum PaletteCell { + /// The swatch at this index of the palette's swatches. + Swatch(usize), + /// The color at this index of the recent row's colors. + Recent(usize), } impl Outcome for SwatchPaletteOutput { @@ -112,8 +124,8 @@ impl PaletteColor<'_> { /// What the body picked in its pass. #[derive(Clone, Copy)] enum Pick { - /// A swatch or a recent colour. - Color { color: Srgba, swatch: Option }, + /// A swatch or a recent color, and its cell. + Color(Srgba, PaletteCell), /// The Other… cell. Other, } @@ -235,7 +247,7 @@ impl<'a> SwatchPalette<'a> { // The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates // on its release, so only the activation files the request: one request for one click. pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) { - Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }), + Some((_, picked)) => Some(Pick::Color(*picked, PaletteCell::Swatch(at))), None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other), }); } @@ -249,8 +261,8 @@ impl<'a> SwatchPalette<'a> { .space(SpaceAction::ActivateLead) .selection(Bind::bound(&mut current)) .show_all(ui); - if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) { - pick = Some(Pick::Color { color: *picked, swatch: None }); + if let Some((at, (_, picked))) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at).map(|cell| (at, cell))) { + pick = Some(Pick::Color(*picked, PaletteCell::Recent(at))); } } Some((before, pick)) @@ -265,19 +277,23 @@ impl<'a> SwatchPalette<'a> { let key = other.as_ref().map(|(key, _)| key.clone())?; Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None)) } - Pick::Color { color: after, swatch } => { + Pick::Color(after, cell) => { let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba()); let edit = (!unchanged).then(|| { color.write(cx, before, after, name.as_str()); let reported = bound.map_or(Mixed::Mixed, Mixed::Same); EditEvent::set(reported, after, Arc::from(name.as_str()), None) }); - Some((Some(after), edit, None, swatch)) + Some((Some(after), edit, None, Some(cell))) } } }) .flatten(); - let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None)); - SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch } + let (picked, edit, pick_color, cell) = settled.unwrap_or((None, None, None, None)); + let picked_swatch = match cell { + Some(PaletteCell::Swatch(at)) => Some(at), + _ => None, + }; + SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch, cell } } } diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 1363d82c47..d2548b1045 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -245,7 +245,8 @@ pub struct ColorPanelState { pub hide_options: bool, /// The FillStroke layout shows the Recent Colors slot. pub recent_colors: bool, - /// The R, G and B rows count percents, 0 to 100, in place of 0 to 255. + /// The R, G and B rows count percents, 0 to 100, in place of 0 to 255; Web Color's rows keep 0 to 255. A double + /// click on a units cell ([`ColorPanel::rgb_units_cell`]) switches it. pub rgb_percent: bool, } @@ -446,12 +447,14 @@ pub struct ColorPanel<'a> { cmyk: Option<&'a CmykConverter>, rgb: Option<&'a dyn ColorModel>, dynamic: bool, + rgb_units: bool, layout: ColorPanelLayout, wells: Option<([PairWell; 2], Bind<'a, Well>)>, buttons: Option<[Label; 2]>, edited: Option>, shown: Option, recent: Option<&'a [Srgba]>, + recent_models: &'a [Option], recent_setup: Option, gamut: Option>, } @@ -476,6 +479,7 @@ struct Inputs<'a> { edited: Option<&'a Option>, shown: &'a ColorPanelShown, recent: Option<&'a [Srgba]>, + recent_models: &'a [Option], recent_setup: Option<&'a RecentSetup>, } @@ -488,12 +492,14 @@ impl<'a> ColorPanel<'a> { cmyk: None, rgb: None, dynamic: true, + rgb_units: false, layout: ColorPanelLayout::default(), wells: None, buttons: None, edited: None, shown: None, recent: None, + recent_models: &[], recent_setup: None, gamut: None, } @@ -520,6 +526,14 @@ impl<'a> ColorPanel<'a> { self } + /// A units cell right of each R, G and B field (not Web Color's): a double click on it switches + /// [`ColorPanelState::rgb_percent`]. The cell has no keyboard stop, so a host that turns it on offers the same + /// switch as a command that writes `rgb_percent`. Off by default. + pub fn rgb_units_cell(mut self, on: bool) -> Self { + self.rgb_units = on; + self + } + /// How the panel arranges its body; the Photoshop foreground and background arrangement by default. pub fn layout(mut self, layout: ColorPanelLayout) -> Self { self.layout = layout; @@ -563,6 +577,15 @@ impl<'a> ColorPanel<'a> { self } + /// The model values of each Recent Colors chip, in the order of [`recent`](Self::recent). A pick on a chip that has + /// them reports them with its color (`PickedColor::in_model`), so a CMYK recent color stays CMYK, and a chip + /// that shows the edited color's sRGB in another model still sets it. A chip with `None`, or past the end of + /// `models`, works as without this call: a pick sets its sRGB, and a pick of the color already shown sets nothing. + pub fn recent_models(mut self, models: &'a [Option]) -> Self { + self.recent_models = models; + self + } + /// The payload a Recent Colors chip drags. pub fn recent_payload(mut self, map: impl Fn(usize) -> Option

+ Send + Sync + 'static) -> Self { self.recent_setup = Some(recent_setup(map)); @@ -577,7 +600,23 @@ impl<'a> ColorPanel<'a> { /// Shows the panel and returns this pass's edits and requests. pub fn show(self, ui: &mut Ui) -> ColorPanelOutput { - let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self; + let ColorPanel { + state, + colors, + cmyk, + rgb, + dynamic, + rgb_units, + layout, + wells, + buttons, + edited, + shown: rows, + recent, + recent_models, + recent_setup, + gamut, + } = self; let env = Env::of(ui); let (words, dialog) = (env.words::(), env.words::()); let mut held = Held::new(state); @@ -609,6 +648,7 @@ impl<'a> ColorPanel<'a> { rgb, gamut: &gamut, dynamic, + rgb_units, words: &words, dialog: &dialog, inputs: Inputs { @@ -617,6 +657,7 @@ impl<'a> ColorPanel<'a> { edited: edited.as_ref(), shown: rows.as_ref().unwrap_or(&default_rows), recent, + recent_models, recent_setup: recent_setup.as_ref(), }, now: before, @@ -908,6 +949,8 @@ struct Body<'a> { rgb: &'a dyn ColorModel, gamut: &'a Gamut<'a>, dynamic: bool, + /// The R, G and B rows have units cells ([`ColorPanel::rgb_units_cell`]). + rgb_units: bool, words: &'a ColorPanelWords, dialog: &'a ColorPickerDialogWords, /// The state as this pass leaves it. @@ -1159,15 +1202,18 @@ impl Body<'_> { self.kept.tracks.retain(|(id, target, _)| (*id, *target) != slot); self.kept.tracks.push((slot.0, slot.1, current)); } + // The R, G and B rows are not Web Color's. The units are read once, so a double click on one units cell + // switches all three rows together, from the next pass. + let rgb = !web && model.id() == self.rgb.id(); + let rgb_percent = self.now.rgb_percent; for (i, ch) in model.channels().iter().enumerate() { let mut rule = ChannelRule::of(ch); if web { rule.step = WEB_STEP; } - // The R, G and B rows count percents of the channel's range; an edit goes back through `scale`. - // PLAN: a double click on the units cell flips `rgb_percent` while the rows are enabled; `ChannelRow` - // (color-w2) reports no signal for its units cell, so the panel cannot read it. - let percent = self.now.rgb_percent && model.id() == self.rgb.id(); + // With `rgb_percent` the R, G and B rows count percents of the channel's range; an edit goes back through + // `scale`. + let percent = rgb && rgb_percent; let scale = if percent { 100.0 / *rule.range.end() } else { 1.0 }; let unit = if percent { ChannelUnit::Percent } else { ChannelUnit::of(ch.unit) }; if percent { @@ -1183,8 +1229,17 @@ impl Body<'_> { // The field shows the channel's places, as Photoshop's; the edits start from the unrounded values. let places = 10f64.powi(i32::from(rule.decimals)); let shown = (f64::from(current.values[i]) * scale * places).round() / places; - let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track).show(ui); - for event in row.into_iter().flat_map(|row| row.events) { + let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track); + let edit = if rgb && self.rgb_units { + let row = row.show_with_units(ui); + if row.units_double_clicked { + self.now.rgb_percent = !rgb_percent; + } + row.edit + } else { + row.show(ui) + }; + for event in edit.into_iter().flat_map(|row| row.events) { self.channel_event(model, current, i, event.map(|x| x / scale)); } } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index 183844b574..1e6dd88dd9 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -3,7 +3,7 @@ //! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers. use craft_behavior::{EditEvent, Mixed}; -use craft_theme::Srgba; +use craft_theme::{ModelValues, Srgba}; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::{Shade, Text}; @@ -15,7 +15,7 @@ use craft_ui::text::{HexField, TextField}; use egui::Ui; use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow}; -use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette}; +use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PaletteCell, PickedColor, RampKind, SwatchPalette}; impl Body<'_> { /// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the @@ -156,8 +156,8 @@ impl Body<'_> { } } - /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list - /// is empty, where the first applied color will go. + /// The Recent Colors caption over a spaced palette; a pick sets the color, in the chip's model when the host gave it. + /// The caption shows while the host's list is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { @@ -174,13 +174,34 @@ impl Body<'_> { if let Some(setup) = self.inputs.recent_setup { palette = setup(palette); } - if let Some(event) = palette.show(ui).edit + let out = palette.show(ui); + let values = match out.cell { + Some(PaletteCell::Swatch(at)) => self.inputs.recent_models.get(at).copied().flatten(), + _ => None, + }; + if let (Some(color), Some(values)) = (out.picked, values) { + self.set_in_model(color, values); + } else if let Some(event) = out.edit && let Some(color) = event.value() { self.set_color(self.target, *color); } } + /// Sets the edited color to `color` in the model of `values`, keeping its alpha. It sets nothing when the host's + /// color already has those values and shows that color. + fn set_in_model(&mut self, color: Srgba, values: ModelValues) { + let before = self.picked().copied().unwrap_or_else(|| PickedColor::rgb(self.colors[self.target.index()])); + let after = PickedColor::in_model(color.with_alpha(before.color.a), values); + if before.model == after.model && before.color.to_rgba() == after.color.to_rgba() { + return; + } + // The rows' kept values in the chip's model would win over a host that keeps only sRGB (a grey's HSB hue). + self.kept.values[self.target.index()].retain(|v| v.model != values.model); + let name = self.words.title.as_str(); + self.push(self.target, EditEvent::set(Mixed::Same(before), after, name.into(), None)); + } + /// Sets `target`'s colour to `color`, keeping its alpha. fn set_color(&mut self, target: PanelTarget, color: Srgba) { let before = self.colors[target.index()]; diff --git a/crates/color-ui/src/ui/picker/channel.rs b/crates/color-ui/src/ui/picker/channel.rs index 34807fb607..ccd97daa06 100644 --- a/crates/color-ui/src/ui/picker/channel.rs +++ b/crates/color-ui/src/ui/picker/channel.rs @@ -3,14 +3,18 @@ use std::ops::RangeInclusive; -use craft_behavior::{Axis, Sense}; +use craft_behavior::press::MULTI_CLICK_TIME; +use craft_behavior::{Axis, Metrics, PartKey, PressPhase, Sense}; use craft_theme::{Channel, ColorModel, Srgba}; use craft_ui::contract::{ - Bind, Common, Component, Cx, DisabledLook, EditResponse, GlyphLabel, LabelKind, MeasureCx, Role, Show as _, ShowContainer as _, SideLabel, Sizing, + Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, GlyphLabel, LabelKind, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Role, + Show as _, ShowContainer as _, SideLabel, Sizing, }; use craft_ui::form::{Field, SliderField, SliderFieldLayout}; +use craft_ui::layout_components::Row; use craft_ui::primitives::{PaintShape, StrokeWidth}; use craft_ui::runtime::env::{Label, UnitKind}; +use craft_ui::runtime::pointer; use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx}; use craft_ui::value_drag::{SliderThumb, TrackFace}; use egui::{Color32, CornerRadius, Ui, Vec2}; @@ -183,6 +187,15 @@ pub struct ChannelRow<'a> { marks: &'a [f64], } +/// What [`ChannelRow::show_with_units`] reports. +#[non_exhaustive] +pub struct ChannelRowOutput { + /// The edit of the slider or the field, `None` when the row did not run. + pub edit: Option>, + /// The units cell was double-clicked in this pass: the host switches the units the row counts in. + pub units_double_clicked: bool, +} + impl<'a> ChannelRow<'a> { /// A row named `label` over `value`, ruled by `rule`. pub fn new(label: impl Into

(place, move |payload: &P, at: &DropAt| accepts(payload, at)) })); @@ -270,8 +270,8 @@ impl<'a> SwatchesPanel<'a> { search, row_icons, select, + drops, report_invalid_renames, - takes_drop, payloads, row_items, document, @@ -331,7 +331,7 @@ impl<'a> SwatchesPanel<'a> { if let Some(items) = &row_items { browser = browser.row_menu(PresetRowMenu::Host).row_items(|key: &SwatchKey| items(key)); } - if let Some(make) = &takes_drop { + for make in &drops { browser = browser.takes_drop(make()); } for add in &payloads { diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 6efa4a64a3..5982f8222f 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -8,11 +8,11 @@ use craft_behavior::{EditEvent, Mixed, Selection}; use craft_color_ui::palette::{SwatchColor, SwatchGroup}; use craft_color_ui::ui::{ ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel, - PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, - SwatchesWords, swatch_rows, + PaletteCell, PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, + SwatchesState, SwatchesWords, swatch_rows, }; use craft_host::target::Os; -use craft_theme::{ColorModel as _, HsbModel, Srgba}; +use craft_theme::{ColorModel as _, HsbModel, ModelValues, Srgba}; use craft_ui::buttons::Button; use craft_ui::choice::SwatchTable; use craft_ui::contract::Role; @@ -38,6 +38,7 @@ type Edits = Rc)>>>; /// The Color panel on a state and two colours the test can change, collecting what it reports. struct PanelRig { fixture: Fixture, + state: Rc>, colors: Rc>, edits: Edits, } @@ -48,15 +49,19 @@ impl PanelRig { } fn in_room(mode: ColorPanelMode, room: Vec2) -> Self { - let start = ColorPanelState { mode, ..Default::default() }; + Self::with_state(ColorPanelState { mode, ..Default::default() }, room, true) + } + + /// The panel from `start`, with the RGB units cells where `units` is set. + fn with_state(start: ColorPanelState, room: Vec2, units: bool) -> Self { let state = Rc::new(RefCell::new(start)); let colors = Rc::new(Cell::new([RED, BLUE])); type Shared = (Edits, Rc>>, Rc>>); let (edits, opened, added): Shared = Default::default(); - let (s, c, e, o, a) = (state, colors.clone(), edits.clone(), opened, added); + let (s, c, e, o, a) = (state.clone(), colors.clone(), edits.clone(), opened, added); let mut fixture = Fixture::new(move |ui| { let mut current = *s.borrow(); - let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).show(ui); + let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).rgb_units_cell(units).show(ui); *s.borrow_mut() = current; e.borrow_mut().extend(shown.edits); o.borrow_mut().extend(shown.pick_color); @@ -64,7 +69,7 @@ impl PanelRig { }); fixture.room(room); fixture.settle(); - PanelRig { fixture, colors, edits } + PanelRig { fixture, state, colors, edits } } fn set_colors(&mut self, colors: [Srgba; 2]) { @@ -197,6 +202,145 @@ fn a_channel_step_keeps_the_other_channels_unrounded() { } } +/// A point in the units cell right of `field`, on its line. +fn right_of(field: &craft_ui::testing::Target) -> egui::Pos2 { + egui::pos2(field.rect.right() + 6.0, field.rect.center().y) +} + +/// The number fields' values, top to bottom, and the end of the first one's range. +fn field_values(fixture: &Fixture) -> (Vec, f64) { + let tree = fixture.tree(); + let fields = fixture.by_role(Role::SPIN_BUTTON); + let numbers: Vec<_> = fields.iter().map(|field| tree.numeric_of(field.node).expect("a field's value and range")).collect(); + let values = numbers.iter().map(|number| number.value.expect("a field's value")).collect(); + (values, *numbers[0].range.end()) +} + +/// A double click right of the R, G or B field switches all three rows between 0 to 255 and percent, and the next one +/// switches them back. The colour does not change. +#[trial] +fn a_double_click_right_of_an_rgb_field_switches_the_rgb_units() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + rig.set_colors([Srgba::rgb(1.0, 0.5, 0.0), BLUE]); + let (bytes, end) = field_values(&rig.fixture); + assert!(!rig.state.borrow().rgb_percent && end > 100.0, "the rows start at 0 to 255 ({bytes:?}, to {end})"); + + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[0]); + rig.fixture.click_at(at).click_at(at).settle(); + assert!(rig.state.borrow().rgb_percent, "a double click right of R switches to percent"); + let (percents, end) = field_values(&rig.fixture); + assert_eq!(end, 100.0, "the fields count to 100 %"); + for (percent, byte) in percents.iter().zip(&bytes) { + assert!((percent - byte / 2.55).abs() < 0.51, "every row shows its percent ({percents:?}, {bytes:?})"); + } + + rig.fixture.advance(1.0); + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[2]); + rig.fixture.click_at(at).click_at(at).settle(); + assert!(!rig.state.borrow().rgb_percent, "a double click right of B switches back"); + assert_eq!(field_values(&rig.fixture).0, bytes, "the rows count 0 to 255 again"); + assert!(rig.edits.borrow().is_empty(), "switching the units changes no colour: {:?}", rig.edits.borrow()); +} + +/// A single click right of an RGB field, and a double click on the field itself, leave the units as they are. +#[trial] +fn only_a_double_click_on_the_units_cell_switches_the_rgb_units() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + rig.fixture.click_at(right_of(&fields[1])).settle(); + assert!(!rig.state.borrow().rgb_percent, "a single click right of G switches nothing"); + rig.fixture.advance(1.0); + let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(1); + rig.fixture.click(&field).click(&field).settle(); + assert!(!rig.state.borrow().rgb_percent, "a double click on the G field switches nothing"); +} + +/// A click at the right edge of an RGB field followed at once by a click on the units cell beside it is not a double +/// click on the cell, though the two presses are close enough to count as one, nor are two clicks on the cell with a +/// click on the field between them. +#[trial] +fn a_click_on_the_field_then_one_on_the_units_cell_switches_nothing() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0); + let (edge, cell) = (egui::pos2(field.rect.right() - 0.4, field.rect.center().y), egui::pos2(field.rect.right() + 2.4, field.rect.center().y)); + rig.fixture.click_at(cell).click_at(cell).settle(); + assert!(rig.state.borrow().rgb_percent, "a double click at {cell:?} is on the units cell"); + rig.fixture.advance(1.0); + rig.fixture.click_at(edge).click_at(cell).settle(); + assert!(rig.state.borrow().rgb_percent, "a click on the field's edge and one on the cell switch nothing"); + rig.fixture.advance(1.0); + rig.fixture.click_at(cell).click_at(edge).click_at(cell).settle(); + assert!(rig.state.borrow().rgb_percent, "two clicks on the cell with one on the field between them switch nothing"); +} + +/// Two clicks on the units cell with a click on the field between them switch nothing when the field click is too far +/// from the first to continue its click run, and the second cell click is close enough to the field click to count as +/// its second click. +#[trial] +fn a_field_click_that_starts_a_new_run_between_two_units_cell_clicks_switches_nothing() { + let mut rig = PanelRig::new(ColorPanelMode::RgbSliders); + let field = rig.fixture.by_role(Role::SPIN_BUTTON).remove(0); + let (top, bottom) = (field.rect.top() + 1.0, field.rect.bottom() - 1.0); + let (first, edge, second) = + (egui::pos2(field.rect.right() + 2.4, top), egui::pos2(field.rect.right() - 0.4, bottom), egui::pos2(field.rect.right() + 2.4, bottom)); + rig.fixture.click_at(second).click_at(second).settle(); + assert!(rig.state.borrow().rgb_percent, "a double click at {second:?} is on the units cell"); + rig.fixture.advance(1.0); + rig.fixture.click_at(first).click_at(edge).click_at(second).settle(); + assert!(rig.state.borrow().rgb_percent, "a field click that starts a new run between two cell clicks switches nothing"); +} + +/// Rows of other modes have no units cell, nor do the RGB rows of a panel whose host did not ask for them, and Web +/// Color keeps 0 to 255 while the RGB rows show percent. +#[trial] +fn rows_other_than_rgb_keep_their_units() { + let rgb = ColorPanelState { mode: ColorPanelMode::RgbSliders, ..Default::default() }; + let mut rigs = vec![("RGB without units cells".to_owned(), PanelRig::with_state(rgb, COLOR_ROOM, false))]; + for mode in [ColorPanelMode::CmykSliders, ColorPanelMode::HsbSliders, ColorPanelMode::WebColorSliders] { + rigs.push((format!("{mode:?}"), PanelRig::new(mode))); + } + for (case, mut rig) in rigs { + let fields = rig.fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[0]); + rig.fixture.click_at(at).click_at(at).settle(); + assert!(!rig.state.borrow().rgb_percent, "{case}: a double click right of a field switches nothing"); + } + let start = ColorPanelState { mode: ColorPanelMode::WebColorSliders, rgb_percent: true, ..Default::default() }; + let rig = PanelRig::with_state(start, COLOR_ROOM, true); + let (_, end) = field_values(&rig.fixture); + assert!(end > 100.0, "Web Color counts 0 to 255 while the RGB rows show percent (to {end})"); +} + +/// The FillStroke layout's RGB rows switch their units the same way, and not while a mixed selection disables them. +#[trial] +fn a_disabled_fill_stroke_rgb_row_does_not_switch_its_units() { + let state = Rc::new(RefCell::new(ColorPanelState::default())); + let edited = Rc::new(Cell::new(Some(PickedColor::rgb(RED)))); + let (s, e) = (state.clone(), edited.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut current = *s.borrow(); + let _ = ColorPanel::new(Bind::bound(&mut current), [RED, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .shown(ColorPanelShown::Mode(ColorPanelMode::RgbSliders)) + .rgb_units_cell(true) + .edited(e.get()) + .show(ui); + *s.borrow_mut() = current; + }); + fixture.room(COLOR_ROOM).settle(); + let fields = fixture.by_role(Role::SPIN_BUTTON); + let at = right_of(&fields[0]); + fixture.click_at(at).click_at(at).settle(); + assert!(state.borrow().rgb_percent, "a double click right of R switches the FillStroke rows to percent"); + + edited.set(None); + fixture.settle().advance(1.0); + fixture.click_at(at).click_at(at).settle(); + assert!(state.borrow().rgb_percent, "with the rows disabled a double click switches nothing"); +} + /// A Color panel whose host supplies authoritative native CMYK components. fn native_cmyk_panel(picked: PickedColor) -> (Fixture, Rc>, Edits) { let host = Rc::new(RefCell::new(picked)); @@ -367,6 +511,88 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow()); } +/// A Recent Colors pick in the FillStroke layout reports the chip's model values with its color, also when the chip +/// shows the edited color's sRGB in another model or without one; a chip whose values the edited color already has +/// sets nothing. +#[trial] +fn a_fill_stroke_recent_pick_keeps_the_chips_model() { + let chip = RECENT[0]; + let cmyk = ModelValues::new("cmyk", &[60.0, 90.0, 0.0, 0.0]); + let pick = |edited: PickedColor| { + let edits: Edits = Default::default(); + let seen = Rc::clone(&edits); + let mut fixture = Fixture::new(move |ui| { + let mut state = ColorPanelState::default(); + let out = ColorPanel::new(Bind::bound(&mut state), [edited.color, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(edited)) + .recent(&RECENT) + .recent_models(&[Some(cmyk)]) + .show(ui); + seen.borrow_mut().extend(out.edits); + }); + fixture.room(COLOR_ROOM).settle(); + let recent = fixture.by_label(&chip.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + edits.take() + }; + let rgb_of = |color: Srgba| ModelValues::new("rgb", &[color.r * 255.0, color.g * 255.0, color.b * 255.0]); + for edited in [PickedColor::in_model(RED, rgb_of(RED)), PickedColor::in_model(chip, rgb_of(chip)), PickedColor::rgb(chip)] { + let edits = pick(edited); + assert!( + matches!(edits.as_slice(), [(PanelTarget::Foreground, EditEvent::Set { after, .. })] + if after.model == Some(cmyk) && after.color.to_rgba() == chip.to_rgba()), + "one Set to the chip in CMYK from {edited:?}: {edits:?}" + ); + } + let edits = pick(PickedColor::in_model(chip, cmyk)); + assert!(edits.is_empty(), "the chip's own values set nothing: {edits:?}"); +} + +/// A Recent Colors pick drops the HSB values the rows kept for a grey: after a host that keeps only sRGB applies a grey +/// chip with HSB values, the Hue row reads the grey afresh instead of the hue of the earlier row edits. +#[trial] +fn a_fill_stroke_recent_pick_drops_the_rows_kept_hue() { + let grey = Srgba::rgb(0.5, 0.5, 0.5); + let chip = [grey]; + let chip_hsb = ModelValues::new("hsb", &[0.0, 0.0, 50.0]); + let host = Rc::new(RefCell::new(grey)); + let color = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let current = *color.borrow(); + let mut state = ColorPanelState { mode: ColorPanelMode::HsbSliders, ..Default::default() }; + let shown = ColorPanel::new(Bind::bound(&mut state), [current, BLUE]) + .layout(ColorPanelLayout::FillStroke) + .edited(Some(PickedColor::rgb(current))) + .shown(ColorPanelShown::Mode(ColorPanelMode::HsbSliders)) + .recent(&chip) + .recent_models(&[Some(chip_hsb)]) + .show(ui); + for (_, event) in &shown.edits { + if let Some(picked) = event.landed() { + *color.borrow_mut() = picked.color; + } + } + }); + fixture.room(COLOR_ROOM).settle(); + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + for _ in 0..20 { + fixture.key(Key::ArrowRight, Modifiers::NONE).settle(); + } + let hue_value = |fixture: &mut Fixture| { + let hue = fixture.by_role(Role::SLIDER).into_iter().next().expect("the hue slider"); + fixture.access(AccessActionKind::Focus, &hue).settle(); + let id = fixture.focused().expect("the hue slider takes the focus"); + fixture.tree().value(id).expect("the hue slider reports its value").to_owned() + }; + let stepped = hue_value(&mut fixture); + assert_ne!(stepped, "0", "the steps moved the kept hue of the grey"); + let recent = fixture.by_label(&grey.to_hex()).expect("the recent chip is named by its hex"); + fixture.click(&recent).settle(); + assert_eq!(hue_value(&mut fixture), "0", "the pick drops the kept hue {stepped}"); +} + /// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked, /// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls. #[trial] @@ -471,6 +697,7 @@ struct PaletteReports { edits: Vec>, requests: Vec, picked: Vec, + cells: Vec, swatches: Vec, } @@ -482,6 +709,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) { reports.edits.extend(shown.edit); reports.requests.extend(shown.pick_color); reports.picked.extend(shown.picked); + reports.cells.extend(shown.cell); reports.swatches.extend(shown.picked_swatch); } @@ -539,11 +767,13 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() { taken.edits[0] ); assert_eq!(bound.get().to_rgba(), RECENT[0].to_rgba(), "the recent pick is written"); + assert_eq!(taken.cells, [PaletteCell::Recent(0)], "the pick names its cell in the recent row"); let violet = fixture.by_label("Violet").expect("violet"); fixture.click(&violet).settle(); - let _ = std::mem::take(&mut *reports.borrow_mut()); + let taken = std::mem::take(&mut *reports.borrow_mut()); assert_eq!(bound.get().to_rgba(), swatch("Violet").to_rgba()); + assert_eq!(taken.cells, [PaletteCell::Swatch(5)], "the pick names its swatch"); // Past the double-click time, so the repeat is a single click of its own. fixture.advance(1.0); let violet = fixture.by_label("Violet").expect("violet"); @@ -908,6 +1138,56 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() { assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow()); } +#[trial] +fn swatches_keep_both_host_drop_places() { + use craft_color_ui::palette::SwatchEntry; + use craft_ui::contract::{DropAt, DropPlace, ListDrag, ShowCollection as _}; + use craft_ui::list::{List, ListRow}; + use craft_ui::patterns::presets::{PresetEvent, PresetView}; + use egui::{Pos2, Rect, UiBuilder}; + + #[derive(Clone)] + struct Art; + + const SWATCHES: Rect = Rect { min: Pos2::ZERO, max: Pos2::new(300.0, 300.0) }; + const LAYERS: Rect = Rect { min: Pos2::new(320.0, 0.0), max: Pos2::new(460.0, 120.0) }; + let groups = vec![SwatchGroup { + name: String::new(), + entries: vec![SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), SwatchEntry::new("Blue", SwatchColor::Rgb([0.0, 0.0, 1.0]))], + }]; + let received = Rc::new(RefCell::new(Vec::new())); + let seen = Rc::clone(&received); + let mut state = SwatchesState::default(); + state.browser.view = PresetView::List; + let mut fixture = Fixture::new(move |ui| { + ui.scope_builder(UiBuilder::new().max_rect(LAYERS), |ui| { + let ids = [7_u32]; + let source = craft_behavior::keyed(&ids, |id: &u32| *id); + List::::new("Layers").drag_payload(|_: &ListDrag| Some(Art)).show_items(ui, &source, &mut |_, _| ListRow::new("Art")); + }); + ui.scope_builder(UiBuilder::new().max_rect(SWATCHES), |ui| { + let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED) + .takes_drop::(DropPlace::Between, |_, _| true) + .takes_drop::(DropPlace::Onto, |_, _| true) + .show(ui); + seen.borrow_mut().extend( + out.events + .into_iter() + .filter_map(|event| if let PresetEvent::Dropped { at, payload, .. } = event { payload.get::().map(|_| at) } else { None }), + ); + }); + }); + fixture.room(Vec2::new(480.0, 320.0)).settle(); + let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch").rect; + let gap = Pos2::new(blue.center().x, blue.min.y + 2.0); + for to in [gap, blue.center()] { + let from = fixture.by_label("Art").expect("the layer row").center(); + fixture.drag_at(from, to - from).settle(); + } + let blue = SwatchKey::Swatch("Blue".into()); + assert_eq!(*received.borrow(), [DropAt::gap(Some(blue.clone()), 1), DropAt::Onto(blue)]); +} + /// A panel shown for one document after another keeps a rename left open with its document: the other document's /// swatch of the same name opens no field, and Enter there renames nothing. #[trial] diff --git a/crates/color-ui/tests/it/picker.rs b/crates/color-ui/tests/it/picker.rs index 7a00b133e8..d6dc9368a8 100644 --- a/crates/color-ui/tests/it/picker.rs +++ b/crates/color-ui/tests/it/picker.rs @@ -5,12 +5,12 @@ use std::rc::Rc; use craft_behavior::Mixed; use craft_color_ui::ui::{ - ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, ColorPopover, ColorReadout, ColorWarning, - PickedColor, PickerLibrary, PickerSwatches, + ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab, + ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches, }; use craft_host::{AppInfo, Host}; use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId}; -use craft_ui::contract::{Bind, Role, ShowContainer as _}; +use craft_ui::contract::{Bind, EditResponse, Role, ShowContainer as _}; use craft_ui::dialog::{DialogHost, DialogResult, StackDialog, dialog_id}; use craft_ui::layout::RowAlign; use craft_ui::layout_components::Row; @@ -177,6 +177,45 @@ fn the_dialogs_rgb_fields_show_the_hosts_working_values() { } } +/// `ChannelRow::show` returns the row's edit, and `show_with_units` returns the same edit with the units cell's +/// double click, which typing into the field does not report. +#[trial] +fn a_channel_rows_show_returns_its_edit_and_show_with_units_adds_the_units_cell() { + let rule = ChannelRule { range: 0.0..=100.0, step: 1.0, decimals: 0 }; + /// Each edit: the row, the value and whether the units cell was double-clicked. + type Seen = Rc>>; + let got: Seen = Rc::default(); + let seen = Rc::clone(&got); + let mut fixture = Fixture::new(move |ui| { + let edit: Option> = ChannelRow::new("Plain", Bind::given(40.0), rule.clone()).show(ui); + for event in edit.into_iter().flat_map(|edit| edit.events) { + if let Some(v) = event.value() { + seen.borrow_mut().push(("Plain", *v, false)); + } + } + let row: ChannelRowOutput = ChannelRow::new("Units", Bind::given(40.0), rule.clone()).show_with_units(ui); + for event in row.edit.into_iter().flat_map(|edit| edit.events) { + if let Some(v) = event.value() { + seen.borrow_mut().push(("Units", *v, row.units_double_clicked)); + } + } + }); + fixture.room(vec2(320.0, 200.0)); + fixture.idle(2); + for (i, text) in [(0, "70"), (1, "20")] { + let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().nth(i).unwrap_or_else(|| panic!("number field {i}")); + fixture.click(&field); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.type_text(text); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + } + let got = got.borrow(); + assert!(got.iter().any(|&(row, v, _)| row == "Plain" && v == 70.0), "show reports the typed value: {got:?}"); + assert!(got.iter().any(|&(row, v, _)| row == "Units" && v == 20.0), "show_with_units reports the typed value: {got:?}"); + assert!(got.iter().all(|&(_, _, clicked)| !clicked), "typing is not a double click on the units cell: {got:?}"); +} + /// The densities and themes every layout trial runs in: compact and comfortable, a Pro and a Studio theme. const LOOKS: [(Size, &str); 4] = [(Size::Compact, "craft.pro"), (Size::Comfortable, "craft.pro"), (Size::Compact, "craft.studio"), (Size::Comfortable, "craft.studio")]; @@ -558,6 +597,15 @@ fn the_tabbed_colors_dialog_opens_on_its_tab_and_answers_from_either_page() { fixture.click(&cell); fixture.idle(4); assert_eq!(dialog_color(&dialogs).as_deref(), Some("#0000ff"), "a honeycomb pick is the colour"); + // #7984: the Standard page shows the compare block too, and its current half restores the opening colour. + assert!(fixture.by_label("New color").is_some(), "the Standard page shows the compare block"); + let restore = fixture.by_label("Restore current color").expect("the compare block's current half"); + fixture.click(&restore); + fixture.idle(4); + assert_eq!(dialog_color(&dialogs).as_deref(), Some("#123456"), "the current half restores the opening colour"); + let cell = fixture.by_label("Standard 2").expect("the honeycomb shows its cells"); + fixture.click(&cell); + fixture.idle(4); assert!(dialogs.borrow_mut().confirm::(&ctx), "OK answers"); let answered = dialogs.borrow_mut().take::().and_then(DialogResult::ok).map(|result| result.picked.color.to_hex()); diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 88c9f4523e..e989add35f 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -114,6 +114,7 @@ craft-material-graph = { workspace = true, optional = true } craft-materialx = { workspace = true, optional = true } craft-math = { workspace = true, optional = true } craft-mesh = { workspace = true, optional = true } +craft-mesh-ops = { workspace = true, optional = true } craft-metadata = { workspace = true, optional = true } craft-metafile = { workspace = true, optional = true } craft-midi = { workspace = true, optional = true } @@ -675,6 +676,8 @@ mesh-ply = ["mesh", "craft-mesh/ply"] mesh-stl = ["mesh", "craft-mesh/stl"] mesh-threemf = ["mesh", "craft-mesh/threemf"] +mesh-ops = ["dep:craft-mesh-ops"] + metadata = ["dep:craft-metadata"] metafile = ["dep:craft-metafile"] @@ -706,6 +709,8 @@ pages = ["dep:craft-pages", "keymap", "text"] palette = ["dep:craft-palette"] pbr = ["dep:craft-pbr"] +pbr-materialx = ["pbr", "craft-pbr/materialx"] +pbr-mesh = ["pbr", "craft-pbr/mesh"] pbr-parallel = ["pbr", "craft-pbr/parallel"] pcap = ["dep:craft-pcap"] @@ -945,7 +950,12 @@ text-ukrainian = ["text", "craft-text/ukrainian"] texture = ["dep:craft-texture"] texture-dds = ["texture", "craft-texture/dds"] +texture-decode = ["texture", "craft-texture/decode"] +texture-exr = ["texture", "craft-texture/exr"] +texture-hdr = ["texture", "craft-texture/hdr"] texture-parallel = ["texture", "craft-texture/parallel"] +texture-png = ["texture", "craft-texture/png"] +texture-tiff = ["texture", "craft-texture/tiff"] tga = ["dep:craft-tga"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 8290887540..60863cda9a 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -251,6 +251,8 @@ pub use craft_media_source as media_source; pub use craft_menu as menu; #[cfg(feature = "mesh")] pub use craft_mesh as mesh; +#[cfg(feature = "mesh-ops")] +pub use craft_mesh_ops as mesh_ops; #[cfg(feature = "metadata")] pub use craft_metadata as metadata; #[cfg(feature = "metafile")] diff --git a/crates/draw/src/ui/corner/style.rs b/crates/draw/src/ui/corner/style.rs index 1517afb33d..1401ec4ed1 100644 --- a/crates/draw/src/ui/corner/style.rs +++ b/crates/draw/src/ui/corner/style.rs @@ -19,7 +19,7 @@ pub struct CornerStyle { pub(super) dot: f32, /// The pointer's reach. pub(super) reach: f32, - /// The least distance inside a corner. + /// The least distance inside a corner: [`CornerWidgets::INSET`](super::CornerWidgets::INSET). pub(super) inset: f32, /// The shortest side, on the screen, whose corners show widgets. pub(super) min_side: f32, @@ -38,7 +38,7 @@ impl CornerStyle { widget: tokens.size.handle.md, dot: tokens.size.handle.sm, reach: tokens.size.hit.target, - inset: tokens.space.gap.stack, + inset: super::CornerWidgets::INSET, min_side: MIN_SIDE, fill: cx.color(tokens.color.overlay.handle_fill), color: cx.color(tokens.color.overlay.line), diff --git a/crates/draw/src/ui/corner/widgets.rs b/crates/draw/src/ui/corner/widgets.rs index b2ebaff95f..d2a4ce6f6b 100644 --- a/crates/draw/src/ui/corner/widgets.rs +++ b/crates/draw/src/ui/corner/widgets.rs @@ -101,6 +101,10 @@ impl<'a> CornerWidgets<'a> { /// The widest inner angle, in degrees, a widget shows at unless [`hide_above`](Self::hide_above) says otherwise. pub const HIDE_ABOVE: f64 = 180.0; + + /// The least distance, in screen points along each side of a right angle, a widget sits inside its corner, at every + /// density. A host that hit-tests the widgets itself reads it from here. + pub const INSET: f32 = 10.0; } /// What the widgets report: the edit of the targets and what the widgets ask the host to do. diff --git a/crates/draw/tests/it/corner.rs b/crates/draw/tests/it/corner.rs index 966d6b0650..37654cf4f0 100644 --- a/crates/draw/tests/it/corner.rs +++ b/crates/draw/tests/it/corner.rs @@ -118,3 +118,30 @@ fn a_triangle_apex_rounds_with_the_pointer_travel() { assert!(small > START_RADIUS, "a short pull rounds the apex: {small}"); assert!(large > small, "a longer pull rounds it more: {small} then {large}"); } + +/// A slightly rounded right-angle corner's widget sits `CornerWidgets::INSET` points inside the corner along each side, +/// at every density, so a host that hit-tests the widgets with that constant presses where the widget is drawn. +#[trial] +fn a_widget_sits_the_published_inset_inside_its_corner_at_every_density() { + for density in [craft_theme::Size::Compact, craft_theme::Size::Comfortable] { + let vertex = Rc::new(Cell::new(egui::Pos2::ZERO)); + let seen = Rc::clone(&vertex); + let mut targets = vec![square()]; + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(210.0, 200.0), 1.0); + seen.set(view.to_screen(targets[0].corners[0].vertex)); + Canvas::new("Document") + .view(view) + .show(ui, |ui, body| CornerWidgets::new("Corner radius", Bind::bound(&mut targets)).show_at(ui, body.rect)); + }); + fixture.density(density).settle(); + let widget = fixture.by_label("Corner 1 of 4").expect("the first corner has a widget"); + let offset = widget.center() - vertex.get(); + let inset = CornerWidgets::INSET; + assert!( + (offset.x - inset).abs() < 0.5 && (offset.y - inset).abs() < 0.5, + "{density:?}: the widget sits {offset:?} from its corner, not {inset} along each side" + ); + } +} diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index 359679cdd8..b3332f7f77 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -1757,7 +1757,8 @@ fn deflate_rows( /// and completes the flush: when a sync flush fills the buffer, miniz_oxide (flate2's former Rust /// backend) can return before compressing the last lookahead bytes, and the next call only /// drains the pending output, so a resumed flush silently drops data. `None` (the caller then -/// uses the serial encoder) if the single call did not finish. +/// uses the serial encoder) if the single call did not finish. The returned bytes keep no +/// spare capacity, because the caller holds every band until it joins them into one stream. fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option> { let mut c = flate2::Compress::new(lvl, false); // Stored blocks cost 5 bytes per 64 KiB, the flush an empty stored block: 1/8 is ample. @@ -1766,7 +1767,10 @@ fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option let flush = if last { flate2::FlushCompress::Finish } else { flate2::FlushCompress::Sync }; let status = c.compress_vec(filtered, &mut z, flush).ok()?; let done = if last { status == flate2::Status::StreamEnd } else { c.total_in() as usize == filtered.len() && z.len() < z.capacity() }; - done.then_some(z) + done.then(|| { + z.shrink_to_fit(); + z + }) } /// One scanline with the adaptive filter choice, appended to `out` (type byte + data). @@ -2256,6 +2260,19 @@ mod parallel_tests { } } + /// Every band is held until the stream is joined, so a band keeps only the bytes it holds, + /// not the worst-case buffer it was deflated into (about 1.125 times the image in all). + #[test] + fn deflated_bands_keep_no_spare_capacity() { + let (w, h, bpp) = (1024usize, 600usize, 3usize); + let px: Vec = (0..w * h * bpp).map(|i| (i % 7) as u8).collect(); + let parts = deflate_rows(&px, None, w * bpp, bpp, band_rows(w * bpp), flate2::Compression::default(), true, 2).unwrap(); + assert!(parts.len() > 2); + for (i, p) in parts.iter().enumerate() { + assert!(p.z.capacity() <= p.z.len() + 64, "band {i}: capacity {} for {} bytes of {}", p.z.capacity(), p.z.len(), p.len); + } + } + /// The bytes depend on the image, not on the machine: one, two and 32 worker threads /// (and the machine's own count, through `encode`) give the same stream. #[test] diff --git a/crates/image-codecs/src/codecs/tiff/decode.rs b/crates/image-codecs/src/codecs/tiff/decode.rs index c365d01581..dcccadde66 100644 --- a/crates/image-codecs/src/codecs/tiff/decode.rs +++ b/crates/image-codecs/src/codecs/tiff/decode.rs @@ -747,8 +747,8 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result Vec { self.find(command).map(|i| self.current[i].iter().filter(|b| self.counts(b)).map(|b| self.public(i, b)).collect()).unwrap_or_default() } @@ -455,7 +457,8 @@ impl Keymap { } } - /// The command `chord` (pressed twice when `double`) runs with `active` focus. + /// The command `chord` (pressed twice when `double`) runs with `active` focus. A command the app runs itself + /// ([`Dispatch::App`]) is none of them: its chords belong to the app's own key handling. pub fn lookup(&self, chord: &Chord, double: bool, active: &Active) -> Lookup { self.lookup_nested(chord, double, active, &[]) } @@ -522,6 +525,9 @@ impl Keymap { /// applies (an application binding with no panel focused, a panel binding with its panel focused, a context /// binding with its context active), gives the command or a cycle that holds it. `None` when every binding is /// shadowed or the command has none. Read from a table the keymap builds when its bindings change. + /// + /// A command the app runs itself ([`Dispatch::App`]) shows its first single-press binding wherever it is, home + /// scope first: nothing here matches its chords, so nothing here can shadow them. pub fn shown_chord(&self, command: &CommandRef) -> Option { self.find(command).and_then(|i| self.shown[i]) } @@ -537,6 +543,15 @@ impl Keymap { fn shown_of(&self, i: usize) -> Option { let home = &self.catalog[i].scope; let single = || self.current[i].iter().filter(|(trigger, _)| trigger.press == PressKind::Single); + // The app runs a command marked `Dispatch::App` on its own, so the keymap cannot tell whether a chord it also + // binds takes the key first: it shows the command's first binding rather than dropping it as shadowed. + if self.catalog[i].dispatch == Dispatch::App { + return single() + .filter(|(_, scope)| scope == home) + .chain(single().filter(|(_, scope)| scope != home)) + .map(|(trigger, _)| trigger.chord) + .next(); + } let runs = |(trigger, scope): &&Bound| { let name = [scope.as_str()]; let active = match self.scopes.kind(scope) { @@ -1061,6 +1076,11 @@ impl Keymap { fn index_command(&mut self, i: usize) { let Some(list) = self.current.get(i) else { return }; + // A command the app runs itself matches nothing here: its chords stay in the app's hands, as the raw input + // holds them. + if self.catalog[i].dispatch == Dispatch::App { + return; + } let holds = self.holds; for (k, (t, _)) in list.iter().enumerate().filter(|(_, (t, _))| holds || !t.is_hold()) { self.by_trigger.entry(t.effective(self.platform)).or_default().insert((i, k)); diff --git a/crates/keymap/src/keymap/command.rs b/crates/keymap/src/keymap/command.rs index e29300cdd7..b97c7c6d6f 100644 --- a/crates/keymap/src/keymap/command.rs +++ b/crates/keymap/src/keymap/command.rs @@ -28,6 +28,27 @@ pub enum CommandKind { Momentary, } +/// Who runs a command's keys. +/// +/// A command the app runs itself keeps its place in the catalog and its bindings: menus, tooltips, rails and buttons +/// show its chords ([`Keymap::shown_chord`](crate::Keymap::shown_chord)) and the shortcut editor lists them, and the +/// keymap matches none of them, so the press goes to the app as it would for a command with no binding here. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum Dispatch { + /// This keymap runs the command on its chords ([`Keymap::lookup`](crate::Keymap::lookup)). + #[default] + Keymap, + /// The app runs the command from its own key handling (a canvas editor with its own keymap). + App, +} + +/// Whether a command's keys are the keymap's, which written catalogs leave out as the default. +fn is_keymap(dispatch: &Dispatch) -> bool { + *dispatch == Dispatch::Keymap +} + /// Whether a command fires while a dialog is open. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -82,6 +103,10 @@ pub struct CommandDef { /// Whether the command fires while a dialog is open. #[serde(default)] pub modal: ModalRule, + /// Who runs the command's keys: this keymap, or the app, which shows them and matches none of them + /// ([`Dispatch`]). + #[serde(default, skip_serializing_if = "is_keymap")] + pub dispatch: Dispatch, } impl CommandDef { @@ -99,6 +124,7 @@ impl CommandDef { defaults: Vec::new(), icon: None, modal: ModalRule::default(), + dispatch: Dispatch::Keymap, } } @@ -137,6 +163,12 @@ impl CommandDef { self } + /// Sets the [`dispatch`](CommandDef::dispatch). + pub fn with_dispatch(mut self, dispatch: Dispatch) -> CommandDef { + self.dispatch = dispatch; + self + } + /// Adds a default binding. pub fn with_default(mut self, binding: Binding) -> CommandDef { self.defaults.push(binding); diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index 02a8abc3e2..df067d7cea 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -62,6 +62,10 @@ //! assert_eq!(press("M", &editing), Lookup::None, "plain keys go to the text field"); //! ``` //! +//! A command whose keys the app runs itself keeps its bindings and shows their chords, and the keymap matches none of +//! them: `CommandDef::new(..).with_dispatch(Dispatch::App)` tells the surfaces what to show for a command whose keys +//! the app's own key handling takes (a canvas's tool keys), so the menus and the shortcut editor still read the catalog. +//! //! # Storing overrides //! //! [`Overrides`] is a field of the app's craft-settings type, marked @@ -158,8 +162,8 @@ pub use import::{ ContextRule, DecodedCode, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, NotRead, Start, plan, }; pub use keymap::{ - AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, DropReason, Holder, Keymap, Lookup, - MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, + AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DeleteKeys, Dispatch, DropReason, Holder, Keymap, + Lookup, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, }; pub use layout::{COMMON_SYMBOLS, KeyInput, Layout, SYMBOL_TABLE, SymbolLayout}; pub use matcher::{Hit, Matcher, Press}; diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 215668bdd7..64ceb0f7e2 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -1,8 +1,8 @@ //! Integration tests of craft-keymap: keymap. use craft_keymap::{ - Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods, - Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger, + Active, Binding, Chord, CommandDef, CommandRef, DeleteKeys, Dispatch, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, + Mods, Overrides, Platform, Policy, Press, Problem, Scope, Scopes, Trigger, }; use serde_json::json; @@ -152,6 +152,35 @@ fn a_command_shows_only_the_chords_the_lookup_runs_it_for() { assert_eq!(alone.shown_chord(&cmd("edit.settings")), None, "every key shadowed"); } +/// A command the app runs itself keeps its bindings and the chord they show, and matching passes over it: the lookup +/// finds nothing for its chords, the command holds none, another command on a chord it binds still shows it, and an +/// assignment takes nothing from it. +#[test] +fn a_command_the_app_runs_itself_shows_its_chords_and_matches_none() { + let own = |id: &str, keys: &[&str]| app(id, keys).with_dispatch(Dispatch::App); + let km = Keymap::new(vec![own("tool.brush", &["J", "B"])], Scopes::new(), Platform::Mac); + assert_eq!(km.shown_chord(&cmd("tool.brush")), Some(chord("J")), "its first binding shows"); + assert_eq!(km.bindings(&cmd("tool.brush")), [b("J"), b("B")], "and the shortcut editor lists them"); + assert_eq!(press(&km, "J", &Active::NONE), Lookup::None, "the lookup passes over its chords"); + assert_eq!(press(&km, "B", &Active::NONE), Lookup::None); + assert_eq!(km.holder(&chord("J")), None, "it holds no chord"); + assert!(km.holders(&chord("J")).is_empty()); + + // Another command on a chord it binds runs, and it still shows its own chord: nothing here shadows it. + let shared = Keymap::new(vec![own("tool.brush", &["J"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac); + assert_eq!(press(&shared, "J", &Active::NONE), run("view.grid"), "the chord is the other command's"); + assert_eq!(shared.shown_chord(&cmd("tool.brush")), Some(chord("J"))); + assert_eq!(shared.shown_chord(&cmd("view.grid")), Some(chord("J"))); + assert!(shared.conflicts().is_empty(), "a chord the app runs clashes with nothing here"); + + // Assigning a chord it binds to another command takes nothing from it. + let mut stealer = Keymap::new(vec![own("tool.brush", &["B"]), app("view.grid", &["J"])], Scopes::new(), Platform::Mac); + let done = stealer.assign(&cmd("view.grid"), b("B"), Policy::Steal).expect("the assignment is taken"); + assert!(done.taken_from.is_empty(), "the command the app runs keeps its binding"); + assert_eq!(stealer.bindings(&cmd("tool.brush")), [b("B")]); + assert_eq!(press(&stealer, "B", &Active::NONE), run("view.grid")); +} + /// The shown chords are worked out when the bindings change, not per call, and follow every change: a key freed by one /// command shows on the command it no longer shadows, and a stolen key leaves the command it was taken from. #[test] diff --git a/crates/materialx/src/lib.rs b/crates/materialx/src/lib.rs index 99701366f9..e9c98a51c8 100644 --- a/crates/materialx/src/lib.rs +++ b/crates/materialx/src/lib.rs @@ -7,7 +7,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use craft_xml::{Doctype, El, Error as XmlError, Limits, Options, UnknownEntity}; @@ -65,6 +65,31 @@ pub enum Value { Image(String), } +/// The value connected to a shader input, as [`Document::read_material_strict`] resolves it. +#[derive(Clone, Debug, PartialEq)] +pub enum Resolved { + /// One to four finite numbers, kept in the source color space. The numbers may be separated + /// by commas, spaces or both, a `boolean` input's `true` and `false` are 1 and 0, and an + /// `integer` input holds one whole number. A `convert` node's output holds the converted channels. `colorspace` is the color + /// space in effect where the value is written: the input's own `colorspace`, else that of the + /// nearest enclosing element (the node, then its nodegraph), else the document's. A value + /// written on an input with a boolean, integer, float or vector type, on such a `constant` + /// node, or with no type on a `convert` node's input, is in the document's working color + /// space (the root element's `colorspace`). A `convert` node, and a `constant` node whose + /// value is connected, keep the color space of their input. + Constant { values: Vec, colorspace: Option }, + /// A file from an image node, with the file prefix in effect applied: the `file` input's + /// `fileprefix`, else the node's, its nodegraph's or the document's. `colorspace` is the + /// color space in effect on the node's `file` input, found the same way as for a constant, + /// and `uv_tiling` is the node's `uvtiling` as written. A `uvtiling` value that is not two + /// finite numbers is [`Error::Malformed`]. An image node with a boolean, integer, float or + /// vector type is in the document's working color space. + Image { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, + /// This variant stores an encoded tangent-space image connected through a `normalmap` node. + /// The fields have the same meaning as [`Self::Image`]. + NormalMap { file: String, colorspace: Option, uv_tiling: Option<[f32; 2]> }, +} + /// A surface material resolved from a MaterialX document. #[derive(Clone, Debug, PartialEq)] pub struct Material { @@ -82,12 +107,41 @@ pub struct Material { pub warnings: Vec, } +/// A surface material resolved by [`Document::read_material_strict`]. +#[derive(Clone, Debug, PartialEq)] +pub struct StrictMaterial { + /// Material name, or `Material` when omitted. + pub name: String, + /// Shader dialect represented by the material. + pub shader: Shader, + /// Resolved inputs in the shader table's deterministic order. + pub inputs: Vec<(String, Resolved)>, + /// Resolved scalar displacement input, if present. Vector displacement is reported as unsupported. + pub displacement: Option, + /// First image tiling of two positive numbers, kept in `0.001..=1000`, or `[1, 1]`. + pub uv_tiling: [f32; 2], + /// Unsupported or ignored constructs encountered while resolving values, and shader inputs + /// that are not in the shader's table and so are not read. + pub warnings: Vec, +} + #[derive(Clone, Debug)] struct Found { value: Value, tiling: Option<[f32; 2]>, } +/// The material, its surface shader and the document's nodes, found for a read. +struct Located<'a> { + mat: &'a El, + shader: &'a El, + scope: Option, + kind: Shader, + nodes: HashMap, + graphs: HashMap<&'a str, &'a El>, + outputs: Vec<(String, String)>, +} + const OPEN_PBR_INPUTS: &[&str] = &[ "base_color", "base_metalness", @@ -138,6 +192,76 @@ const GLTF_INPUTS: &[&str] = &[ "transmission", ]; +const OPEN_PBR_STRICT_INPUTS: &[&str] = &[ + "base_color", + "base_metalness", + "specular_roughness", + "geometry_normal", + "geometry_opacity", + "emission_color", + "coat_weight", + "coat_roughness", + "geometry_coat_normal", + "fuzz_weight", + "fuzz_color", + "fuzz_roughness", + "specular_roughness_anisotropy", + "transmission_weight", + "subsurface_weight", + "base_weight", + "specular_weight", + "specular_color", + "specular_ior", + "coat_color", + "coat_ior", + "emission_luminance", +]; +const STANDARD_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metalness", + "specular_roughness", + "normal", + "opacity", + "emission_color", + "coat", + "coat_roughness", + "coat_normal", + "sheen", + "sheen_color", + "sheen_roughness", + "specular_anisotropy", + "transmission", + "subsurface", + "base", + "specular", + "specular_color", + "specular_IOR", + "coat_color", + "coat_IOR", + "emission", +]; +const GLTF_STRICT_INPUTS: &[&str] = &[ + "base_color", + "metallic", + "roughness", + "normal", + "alpha", + "emissive", + "occlusion", + "clearcoat", + "clearcoat_roughness", + "clearcoat_normal", + "sheen_color", + "sheen_roughness", + "transmission", + "emissive_strength", + "ior", + "specular", + "specular_color", + "alpha_mode", + "alpha_cutoff", +]; + /// OpenPBR input kind accepted by [`write_open_pbr`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum InputKind { @@ -253,49 +377,13 @@ impl Document { /// Resolves a surface material into shader inputs, image paths and warnings. pub fn read_material(&self, material: Option<&str>) -> Result { - let materials: Vec<&El> = self.root.children("surfacematerial").collect(); - let mat = match material { - Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, - None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + let Located { mat, shader, kind, nodes, outputs, .. } = self.locate(material, false)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_INPUTS, + Shader::StandardSurface => STANDARD_INPUTS, + Shader::GltfPbr => GLTF_INPUTS, }; - let mut nodes = HashMap::new(); - let mut outputs = Vec::new(); - for child in self.root.elements() { - if child.name == "nodegraph" { - let Some(graph) = child.attr("name") else { continue }; - for node in child.elements() { - let Some(name) = node.attr("name") else { continue }; - if node.name == "output" { - if let Some(from) = node.attr("nodename") { - outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); - } - } else { - nodes.insert(format!("{graph}/{name}"), node); - } - } - } else if let Some(name) = child.attr("name") { - nodes.insert(name.to_owned(), child); - } - } - let shader_name = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")).and_then(|i| i.attr("nodename")); - let shader = shader_name.and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; - let (kind, inputs) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR_INPUTS), - "standard_surface" => (Shader::StandardSurface, STANDARD_INPUTS), - "gltf_pbr" => (Shader::GltfPbr, GLTF_INPUTS), - other => return Err(Error::Unsupported(format!("surface shader is {other}"))), - }; - let emission_gate = match kind { - Shader::OpenPbr => Some(("emission_luminance", true)), - Shader::StandardSurface => Some(("emission", true)), - Shader::GltfPbr => None, - }; - let emission_enabled = emission_gate.is_none_or(|(name, _)| { - shader - .children("input") - .find(|i| i.attr("name") == Some(name)) - .is_some_and(|i| i.attr("value").is_none_or(|v| parse_numbers(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) - }); + let emission_enabled = emission_enabled(kind, shader, parse_numbers); let mut warnings = Vec::new(); let base_weight_name = match kind { Shader::OpenPbr => Some("base_weight"), @@ -343,6 +431,166 @@ impl Document { warnings, }) } + + /// Resolves a surface material like [`Document::read_material`], with a wider input table, the + /// color space in effect and the UV tiling of each image, and stricter checks. + /// + /// The tables add each shader's weight, specular, IOR and coat color inputs, OpenPBR's + /// `emission_luminance`, and glTF PBR's `emissive_strength` and alpha mode inputs; glTF PBR's + /// emission color is read from `emissive`, the name its node definition gives it. Values may + /// be separated by commas, spaces or both, `convert` nodes follow the Standard Nodes rules, + /// and an image inside a nodegraph takes the nodegraph's `fileprefix`. A repeated shader + /// input, a value that is not one to four finite numbers or does not fit its type, and a + /// `uvtiling` that is not two finite numbers are [`Error::Malformed`]. A shader input that is + /// not in the table gives the warning `input is not read`; the base weight warning of + /// [`Document::read_material`] is not given, since the weight is read. A `normalmap` node's + /// `scale` other than 1 and authored `normal`, `tangent`, and `bitangent` inputs are not applied + /// and give warnings. Image inputs of `normalmap` nodes resolve as [`Resolved::NormalMap`]. + /// Three-component literal normal-map inputs are unsupported and give warnings. Other literal + /// sizes return [`Error::Malformed`]. + /// Surface shaders may connect through graph outputs. A graph with several outputs needs a + /// named selection; a graph with one output uses it regardless of the selection attribute. + /// Missing node and graph-output references are errors. Supported numeric `constant` nodes + /// use their typed zero values when `value` is omitted. Emission colors remain resolved when + /// their strength is zero. Nonzero image `uvoffset`, nonidentity displacement `scale`, and + /// vector displacement are reported as unsupported. + pub fn read_material_strict(&self, material: Option<&str>) -> Result { + let Located { mat, shader, scope, kind, nodes, graphs, outputs } = self.locate(material, true)?; + let inputs = match kind { + Shader::OpenPbr => OPEN_PBR_STRICT_INPUTS, + Shader::StandardSurface => STANDARD_STRICT_INPUTS, + Shader::GltfPbr => GLTF_STRICT_INPUTS, + }; + let mut warnings = Vec::new(); + let mut seen = HashSet::new(); + for name in shader.children("input").filter_map(|i| i.attr("name")) { + if !seen.insert(name) { + return Err(Error::Malformed(format!("the shader has more than one {name} input"))); + } + if !inputs.contains(&name) { + warnings.push(format!("input {name} is not read")); + } + } + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + let shader_space = resolver.space_of(shader, scope.as_deref()); + let mut resolved = Vec::new(); + let mut tiling = None; + for name in inputs { + let Some(input) = shader.children("input").find(|i| i.attr("name") == Some(*name)) else { continue }; + if let Some(value) = resolver.value(input, scope.as_deref(), shader_space, 0, &mut warnings)? { + if tiling.is_none() { + tiling = image_tiling(&value); + } + resolved.push(((*name).to_owned(), value)); + } + } + let mut displacement = None; + if let Some(connection) = mat.children("input").find(|i| i.attr("name") == Some("displacementshader")) { + let target = resolver.target(connection, None)?; + if let Some(node) = target.as_ref().and_then(|name| nodes.get(name).copied()) { + let node_scope = target.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph); + let space = resolver.space_of(node, node_scope); + if let Some(input) = node.children("input").find(|i| i.attr("name") == Some("displacement")) { + let value = resolver.value(input, node_scope, space, 0, &mut warnings)?; + if resolver.value_type(input, node_scope)? == Some("vector3") + || matches!(&value, Some(Resolved::Constant { values, .. }) if values.len() == 3) + { + warnings.push("vector displacement is not supported; its input was skipped".into()); + } else { + displacement = value; + } + } + if let Some(scale) = node.children("input").find(|i| i.attr("name") == Some("scale")).filter(|i| has_authored_value(i)) { + let value = resolver.value(scale, node_scope, space, 0, &mut warnings)?; + match value { + Some(Resolved::Constant { values, .. }) if values.len() != 1 => { + return Err(Error::Malformed("displacement scale is not one finite number".into())); + } + Some(Resolved::Constant { values, .. }) if values == [1.0] => {} + _ => warnings.push("the scale of the displacement node is not read".into()), + } + } + if tiling.is_none() { + tiling = displacement.as_ref().and_then(image_tiling); + } + } + } + Ok(StrictMaterial { + name: mat.attr("name").unwrap_or("Material").to_owned(), + shader: kind, + inputs: resolved, + displacement, + uv_tiling: tiling.unwrap_or([1.0, 1.0]), + warnings, + }) + } + + /// The surface material named `material` (or the first one), its surface shader, and the + /// document's nodes, nodegraphs and graph outputs. + fn locate(&self, material: Option<&str>, strict: bool) -> Result, Error> { + let materials: Vec<&El> = self.root.children("surfacematerial").collect(); + let mat = match material { + Some(name) => materials.iter().copied().find(|m| m.attr("name") == Some(name)).ok_or_else(|| Error::MissingMaterial(name.to_owned()))?, + None => materials.first().copied().ok_or_else(|| Error::Unsupported("document has no surfacematerial".into()))?, + }; + let mut nodes = HashMap::new(); + let mut graphs = HashMap::new(); + let mut outputs = Vec::new(); + for child in self.root.elements() { + if child.name == "nodegraph" { + let Some(graph) = child.attr("name") else { continue }; + graphs.insert(graph, child); + for node in child.elements() { + let Some(name) = node.attr("name") else { continue }; + if node.name == "output" { + if let Some(from) = node.attr("nodename") { + outputs.push((format!("{graph}/{name}"), format!("{graph}/{from}"))); + } else if strict { + outputs.push((format!("{graph}/{name}"), String::new())); + } + } else { + nodes.insert(format!("{graph}/{name}"), node); + } + } + } else if let Some(name) = child.attr("name") { + nodes.insert(name.to_owned(), child); + } + } + let connection = mat.children("input").find(|i| i.attr("name") == Some("surfaceshader")); + let shader_name = if strict { + let resolver = Resolver { root: &self.root, nodes: &nodes, graphs: &graphs, outputs: &outputs }; + connection.map(|input| resolver.target(input, None)).transpose()?.flatten() + } else { + connection.and_then(|input| input.attr("nodename")).map(str::to_owned) + }; + let shader = + shader_name.as_ref().and_then(|n| nodes.get(n).copied()).ok_or_else(|| Error::Malformed("material has no surface shader".into()))?; + let scope = shader_name.as_deref().and_then(|name| name.split_once('/')).map(|(graph, _)| graph.to_owned()); + let kind = match shader.name.as_str() { + "open_pbr_surface" => Shader::OpenPbr, + "standard_surface" => Shader::StandardSurface, + "gltf_pbr" => Shader::GltfPbr, + other => return Err(Error::Unsupported(format!("surface shader is {other}"))), + }; + Ok(Located { mat, shader, scope, kind, nodes, graphs, outputs }) + } +} + +/// Whether the shader's emission is on: its strength input (`emission_luminance` or +/// `emission`) is connected or holds a value above 0, read with `parse`. glTF PBR has no such +/// input, so its emission is always on. +fn emission_enabled(kind: Shader, shader: &El, parse: fn(&str) -> Option>) -> bool { + let gate = match kind { + Shader::OpenPbr => Some("emission_luminance"), + Shader::StandardSurface => Some("emission"), + Shader::GltfPbr => None, + }; + gate.is_none_or(|name| { + shader + .children("input") + .find(|i| i.attr("name") == Some(name)) + .is_some_and(|i| i.attr("value").is_none_or(|v| parse(v).and_then(|n| n.first().copied()).is_some_and(|v| v > 0.0))) + }) } fn numeric_input(shader: &El, name: &str) -> Option { @@ -424,6 +672,373 @@ fn resolve_value( } } +fn image_tiling(value: &Resolved) -> Option<[f32; 2]> { + match value { + Resolved::Image { uv_tiling, .. } | Resolved::NormalMap { uv_tiling, .. } => { + uv_tiling.filter(|n| n.iter().all(|v| *v > 0.0)).map(|n| [n[0].clamp(0.001, 1000.0), n[1].clamp(0.001, 1000.0)]) + } + Resolved::Constant { .. } => None, + } +} + +fn has_authored_value(input: &El) -> bool { + ["value", "nodename", "nodegraph", "interfacename"].iter().any(|name| input.attr(name).is_some()) +} + +/// One to four finite numbers separated by commas, spaces or both, as MaterialX's own value +/// reader splits vector and color values. +fn parse_values(text: &str) -> Option> { + let nums: Option> = text + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|part| !part.is_empty()) + .map(|part| part.parse::().ok().filter(|v| v.is_finite())) + .collect(); + nums.filter(|v| !v.is_empty() && v.len() <= 4) +} + +/// The value of the input `input`, read as a `boolean` (`true` or `false`, as 1 or 0) or an +/// `integer` (one whole number) when its type says so, and as numbers otherwise. A `float`, +/// vector or color type needs as many numbers as it has channels. +fn input_numbers(input: &El, text: &str) -> Option> { + match input.attr("type") { + Some("boolean") => match text.trim() { + "true" => Some(vec![1.0]), + "false" => Some(vec![0.0]), + _ => None, + }, + Some("integer") => text.trim().parse::().ok().map(|v| vec![v as f32]), + ty => parse_values(text).filter(|v| ty.and_then(channels).is_none_or(|n| v.len() == n)), + } +} + +/// The number of channels of a MaterialX numeric type. +fn channels(ty: &str) -> Option { + match ty { + "float" | "integer" | "boolean" => Some(1), + "vector2" => Some(2), + "color3" | "vector3" => Some(3), + "color4" | "vector4" => Some(4), + _ => None, + } +} + +/// Whether `ty` is a numeric MaterialX type that is not a color: a boolean, integer, float or +/// vector. A `colorspace` does not apply to values of these types. +fn is_numeric_non_color(ty: Option<&str>) -> bool { + ty.is_some_and(|ty| channels(ty).is_some() && !matches!(ty, "color3" | "color4")) +} + +/// The type of `count` numbers whose type is not written: a float, or a vector. +fn untyped(count: usize) -> &'static str { + match count { + 1 => "float", + 2 => "vector2", + 3 => "vector3", + _ => "vector4", + } +} + +/// `values` of type `from` converted to type `to` by the `convert` node's rules in the MaterialX +/// Standard Nodes: a boolean becomes a float or integer of 0 or 1, an integer becomes a float or +/// a boolean (1 for any value that is not 0), a boolean, float or integer is copied to every +/// channel of a color or vector, and a color or vector keeps its first channels and fills +/// missing ones with 0 (1 in the fourth). `None` for a pair the node does not define, such as a +/// float to an integer or a color to a float, and for values that do not fit `from`. +fn converted(values: &[f32], from: &str, to: &str) -> Option> { + if channels(from)? != values.len() { + return None; + } + let out = channels(to)?; + match (from, to) { + _ if from == to => Some(values.to_vec()), + ("boolean", "float" | "integer") | ("integer", "float") => Some(values.to_vec()), + ("integer", "boolean") => Some(vec![if values[0] != 0.0 { 1.0 } else { 0.0 }]), + ("boolean" | "float" | "integer", _) if out > 1 => Some(vec![values[0]; out]), + _ if values.len() > 1 && out > 1 => Some((0..out).map(|c| values.get(c).copied().unwrap_or(if c == 3 { 1.0 } else { 0.0 })).collect()), + _ => None, + } +} + +/// The document's nodes, nodegraphs and graph outputs, for following input connections. +struct Resolver<'a> { + root: &'a El, + nodes: &'a HashMap, + graphs: &'a HashMap<&'a str, &'a El>, + outputs: &'a [(String, String)], +} + +impl<'a> Resolver<'a> { + /// The color space in effect on `element`: its own, else its nodegraph's when `scope` names + /// one, else the document's. + fn space_of(&self, element: &'a El, scope: Option<&str>) -> Option<&'a str> { + element + .attr("colorspace") + .or_else(|| scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("colorspace"))) + .or_else(|| self.root.attr("colorspace")) + } + + /// The document's working color space, the root element's `colorspace`. + fn working(&self) -> Option<&'a str> { + self.root.attr("colorspace") + } + + /// The value of `input`, an input of an element in nodegraph `scope` (or at the top level) + /// whose color space in effect is `space`. A `value` that is not one to four finite numbers, + /// or that does not fit a `boolean` or `integer` type, is [`Error::Malformed`]; an + /// unsupported connection is skipped with a warning. + fn value( + &self, + input: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if hops > 16 { + warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); + return Ok(None); + } + if let Some(interface) = input.attr("interfacename") { + warnings.push(format!("interface input {interface:?} is not supported; its value was skipped")); + return Ok(None); + } + if let Some(value) = input.attr("value") { + let Some(values) = input_numbers(input, value) else { + let name = input.attr("name").unwrap_or(""); + return Err(Error::Malformed(format!("input {name} has a value that is not one to four finite numbers or does not fit its type"))); + }; + let colorspace = if is_numeric_non_color(input.attr("type")) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + let target = self.target(input, scope)?; + let Some(node) = target.as_ref().and_then(|t| self.nodes.get(t).copied()) else { return Ok(None) }; + let node_scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g); + let node_space = self.space_of(node, node_scope); + let child = |name: &str| node.children("input").find(|i| i.attr("name") == Some(name)); + let node_name = node.attr("name").unwrap_or(""); + match node.name.as_str() { + "image" | "tiledimage" => { + let file = child("file").and_then(|input| input.attr("value").filter(|file| !file.is_empty()).map(|file| (input, file))); + let Some((file_input, file)) = file else { + warnings.push(format!("image node {node_name:?} has no nonempty literal file value; its image was skipped")); + return Ok(None); + }; + let prefix = file_input + .attr("fileprefix") + .or_else(|| node.attr("fileprefix")) + .or_else(|| node_scope.and_then(|g| self.graphs.get(g)).and_then(|g| g.attr("fileprefix"))) + .or_else(|| self.root.attr("fileprefix")) + .unwrap_or(""); + let uv_tiling = match child("uvtiling").filter(|input| has_authored_value(input)) { + None => None, + Some(input) => match self.value(input, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() == 2 => Some([values[0], values[1]]), + Some(Resolved::Constant { .. }) => { + return Err(Error::Malformed(format!("the uvtiling of image {node_name:?} is not two finite numbers"))); + } + _ => { + warnings.push(format!("the uvtiling of image {node_name:?} is not read")); + None + } + }, + }; + if let Some(offset) = child("uvoffset").filter(|input| has_authored_value(input)) { + match self.value(offset, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if values.len() != 2 => { + return Err(Error::Malformed(format!("the uvoffset of image {node_name:?} is not two finite numbers"))); + } + Some(Resolved::Constant { values, .. }) if values == [0.0, 0.0] => {} + _ => warnings.push(format!("the uvoffset of image {node_name:?} is not read")), + } + } + for mode in ["uaddressmode", "vaddressmode"] { + if let Some(input) = child(mode).filter(|input| has_authored_value(input)) { + match input.attr("value") { + Some("periodic") => {} + Some("constant" | "clamp" | "mirror") | None => warnings.push(format!("the {mode} of image {node_name:?} is not read")), + Some(_) => return Err(Error::Malformed(format!("the {mode} of image {node_name:?} is not a supported addressing mode"))), + } + } + } + let colorspace = if is_numeric_non_color(node.attr("type")) { self.working() } else { file_input.attr("colorspace").or(node_space) } + .map(str::to_owned); + Ok(Some(Resolved::Image { file: format!("{prefix}{file}"), colorspace, uv_tiling })) + } + "normalmap" => { + for name in ["normal", "tangent", "bitangent"] { + if child(name).is_some_and(has_authored_value) { + warnings.push(format!("the {name} of normalmap node {node_name:?} is not read")); + } + } + // The normal is passed on without the node's scale, so a scale other than 1 is + // reported. + if let Some(scale) = child("scale").filter(|input| has_authored_value(input)) { + let resolved = self.value(scale, node_scope, node_space, hops + 1, &mut Vec::new())?; + if !matches!(resolved, Some(Resolved::Constant { ref values, .. }) if values.iter().all(|s| *s == 1.0)) { + warnings.push(format!("the scale of normalmap node {node_name:?} is not read")); + } + } + match child("in") { + Some(i) => Ok(match self.value(i, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Image { file, colorspace, uv_tiling }) => Some(Resolved::NormalMap { file, colorspace, uv_tiling }), + Some(Resolved::Constant { values, .. }) if values.len() != 3 => { + return Err(Error::Malformed(format!("the input of normalmap node {node_name:?} is not three finite numbers"))); + } + Some(Resolved::Constant { .. }) => { + warnings.push(format!("the literal input of normalmap node {node_name:?} is not supported; its value was skipped")); + None + } + Some(Resolved::NormalMap { .. }) => { + warnings.push(format!("the nested normalmap input of node {node_name:?} is not supported; its value was skipped")); + None + } + value => value, + }), + None => Ok(None), + } + } + "convert" => { + let Some(i) = child("in").filter(|input| has_authored_value(input)) else { + let definition = node.attr("nodedef").and_then(|name| name.strip_prefix("ND_convert_")).and_then(|name| name.split_once('_')); + if let Some((from, to)) = definition + && from != to + && node.attr("type").is_none_or(|ty| ty == to) + && let Some(count) = channels(from) + && let Some(values) = converted(&vec![0.0; count], from, to) + { + return Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })); + } + warnings.push(format!("the input default of convert node {node_name:?} cannot be identified; its value was skipped")); + return Ok(None); + }; + let Some(value) = self.value(i, node_scope, node_space, hops + 1, warnings)? else { return Ok(None) }; + let to = node.attr("type").unwrap_or(""); + let from = self.value_type(i, node_scope)?; + match value { + Resolved::Constant { values, colorspace } => { + // A value with no type is a float or a vector, so it is in the working + // color space like a typed one. + let colorspace = if from.is_none() && i.attr("value").is_some() { self.working().map(str::to_owned) } else { colorspace }; + let from = from.unwrap_or_else(|| untyped(values.len())); + match converted(&values, from, to) { + Some(values) => Ok(Some(Resolved::Constant { values, colorspace })), + None => { + warnings.push(format!( + "a convert node ({node_name:?}) from type {from:?} to type {to:?} is not supported; its input was skipped" + )); + Ok(None) + } + } + } + // An image keeps its own channels, so only a convert that copies every + // channel as it is passes it on. + image @ (Resolved::Image { .. } | Resolved::NormalMap { .. }) => { + let copies = from.is_some_and(|from| from == to || channels(from).is_some_and(|n| n > 1 && channels(to) == Some(n))); + if copies { + Ok(Some(image)) + } else { + warnings.push(format!( + "a convert node ({node_name:?}) changes an image's channels to type {to:?}, which is not supported; its input was skipped" + )); + Ok(None) + } + } + } + } + "constant" => { + let value = child("value").filter(|input| has_authored_value(input)); + match value { + // A connected value keeps the color space it resolved; only a written value takes + // the working color space. + Some(i) => match self.constant_value(i, node, node_scope, node_space, hops + 1, warnings)? { + Some(Resolved::Constant { values, .. }) if is_numeric_non_color(node.attr("type")) && i.attr("value").is_some() => { + Ok(Some(Resolved::Constant { values, colorspace: self.working().map(str::to_owned) })) + } + value => Ok(value), + }, + None => match node.attr("type").and_then(channels) { + Some(count) => { + let space = if is_numeric_non_color(node.attr("type")) { self.working() } else { node_space }; + Ok(Some(Resolved::Constant { values: vec![0.0; count], colorspace: space.map(str::to_owned) })) + } + None => { + warnings.push(format!("the default of constant node {node_name:?} has an unsupported type")); + Ok(None) + } + }, + } + } + other => { + warnings.push(format!("a {other} node ({node_name:?}) is not supported; its input was skipped")); + Ok(None) + } + } + } + + fn constant_value( + &self, + input: &'a El, + node: &'a El, + scope: Option<&str>, + space: Option<&'a str>, + hops: usize, + warnings: &mut Vec, + ) -> Result, Error> { + if input.attr("type").is_none() + && input.attr("interfacename").is_none() + && let Some(text) = input.attr("value") + && let Some(ty) = node.attr("type") + { + let typed = El::new("input").with_attr("type", ty); + let values = input_numbers(&typed, text) + .ok_or_else(|| Error::Malformed(format!("constant {:?} has a value that does not fit {ty}", node.attr("name").unwrap_or(""))))?; + let colorspace = if is_numeric_non_color(Some(ty)) { self.working() } else { input.attr("colorspace").or(space) }; + return Ok(Some(Resolved::Constant { values, colorspace: colorspace.map(str::to_owned) })); + } + self.value(input, scope, space, hops, warnings) + } + + /// The key in `nodes` of the node that `input`, an input of an element in nodegraph `scope` + /// (or at the top level), connects to. + fn target(&self, input: &El, scope: Option<&str>) -> Result, Error> { + let target = if let Some(graph) = input.attr("nodegraph") { + let prefix = format!("{graph}/"); + let outputs: Vec<_> = self.outputs.iter().filter(|(name, _)| name.starts_with(&prefix)).collect(); + let selected = if outputs.len() == 1 { + outputs.first().copied() + } else { + input.attr("output").and_then(|output| outputs.iter().rev().copied().find(|(name, _)| name == &format!("{graph}/{output}"))) + }; + Some( + selected + .ok_or_else(|| { + Error::Malformed(format!("input {:?} has no selected output in nodegraph {graph:?}", input.attr("name").unwrap_or(""))) + })? + .1 + .clone(), + ) + } else if let Some(name) = input.attr("nodename") { + let qualified = scope.map(|g| format!("{g}/{name}")); + Some(qualified.unwrap_or_else(|| name.to_owned())) + } else { + None + }; + if let Some(name) = target.as_ref() + && !self.nodes.contains_key(name) + { + return Err(Error::Malformed(format!("input {:?} references missing node {name:?}", input.attr("name").unwrap_or("")))); + } + Ok(target) + } + + fn value_type(&self, input: &'a El, scope: Option<&str>) -> Result, Error> { + if input.attr("type").is_some() || input.attr("value").is_some() { + return Ok(input.attr("type")); + } + Ok(self.target(input, scope)?.as_ref().and_then(|name| self.nodes.get(name).copied()).and_then(|node| node.attr("type"))) + } +} + /// Writes an OpenPBR MaterialX document for the supplied textures. /// /// Unknown inputs and duplicate inputs are skipped; the first texture for an input wins. Color @@ -566,9 +1181,13 @@ mod tests { "#; - let material = Document::parse(xml).unwrap().read_material(None).unwrap(); + let doc = Document::parse(xml).unwrap(); + let material = doc.read_material(None).unwrap(); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); assert_eq!(material.uv_tiling, [4.0, 2.0]); + let strict = doc.read_material_strict(None).unwrap(); + assert_eq!(strict.displacement, Some(Resolved::Image { file: "height.png".into(), colorspace: None, uv_tiling: Some([4.0, 2.0]) })); + assert_eq!(strict.uv_tiling, [4.0, 2.0]); } #[test] @@ -594,6 +1213,22 @@ mod tests { assert_eq!(material.inputs[2].1, Value::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); assert_eq!(material.displacement, Some(Value::Constant { values: vec![0.25], colorspace: None })); assert_eq!(material.uv_tiling, [2.0, 4.0]); + assert!(matches!(doc.read_material_strict(None), Err(Error::Malformed(_)))); + let mut explicit = doc.clone(); + let normalmap = explicit.root.elements_mut().find(|node| node.attr("name") == Some("N")).unwrap(); + normalmap.child_mut("input").unwrap().set_attr("output", "first"); + let strict = explicit.read_material_strict(None).unwrap(); + assert_eq!( + strict.inputs[0], + ("base_color".into(), Resolved::Image { file: "tex/albedo.png".into(), colorspace: None, uv_tiling: Some([2.0, 4.0]) }) + ); + assert_eq!( + strict.inputs[1], + ("geometry_normal".into(), Resolved::NormalMap { file: "tex/normal.png".into(), colorspace: None, uv_tiling: None }) + ); + assert_eq!(strict.inputs[2].1, Resolved::Constant { values: vec![1.0, 0.5, 0.25], colorspace: None }); + assert_eq!(strict.displacement, Some(Resolved::Constant { values: vec![0.25], colorspace: None })); + assert_eq!(strict.uv_tiling, [2.0, 4.0]); } #[test] @@ -612,8 +1247,423 @@ mod tests { assert_eq!(material.inputs[1], ("specular_roughness".into(), Value::Image("rough.png".into()))); assert_eq!(material.inputs[2], ("geometry_normal".into(), Value::Image("normal.png".into()))); assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); + let strict = doc.read_material_strict(None).unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(strict.inputs[0], ("base_color".into(), image("albedo<&.png", "srgb_texture"))); + assert_eq!(strict.inputs[1], ("specular_roughness".into(), image("rough.png", "lin_rec709"))); + assert_eq!( + strict.inputs[2], + ("geometry_normal".into(), Resolved::NormalMap { file: "normal.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + assert_eq!(strict.displacement, Some(image("height.png", "lin_rec709"))); assert!(xml.contains("colorspace=\"srgb_texture\"")); assert!(xml.contains("doc=\"Tiles every 100 x 50 cm\"")); assert!(!xml.contains("colorspace=\"ignored\"")); } + + #[test] + fn read_material_keeps_its_input_table_values_and_lenient_checks() { + // `read_material` reads glTF PBR's `emission`, keeps the base weight warning, skips + // repeated inputs, bad values and bad `uvtiling` instead of failing, and gives a + // constant only its own `colorspace`; `read_material_strict` is the stricter read. + let xml = r#" + + + + + + + "#; + let doc = Document::parse(xml.as_bytes()).unwrap(); + let gltf = doc.read_material(Some("M")).unwrap(); + assert_eq!( + gltf.inputs, + vec![ + ("base_color".into(), Value::Image("a.png".into())), + ("roughness".into(), Value::Constant { values: vec![0.25], colorspace: None }), + ("alpha".into(), Value::Constant { values: vec![0.5], colorspace: None }), + ("emission".into(), Value::Constant { values: vec![1.0, 0.5, 0.0], colorspace: None }), + ] + ); + assert_eq!(gltf.uv_tiling, [1.0, 1.0]); + assert!(gltf.warnings.is_empty(), "{:?}", gltf.warnings); + assert!(matches!(doc.read_material_strict(Some("M")), Err(Error::Malformed(_)))); + let open = doc.read_material(Some("N")).unwrap(); + assert_eq!(open.warnings, vec!["the base weight isn't 1; it was ignored".to_owned()]); + assert!(open.inputs.is_empty(), "{:?}", open.inputs); + let strict = doc.read_material_strict(Some("N")).unwrap(); + assert!(strict.warnings.is_empty(), "{:?}", strict.warnings); + assert_eq!(input(&strict, "base_weight"), Some(&constant(&[0.5], Some("srgb_texture")))); + assert_eq!(input(&strict, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + } + + fn read(xml: &str) -> Result { + Document::parse(xml.as_bytes())?.read_material_strict(None) + } + + fn input<'m>(material: &'m StrictMaterial, name: &str) -> Option<&'m Resolved> { + material.inputs.iter().find(|(n, _)| n == name).map(|(_, v)| v) + } + + fn constant(values: &[f32], space: Option<&str>) -> Resolved { + Resolved::Constant { values: values.to_vec(), colorspace: space.map(str::to_owned) } + } + + #[test] + fn gltf_pbr_reads_the_emissive_input_its_definition_names() { + // The gltf_pbr node definition calls its emission color `emissive` + // (https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/bxdf/gltf_pbr.mtlx). + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(input(&m, "emissive"), Some(&constant(&[0.5, 0.25, 0.0], None))); + assert_eq!(input(&m, "emissive_strength"), Some(&constant(&[2.0], None))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + } + + #[test] + fn weights_ior_and_alpha_inputs_are_read_for_each_shader() { + let open = read( + r#" + + + "#, + ) + .unwrap(); + for (name, values) in [ + ("base_weight", &[0.5][..]), + ("specular_weight", &[2.0]), + ("specular_color", &[1.0, 0.5, 0.5]), + ("specular_ior", &[1.33]), + ("coat_color", &[0.9, 0.9, 1.0]), + ("coat_ior", &[1.4]), + ("emission_luminance", &[10.0]), + ] { + assert_eq!(input(&open, name), Some(&constant(values, None)), "{name}"); + } + assert!(open.warnings.is_empty(), "{:?}", open.warnings); + let standard = read( + r#" + + "#, + ) + .unwrap(); + for (name, value) in [("base", 0.8), ("specular", 0.5), ("specular_IOR", 1.6), ("coat_IOR", 1.3), ("emission", 0.0)] { + assert_eq!(input(&standard, name), Some(&constant(&[value], None)), "{name}"); + } + let gltf = read( + r#" + + "#, + ) + .unwrap(); + for (name, values) in + [("alpha_mode", &[1.0][..]), ("alpha_cutoff", &[0.25]), ("ior", &[1.7]), ("specular", &[0.5]), ("specular_color", &[1.0, 1.0, 0.0])] + { + assert_eq!(input(&gltf, name), Some(&constant(values, None)), "{name}"); + } + } + + #[test] + fn constants_and_images_carry_the_color_space_in_effect_where_they_are_written() { + // An untagged value takes the nearest enclosing element's color space, then the + // document's (MaterialX specification, Color Spaces and Color Management Systems). + let m = read( + r#" + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("g22_rec709")))); + assert_eq!( + input(&m, "fuzz_color"), + Some(&Resolved::Image { file: "fuzz.png".into(), colorspace: Some("lin_rec709".into()), uv_tiling: None }) + ); + let doc = Document::parse( + br#" + "#, + ) + .unwrap(); + let tagged = doc.read_material_strict(Some("N")).unwrap(); + assert_eq!(input(&tagged, "base_color"), Some(&constant(&[0.2; 3], Some("acescg")))); + } + + #[test] + fn duplicate_inputs_and_values_that_are_not_finite_numbers_are_malformed() { + let shader = |inputs: &str| { + format!( + r#"{inputs}"# + ) + }; + let dup = read(&shader(r#""#)); + assert!(matches!(dup, Err(Error::Malformed(ref m)) if m.contains("base_metalness")), "{dup:?}"); + for bad in ["nan", "inf", "-inf", "1e40", "0.5,x", "", "1,2,3,4,5"] { + let r = read(&shader(&format!(r#""#))); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("specular_roughness")), "{bad}: {r:?}"); + } + } + + #[test] + fn a_normalmap_scale_other_than_1_gives_a_warning() { + let with_scale = |scale: &str| { + read(&open_pbr( + r#""#, + &format!(r#"{scale}"#), + )) + .unwrap() + }; + let scaled = with_scale(r#""#); + assert_eq!(scaled.warnings, vec![r#"the scale of normalmap node "N" is not read"#.to_owned()]); + assert!(matches!(input(&scaled, "geometry_normal"), Some(Resolved::NormalMap { .. }))); + for plain in ["", r#""#, r#""#] { + assert!(with_scale(plain).warnings.is_empty(), "{plain}"); + } + // A scale connected to a constant node is read through it. + let connected = |value: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + assert!(connected("1").warnings.is_empty(), "{:?}", connected("1").warnings); + assert_eq!(connected("2").warnings.len(), 1, "{:?}", connected("2").warnings); + } + + #[test] + fn shader_inputs_that_are_not_read_give_a_warning() { + let m = read( + r#" + "#, + ) + .unwrap(); + assert_eq!(m.warnings, vec!["input thin_film_weight is not read".to_owned()]); + assert_eq!(input(&m, "base_metalness"), Some(&constant(&[1.0], None))); + } + + fn open_pbr(inputs: &str, rest: &str) -> String { + format!( + r#"{inputs}{rest}"# + ) + } + + #[test] + fn vector_values_may_be_separated_by_commas_spaces_or_both() { + // MaterialX's value reader splits vector and color values on commas and spaces + // (ARRAY_VALID_SEPARATORS, ", ", in source/MaterialXCore/Types.cpp). + for text in ["0.5 0.25 0.125", "0.5, 0.25, 0.125", "0.5,0.25,0.125", " 0.5 0.25 ,0.125 "] { + let m = read(&open_pbr(&format!(r#""#), "")).unwrap(); + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5, 0.25, 0.125], None)), "{text:?}"); + } + // A color3 holds three numbers. + for bad in ["0.5 x 1", "0.5 0.25 0.125 1 2", " ", "0.5", "0.5, 0.25", "0.5 0.25 0.125 1"] { + let r = read(&open_pbr(&format!(r#""#), "")); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("base_color")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn a_nodegraph_file_prefix_applies_to_the_images_inside_it() { + // The nearest enclosing fileprefix applies (MaterialX specification, File Prefixes). + let m = read(&open_pbr( + r#""#, + r#" + + + + + "#, + ) + .replacen("", r#""#, 1)) + .unwrap(); + let file = |name: &str| match input(&m, name) { + Some(Resolved::Image { file, .. }) => file.clone(), + other => panic!("{name}: {other:?}"), + }; + assert_eq!( + (file("base_color"), file("specular_roughness"), file("base_metalness")), + ("stone/albedo.png".into(), "own/rough.png".into(), "shared/metal.png".into()) + ); + } + + #[test] + fn uv_tiling_is_kept_as_written_and_malformed_tiling_is_an_error() { + let tiled = |tiling: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + }; + let tiling_of = |m: &StrictMaterial| match input(m, "base_color") { + Some(Resolved::Image { uv_tiling, .. }) => *uv_tiling, + other => panic!("{other:?}"), + }; + let wide = tiled("2000, 2").unwrap(); + assert_eq!((tiling_of(&wide), wide.uv_tiling), (Some([2000.0, 2.0]), [1000.0, 2.0])); + let flat = tiled("0 2").unwrap(); + assert_eq!((tiling_of(&flat), flat.uv_tiling), (Some([0.0, 2.0]), [1.0, 1.0])); + for bad in ["x", "1", "1,2,3", "nan,1"] { + let r = tiled(bad); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("uvtiling")), "{bad:?}: {r:?}"); + } + } + + #[test] + fn convert_nodes_change_the_number_of_channels() { + // The convert node's rules in the MaterialX Standard Nodes: a float is copied to every + // channel, a shorter color or vector is filled with 0 (1 in the fourth channel), a + // longer one keeps its first channels, and a boolean is 0 or 1. + let via = |ty: &str, in_ty: &str, value: &str| { + read(&open_pbr( + r#""#, + &format!(r#""#), + )) + .unwrap() + }; + assert_eq!(input(&via("color3", "float", "0.25"), "base_color"), Some(&constant(&[0.25; 3], None))); + assert_eq!(input(&via("color4", "color3", "0.1,0.2,0.3"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3, 1.0], None))); + assert_eq!(input(&via("color3", "color4", "0.1,0.2,0.3,0.4"), "base_color"), Some(&constant(&[0.1, 0.2, 0.3], None))); + assert_eq!(input(&via("vector3", "vector2", "0.1,0.2"), "base_color"), Some(&constant(&[0.1, 0.2, 0.0], None))); + assert_eq!(input(&via("float", "boolean", "true"), "base_color"), Some(&constant(&[1.0], None))); + assert_eq!(input(&via("float", "integer", "3"), "base_color"), Some(&constant(&[3.0], None))); + assert_eq!(input(&via("boolean", "integer", "2"), "base_color"), Some(&constant(&[1.0], None))); + // An input with no type is a float or a vector by its count. + let untyped = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&untyped, "base_color"), Some(&constant(&[0.5; 3], None))); + // A color to a float and a float to an integer are not conversions the node defines. + for (ty, in_ty, value) in [("float", "color3", "0.1,0.2,0.3"), ("integer", "float", "0.5"), ("boolean", "float", "1")] { + let unsupported = via(ty, in_ty, value); + assert_eq!(input(&unsupported, "base_color"), None, "{in_ty} to {ty}"); + assert!(unsupported.warnings.iter().any(|w| w.contains("convert node")), "{:?}", unsupported.warnings); + } + // An integer is one whole number. + for bad in ["1.5", "1.00000001", "1 2"] { + let r = read(&open_pbr( + r#""#, + &format!(r#""#), + )); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("input in ")), "{bad:?}: {r:?}"); + } + let image = |ty: &str, image_ty: &str| { + read(&open_pbr( + r#""#, + &format!( + r#""# + ), + )) + .unwrap() + }; + let g = Resolved::Image { file: "g.png".into(), colorspace: None, uv_tiling: None }; + assert_eq!(input(&image("float", "float"), "base_color"), Some(&g)); + assert_eq!(input(&image("vector3", "color3"), "base_color"), Some(&g)); + for (ty, image_ty) in [("color3", "float"), ("color3", "color4")] { + let changed = image(ty, image_ty); + assert_eq!(input(&changed, "base_color"), None, "{image_ty} to {ty}"); + assert!(changed.warnings.iter().any(|w| w.contains("convert node")), "{:?}", changed.warnings); + } + } + + #[test] + fn a_color_converted_from_another_type_is_in_the_working_color_space() { + // A colorspace applies to color values and color image files (MaterialX specification, + // Color Spaces and Color Management Systems), so a float or vector copied into a color + // by a convert node holds working-space channels; a color keeps its own color space. + let m = read( + r#" + + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + let image = |file: &str, space: &str| Resolved::Image { file: file.into(), colorspace: Some(space.into()), uv_tiling: None }; + assert_eq!(input(&m, "base_color"), Some(&constant(&[0.5; 3], Some("lin_rec709")))); + assert_eq!(input(&m, "specular_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("lin_rec709")))); + assert_eq!(input(&m, "coat_color"), Some(&constant(&[0.1, 0.2, 0.3], Some("srgb_texture")))); + assert_eq!(input(&m, "fuzz_color"), Some(&image("v.png", "lin_rec709"))); + assert_eq!(input(&m, "emission_color"), Some(&image("c.png", "srgb_texture"))); + assert!(m.warnings.is_empty(), "{:?}", m.warnings); + // A color passed through a vector, also by way of a vector constant node, keeps its color + // space, and a float constant node or an untyped value is in the working color space. + let chain = read( + r#" + + + + + + + + + + + + + + + + "#, + ) + .unwrap(); + assert_eq!(input(&chain, "base_color"), Some(&constant(&[0.5; 3], Some("srgb_texture")))); + assert_eq!(input(&chain, "specular_color"), Some(&constant(&[0.25; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "coat_color"), Some(&constant(&[0.75; 3], Some("lin_rec709")))); + assert_eq!(input(&chain, "fuzz_color"), Some(&constant(&[0.4; 3], Some("srgb_texture")))); + assert!(chain.warnings.is_empty(), "{:?}", chain.warnings); + // A document without a working color space leaves the converted color untagged. + let plain = read(&open_pbr( + r#""#, + r#""#, + )) + .unwrap(); + assert_eq!(input(&plain, "base_color"), Some(&constant(&[0.5; 3], None))); + } + + #[test] + fn an_emission_color_is_checked_while_the_emission_is_0() { + let standard = |color: &str| { + read(&format!( + r#" + "# + )) + }; + let r = standard("0.5,x,1"); + assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("emission_color")), "{r:?}"); + let m = standard("0.5,0.5,1").unwrap(); + assert_eq!(input(&m, "emission_color"), Some(&constant(&[0.5, 0.5, 1.0], None))); + assert!(m.warnings.is_empty()); + } } diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 683fb76fb2..08f9683a10 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -226,6 +226,8 @@ pub enum GalleryFace<'a> { thumbnails: &'a Thumbnails, /// What renders the thumbnail. source: &'a dyn ThumbSource, + /// Whether the transparency grid shows behind transparent pixels. + checker: bool, }, /// A tile painted directly. Paint(&'a dyn Fn(&ContentPainterCx, Rect)), @@ -250,7 +252,17 @@ impl<'a> GalleryFace<'a> { /// A thumbnail under `key`, rendered by `source` into `thumbnails`. pub fn rendered(key: u64, thumbnails: &'a Thumbnails, source: &'a dyn ThumbSource) -> Self { - GalleryFace::Rendered { key, thumbnails, source } + GalleryFace::Rendered { key, thumbnails, source, checker: true } + } + + /// Whether a rendered thumbnail shows the transparency grid behind its transparent pixels (default on). Off for a + /// thumbnail that is a mask on the surface it sits on, such as an equation symbol. Other faces ignore it. + #[must_use] + pub fn checker(mut self, on: bool) -> Self { + if let GalleryFace::Rendered { checker, .. } = &mut self { + *checker = on; + } + self } /// The picture this face shows, `size` high and `aspect` times as wide. It is decoration: the tile that holds it @@ -258,7 +270,9 @@ impl<'a> GalleryFace<'a> { fn picture(&self, aspect: ThumbAspect, size: ThumbSize) -> Picture<'a> { let picture = match self { GalleryFace::Image { key, revision, image } => Picture::new(Label::default(), *key, *image).revision(*revision), - GalleryFace::Rendered { key, thumbnails, source } => Picture::rendered(Label::default(), *key, thumbnails, *source), + GalleryFace::Rendered { key, thumbnails, source, checker } => { + Picture::rendered(Label::default(), *key, thumbnails, *source).checker(*checker) + } GalleryFace::Paint(paint) => { let paint = *paint; Picture::painter(Label::default(), aspect, move |cx: &ContentPainterCx<'_>, rect: Rect| paint(cx, rect)) diff --git a/crates/menu/src/ribbon/gallery/stories.rs b/crates/menu/src/ribbon/gallery/stories.rs index 786f074e2b..2a80c79e78 100644 --- a/crates/menu/src/ribbon/gallery/stories.rs +++ b/crates/menu/src/ribbon/gallery/stories.rs @@ -172,8 +172,7 @@ fn gallery_rendered(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let options = ThumbnailOptions::new(); let thumbnails = Thumbnails::::in_context(ui.ctx(), "craft_menu.gallery.story", options); let source = FakeThumbSource::::new().later(true); - let items: Vec> = (0..COUNT) - .map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::Rendered { key: at as u64, thumbnails: &thumbnails, source: &source } }) - .collect(); + let items: Vec> = + (0..COUNT).map(|at| GalleryItem { key: at, label: name(at), face: GalleryFace::rendered(at as u64, &thumbnails, &source) }).collect(); show(ui, &items) } diff --git a/crates/menu/src/shortcuts/view/lists.rs b/crates/menu/src/shortcuts/view/lists.rs index 00b35ce177..5bd47ed1a5 100644 --- a/crates/menu/src/shortcuts/view/lists.rs +++ b/crates/menu/src/shortcuts/view/lists.rs @@ -24,6 +24,8 @@ use crate::shortcuts::state::{DialogState, Env}; const LISTS_SHARE: f32 = 0.5; /// The detail column's share of the width beside the lists. const DETAIL_SHARE: f32 = 0.5; +/// The most Categories rows shown before the list scrolls. +const CATEGORY_ROWS: u16 = 6; const PANES: [ColumnWidth; 2] = [ColumnWidth::fill(LISTS_SHARE), ColumnWidth::fill(DETAIL_SHARE)]; /// One frame of the command-lists body: a search field, the Categories list beside the Commands @@ -62,6 +64,8 @@ fn categories(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState) { let mut selection = Selection::new(at.into_iter().collect(), at, at); let out = List::::new(words.categories.clone()) .id_salt("categories") + // A short list, so the Commands list under it keeps room in a dialog of ordinary height. + .max_rows(CATEGORY_ROWS) .select(SelectMode::Single) .selection(Bind::bound(&mut selection)) .show_items(ui, &Titles(&labels), &mut |key, _| ListRow::new(labels[*key].clone())); diff --git a/crates/menu/tests/it/ribbon_gallery.rs b/crates/menu/tests/it/ribbon_gallery.rs index 44abf3d767..93e83d0e78 100644 --- a/crates/menu/tests/it/ribbon_gallery.rs +++ b/crates/menu/tests/it/ribbon_gallery.rs @@ -263,3 +263,26 @@ fn the_current_tile_paints_an_accent_fill_and_edge_even_when_focused() { assert!(shapes.iter().any(|p| p.fill == fill && near(p, current)), "{who}: the focused current tile keeps its fill"); } } + +/// How many shapes a gallery of one rendered tile of a transparent image paints, as built or with `checker(false)`. +fn shapes_of_rendered(opt_out: bool) -> usize { + use craft_ui::primitives::textures::{FakeThumbSource, ThumbnailOptions, Thumbnails}; + let mut fixture = Fixture::new(move |ui| { + let options = ThumbnailOptions::new().jobs(std::sync::Arc::new(craft_host::InlineJobs)); + let thumbnails = Thumbnails::::in_context(ui.ctx(), "gallery_checker_test", options); + let source = FakeThumbSource::::new(); + // The default case sets nothing, so a default that turned the grid off fails here. + let face = GalleryFace::rendered(1, &thumbnails, &source); + let face = if opt_out { face.checker(false) } else { face }; + let items = [GalleryItem { key: 0_usize, label: Label::from("Mask"), face }]; + Gallery::new("Symbols", &items, None).tiles(1, 1).show(ui); + }); + fixture.settle(); + fixture.frame_shapes().len() +} + +#[trial] +fn a_rendered_gallery_tile_paints_a_checker_unless_it_opts_out() { + let (with, without) = (shapes_of_rendered(false), shapes_of_rendered(true)); + assert!(with > without, "the default paints {with} shapes, the opt-out {without}: the grid is the difference"); +} diff --git a/crates/menu/tests/it/shortcuts/lists.rs b/crates/menu/tests/it/shortcuts/lists.rs index 6322b27524..71131385c9 100644 --- a/crates/menu/tests/it/shortcuts/lists.rs +++ b/crates/menu/tests/it/shortcuts/lists.rs @@ -1,7 +1,7 @@ //! The Customize Keyboard layout: each change is applied at once and Escape closes without rolling back. use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Scope, Scopes, Trigger}; -use craft_menu::shortcuts::{Layout, Outcome}; +use craft_menu::shortcuts::{Area, Layout, Outcome}; use craft_ui::contract::Role; use craft_ui::testing::trial; use egui::{Key, Modifiers}; @@ -79,3 +79,29 @@ fn command_lists_assign_remove_and_close_apply_each_change_at_once() { assert_eq!(keys(&rig), left, "the keymap keeps the edits"); assert!(rig.bindings("file.export").is_empty(), "the taken chord is not given back"); } + +/// A long Categories list must not take the room the Commands list needs: in a dialog of ordinary height a command row +/// still shows above the footer. +#[trial] +fn commands_keep_room_beside_a_long_categories_list() { + let rig = Rig::tuned(Platform::Mac, |options| { + options.layout = Layout::CommandLists; + options.own_areas = true; + options.size = Some(egui::vec2(640.0, 460.0)); + options.areas = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"].map(|name| Area::new(name, name, |_| true)).to_vec(); + }); + let row = rig.find("Bring to Front").center(); + let footer = rig.find("Reset All…").center(); + assert!(row.y < footer.y, "the command row ({row:?}) sits above the footer ({footer:?})"); + // The capped list scrolls: the arrow keys still reach its last entry. + let mut rig = rig; + rig.click("A"); + for _ in 0..11 { + rig.press(Modifiers::NONE, Key::ArrowDown); + } + let area = { + let shared = rig.shared.borrow(); + shared.state.snapshot(&shared.km).expect("the dialog has shown").area + }; + assert_eq!(area, "L", "the last Categories entry is reachable"); +} diff --git a/crates/mesh-ops/ATTRIBUTION.md b/crates/mesh-ops/ATTRIBUTION.md new file mode 100644 index 0000000000..6e592bafa0 --- /dev/null +++ b/crates/mesh-ops/ATTRIBUTION.md @@ -0,0 +1,32 @@ +# Attribution + +`craft-mesh-ops` generates tangents with the `mikktspace` crate. + +| Package | Authors | Source | License | +|---|---|---|---| +| `mikktspace` 0.3.0 | Benjamin Wasty, David Harvey-Macaulay, Layl Bongers | [crates.io](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field) | + +The package's `src/generated.rs` is a translation of Morten S. Mikkelsen's C implementation of +the MikkTSpace algorithm and carries that implementation's notice, reproduced here unchanged: + +```text +Copyright (C) 2011 by Morten S. Mikkelsen + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. +``` diff --git a/crates/mesh-ops/Cargo.toml b/crates/mesh-ops/Cargo.toml new file mode 100644 index 0000000000..441abc88c1 --- /dev/null +++ b/crates/mesh-ops/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "craft-mesh-ops" +description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs, a BVH and an orbit camera" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +glam = { version = "0.30", features = ["serde"] } +# MIT OR Apache-2.0; its src/generated.rs also carries the zlib-style notice of the C original, +# reproduced in ATTRIBUTION.md. +mikktspace = { version = "0.3", default-features = false, features = ["glam"] } +rayon = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md new file mode 100644 index 0000000000..399753a9be --- /dev/null +++ b/crates/mesh-ops/README.md @@ -0,0 +1,47 @@ +# craft-mesh-ops + +Operations on triangle meshes, for apps that paint, bake or preview materials on 3D models. The +crate has no UI, does no file or network I/O and has no `unsafe` code. File formats stay in +[`craft-mesh`](../mesh/README.md). + +- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes + and polygon-diagonal flags, with `validate`, `append`, `subdivided`, `normalize_to`, wireframe + and UV-seam edges, and UV-tile helpers. +- **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which + glTF 2.0 recommends for meshes without tangents + (): `w` holds the bitangent sign. +- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting + vertices where charts meet. +- **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle + and barycentrics under the texel center; `surface_at` turns them into a position, normal and + tangent frame. `UvGBuffer::new` returns an error for a side of 0 or above `MAX_SIDE` (16,384), + for more than `MAX_TEXELS` texels (8,192 × 8,192), when the triangles touch more than + `MAX_BAND_ENTRIES` bands of 32 rows in all, and when the memory cannot be reserved. +- **Primitives.** Sphere, rounded box, cube, cylinder, torus and plane with UVs and tangents, and + the built-in scenes in `primitives::BUILTINS`. `primitives::cube` and `primitives::rounded_box` + return `Result`. They reject non-finite or nonpositive dimensions and dimensions whose + doubled half extents overflow. A box bevel must be finite and between zero and 95% of its + smallest half extent; an invalid bevel returns `GeomError::Invalid`. +- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a + leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box + queries. +- **Camera.** `OrbitCamera` and `Ray` give an orbit view and picking rays. + +`GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde` +serializes `OrbitCamera`; both are always on. + +## Origin + +| Part | Source | +|---|---| +| `mesh.rs`, `bvh.rs`, `primitives.rs`, `gbuffer.rs`, `unwrap.rs`, `camera.rs` and their tests | TextureCraft `crates/geom` at [386630e](https://github.com/storytold/texturecraft/commit/386630ee85cb22679295b24013575d1aecb39ad2) | +| `Mesh::subdivided` and `subdivision_shares_edge_midpoints` | MaterialCraft `crates/geom/src/mesh.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | + +MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](ATTRIBUTION.md). + +## Migration + +| App | Status | +|---|---| +| TextureCraft | `texturecraft-geom` is the source. The app switches to this crate in its own pull request. | +| MaterialCraft | `materialcraft-geom` is the source of `subdivided`. The app switches in its own pull request. | diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs new file mode 100644 index 0000000000..9b01c84155 --- /dev/null +++ b/crates/mesh-ops/src/bvh.rs @@ -0,0 +1,678 @@ +//! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and +//! box queries (used by picking, baking and brush stamps). + +use glam::{Vec3, Vec3A}; + +use crate::Mesh; + +#[derive(Clone, Copy, Debug)] +struct Node { + lo: Vec3A, + hi: Vec3A, + /// Leaf: first triangle in `order`; inner: index of the left child (right = left + 1). + first: u32, + /// Triangles in a leaf; 0 for inner nodes. + count: u32, +} + +/// A ray hit: distance, triangle and barycentrics (weights of vertices 1 and 2). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hit { + pub t: f32, + pub tri: u32, + pub u: f32, + pub v: f32, +} + +#[derive(Clone, Debug)] +pub struct Bvh { + nodes: Vec, + /// Triangle vertices in BVH order. + tris: Vec<[Vec3; 3]>, + /// Original triangle index of each entry in `tris`. + order: Vec, +} + +const LEAF: usize = 4; + +/// Traversal stack of (node, entry distance): inline for typical depths (no allocation per +/// ray), spilling to the heap for degenerate trees. +struct Stack { + inline: [(u32, f32); 64], + len: usize, + spill: Vec<(u32, f32)>, +} + +impl Default for Stack { + fn default() -> Self { + Stack { inline: [(0, 0.0); 64], len: 0, spill: Vec::new() } + } +} + +impl Stack { + fn push(&mut self, v: (u32, f32)) { + match self.inline.get_mut(self.len) { + Some(slot) if self.spill.is_empty() => { + *slot = v; + self.len += 1; + } + _ => self.spill.push(v), + } + } + + fn pop(&mut self) -> Option<(u32, f32)> { + self.spill.pop().or_else(|| { + self.len = self.len.checked_sub(1)?; + self.inline.get(self.len).copied() + }) + } +} +const BINS: usize = 12; + +fn grow(lo: &mut Vec3, hi: &mut Vec3, p: Vec3) { + *lo = lo.min(p); + *hi = hi.max(p); +} + +fn area(lo: Vec3, hi: Vec3) -> f32 { + let d = (hi - lo).max(Vec3::ZERO); + d.x * d.y + d.y * d.z + d.z * d.x +} + +impl Bvh { + pub fn new(mesh: &Mesh) -> Bvh { + let triangle_count = mesh.triangle_count(); + let mut tris = Vec::with_capacity(triangle_count); + + for triangle in 0..triangle_count { + let Some([a, b, c]) = mesh.tri(triangle) else { continue }; + let position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); + tris.push([position(a), position(b), position(c)]); + } + + let mut order: Vec = (0..tris.len() as u32).collect(); + let centroids: Vec = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect(); + + let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }]; + let mut stack = vec![0usize]; + + while let Some(node_index) = stack.pop() { + let Node { first, count, .. } = nodes[node_index]; + let (start, count) = (first as usize, count as usize); + let (mut bounds_min, mut bounds_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + let (mut centroid_min, mut centroid_max) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + + for &triangle in &order[start..start + count] { + for position in tris[triangle as usize] { + grow(&mut bounds_min, &mut bounds_max, position); + } + grow(&mut centroid_min, &mut centroid_max, centroids[triangle as usize]); + } + + nodes[node_index].lo = bounds_min.into(); + nodes[node_index].hi = bounds_max.into(); + + if count <= LEAF { + continue; + } + + let centroid_extent = centroid_max - centroid_min; + let bin_of = |triangle: u32, axis: usize| { + let offset = centroids[triangle as usize][axis] - centroid_min[axis]; + ((offset / centroid_extent[axis] * BINS as f32) as usize).min(BINS - 1) + }; + + // Reuse each triangle's bounds across all three axes + let mut axis_bins = [[(0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); BINS]; 3]; + + for &triangle in &order[start..start + count] { + let [a, b, c] = tris[triangle as usize]; + let (triangle_min, triangle_max) = (a.min(b).min(c), a.max(b).max(c)); + + for axis in 0..3 { + if centroid_extent[axis] <= 1e-12 { + continue; + } + + let bin = &mut axis_bins[axis][bin_of(triangle, axis)]; + bin.0 += 1; + bin.1 = bin.1.min(triangle_min); + bin.2 = bin.2.max(triangle_max); + } + } + + let mut best_axis = 0; + let mut best_split = 0; + let mut best_cost = f32::MAX; + + for axis in 0..3 { + if centroid_extent[axis] <= 1e-12 { + continue; + } + + let bins = axis_bins[axis]; + + // Cache right bounds once and advance the left bounds per split + let mut suffix = bins; + for i in (0..BINS - 1).rev() { + suffix[i] = (suffix[i].0 + suffix[i + 1].0, suffix[i].1.min(suffix[i + 1].1), suffix[i].2.max(suffix[i + 1].2)); + } + + let (mut left_count, mut left_min, mut left_max) = (0u32, Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)); + + for split in 1..BINS { + let bin = bins[split - 1]; + left_count += bin.0; + left_min = left_min.min(bin.1); + left_max = left_max.max(bin.2); + + let (right_count, right_min, right_max) = suffix[split]; + if left_count == 0 || right_count == 0 { + continue; + } + + let cost = left_count as f32 * area(left_min, left_max) + right_count as f32 * area(right_min, right_max); + if cost < best_cost { + best_cost = cost; + best_axis = axis; + best_split = split; + } + } + } + + let node_order = &mut order[start..start + count]; + let left_count = if best_split == 0 || best_cost >= count as f32 * area(bounds_min, bounds_max) { + // Split by count when SAH cannot help, including tied centroids + let axis = if centroid_extent.x >= centroid_extent.y && centroid_extent.x >= centroid_extent.z { + 0 + } else if centroid_extent.y >= centroid_extent.z { + 1 + } else { + 2 + }; + + let mid = count / 2; + node_order.select_nth_unstable_by(mid, |&a, &b| centroids[a as usize][axis].total_cmp(¢roids[b as usize][axis])); + mid + } else { + let mut left_count = 0; + + for i in 0..node_order.len() { + if bin_of(node_order[i], best_axis) < best_split { + node_order.swap(left_count, i); + left_count += 1; + } + } + + left_count + }; + + if left_count == 0 || left_count == count { + continue; + } + + let left_child = nodes.len(); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first, count: left_count as u32 }); + nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: first + left_count as u32, count: (count - left_count) as u32 }); + + nodes[node_index].first = left_child as u32; + nodes[node_index].count = 0; + + stack.push(left_child); + stack.push(left_child + 1); + } + + let tris = order.iter().map(|t| tris[*t as usize]).collect(); + Bvh { nodes, tris, order } + } + + pub fn is_empty(&self) -> bool { + self.tris.is_empty() + } + + /// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range + /// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children + /// `first` and `first + 1`. + pub fn nodes(&self) -> impl ExactSizeIterator + '_ { + self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count)) + } + + /// Triangle vertices in BVH order, and the original triangle index of each. + pub fn triangles(&self) -> (&[[Vec3; 3]], &[u32]) { + (&self.tris, &self.order) + } + + fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option { + let t0 = (lo - o) * inv; + let t1 = (hi - o) * inv; + // A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does + // not bound the hit. + let open = t0.is_nan_mask() | t1.is_nan_mask(); + let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0); + let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax); + (tn <= tf).then_some(tn) + } + + /// Möller–Trumbore, double sided. + fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { + let e1 = t[1] - t[0]; + let e2 = t[2] - t[0]; + let p = d.cross(e2); + let det = e1.dot(p); + if det.abs() < 1e-12 { + return None; + } + let inv = 1.0 / det; + let s = o - t[0]; + // A little slack on the edges: rays through a shared edge must not slip between its + // two triangles to a surface behind. + const EDGE: f32 = 1e-5; + let u = s.dot(p) * inv; + if !(-EDGE..=1.0 + EDGE).contains(&u) { + return None; + } + let q = s.cross(e1); + let v = d.dot(q) * inv; + if v < -EDGE || u + v > 1.0 + EDGE { + return None; + } + let tt = e2.dot(q) * inv; + (tt > 0.0).then_some((tt, u, v)) + } + + fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty())?; + let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d)); + let mut best = None; + let mut stack = Stack::default(); + stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?)); + // Entries carry their entry distance: nodes behind a closer hit are skipped unopened. + while let Some((ni, tn)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue }; + if n.count > 0 { + let (f, c) = (n.first as usize, n.count as usize); + for i in f..(f + c).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if let Some((t, u, v)) = Self::hit_tri(tri, o, d) + && t < tmax + && filter(orig) + { + tmax = t; + best = Some(Hit { t, tri: orig, u, v }); + if any { + return best; + } + } + } + } else { + // Visit the nearer child first. + let (l, r) = (n.first, n.first + 1); + let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + match (dl, dr) { + (Some(a), Some(b)) if a <= b => { + stack.push((r, b)); + stack.push((l, a)); + } + (Some(a), Some(b)) => { + stack.push((l, a)); + stack.push((r, b)); + } + (Some(a), None) => stack.push((l, a)), + (None, Some(b)) => stack.push((r, b)), + (None, None) => {} + } + } + } + best + } + + /// Closest hit along `o + t·d` for `t` in (0, tmax). + pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option { + self.traverse(o, d, tmax, false, &|_| true) + } + + /// Closest hit on triangles accepted by `filter` (original triangle index). + pub fn closest_filtered(&self, o: Vec3, d: Vec3, tmax: f32, filter: &dyn Fn(u32) -> bool) -> Option { + self.traverse(o, d, tmax, false, filter) + } + + /// Whether anything is hit before `tmax` (occlusion rays). + pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool { + self.traverse(o, d, tmax, true, &|_| true).is_some() + } + + /// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original + /// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2. + pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option { + let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?; + let pa = Vec3A::from(p); + let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared(); + let (mut best_d2, mut best) = (max_dist * max_dist, None); + let mut stack = Stack::default(); + stack.push((0, box_d2(root))); + while let Some((ni, d2)) = stack.pop() { + let Some(n) = self.nodes.get(ni as usize).filter(|_| d2 <= best_d2) else { continue }; + if n.count > 0 { + for i in n.first as usize..(n.first as usize + n.count as usize).min(self.tris.len()) { + let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; + if !filter(orig) { + continue; + } + let (q, u, v) = closest_on_triangle(p, tri); + let dd = (q - p).length_squared(); + if dd < best_d2 { + best_d2 = dd; + best = Some(Hit { t: dd.sqrt(), tri: orig, u, v }); + } + } + } else { + // Push the farther child first so the nearer one is searched first. + let child = |c: u32| self.nodes.get(c as usize).map(|n| (c, box_d2(n))); + let (Some(l), Some(r)) = (child(n.first), child(n.first + 1)) else { continue }; + let (near, far) = if l.1 <= r.1 { (l, r) } else { (r, l) }; + stack.push(far); + stack.push(near); + } + } + best + } + + /// Call `f` with every triangle (original index) whose bounds overlap the box. + pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) { + let mut stack = vec![0u32]; + while let Some(i) = stack.pop() { + let Some(n) = self.nodes.get(i as usize) else { continue }; + if self.tris.is_empty() || n.hi.cmplt(lo.into()).any() || n.lo.cmpgt(hi.into()).any() { + continue; + } + if n.count > 0 { + for k in n.first as usize..(n.first + n.count) as usize { + let (Some(t), Some(o)) = (self.tris.get(k), self.order.get(k)) else { continue }; + let tlo = t[0].min(t[1]).min(t[2]); + let thi = t[0].max(t[1]).max(t[2]); + if !(thi.cmplt(lo).any() || tlo.cmpgt(hi).any()) { + f(*o); + } + } + } else { + stack.push(n.first); + stack.push(n.first + 1); + } + } + } +} + +/// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2), +/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give +/// a non-finite distance and are never nearest. +fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) { + let [a, b, c] = *t; + let (ab, ac, ap) = (b - a, c - a, p - a); + let (d1, d2) = (ab.dot(ap), ac.dot(ap)); + if d1 <= 0.0 && d2 <= 0.0 { + return (a, 0.0, 0.0); + } + let bp = p - b; + let (d3, d4) = (ab.dot(bp), ac.dot(bp)); + if d3 >= 0.0 && d4 <= d3 { + return (b, 1.0, 0.0); + } + let vc = d1 * d4 - d3 * d2; + if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { + let v = d1 / (d1 - d3); + return (a + ab * v, v, 0.0); + } + let cp = p - c; + let (d5, d6) = (ab.dot(cp), ac.dot(cp)); + if d6 >= 0.0 && d5 <= d6 { + return (c, 0.0, 1.0); + } + let vb = d5 * d2 - d1 * d6; + if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { + let w = d2 / (d2 - d6); + return (a + ac * w, 0.0, w); + } + let va = d3 * d6 - d5 * d4; + if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 { + let w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); + return (b + (c - b) * w, 1.0 - w, w); + } + let denom = 1.0 / (va + vb + vc); + let (v, w) = (vb * denom, vc * denom); + (a + ab * v + ac * w, v, w) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn nearest_point_matches_brute_force() { + let m = primitives::builtin("torus").unwrap(); + let bvh = Bvh::new(&m); + let mut seed = 7u32; + let mut rnd = move || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 * 4.0 - 2.0 + }; + for _ in 0..200 { + let p = Vec3::new(rnd(), rnd(), rnd()); + let hit = bvh.nearest(p, f32::MAX, &|_| true).unwrap(); + let brute = (0..m.triangle_count()) + .map(|t| { + let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]); + (closest_on_triangle(p, &[a, b, c]).0 - p).length() + }) + .fold(f32::MAX, f32::min); + assert!((hit.t - brute).abs() < 1e-5, "{} vs {brute}", hit.t); + let [a, b, c] = m.tri(hit.tri as usize).unwrap().map(|i| m.positions[i]); + let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v; + assert!(((q - p).length() - hit.t).abs() < 1e-4); + } + assert!(bvh.nearest(Vec3::splat(100.0), 1.0, &|_| true).is_none(), "out of range"); + assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out"); + } + + #[test] + fn traversal_stack_spills_in_lifo_order() { + let mut st = Stack::default(); + for v in 0..200 { + st.push((v, v as f32)); + } + assert!((0..200).rev().all(|v| st.pop() == Some((v, v as f32)))); + assert_eq!(st.pop(), None); + } + + #[test] + fn ray_hits_sphere_at_expected_distance() { + let m = primitives::sphere(1.0, 64, 32); + let bvh = Bvh::new(&m); + let h = bvh.closest(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!((h.t - 4.0).abs() < 0.01, "{}", h.t); + assert!(bvh.closest(Vec3::new(0.0, 3.0, 5.0), Vec3::NEG_Z, 100.0).is_none()); + // Rays lying exactly in a node's bounding plane (y = 0 is the equator) hit the front. + // Axis-aligned rays lying in a node's bounding plane (y = 0) still find the front. + for x in [-0.5f32, -0.4, 0.3] { + let h = bvh.closest(Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + // Rays through shared edges (the equator) hit the front, never slip through to the back. + let m = primitives::sphere(1.0, 48, 24); + let bvh = Bvh::new(&m); + for i in 0..200 { + let x = i as f32 / 100.0 - 1.0; + let o = Vec3::new(0.0, 0.0, 5.0); + let d = (Vec3::new(x * 0.9, 0.0, 0.0) - o).normalize(); + let h = bvh.closest(o, d, 100.0).unwrap(); + assert!(h.t < 5.0, "x {x}: hit the back at t {}", h.t); + } + assert!(bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 10.0)); + assert!(!bvh.occluded(Vec3::new(0.0, 0.0, 5.0), Vec3::NEG_Z, 3.0)); + } + + #[test] + fn matches_brute_force() { + let m = primitives::material_ball(); + let bvh = Bvh::new(&m); + for i in 0..200 { + let a = i as f32 * 0.731; + let o = Vec3::new(a.cos() * 6.0, (i as f32 * 0.37).sin() * 3.0 + 1.0, a.sin() * 6.0); + let d = (Vec3::new(0.0, 1.0, 0.0) + Vec3::new((a * 3.1).sin(), (a * 1.7).cos(), (a * 2.3).sin()) * 0.6 - o).normalize(); + let fast = bvh.closest(o, d, 1e9).map(|h| h.t); + let mut slow: Option = None; + for t in 0..m.triangle_count() { + let [x, y, z] = m.tri(t).unwrap(); + if let Some((tt, _, _)) = Bvh::hit_tri(&[m.positions[x], m.positions[y], m.positions[z]], o, d) { + slow = Some(slow.map_or(tt, |s: f32| s.min(tt))); + } + } + match (fast, slow) { + (Some(a), Some(b)) => assert!((a - b).abs() < 1e-4, "{a} {b}"), + (None, None) => {} + other => panic!("mismatch {other:?}"), + } + } + } + + #[test] + fn box_query_finds_overlapping_triangles() { + let m = primitives::plane(2.0, 4); + let bvh = Bvh::new(&m); + let mut found = Vec::new(); + bvh.query_box(Vec3::new(-0.1, -0.1, -0.1), Vec3::new(0.1, 0.1, 0.1), |t| found.push(t)); + assert!(!found.is_empty() && found.len() <= 8, "{found:?}"); + let empty = Bvh::new(&Mesh::default()); + assert!(empty.closest(Vec3::ZERO, Vec3::X, 1.0).is_none()); + } + + #[test] + fn large_coplanar_plate_does_not_degrade_leaf_sizes() { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + let w = 200.0f32; + let h = 100.0f32; + + // Large plate at z = 0 + let b = positions.len() as u32; + positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]); + indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]); + + // 500 small triangles sitting at z = 0.5 + for i in 0..500 { + let x = 20.0 + (i % 160) as f32; + let y = 10.0 + ((i / 160) % 80) as f32; + let idx = positions.len() as u32; + positions.push(Vec3::new(x, y, 0.5)); + positions.push(Vec3::new(x + 0.5, y, 0.5)); + positions.push(Vec3::new(x, y + 0.5, 0.6)); + indices.extend_from_slice(&[idx, idx + 1, idx + 2]); + } + + let mesh = Mesh { + positions, + normals: Vec::new(), + uvs: Vec::new(), + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: Vec::new(), + materials: Vec::new(), + diagonals: Vec::new(), + }; + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + if count > 0 { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + } + + // The foreground triangle is the closest hit + let hit = bvh.closest(Vec3::new(20.1, 10.1, 10.0), Vec3::NEG_Z, 100.0).unwrap(); + assert!((hit.t - 9.5).abs() < 0.1, "hit t: {}", hit.t); + } + + #[test] + fn clustered_coplanar_fallback_partitions_nodes() { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + let w = 200.0f32; + let h = 100.0f32; + + let b = positions.len() as u32; + positions.extend_from_slice(&[Vec3::new(0.0, 0.0, 0.0), Vec3::new(w, 0.0, 0.0), Vec3::new(w, h, 0.0), Vec3::new(0.0, h, 0.0)]); + indices.extend_from_slice(&[b, b + 1, b + 2, b, b + 2, b + 3]); + + // Shared bins keep every SAH split as costly as an unsplit leaf + for i in 0..500 { + let x = 130.0 + (i % 10) as f32 * 0.1; + let y = 64.0 + (i / 10) as f32 * 0.02; + let idx = positions.len() as u32; + positions.push(Vec3::new(x, y, 0.0)); + positions.push(Vec3::new(x + 0.01, y, 0.0)); + positions.push(Vec3::new(x, y + 0.01, 0.0)); + indices.extend_from_slice(&[idx, idx + 1, idx + 2]); + } + + let mesh = Mesh { + positions, + normals: Vec::new(), + uvs: Vec::new(), + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: Vec::new(), + materials: Vec::new(), + diagonals: Vec::new(), + }; + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + if count > 0 { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + } + } + + #[test] + fn coincident_centroids_still_partition_large_and_small_triangles() { + let mut mesh = Mesh::default(); + + // Different triangle sizes share an exact centroid + for i in 0..=500 { + let size = if i == 0 { 100.0 } else { 0.01 + i as f32 * 0.0001 }; + let first = mesh.positions.len() as u32; + mesh.positions.extend([Vec3::new(-size, -size, 0.0), Vec3::new(size, -size, 0.0), Vec3::new(0.0, 2.0 * size, 0.0)]); + mesh.indices.extend([first, first + 1, first + 2]); + } + + mesh.normals.resize(mesh.positions.len(), Vec3::Z); + mesh.uvs.resize(mesh.positions.len(), glam::Vec2::ZERO); + mesh.tangents.resize(mesh.positions.len(), glam::Vec4::new(1.0, 0.0, 0.0, 1.0)); + mesh.validate().unwrap(); + + let bvh = Bvh::new(&mesh); + + for (_, _, _, count) in bvh.nodes() { + assert!(count <= LEAF as u32, "leaf has too many triangles: {count}"); + } + + // The outer ray only hits the large triangle + let origin = Vec3::new(50.0, 0.0, 10.0); + let hit = bvh.closest(origin, Vec3::NEG_Z, 100.0).unwrap(); + assert_eq!(hit.tri, 0); + assert_eq!(hit.t, 10.0); + + assert!(bvh.occluded(origin, Vec3::NEG_Z, 100.0)); + assert!(!bvh.occluded(origin, Vec3::NEG_Z, 5.0)); + + // Median partitions preserve original triangle IDs + let hit = bvh.closest_filtered(Vec3::new(0.0, 0.0, 10.0), Vec3::NEG_Z, 100.0, &|t| t == 500).unwrap(); + assert_eq!(hit.tri, 500); + assert_eq!(hit.t, 10.0); + } +} diff --git a/crates/mesh-ops/src/camera.rs b/crates/mesh-ops/src/camera.rs new file mode 100644 index 0000000000..1f4156c93e --- /dev/null +++ b/crates/mesh-ops/src/camera.rs @@ -0,0 +1,140 @@ +//! Orbit camera (texture painting navigation) and picking rays. + +use glam::{Mat4, Vec2, Vec3, Vec4}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct OrbitCamera { + pub target: Vec3, + /// Radians around Y. + pub yaw: f32, + /// Radians above the horizon, clamped to ±89°. + pub pitch: f32, + pub distance: f32, + /// Vertical field of view, degrees. + pub fov: f32, + /// Scene radius (sets the clip planes). + pub scene_radius: f32, + /// Orthographic projection instead of perspective. + #[serde(default)] + pub ortho: bool, +} + +impl Default for OrbitCamera { + fn default() -> Self { + OrbitCamera { target: Vec3::ZERO, yaw: 0.0, pitch: 0.12, distance: 5.0, fov: 40.0, scene_radius: 1.0, ortho: false } + } +} + +/// A ray in world space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ray { + pub origin: Vec3, + pub dir: Vec3, +} + +impl OrbitCamera { + pub fn eye(&self) -> Vec3 { + let (sy, cy) = self.yaw.sin_cos(); + let (sp, cp) = self.pitch.sin_cos(); + self.target + Vec3::new(cp * sy, sp, cp * cy) * self.distance + } + + pub fn forward(&self) -> Vec3 { + (self.target - self.eye()).try_normalize().unwrap_or(Vec3::NEG_Z) + } + + pub fn view(&self) -> Mat4 { + Mat4::look_at_rh(self.eye(), self.target, Vec3::Y) + } + + pub fn proj(&self, aspect: f32) -> Mat4 { + let r = self.scene_radius.max(1e-3); + let near = (self.distance - r * 4.0).max(r * 0.01).max(1e-4); + let far = self.distance + r * 50.0; + let aspect = if aspect.is_finite() && aspect > 1e-4 { aspect } else { 1.0 }; + if self.ortho { + let h = self.distance * (self.fov.to_radians() * 0.5).tan(); + Mat4::orthographic_rh(-h * aspect, h * aspect, -h, h, near.min(0.01), far) + } else { + Mat4::perspective_rh(self.fov.clamp(5.0, 150.0).to_radians(), aspect, near, far) + } + } + + pub fn view_proj(&self, aspect: f32) -> Mat4 { + self.proj(aspect) * self.view() + } + + /// Frame a bounding box, keeping the current angles. + pub fn frame(&mut self, lo: Vec3, hi: Vec3) { + self.target = (lo + hi) * 0.5; + let r = ((hi - lo).length() * 0.5).max(1e-3); + self.scene_radius = r; + self.distance = r / (self.fov.clamp(5.0, 150.0).to_radians() * 0.5).sin() * 1.1; + } + + pub fn orbit(&mut self, dx: f32, dy: f32) { + self.yaw -= dx; + self.pitch = (self.pitch + dy).clamp(-89f32.to_radians(), 89f32.to_radians()); + } + + /// Pan by a screen fraction (dx, dy in viewport heights). + pub fn pan(&mut self, dx: f32, dy: f32) { + let f = self.forward(); + let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let up = right.cross(f); + let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0; + self.target += (-right * dx + up * dy) * scale; + } + + /// Dolly by a factor exponent (positive zooms in). + pub fn zoom(&mut self, amount: f32) { + let r = self.scene_radius.max(1e-3); + self.distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0); + } + + /// Ray through a viewport point given in normalized device coordinates (-1..1, y up). + pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray { + let inv = self.view_proj(aspect).inverse(); + let a = inv * Vec4::new(ndc.x, ndc.y, 0.0, 1.0); + let b = inv * Vec4::new(ndc.x, ndc.y, 1.0, 1.0); + let (a, b) = (a.truncate() / a.w, b.truncate() / b.w); + Ray { origin: a, dir: (b - a).try_normalize().unwrap_or(self.forward()) } + } + + /// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera. + pub fn project(&self, p: Vec3, aspect: f32) -> Option { + let c = self.view_proj(aspect) * p.extend(1.0); + (c.w > 1e-6).then(|| c.truncate() / c.w) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn center_ray_points_at_target_and_projection_inverts() { + let mut c = OrbitCamera::default(); + c.frame(Vec3::splat(-1.0), Vec3::splat(1.0)); + let r = c.ray(Vec2::ZERO, 1.5); + assert!((r.dir - c.forward()).length() < 1e-4); + let p = Vec3::new(0.3, -0.2, 0.1); + let ndc = c.project(p, 1.5).unwrap(); + let r = c.ray(ndc.truncate(), 1.5); + let to_p = (p - r.origin).normalize(); + assert!(to_p.dot(r.dir) > 0.9999); + } + + #[test] + fn pitch_is_clamped_and_zoom_bounded() { + let mut c = OrbitCamera::default(); + c.orbit(0.0, 10.0); + assert!(c.pitch <= 89f32.to_radians() + 1e-6); + for _ in 0..1000 { + c.zoom(1.0); + } + assert!(c.distance > 0.0 && c.distance.is_finite()); + let _ = c.proj(f32::NAN); + } +} diff --git a/crates/mesh-ops/src/gbuffer.rs b/crates/mesh-ops/src/gbuffer.rs new file mode 100644 index 0000000000..59757f0462 --- /dev/null +++ b/crates/mesh-ops/src/gbuffer.rs @@ -0,0 +1,309 @@ +//! The UV-space G-buffer: which triangle (and where on it) each texel of a texture set maps +//! to. Painting, compositing, baking and padding all work from this one buffer, so they agree +//! on which texel is which surface point. + +use glam::{Vec2, Vec3, Vec4}; +use rayon::prelude::*; + +use crate::{GeomError, Mesh, Result}; + +/// Texel not covered by any triangle. +pub const NO_TRI: u32 = u32::MAX; + +const BAND: u32 = 32; + +/// Largest width or height of a G-buffer, in texels. +pub const MAX_SIDE: u32 = 16_384; + +/// Largest texel count of a G-buffer (8,192 × 8,192). Each texel takes 12 bytes, so a full +/// buffer takes 768 MiB and its largest vector (`bary`) 512 MiB, which fits a 32-bit address +/// space. +pub const MAX_TEXELS: usize = 1 << 26; + +/// Largest number of (triangle, band of 32 rows) pairs a G-buffer bins before rasterizing: a +/// triangle counts once for every band it touches. The bins take 4 bytes per entry, 512 MiB at +/// most. +pub const MAX_BAND_ENTRIES: usize = 1 << 27; + +#[derive(Clone, Debug, PartialEq)] +pub struct UvGBuffer { + pub width: u32, + pub height: u32, + /// Triangle under each texel center, [`NO_TRI`] when uncovered. + pub tri: Vec, + /// Barycentric weights of the triangle's second and third vertices. + pub bary: Vec<[f32; 2]>, + /// Texels written by more than one triangle (overlapping UVs). + pub overlaps: u32, +} + +/// Interpolated surface attributes at a texel. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Surface { + pub pos: Vec3, + /// Interpolated shading normal (normalized). + pub nrm: Vec3, + /// Flat triangle normal (for ray offsets). + pub geo_nrm: Vec3, + pub tangent: Vec4, + pub uv: Vec2, + pub tri: u32, +} + +/// Checks a requested G-buffer size against [`MAX_SIDE`] and [`MAX_TEXELS`] and returns its +/// texel count. +fn checked_texels(width: u32, height: u32) -> Result { + for (name, side) in [("width", width), ("height", height)] { + if side == 0 || side > MAX_SIDE { + return Err(GeomError::Invalid(format!("G-buffer {name} {side} is outside 1..={MAX_SIDE}"))); + } + } + // Both sides are at most MAX_SIDE, so the product fits in usize on 32-bit targets too. + let n = width as usize * height as usize; + if n > MAX_TEXELS { + return Err(GeomError::Invalid(format!("G-buffer {width}×{height} has more than {MAX_TEXELS} texels"))); + } + Ok(n) +} + +/// A vector of `n` copies of `value`, or an error when the memory cannot be reserved. +fn filled(n: usize, value: T) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|e| GeomError::Invalid(format!("G-buffer of {n} texels: {e}")))?; + v.resize(n, value); + Ok(v) +} + +fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { + (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) +} + +impl UvGBuffer { + /// Rasterize the triangles of material `material` at `width × height`. + /// + /// Returns an error when `width` or `height` is 0 or above [`MAX_SIDE`], when + /// `width × height` is above [`MAX_TEXELS`], when the triangles touch more than + /// [`MAX_BAND_ENTRIES`] bands of 32 rows in all, or when the memory cannot be reserved. + pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> Result { + let n = checked_texels(width, height)?; + let (w, h) = (width, height); + let size = Vec2::new(w as f32, h as f32); + let bands = h.div_ceil(BAND) as usize; + let span = |t: usize| -> Option<(usize, usize)> { + let [a, b, c] = mesh.tri(t)?; + let (ua, ub, uc) = (mesh.uvs.get(a)?, mesh.uvs.get(b)?, mesh.uvs.get(c)?); + let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; + let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; + if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + return None; + } + Some(((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize)) + }; + // The triangles of each band, in mesh order, as one list: band `i` holds + // `bins[start[i]..start[i + 1]]`. A counting pass sizes the list before it is reserved. + let mut start = vec![0usize; bands + 1]; + for t in mesh.triangles_of(material) { + let Some((b0, b1)) = span(t) else { continue }; + for s in start.iter_mut().skip(b0 + 1).take(b1 + 1 - b0) { + *s += 1; + } + } + for i in 1..start.len() { + start[i] = start[i].saturating_add(start[i - 1]); + } + let entries = start.last().copied().unwrap_or(0); + if entries > MAX_BAND_ENTRIES { + return Err(GeomError::Invalid(format!("G-buffer triangles touch {entries} bands in all, more than {MAX_BAND_ENTRIES}"))); + } + let mut bins = filled(entries, 0u32)?; + let mut next = start.clone(); + for t in mesh.triangles_of(material) { + let Some((b0, b1)) = span(t) else { continue }; + for k in next.iter_mut().take(b1 + 1).skip(b0) { + if let Some(slot) = bins.get_mut(*k) { + *slot = t as u32; + } + *k += 1; + } + } + let mut tri = filled(n, NO_TRI)?; + let mut bary = filled(n, [0.0f32; 2])?; + let band_len = BAND as usize * w as usize; + let overlaps: u32 = tri + .par_chunks_mut(band_len) + .zip(bary.par_chunks_mut(band_len)) + .enumerate() + .map(|(bi, (tri, bary))| { + let mut overlaps = 0u32; + let row0 = bi as u32 * BAND; + let rows = (tri.len() as u32) / w; + let band = match (start.get(bi), start.get(bi + 1)) { + (Some(&s), Some(&e)) => bins.get(s..e).unwrap_or(&[]), + _ => &[], + }; + for &t in band { + let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; + let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let (pa, pb, pc) = (ua * size, ub * size, uc * size); + let area = edge(pa, pb, pc); + if area.abs() < 1e-12 { + continue; + } + let eps = -1e-6 * area.abs(); + let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; + let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); + let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); + let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); + for y in y0..y1 { + for x in x0..x1 { + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); + if w0 < eps || w1 < eps || w2 < eps { + continue; + } + let i = (y - row0) as usize * w as usize + x as usize; + if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { + if *slot != NO_TRI { + overlaps += 1; + } + *slot = t; + let inv = 1.0 / area.abs(); + *bw = [w1 * inv, w2 * inv]; + } + } + } + } + overlaps + }) + .sum(); + Ok(UvGBuffer { width: w, height: h, tri, bary, overlaps }) + } + + pub fn covered(&self, i: usize) -> bool { + self.tri.get(i).is_some_and(|t| *t != NO_TRI) + } + + pub fn coverage_mask(&self) -> Vec { + self.tri.iter().map(|t| *t != NO_TRI).collect() + } + + pub fn covered_count(&self) -> usize { + self.tri.iter().filter(|t| **t != NO_TRI).count() + } + + /// Surface attributes at texel index `i` (None when uncovered). + pub fn surface(&self, mesh: &Mesh, i: usize) -> Option { + let t = *self.tri.get(i)?; + if t == NO_TRI { + return None; + } + let [b1, b2] = *self.bary.get(i)?; + surface_at(mesh, t, b1, b2) + } +} + +/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2). +pub fn surface_at(mesh: &Mesh, t: u32, b1: f32, b2: f32) -> Option { + let [a, b, c] = mesh.tri(t as usize)?; + let b0 = 1.0 - b1 - b2; + let p = |v: &[Vec3]| -> Option { Some(*v.get(a)? * b0 + *v.get(b)? * b1 + *v.get(c)? * b2) }; + let pos = p(&mesh.positions)?; + let nrm = p(&mesh.normals)?.try_normalize().unwrap_or(Vec3::Y); + let (pa, pb, pc) = (*mesh.positions.get(a)?, *mesh.positions.get(b)?, *mesh.positions.get(c)?); + let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().unwrap_or(nrm); + let tan = *mesh.tangents.get(a)? * b0 + *mesh.tangents.get(b)? * b1 + *mesh.tangents.get(c)? * b2; + let uv = *mesh.uvs.get(a)? * b0 + *mesh.uvs.get(b)? * b1 + *mesh.uvs.get(c)? * b2; + let tdir = tan.truncate().try_normalize().unwrap_or_else(|| nrm.any_orthonormal_vector()); + let w = mesh.tangents.get(a).map(|t| if t.w < 0.0 { -1.0 } else { 1.0 }).unwrap_or(1.0); + Some(Surface { pos, nrm, geo_nrm, tangent: tdir.extend(w), uv, tri: t }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::primitives; + + #[test] + fn half_triangle_covers_texels_with_centers_inside() { + // One triangle covering the lower-left half of UV space (v down: y = v·H). + let m = Mesh::from_parts( + vec![Vec3::ZERO, Vec3::X, Vec3::Y], + None, + vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], + vec![0, 1, 2], + "m", + ) + .unwrap(); + let g = UvGBuffer::new(&m, 0, 8, 8).unwrap(); + for y in 0..8u32 { + for x in 0..8u32 { + let inside = (x as f32 + 0.5) <= (y as f32 + 0.5); + assert_eq!(g.covered((y * 8 + x) as usize), inside, "({x},{y})"); + } + } + assert_eq!(g.overlaps, 0); + } + + #[test] + fn overlapping_and_degenerate_triangles() { + let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(0.5, 0.5)]; + let m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z], None, uv, vec![0, 1, 2, 0, 1, 2, 0, 3, 3], "m").unwrap(); + let g = UvGBuffer::new(&m, 0, 16, 16).unwrap(); + assert!(g.overlaps > 0); + assert!(g.covered_count() > 0); + } + + #[test] + fn sizes_outside_the_limits_are_rejected() { + // 2^27 + 1 texels wide: 32 rows of it overflow u32. + assert!(checked_texels((1 << 27) + 1, 1).is_err()); + assert!(checked_texels(u32::MAX, u32::MAX).is_err()); + assert!(checked_texels(0, 8).is_err()); + assert!(checked_texels(8, 0).is_err()); + assert!(checked_texels(MAX_SIDE + 1, 1).is_err()); + assert!(checked_texels(1, MAX_SIDE + 1).is_err()); + // Both sides in range, but more than MAX_TEXELS texels. + assert!(checked_texels(MAX_SIDE, MAX_SIDE).is_err()); + assert!(checked_texels(MAX_SIDE, 4_097).is_err()); + assert_eq!(checked_texels(MAX_SIDE, 4_096), Ok(MAX_TEXELS)); + assert_eq!(checked_texels(MAX_SIDE, 1), Ok(MAX_SIDE as usize)); + + let m = primitives::sphere(1.0, 8, 4); + assert!(UvGBuffer::new(&m, 0, MAX_SIDE + 1, 1).is_err()); + assert!(UvGBuffer::new(&m, 0, 0, 1).is_err()); + let g = UvGBuffer::new(&m, 0, 64, 32).unwrap(); + assert_eq!((g.width, g.height, g.tri.len(), g.bary.len()), (64, 32, 2_048, 2_048)); + } + + #[test] + fn too_many_band_entries_are_rejected() { + // 2^27 / 512 + 1 triangles, each spanning all 512 bands of a 1 × 16,384 buffer. + let tall = (MAX_BAND_ENTRIES / 512 + 1) as u32; + let mut m = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], + uvs: vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)], + ..Mesh::default() + }; + m.indices = (0..tall).flat_map(|_| [0, 1, 2]).collect(); + m.submeshes = vec![crate::SubMesh { name: "m".into(), material: 0, start: 0, count: tall * 3 }]; + assert!(UvGBuffer::new(&m, 0, 1, MAX_SIDE).is_err()); + m.indices.truncate(3); + m.submeshes[0].count = 3; + let g = UvGBuffer::new(&m, 0, 1, MAX_SIDE).unwrap(); + // The texel centers at u = 0.5 lie inside the triangle down to v = 0.5. + assert_eq!(g.covered_count(), MAX_SIDE as usize / 2); + } + + #[test] + fn sphere_surface_lies_on_the_sphere() { + let m = primitives::sphere(2.0, 64, 32); + let g = UvGBuffer::new(&m, 0, 128, 128).unwrap(); + assert!(g.covered_count() > 128 * 128 * 9 / 10, "{}", g.covered_count()); + for i in (0..g.tri.len()).step_by(97) { + if let Some(s) = g.surface(&m, i) { + assert!((s.pos.length() - 2.0).abs() < 0.02); + assert!(s.nrm.dot(s.pos.normalize()) > 0.99); + } + } + } +} diff --git a/crates/mesh-ops/src/lib.rs b/crates/mesh-ops/src/lib.rs new file mode 100644 index 0000000000..a30a6ef681 --- /dev/null +++ b/crates/mesh-ops/src/lib.rs @@ -0,0 +1,28 @@ +//! # craft-mesh-ops +//! +//! Triangle mesh operations: the [`Mesh`] type with normals and MikkTSpace tangents, built-in +//! [`primitives`] (material ball, sphere, cube, …), a [`Bvh`] for ray casts and box queries, +//! the UV-space [`UvGBuffer`] that maps texels to surface points, and the [`OrbitCamera`]. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod bvh; +pub mod camera; +pub mod gbuffer; +pub mod mesh; +pub mod primitives; +pub mod unwrap; + +pub use bvh::{Bvh, Hit}; +pub use camera::{OrbitCamera, Ray}; +pub use gbuffer::{MAX_BAND_ENTRIES, MAX_SIDE, MAX_TEXELS, NO_TRI, Surface, UvGBuffer, surface_at}; +pub use glam; +pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; + +#[derive(Debug, thiserror::Error, Clone, PartialEq)] +pub enum GeomError { + #[error("invalid mesh: {0}")] + Invalid(String), +} + +pub type Result = std::result::Result; diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs new file mode 100644 index 0000000000..77c993d3c6 --- /dev/null +++ b/crates/mesh-ops/src/mesh.rs @@ -0,0 +1,647 @@ +//! The internal triangle mesh. + +use glam::{Vec2, Vec3, Vec4}; + +use crate::{GeomError, Result}; + +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + +/// A contiguous index range drawn with one material. +#[derive(Clone, Debug, PartialEq)] +pub struct SubMesh { + pub name: String, + pub material: usize, + /// First index (into [`Mesh::indices`]) and index count. + pub start: u32, + pub count: u32, +} + +/// A material's base color (what a color-map bake transfers): `factor` (linear RGBA) times an +/// optional texture sampled at the mesh UVs. +#[derive(Clone, Debug, PartialEq)] +pub struct BaseColor { + pub factor: Vec4, + pub width: u32, + pub height: u32, + /// `width × height` RGBA8 texels (color sRGB-encoded, alpha linear), rows top → bottom like + /// the UVs' v; empty without a texture. + pub texels: Vec<[u8; 4]>, +} + +/// Triangle mesh in world space. UVs use the glTF convention (origin top-left, v down). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Mesh { + pub positions: Vec, + pub normals: Vec, + /// xyz tangent, w bitangent sign. + pub tangents: Vec, + pub uvs: Vec, + /// RGBA vertex colors in 0..1 (glTF: linear; OBJ, PLY: as stored): one per vertex, or empty. + pub colors: Vec, + pub indices: Vec, + /// Index ranges per material and part (node / object); `name` is the part name. + pub submeshes: Vec, + pub materials: Vec, + /// Per triangle, bit `i` set when edge `i` (corner `i` to corner `i + 1`) is a diagonal the + /// importer added to split a polygon, which wireframes leave out. Empty: every edge is real. + pub diagonals: Vec, +} + +/// Hard cap on mesh size accepted from files (triangles). +pub const MAX_TRIANGLES: usize = 20_000_000; + +impl Mesh { + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } + + pub fn vertex_count(&self) -> usize { + self.positions.len() + } + + /// Axis-aligned bounds (zero box for an empty mesh). + pub fn bounds(&self) -> (Vec3, Vec3) { + if self.positions.is_empty() { + return (Vec3::ZERO, Vec3::ZERO); + } + self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) + } + + /// Bounding-sphere radius around the bounds center (at least a small epsilon). + pub fn radius(&self) -> f32 { + let (lo, hi) = self.bounds(); + ((hi - lo).length() * 0.5).max(1e-4) + } + + /// Vertex indices of triangle `t`. + pub fn tri(&self, t: usize) -> Option<[usize; 3]> { + let i = self.indices.get(t * 3..t * 3 + 3)?; + Some([i[0] as usize, i[1] as usize, i[2] as usize]) + } + + /// The edges wireframes draw: each vertex pair once (smaller index first), leaving out + /// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam + /// split it from its twin), per material in `0..materials.len().max(1)`. + pub fn wire_edges(&self) -> Vec> { + (0..self.materials.len().max(1)) + .map(|m| { + // Edge → (real in some triangle, triangles using it), in first-seen order. + let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); + let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); + for t in self.triangles_of(m) { + let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue }; + let hidden = self.diagonals.get(t).copied().unwrap_or(0); + for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() { + let key = (a.min(b), a.max(b)); + let real = hidden >> i & 1 == 0; + let e = *at.entry(key).or_insert_with(|| { + edges.push((key, false, 0)); + edges.len() - 1 + }); + if let Some((_, r, n)) = edges.get_mut(e) { + *r |= real; + *n = n.saturating_add(1); + } + } + } + edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + }) + .collect() + } + + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { + // Signed zero denotes the same position on either side of an imported seam + let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); + let mut seams = vec![Vec::new(); self.materials.len().max(1)]; + // Match across materials before grouping the lines for texture-set visibility + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + for material in 0..seams.len() { + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + + for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { + let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { + continue; + }; + + let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); + let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + sides.entry(edge).or_default().push((pair.0, pair.1, material)); + } + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + for pairs in sides.into_values() { + let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; + + if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { + for (from, to, material) in pairs { + if let Some(edges) = seams.get_mut(material) { + edges.push((from.min(to), from.max(to))); + } + } + } + } + for edges in &mut seams { + edges.sort_unstable(); + edges.dedup(); + } + + seams + } + + /// Material of triangle `t`. + pub fn material_of(&self, t: usize) -> Option { + let idx = (t * 3) as u32; + self.submeshes.iter().find(|s| idx >= s.start && idx < s.start.saturating_add(s.count)).map(|s| s.material) + } + + /// Triangle index range belonging to material `m` (all submeshes of that material). + pub fn triangles_of(&self, m: usize) -> impl Iterator + '_ { + self.submeshes.iter().filter(move |s| s.material == m).flat_map(|s| (s.start / 3) as usize..((s.start + s.count) / 3) as usize) + } + + /// Check that attribute arrays agree and every index is in range. + pub fn validate(&self) -> Result<()> { + let n = self.positions.len(); + if self.normals.len() != n || self.uvs.len() != n || self.tangents.len() != n { + return Err(GeomError::Invalid(format!( + "attribute counts differ: {} positions, {} normals, {} uvs, {} tangents", + n, + self.normals.len(), + self.uvs.len(), + self.tangents.len() + ))); + } + if !self.colors.is_empty() && self.colors.len() != n { + return Err(GeomError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len()))); + } + if !self.indices.len().is_multiple_of(3) { + return Err(GeomError::Invalid("index count is not a multiple of 3".into())); + } + if self.triangle_count() > MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles"))); + } + if let Some(bad) = self.indices.iter().find(|i| **i as usize >= n) { + return Err(GeomError::Invalid(format!("index {bad} out of range ({n} vertices)"))); + } + if self.positions.iter().any(|p| !p.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite positions".into())); + } + for s in &self.submeshes { + if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { + return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); + } + } + Ok(()) + } + + /// Area-weighted smooth normals over the index buffer. + pub fn compute_normals(&mut self) { + let mut normals = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let face = (*pb - *pa).cross(*pc - *pa); + for v in [a, b, c] { + if let Some(x) = normals.get_mut(v) { + *x += face; + } + } + } + + self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + } + + /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). + pub fn compute_tangents(&mut self) { + self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()]; + if self.normals.len() != self.positions.len() { + self.compute_normals(); + } + if self.uvs.len() != self.positions.len() { + self.uvs = vec![Vec2::ZERO; self.positions.len()]; + } + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. + let usable = !crate::unwrap::all_triangles_degenerate(self); + let mut g = Mikk { mesh: self }; + if !usable || !mikktspace::generate_tangents(&mut g) { + self.simple_tangents(); + } + for (t, n) in self.tangents.iter_mut().zip(&self.normals) { + // Orthonormalize against the normal; repair degenerate results. + let v = t.truncate(); + let o = (v - *n * n.dot(v)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + *t = o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }); + } + } + + fn simple_tangents(&mut self) { + let mut tangents = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; + let (e1, e2) = (*pb - *pa, *pc - *pa); + let (d1, d2) = (*ub - *ua, *uc - *ua); + let determinant = d1.x * d2.y - d2.x * d1.y; + if determinant.abs() < 1e-12 { + continue; + } + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; + for v in [a, b, c] { + if let Some(x) = tangents.get_mut(v) { + *x += tangent; + } + } + } + + self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + } + + /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), + /// ascending. Non-finite UVs are skipped. + pub fn uv_tiles(&self, m: usize) -> std::collections::BTreeSet<(i32, i32)> { + self.triangles_of(m) + .filter_map(|t| { + let [a, b, c] = self.tri(t)?; + let uv = (*self.uvs.get(a)? + *self.uvs.get(b)? + *self.uvs.get(c)?) / 3.0; + uv.is_finite().then(|| (uv.x.floor() as i32, uv.y.floor() as i32)) + }) + .collect() + } + + /// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other + /// materials are duplicated first, so the other triangles keep their UVs. + pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) { + self.map_material_uvs_with(m, |_, uv| f(uv)); + } + + /// [`Mesh::map_material_uvs`] where `f` also gets the UV centroid of the first of the + /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then + /// place a vertex on a tile border with its own triangle's tile. + pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { + let material_triangles: Vec = self.triangles_of(m).collect(); + let mut in_material = vec![false; self.triangle_count()]; + for t in &material_triangles { + if let Some(x) = in_material.get_mut(*t) { + *x = true; + } + } + + let mut shared = vec![false; self.positions.len()]; + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) { + for v in tri { + if let Some(s) = shared.get_mut(*v as usize) { + *s = true; + } + } + } + + let mut duplicates = std::collections::HashMap::new(); + for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { + let Some(&v) = self.indices.get(k) else { continue }; + let v = if shared.get(v as usize).copied().unwrap_or(false) { + *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) + } else { + v + }; + if let Some(i) = self.indices.get_mut(k) { + *i = v; + } + } + + // (vertex, centroid of its first triangle), each vertex once + let mut vertices = Vec::with_capacity(material_triangles.len() * 3); + for t in &material_triangles { + let Some(tri) = self.tri(*t) else { continue }; + let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; + vertices.extend(tri.map(|v| (v, centroid))); + } + + vertices.sort_by_key(|(v, _)| *v); + vertices.dedup_by_key(|(v, _)| *v); + for (v, centroid) in vertices { + if let Some(uv) = self.uvs.get_mut(v) { + *uv = f(centroid, *uv); + } + } + } + + /// Append a copy of vertex `v`; returns its index. + fn duplicate_vertex(&mut self, v: usize) -> u32 { + let i = self.positions.len() as u32; + self.positions.push(self.positions.get(v).copied().unwrap_or_default()); + self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); + self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0))); + self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); + if !self.colors.is_empty() { + self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); + } + i + } + + /// Append `other`, offsetting indices; its submeshes keep their material indices shifted by + /// this mesh's material count. + pub fn append(&mut self, other: &Mesh) { + let base = self.positions.len() as u32; + let ibase = self.indices.len() as u32; + let mbase = self.materials.len(); + self.positions.extend_from_slice(&other.positions); + self.normals.extend_from_slice(&other.normals); + self.tangents.extend_from_slice(&other.tangents); + self.uvs.extend_from_slice(&other.uvs); + if !(self.colors.is_empty() && other.colors.is_empty()) { + // Vertices of the side without colors become white. + self.colors.resize(base as usize, Vec4::ONE); + self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len())); + } + if !(self.diagonals.is_empty() && other.diagonals.is_empty()) { + self.diagonals.resize(ibase as usize / 3, 0); + self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count())); + } + self.indices.extend(other.indices.iter().map(|i| i + base)); + self.materials.extend(other.materials.iter().cloned()); + self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh { + name: s.name.clone(), + material: s.material + mbase, + start: s.start + ibase, + count: s.count, + })); + } + + /// Each triangle split into four at its edge midpoints (shared edges share their midpoint); + /// attributes are interpolated and submesh ranges keep their triangles. + pub fn subdivided(&self) -> Mesh { + let mut m = Mesh { indices: Vec::with_capacity(self.indices.len() * 4), ..self.clone() }; + let has = |len: usize| len == self.positions.len(); + let (has_n, has_t, has_uv, has_c) = (has(self.normals.len()), has(self.tangents.len()), has(self.uvs.len()), has(self.colors.len())); + let mut mids = std::collections::HashMap::new(); + let mut mid = |m: &mut Mesh, a: u32, b: u32| -> u32 { + *mids.entry((a.min(b), a.max(b))).or_insert_with(|| { + let (i, j) = (a as usize, b as usize); + m.positions.push((self.positions[i] + self.positions[j]) * 0.5); + if has_n { + m.normals.push((self.normals[i] + self.normals[j]).normalize_or_zero()); + } + if has_t { + let (ti, tj) = (self.tangents[i], self.tangents[j]); + m.tangents.push((ti.truncate() + tj.truncate()).normalize_or_zero().extend(ti.w)); + } + if has_uv { + m.uvs.push((self.uvs[i] + self.uvs[j]) * 0.5); + } + if has_c { + m.colors.push((self.colors[i] + self.colors[j]) * 0.5); + } + (m.positions.len() - 1) as u32 + }) + }; + for t in self.indices.as_chunks::<3>().0 { + if t.iter().any(|&i| i as usize >= self.positions.len()) { + continue; + } + let (a, b, c) = (t[0], t[1], t[2]); + let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a)); + m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]); + } + for s in &mut m.submeshes { + s.start *= 4; + s.count *= 4; + } + m + } + + /// Uniformly scale and translate so the mesh is centered with the given bounding radius. + pub fn normalize_to(&mut self, radius: f32) { + let (lo, hi) = self.bounds(); + let c = (lo + hi) * 0.5; + let s = radius / self.radius(); + for p in &mut self.positions { + *p = (*p - c) * s; + } + } + + /// A single-material mesh from raw attributes; computes missing normals and tangents. + pub fn from_parts(positions: Vec, normals: Option>, uvs: Vec, indices: Vec, material: &str) -> Result { + let count = indices.len() as u32; + let mut m = Mesh { + normals: normals.unwrap_or_default(), + uvs, + positions, + indices, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + diagonals: Vec::new(), + }; + if m.normals.len() != m.positions.len() { + m.compute_normals(); + } + m.compute_tangents(); + m.validate()?; + Ok(m) + } +} + +struct Mikk<'a> { + mesh: &'a mut Mesh, +} + +impl Mikk<'_> { + fn vi(&self, face: usize, vert: usize) -> usize { + self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize + } +} + +impl mikktspace::Geometry for Mikk<'_> { + fn num_faces(&self) -> usize { + self.mesh.indices.len() / 3 + } + fn num_vertices_of_face(&self, _face: usize) -> usize { + 3 + } + fn position(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array() + } + fn normal(&self, face: usize, vert: usize) -> [f32; 3] { + self.mesh.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y).to_array() + } + fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] { + // MikkTSpace expects OpenGL texture coordinates (v up); our UVs are glTF (v down). With + // v flipped, the bitangent `cross(N, T) * w` points up the image, as glTF requires. + let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default(); + [uv.x, 1.0 - uv.y] + } + fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) { + let i = self.vi(face, vert); + if let Some(t) = self.mesh.tangents.get_mut(i) { + *t = Vec4::from_array(tangent); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn quad() -> Mesh { + Mesh::from_parts( + vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)], + None, + vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)], + vec![0, 1, 2, 0, 2, 3], + "Default", + ) + .unwrap() + } + + #[test] + fn normals_and_tangents_of_a_quad() { + let m = quad(); + for n in &m.normals { + assert!((*n - Vec3::Z).length() < 1e-5); + } + for t in &m.tangents { + assert!((t.truncate() - Vec3::X).length() < 1e-4, "{t:?}"); + } + assert_eq!(m.material_of(1), Some(0)); + assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); + } + + #[test] + fn wire_edges_leave_out_polygon_diagonals() { + let mut m = quad(); + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); + // Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad. + m.diagonals = vec![0b100, 0b001]; + assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); + // A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays. + let mut seam = m.clone(); + seam.indices[3] = 4; + assert_eq!(seam.wire_edges()[0].len(), 6); + // Appending keeps each side's diagonals on its own triangles. + let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap(); + a.append(&m); + assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); + assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); + } + + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + + #[test] + fn uv_seams_join_positions_with_opposite_signed_zero() { + let mut mesh = quad(); + mesh.positions.push(Vec3::new(-0.0, 0.0, 0.0)); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + assert_eq!(mesh.positions[0], mesh.positions[4]); + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + } + + #[test] + fn uv_seams_between_materials_belong_to_both_materials() { + let mut mesh = quad(); + mesh.positions.push(mesh.positions[0]); + mesh.normals.push(mesh.normals[0]); + mesh.tangents.push(mesh.tangents[0]); + mesh.uvs.push(Vec2::new(0.9, 0.9)); + mesh.indices[3] = 4; + mesh.materials.push("second".into()); + mesh.submeshes[0].count = 3; + mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); + + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); + mesh.uvs[4] = mesh.uvs[0]; + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + } + + #[test] + fn subdivision_shares_edge_midpoints() { + let m = quad().subdivided(); + // 4 corners + 5 edge midpoints (the diagonal is shared), 8 triangles. + assert_eq!((m.positions.len(), m.triangle_count()), (9, 8)); + assert_eq!(m.uvs.len(), 9); + assert_eq!((m.submeshes[0].start, m.submeshes[0].count), (0, 24)); + m.validate().unwrap(); + } + + #[test] + fn validate_catches_bad_indices() { + let mut m = quad(); + m.indices[0] = 99; + assert!(m.validate().is_err()); + let mut m = quad(); + m.uvs.pop(); + assert!(m.validate().is_err()); + } + + #[test] + fn append_offsets_indices_and_materials() { + let mut a = quad(); + let b = quad(); + a.append(&b); + assert_eq!(a.indices[6], 4); + assert_eq!(a.submeshes[1].material, 1); + assert_eq!(a.submeshes[1].start, 6); + a.validate().unwrap(); + // Colors on one side only: the other side's vertices become white. + let mut red = quad(); + red.colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 4]; + a.append(&red); + assert_eq!(a.colors.len(), 12); + assert_eq!((a.colors[0], a.colors[8]), (Vec4::ONE, Vec4::new(1.0, 0.0, 0.0, 1.0))); + a.append(&quad()); + assert_eq!(a.colors[15], Vec4::ONE); + a.validate().unwrap(); + a.colors.pop(); + assert!(a.validate().is_err()); + } + + #[test] + fn material_uvs_remap_and_split_shared_vertices() { + // quad(): two triangles sharing an edge; put the second in its own material. + let mut m = quad(); + m.materials = vec!["a".into(), "b".into()]; + m.submeshes = + vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; + let before = m.clone(); + m.map_material_uvs(1, |uv| uv + Vec2::X); + m.validate().unwrap(); + assert_eq!(m.vertex_count(), 6, "the two shared vertices are split"); + assert_eq!(&m.indices[..3], &before.indices[..3]); + for k in 0..3 { + let (old, new) = (before.indices[k] as usize, m.indices[k] as usize); + assert_eq!(m.uvs[new], before.uvs[old], "material a keeps its UVs"); + let (old, new) = (before.indices[3 + k] as usize, m.indices[3 + k] as usize); + assert_eq!((m.uvs[new], m.positions[new]), (before.uvs[old] + Vec2::X, before.positions[old])); + } + assert_eq!(m.uv_tiles(1).into_iter().collect::>(), vec![(1, 0)]); + assert_eq!(m.uv_tiles(0).into_iter().collect::>(), vec![(0, 0)]); + } +} diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs new file mode 100644 index 0000000000..b48d637a19 --- /dev/null +++ b/crates/mesh-ops/src/primitives.rs @@ -0,0 +1,604 @@ +//! Built-in meshes with clean, non-overlapping UVs: material ball, sphere, (rounded) cube, +//! cylinder, torus and plane. Y is up; triangles are counter-clockwise seen from outside. + +use std::f32::consts::{PI, TAU}; + +use glam::{Vec2, Vec3}; + +use crate::mesh::{Mesh, SubMesh}; +use crate::{GeomError, Result}; + +/// A UV-space rectangle: origin and size. +#[derive(Clone, Copy, Debug)] +struct UvRect { + o: Vec2, + s: Vec2, +} + +impl UvRect { + const FULL: UvRect = UvRect { o: Vec2::ZERO, s: Vec2::ONE }; + fn map(&self, u: f32, v: f32) -> Vec2 { + self.o + self.s * Vec2::new(u, v) + } + fn inset(&self, m: f32) -> UvRect { + UvRect { o: self.o + Vec2::splat(m), s: self.s - Vec2::splat(2.0 * m) } + } +} + +#[derive(Default)] +struct Builder { + p: Vec, + n: Vec, + uv: Vec, + idx: Vec, + /// Per triangle: its [`Mesh::diagonals`] bits. + diag: Vec, +} + +impl Builder { + fn vert(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 { + self.p.push(p); + self.n.push(n.try_normalize().unwrap_or(Vec3::Y)); + self.uv.push(uv); + (self.p.len() - 1) as u32 + } + + /// A grid of (rows+1)×(cols+1) vertices from `f(row, col)`, rows going "down" the texture. + fn grid(&mut self, rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> (Vec3, Vec3, Vec2)) { + let base = self.p.len() as u32; + for i in 0..=rows { + for j in 0..=cols { + let (p, n, uv) = f(i, j); + self.vert(p, n, uv); + } + } + let w = (cols + 1) as u32; + for i in 0..rows as u32 { + for j in 0..cols as u32 { + let a = base + i * w + j; + let (b, c, d) = (a + 1, a + w, a + w + 1); + self.idx.extend_from_slice(&[a, c, d, a, d, b]); + // Edge d-a of the first triangle and a-d of the second split the quad. + self.diag.extend_from_slice(&[0b100, 0b001]); + } + } + } + + /// The mesh of one material, with tangents. + fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { + let count = self.idx.len() as u32; + Mesh { + positions: self.p, + normals: self.n, + uvs: self.uv, + indices: self.idx, + tangents: Vec::new(), + colors: Vec::new(), + submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], + materials: vec![material.into()], + diagonals: self.diag, + } + } +} + +/// UV sphere of `radius` centred at `center`. +pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh { + let mut b = Builder::default(); + sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL); + b.finish("Sphere") +} + +fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) { + b.grid(rings, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (center + n * radius, n, r.map(u, v)) + }); +} + +/// A box with rounded edges (`bevel` = edge radius; 0 gives a plain cube). Faces are laid out +/// in a 3×2 UV atlas. +/// Each half extent must be finite and positive, and its doubled value must be finite. +/// `bevel` must be finite and between zero and 95% of the smallest half extent. +pub fn rounded_box(half: Vec3, bevel: f32) -> Result { + if !half.is_finite() || !half.cmpgt(Vec3::ZERO).all() || !(half * 2.0).is_finite() { + return Err(GeomError::Invalid("box half extents must be positive and finite, with finite doubled extents".into())); + } + if !bevel.is_finite() || bevel < 0.0 || bevel > half.min_element() * 0.95 { + return Err(GeomError::Invalid("box bevel must be finite and between zero and 95% of the smallest half extent".into())); + } + let mut b = Builder::default(); + rounded_box_into(&mut b, Vec3::ZERO, half, bevel, UvRect::FULL); + Ok(b.finish("Box")) +} + +/// The cube primitive (sharp edges). `size` must be finite and have a finite positive half extent. +pub fn cube(size: f32) -> Result { + let mut m = rounded_box(Vec3::splat(size * 0.5), 0.0)?; + m.materials = vec!["Cube".into()]; + if let Some(s) = m.submeshes.first_mut() { + s.name = "Cube".into(); + } + Ok(m) +} + +fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) { + let bevel = bevel.clamp(0.0, half.min_element() * 0.95); + // (normal, U = right, V = down) per face, seen from outside. + let faces = [ + (Vec3::Z, Vec3::X, -Vec3::Y), + (Vec3::X, -Vec3::Z, -Vec3::Y), + (-Vec3::Z, -Vec3::X, -Vec3::Y), + (-Vec3::X, Vec3::Z, -Vec3::Y), + (Vec3::Y, Vec3::X, Vec3::Z), + (-Vec3::Y, Vec3::X, -Vec3::Z), + ]; + let (kb, kc) = if bevel > 0.0 { (6usize, 10usize) } else { (0, 12) }; + // Coordinates along one face axis from -h to h, dense in the bevels. + let coords = |h: f32| -> Vec { + let inner = h - bevel; + let mut v = Vec::new(); + for i in 0..kb { + v.push(-h + bevel * (i as f32 / kb as f32)); + } + for i in 0..=kc { + v.push(inner * (2.0 * (i as f32 / kc as f32) - 1.0)); + } + for i in 1..=kb { + v.push(inner + bevel * (i as f32 / kb as f32)); + } + v + }; + let inner = half - Vec3::splat(bevel); + for (f, (n, u, v)) in faces.iter().enumerate() { + let cell = UvRect { o: r.map((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0), s: r.s * Vec2::new(1.0 / 3.0, 0.5) }.inset(0.01 * r.s.x); + let (hu, hv, hn) = ((*u * half).abs().max_element(), (*v * half).abs().max_element(), (*n * half).abs().max_element()); + let (cu, cv) = (coords(hu), coords(hv)); + let (cols, rows) = (cu.len() - 1, cv.len() - 1); + b.grid(rows, cols, |i, j| { + let (a, c) = (cu[j], cv[i]); + let q = *n * hn + *u * a + *v * c; + let clamped = q.clamp(-inner, inner); + let dir = (q - clamped).try_normalize().unwrap_or(*n); + let p = if bevel > 0.0 { clamped + dir * bevel } else { q }; + let nn = if bevel > 0.0 { dir } else { *n }; + (center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv))) + }); + } +} + +/// Surface of revolution of a profile `(radius, y)` listed top → bottom, mapped into `r` +/// (u around, v down the profile by arc length). +fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize, r: UvRect) { + if profile.len() < 2 { + return; + } + let mut len = vec![0.0f32]; + for w in profile.windows(2) { + let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length(); + len.push(len.last().copied().unwrap_or(0.0) + d); + } + let total = len.last().copied().unwrap_or(1.0).max(1e-6); + let rows = profile.len() - 1; + b.grid(rows, segs, |i, j| { + let (rad, y) = profile[i]; + // Profile tangent (downwards) → outward normal in the (r, y) plane. + let prev = profile[i.saturating_sub(1)]; + let next = profile[(i + 1).min(rows)]; + let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y); + let n2 = Vec2::new(-t.y, t.x); + let u = j as f32 / segs as f32; + let phi = u * TAU + PI * 1.5; + let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let p = center + dir * rad + Vec3::Y * y; + let n = dir * n2.x + Vec3::Y * n2.y; + (p, n, r.map(u, len[i] / total)) + }); +} + +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = + if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + +/// A flat disk facing up (+Y) or down, with planar UVs inside `r`. +fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { + let n = if up { Vec3::Y } else { Vec3::NEG_Y }; + let c = b.vert(center, n, r.map(0.5, 0.5)); + let first = b.p.len() as u32; + for j in 0..segs { + let a = j as f32 / segs as f32 * TAU; + let (x, z) = (a.cos(), a.sin()); + // Top view: +X right, +Z down the texture; bottom view mirrors X. + let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) }; + b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv); + } + for j in 0..segs as u32 { + let (a, bb) = (first + j, first + (j + 1) % segs as u32); + if up { + b.idx.extend_from_slice(&[c, bb, a]); + } else { + b.idx.extend_from_slice(&[c, a, bb]); + } + b.diag.push(0); + } +} + +/// A capped cylinder along Y. +pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh { + let mut b = Builder::default(); + let h = height * 0.5; + lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut b, Vec3::Y * h, radius, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut b, -Vec3::Y * h, radius, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + b.finish("Cylinder") +} + +/// A torus around Y. +pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh { + let mut b = Builder::default(); + let (segs, sides) = (segs.max(3), sides.max(3)); + b.grid(sides, segs, |i, j| { + let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32); + let phi = u * TAU + PI * 1.5; + let theta = v * TAU; + let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let n = dir * theta.cos() - Vec3::Y * theta.sin(); + (dir * major + n * minor, n, Vec2::new(u, v)) + }); + b.finish("Torus") +} + +/// A subdivided plane facing +Y. +pub fn plane(size: f32, subdivisions: usize) -> Mesh { + let mut b = Builder::default(); + let s = subdivisions.max(1); + b.grid(s, s, |i, j| { + let (u, v) = (j as f32 / s as f32, i as f32 / s as f32); + (Vec3::new((u - 0.5) * size, 0.0, (v - 0.5) * size), Vec3::Y, Vec2::new(u, v)) + }); + b.finish("Plane") +} + +/// Two planes side by side on UV tiles 1001 and 1002 (UDIM): one material, 4 × 2 units. +pub fn udim_plane() -> Mesh { + let mut m = plane(2.0, 16); + let mut right = m.clone(); + for p in &mut m.positions { + p.x -= 1.0; + } + for p in &mut right.positions { + p.x += 1.0; + } + for uv in &mut right.uvs { + uv.x += 1.0; + } + right.materials.clear(); + right.submeshes.clear(); + m.append(&right); + let count = m.indices.len() as u32; + if let Some(s) = m.submeshes.first_mut() { + s.count = count; + } + m +} + +/// The default project mesh: a ball on a beveled pedestal, two materials ("Ball", "Base"). +pub fn material_ball() -> Mesh { + let mut ball = Builder::default(); + sphere_into(&mut ball, Vec3::new(0.0, 1.32, 0.0), 1.0, 128, 64, UvRect::FULL); + let mut ball = ball.finish("Ball"); + + let mut base = Builder::default(); + let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32); + let mut profile = vec![(0.42, top + 0.06), (0.62, top + 0.06)]; + // Collar bevel and the ring the ball sits on, then the beveled drum. + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((0.62 + 0.06 * a.sin(), top + 0.06 * a.cos())); + } + profile.push((r - bev, top)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.sin(), top - bev + bev * a.cos())); + } + profile.push((r, bot + bev)); + for k in 1..=6 { + let a = k as f32 / 6.0 * PI * 0.5; + profile.push((r - bev + bev * a.cos(), bot + bev - bev * a.sin())); + } + lathe_into(&mut base, Vec3::ZERO, &profile, 128, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, top + 0.06, 0.0), 0.42, true, 128, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut base, Vec3::new(0.0, bot, 0.0), r - bev, false, 128, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + let base = base.finish("Base"); + ball.append(&base); + ball +} + +/// A small showcase scene: a beveled crate with a rounded lid and a cylinder handle, in three +/// materials (used for demo projects and tests of multiple texture sets). +pub fn crate_scene() -> Mesh { + let mut body = Builder::default(); + rounded_box_into(&mut body, Vec3::new(0.0, 0.8, 0.0), Vec3::new(1.2, 0.8, 0.8), 0.12, UvRect::FULL); + let mut m = body.finish("Crate"); + let mut lid = Builder::default(); + rounded_box_into(&mut lid, Vec3::new(0.0, 1.72, 0.0), Vec3::new(1.28, 0.12, 0.88), 0.08, UvRect::FULL); + m.append(&lid.finish("Lid")); + let mut handle = torus(0.32, 0.07, 64, 24); + for p in &mut handle.positions { + *p = Vec3::new(p.x, p.z, -p.y) + Vec3::new(0.0, 1.84, 0.0); + } + for n in &mut handle.normals { + *n = Vec3::new(n.x, n.z, -n.y); + } + handle.materials = vec!["Handle".into()]; + if let Some(s) = handle.submeshes.first_mut() { + s.name = "Handle".into(); + } + handle.compute_tangents(); + m.append(&handle); + m +} + +/// Built-in mesh by id (`builtin:` in project files). +pub fn builtin(id: &str) -> Option { + Some(match id { + "material_ball" | "materialball" | "ball" => material_ball(), + "sphere" => sphere(1.0, 128, 64), + "cube" => cube(2.0).ok()?, + "rounded_cube" | "roundedcube" | "box" => rounded_box(Vec3::ONE, 0.15).ok()?, + "cylinder" => cylinder(1.0, 2.0, 96), + "torus" => torus(1.0, 0.35, 128, 48), + "plane" => plane(2.0, 16), + "crate" => crate_scene(), + "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), + _ => return None, + }) +} + +/// Ids accepted by [`builtin`], in menu order. +pub const BUILTINS: [(&str, &str); 9] = [ + ("material_ball", "Material ball"), + ("sphere", "Sphere"), + ("cube", "Cube"), + ("rounded_cube", "Rounded cube"), + ("cylinder", "Cylinder"), + ("torus", "Torus"), + ("plane", "Plane"), + ("crate", "Crate"), + ("udim_plane", "UDIM plane"), +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn invalid_cube_dimensions_do_not_panic() { + for size in [-1.0, 0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let result = std::panic::catch_unwind(|| cube(size)); + assert!(result.is_ok(), "cube({size}) panicked"); + assert!(result.unwrap().is_err(), "cube({size}) must reject invalid dimensions"); + } + } + + #[test] + fn invalid_rounded_box_dimensions_do_not_panic() { + for axis in 0..3 { + for value in [-1.0, 0.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX] { + let mut half = Vec3::ONE; + half[axis] = value; + let result = std::panic::catch_unwind(|| rounded_box(half, 0.0)); + assert!(result.is_ok(), "rounded_box({half:?}) panicked"); + assert!(result.unwrap().is_err(), "rounded_box({half:?}) must reject invalid dimensions"); + } + } + } + + #[test] + fn invalid_box_bevels_are_rejected_instead_of_clamped() { + for bevel in [-1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.950001] { + assert!(rounded_box(Vec3::ONE, bevel).is_err(), "{bevel}"); + } + for bevel in [0.0, 0.95] { + assert!(rounded_box(Vec3::ONE, bevel).is_ok(), "{bevel}"); + } + assert!(cube(2.0).is_ok()); + } + + #[test] + fn large_finite_box_extents_keep_generated_positions_finite() { + let mesh = rounded_box(Vec3::new(1e38, 1.0, 1.0), 0.0).unwrap(); + assert!(mesh.positions.iter().all(|p| p.is_finite())); + } + + /// Every triangle's winding agrees with its vertex normals, UVs stay in 0..1 (u in 0..max_u), + /// and the UV mapping is not mirrored (tangent handedness +1). + fn check(m: &Mesh, max_u: f32) { + m.validate().unwrap(); + let mut bad = 0; + for t in 0..m.triangle_count() { + let [a, b, c] = m.tri(t).unwrap(); + let face = (m.positions[b] - m.positions[a]).cross(m.positions[c] - m.positions[a]); + if face.length() < 1e-9 { + continue; + } + let n = m.normals[a] + m.normals[b] + m.normals[c]; + if face.dot(n) <= 0.0 { + bad += 1; + } + } + assert_eq!(bad, 0, "{} triangles wound against their normals", bad); + for uv in &m.uvs { + assert!((0.0..=max_u).contains(&uv.x) && (0.0..=1.0).contains(&uv.y), "{uv:?}"); + } + let mirrored = m.tangents.iter().filter(|t| t.w < 0.0).count(); + assert!(mirrored * 50 < m.tangents.len().max(1), "{mirrored} mirrored tangents"); + } + + #[test] + fn primitives_are_well_formed() { + for (id, _) in BUILTINS { + let m = builtin(id).unwrap(); + assert!(m.triangle_count() > 0, "{id}"); + check(&m, if id == "udim_plane" { 2.0 } else { 1.0 }); + } + assert!(builtin("nope").is_none()); + assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); + } + + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + + #[test] + fn material_ball_has_two_materials() { + let m = material_ball(); + assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]); + assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0); + } +} diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs new file mode 100644 index 0000000000..4327f625f8 --- /dev/null +++ b/crates/mesh-ops/src/unwrap.rs @@ -0,0 +1,412 @@ +//! Automatic UV unwrapping for meshes imported without texture coordinates. +//! +//! Triangles are grouped into charts by flood fill across shared (welded) edges while each face +//! normal stays within 60° of the chart's seed face, so every chart is a height field over its +//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes +//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same +//! everywhere within a material. + +use std::collections::{HashMap, VecDeque}; + +use glam::{Vec2, Vec3}; + +use crate::{GeomError, Mesh, Result}; + +/// Faces of a chart stay within this angle of the seed face normal (cos 60°). +const CHART_COS: f32 = 0.5; +/// Packing never goes beyond this virtual resolution (texels per side). +const MAX_PACK_RES: f32 = 65_536.0; + +/// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of +/// the bounding diagonal) share an id. Ids are dense, in order of first appearance. +pub fn weld_ids(positions: &[Vec3]) -> Vec { + let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + let cell = ((hi - lo).length() * 1e-6).max(1e-12); + let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len()); + positions + .iter() + .map(|p| { + let q = ((*p - lo) / cell).round(); + let next = map.len() as u32; + *map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next) + }) + .collect() +} + +/// True when the mesh has triangles and every one of them has two corners at the same position. +/// MikkTSpace (and so [`Mesh::compute_tangents`]) crashes on such meshes, so callers reject them. +pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { + let p = |i: &u32| mesh.positions.get(*i as usize); + !mesh.indices.is_empty() + && mesh.indices.chunks(3).all(|t| match t { + [a, b, c] => p(a) == p(b) || p(a) == p(c) || p(b) == p(c), + _ => true, + }) +} + +struct Chart { + material: usize, + /// Projection basis (right-handed with the seed normal). + t: Vec3, + b: Vec3, + /// Rotation to the chart's principal axes (cos, sin). + rot: Vec2, + lo: Vec2, + hi: Vec2, + /// Texel offset of the chart's packed rectangle and the material's scale and resolution. + offset: Vec2, +} + +impl Chart { + fn local(&self, p: Vec3) -> Vec2 { + let q = Vec2::new(p.dot(self.t), p.dot(self.b)); + Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) + } + fn size(&self) -> Vec2 { + (self.hi - self.lo).max(Vec2::ZERO) + } +} + +/// The material each triangle is unwrapped for; triangles in no submesh count as material 0. Returns an error when submeshes of two +/// materials share a triangle. +fn triangle_materials(mesh: &Mesh) -> Result> { + let mut material = vec![None; mesh.triangle_count()]; + for s in &mesh.submeshes { + for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) { + if let Some(m) = material.get_mut(t) { + if let Some(other) = *m + && other != s.material + { + return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {other} and {}", s.material))); + } + *m = Some(s.material); + } + } + } + Ok(material.into_iter().map(|m| m.unwrap_or(0)).collect()) +} + +/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its +/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and +/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed. +/// Returns the number of charts, or an error, before any change to the mesh, when submeshes of +/// two materials share a triangle. +pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result { + mesh.validate_indices()?; + if all_triangles_degenerate(mesh) { + return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); + } + let material = triangle_materials(mesh)?; + if mesh.normals.len() != mesh.positions.len() { + mesh.compute_normals(); + } + let n = mesh.triangle_count(); + let weld = weld_ids(&mesh.positions); + let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); + let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX); + + // Face normals (None for degenerate faces) and materials. + let mut normal: Vec> = Vec::with_capacity(n); + let mut area = Vec::with_capacity(n); + for t in 0..n { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a)); + area.push(cr.length() * 0.5); + normal.push(cr.try_normalize()); + } + + // Manifold edge adjacency over welded vertices: edge → (face, face, count). + let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2); + let tri_edges = |t: usize| -> [(u32, u32); 3] { + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let key = |x: usize, y: usize| { + let (p, q) = (wid(x), wid(y)); + (p.min(q), p.max(q)) + }; + [key(a, b), key(b, c), key(c, a)] + }; + for t in 0..n { + for e in tri_edges(t) { + if e.0 == e.1 { + continue; + } + let slot = edges.entry(e).or_insert((t as u32, u32::MAX, 0)); + if slot.2 == 1 { + slot.1 = t as u32; + } + slot.2 = slot.2.saturating_add(1); + } + } + + // Grow charts from the largest unassigned faces. + let mut order: Vec = (0..n).collect(); + order.sort_by(|a, b| area[*b].total_cmp(&area[*a])); + let mut chart_of = vec![u32::MAX; n]; + let mut charts: Vec = Vec::new(); + let mut queue = VecDeque::new(); + for &seed in &order { + if chart_of[seed] != u32::MAX { + continue; + } + let id = charts.len() as u32; + let sn = normal[seed].unwrap_or(Vec3::Z); + let t = sn.any_orthonormal_vector(); + charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO }); + chart_of[seed] = id; + queue.push_back(seed); + while let Some(f) = queue.pop_front() { + for e in tri_edges(f) { + let Some(&(f0, f1, 2)) = edges.get(&e) else { continue }; + let g = if f0 as usize == f { f1 } else { f0 } as usize; + let ok = normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS)); + if ok && chart_of.get(g) == Some(&u32::MAX) && material.get(g) == Some(&material[seed]) { + chart_of[g] = id; + queue.push_back(g); + } + } + } + } + + // Principal axes and bounds of every chart. + let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) { + let q = ch.local(pos(v)); + acc.0 += q; + acc.1[0] += (q.x * q.x) as f64; + acc.1[1] += (q.y * q.y) as f64; + acc.1[2] += (q.x * q.y) as f64; + acc.2 += 1; + } + } + } + for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) { + let k = (*k).max(1) as f64; + let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k); + let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my); + let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy); + // Rotate so the principal axis lies along x. + ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32); + ch.lo = Vec2::splat(f32::MAX); + ch.hi = Vec2::splat(f32::MIN); + } + for (t, &c) in chart_of.iter().enumerate() { + let c = c as usize; + for v in mesh.tri(t).unwrap_or([0; 3]) { + if let Some(ch) = charts.get_mut(c) { + let q = ch.local(pos(v)); + ch.lo = ch.lo.min(q); + ch.hi = ch.hi.max(q); + } + } + } + for ch in &mut charts { + if ch.size().y > ch.size().x { + // Quarter turn (x, y) → (y, −x) so shelves stay low. + ch.rot = Vec2::new(ch.rot.y, -ch.rot.x); + let (lo, hi) = (ch.lo, ch.hi); + ch.lo = Vec2::new(lo.y, -hi.x); + ch.hi = Vec2::new(hi.y, -lo.x); + } + } + + // Pack each material's charts into its own 0..1 square. + let pad = padding_texels.max(1.0); + let mut scale = HashMap::new(); + let mats: std::collections::BTreeSet = charts.iter().map(|c| c.material).collect(); + for m in mats { + let ids: Vec = (0..charts.len()).filter(|i| charts[*i].material == m).collect(); + let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); + let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?; + for (i, o) in ids.iter().zip(offsets) { + charts[*i].offset = o; + } + scale.insert(m, (s, res)); + } + + // Rebuild vertices: one per (vertex, chart). + let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2); + let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut indices = Vec::with_capacity(mesh.indices.len()); + for (t, &c) in chart_of.iter().enumerate() { + let Some(ch) = charts.get(c as usize) else { continue }; + let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0)); + for v in mesh.tri(t).unwrap_or([0; 3]) { + let idx = *remap.entry((v as u32, c)).or_insert_with(|| { + let q = ch.local(pos(v)); + // Chart y points up; UV v points down the image. + let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; + positions.push(pos(v)); + normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y)); + if let Some(c) = mesh.colors.get(v) { + colors.push(*c); + } + uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE)); + (positions.len() - 1) as u32 + }); + indices.push(idx); + } + } + mesh.positions = positions; + mesh.normals = normals; + mesh.uvs = uvs; + mesh.colors = colors; + mesh.indices = indices; + mesh.compute_tangents(); + mesh.validate()?; + Ok(charts.len()) +} + +/// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of +/// `res` texels with the largest uniform scale that fits. Returns (texels per world unit, +/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone +/// cannot fit (very many charts), so the result always fits in 0..1. +fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec)> { + let mut order: Vec = (0..sizes.len()).collect(); + order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y)); + let place = |s: f32, res: f32| -> Option> { + let mut out = vec![Vec2::ZERO; sizes.len()]; + let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32); + for &i in &order { + let r = sizes[i] * s + Vec2::splat(2.0 * pad); + if r.x > res { + return None; + } + if x + r.x > res { + y += shelf; + x = 0.0; + shelf = 0.0; + } + if y + r.y > res { + return None; + } + out[i] = Vec2::new(x, y); + x += r.x; + shelf = shelf.max(r.y); + } + Some(out) + }; + while place(0.0, res).is_none() { + res *= 2.0; + if res > MAX_PACK_RES { + return Err(GeomError::Invalid("too many UV charts to pack".into())); + } + } + let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max); + if largest <= 0.0 { + return Ok((0.0, res, place(0.0, res).unwrap_or_default())); + } + let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest); + if place(hi, res).is_some() { + lo = hi; + } + for _ in 0..40 { + if hi - lo <= lo * 1e-4 { + break; + } + let mid = 0.5 * (lo + hi); + if place(mid, res).is_some() { lo = mid } else { hi = mid } + } + Ok((lo, res, place(lo, res).unwrap_or_default())) +} + +impl Mesh { + /// Index-range checks only (attribute arrays may be incomplete before unwrapping). + fn validate_indices(&self) -> Result<()> { + let n = self.positions.len(); + if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|i| *i as usize >= n) { + return Err(GeomError::Invalid("mesh indices are out of range".into())); + } + if self.triangle_count() > crate::MAX_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES))); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{UvGBuffer, primitives}; + + fn check(mut m: Mesh, min_coverage: f32) { + m.uvs.clear(); + let charts = auto_unwrap(&mut m, 4.0, 512).unwrap(); + assert!(charts >= 1); + m.validate().unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + let g = UvGBuffer::new(&m, 0, 512, 512).unwrap(); + let covered = g.covered_count() as f32; + let coverage = covered / (512.0 * 512.0); + assert!(coverage > min_coverage, "coverage {coverage} with {charts} charts"); + assert!((g.overlaps as f32) < covered * 0.005, "overlaps {} of {covered}", g.overlaps); + } + + #[test] + fn sphere_unwraps_without_overlaps() { + check(primitives::sphere(1.0, 48, 24), 0.3); + } + + #[test] + fn cube_unwraps_without_overlaps() { + check(primitives::cube(2.0).unwrap(), 0.3); + } + + #[test] + fn torus_and_material_ball_unwrap() { + check(primitives::torus(1.0, 0.3, 48, 24), 0.2); + let mut ball = primitives::material_ball(); + ball.uvs.clear(); + auto_unwrap(&mut ball, 2.0, 1024).unwrap(); + for m in 0..ball.materials.len() { + let g = UvGBuffer::new(&ball, m, 512, 512).unwrap(); + assert!((g.overlaps as f32) < g.covered_count() as f32 * 0.005 + 1.0, "material {m}: {} overlaps", g.overlaps); + } + } + + #[test] + fn triangles_in_two_materials_are_rejected_unchanged() { + // Two congruent triangles in material 0; material 1 also lists the first. + let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z * 5.0, Vec3::Z * 5.0 + Vec3::X, Vec3::Z * 5.0 + Vec3::Y]; + let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "a").unwrap(); + m.materials.push("b".into()); + m.submeshes.push(crate::SubMesh { name: "b".into(), material: 1, start: 0, count: 3 }); + let before = m.clone(); + assert!(auto_unwrap(&mut m, 2.0, 64).is_err()); + assert_eq!(m, before); + // The same material listed twice is not a conflict. + m.submeshes[1].material = 0; + assert_eq!(auto_unwrap(&mut m, 2.0, 64).unwrap(), 2); + } + + #[test] + fn many_tiny_charts_still_fit() { + // 2000 disconnected triangles: the packer grows its virtual resolution. + let mut p = Vec::new(); + let mut idx = Vec::new(); + for i in 0..2000u32 { + let o = Vec3::new(i as f32 * 3.0, 0.0, 0.0); + p.extend([o, o + Vec3::X, o + Vec3::Y]); + idx.extend([i * 3, i * 3 + 1, i * 3 + 2]); + } + let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap(); + auto_unwrap(&mut m, 4.0, 128).unwrap(); + assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); + } + + #[test] + fn degenerate_and_empty_meshes_do_not_fail() { + let mut empty = Mesh::default(); + assert_eq!(auto_unwrap(&mut empty, 4.0, 256).unwrap(), 0); + // A sliver (zero-area) triangle next to a real one. + let p = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * 2.0]; + let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 1, 3], "m").unwrap(); + auto_unwrap(&mut m, 4.0, 256).unwrap(); + m.validate().unwrap(); + let mut point = Mesh { positions: vec![Vec3::ONE; 3], indices: vec![0, 1, 2], ..Mesh::default() }; + assert!(all_triangles_degenerate(&point)); + assert!(auto_unwrap(&mut point, 4.0, 256).is_err()); + } +} diff --git a/crates/pages/src/ui/mod.rs b/crates/pages/src/ui/mod.rs index 6b1fbfffca..62446f4cd6 100644 --- a/crates/pages/src/ui/mod.rs +++ b/crates/pages/src/ui/mod.rs @@ -52,8 +52,8 @@ pub use reading::{ReadingNav, ReadingNavOutput, ReadingState, ReadingView, Readi pub use setup::{PageLayoutChoice, PageLayoutMenus, PageSetupDialog}; pub use sync_views::{Lead, SyncedViews, SyncedViewsOutput, SyncedViewsState}; pub use table::{ - BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, RowHeight, SampleArea, TableChange, TableGeometry, - TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection, + BorderEdges, BorderPreset, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, EdgeSize, RowHeight, SampleArea, TableChange, + TableGeometry, TableProperties, TablePropertiesOutput, TableSizePicker, TableSizePickerOutput, TableValues, TextDirection, }; pub use text_selection::{ MarkArea, MarkKind, PageTextSource, PageTexts, TextMark, TextMarks, TextSelectState, TextSelectTool, TextSelection, TextSpan, diff --git a/crates/pages/src/ui/table/edges.rs b/crates/pages/src/ui/table/edges.rs index 06d5626abc..8bf957674c 100644 --- a/crates/pages/src/ui/table/edges.rs +++ b/crates/pages/src/ui/table/edges.rs @@ -163,6 +163,8 @@ pub struct EdgePickerStyle { focus: FocusLook, /// The side of the square. side: f32, + /// The side of the square at [`EdgeSize::Sample`]. + sample_side: f32, /// How far the outer lines sit inside the square, and how near a line the pointer picks it. inset: f32, /// The area inside the lines. @@ -198,6 +200,20 @@ pub struct EdgePicker<'a> { /// How the picture is drawn: the proxy diagram, or a sample of the borders on text, a paragraph or a page. #[prop] look: EdgeLook, + /// The extent of the square: a thumbnail, or a sample-sized preview. + #[prop] + preview: EdgeSize, +} + +/// How large the picker's square is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum EdgeSize { + /// A thumbnail (`size.thumb.lg`). + #[default] + Thumb, + /// A preview at sample size (`size.thumb.sample.lg`), for a Borders or Shading dialog's page-like preview. + Sample, } /// How the borders preview is drawn. @@ -246,7 +262,7 @@ struct ClickRun { impl<'a> EdgePicker<'a> { /// A picker named `label` editing `edges`. pub fn new(label: impl Into

, sizes: &DockSizes) -> f32 { let content = group .panels .iter() - .filter_map(|panel| (self.spec)(panel).heights.filter(|heights| heights.valid())) + .map(|panel| (self.spec)(panel)) + .filter(|spec| spec.flyout_height == FlyoutHeight::Docked) + .filter_map(|spec| spec.heights.filter(|heights| heights.valid())) .map(|heights| heights.default + sizes.strip) .fold(sizes.strip + sizes.least, f32::max); group.height.filter(|height| height.is_finite() && *height > 0.0).unwrap_or(content).max(sizes.strip + sizes.least) diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index a511f7bb6e..4f09347f0d 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -1,5 +1,5 @@ //! Trials of `IconicColumn`: the letter of a panel without an icon, the names a wide column shows, the grips of its -//! groups, the resizes of its flyouts, and a flyout that a command leaves open. +//! groups, the heights and resizes of its flyouts, and a flyout that a command leaves open. #![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")] use super::{CELL, GRIP}; @@ -8,8 +8,8 @@ use crate::contract::overlay::{self, OpenFilter}; use crate::contract::{Bind, Show as _, ShowContainer as _}; use crate::docking::group::GRIP_ABOVE; use crate::docking::{ - DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutResize, GroupAt, GroupDrag, GroupGrip, IconGroupSeparator, IconicColumn, PanelKey, - PanelSpec, + DockColumn, DockHeights, DockSizes, DockSpot, DockTargets, DragUnit, FlyoutHeight, FlyoutResize, GroupAt, GroupDrag, GroupGrip, + IconGroupSeparator, IconicColumn, PanelKey, PanelSpec, }; use crate::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, Scope}; use crate::runtime::drag; @@ -422,6 +422,79 @@ fn a_flyout_with_an_offset_in_a_short_viewport_stays_inside_and_resizes_its_widt } } +/// The body height a panel asks for docked in a column, well above what its one-line body measures. +const DOCKED: f32 = 260.0; + +/// A panel with a one-line body that asks for [`DOCKED`] in a dock column, its flyout `height` tall; the other panel +/// asks for no height. +fn docked_tall(height: FlyoutHeight) -> impl Fn(&u8) -> PanelSpec { + move |panel| match panel { + 0 => PanelSpec::new("Swatches").heights(DockHeights::new(DOCKED)).flyout_height(height), + _ => PanelSpec::new("Brushes"), + } +} + +/// What a group with a one-line body measures in the trials: its strip, the body's padding and a line, four strips. +fn one_line(sizes: &DockSizes) -> f32 { + sizes.strip * 4.0 +} + +/// The height of the flyout of the [`docked_tall`] panel at `height`, whose group measures [`one_line`], and the dock +/// sizes it showed in. +fn flyout_height_of(height: FlyoutHeight) -> (f32, DockSizes) { + let shown = Rc::new(Cell::new(None)); + let (seen, open) = (Rc::clone(&shown), Cell::new(None)); + let spec = docked_tall(height); + let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)); + let mut fixture = Fixture::new(move |ui| { + let column = Column::new(vec![Group::new(vec![0], 0)]); + let measured = one_line(&StyleCx::with_root(ui.ctx(), DockSizes::style)); + let mut now = open.get(); + IconicColumn::new("Panels", global("iconic column", "flyout height"), &column, Bind::bound(&mut now), &spec) + .within(screen()) + .show_flyouts_at(ui, place, |_, at, _, _| match at { + GroupAt::Measure(_) => Some(measured), + GroupAt::Show(rect) => { + seen.set(Some(rect)); + None + } + }); + open.set(now); + }); + fixture.room(SCREEN).settle(); + let icon = fixture.by_label("Swatches").expect("the Swatches icon").rect.center(); + fixture.click_at(icon).settle(); + (shown.get().expect("the flyout is open").height(), StyleCx::with_root(fixture.ctx(), DockSizes::style)) +} + +/// A panel that asks for a tall docked height opens a flyout at least that tall by default; with +/// `FlyoutHeight::Content` its flyout is as tall as its one-line body measures, while docked in a column its group +/// keeps the docked height. +#[trial] +fn a_content_tall_flyout_ignores_the_docked_height_that_its_docked_group_keeps() { + let (by_default, sizes) = flyout_height_of(FlyoutHeight::Docked); + let (docked, measured) = (DOCKED + sizes.strip, one_line(&sizes)); + assert!(measured < docked && measured > sizes.strip + sizes.least, "the body measures between the least and the docked height"); + assert!(near(by_default, docked), "by default the flyout takes the docked height: {by_default} for {docked}"); + let (content, _) = flyout_height_of(FlyoutHeight::Content); + assert!(near(content, measured), "a content-tall flyout is as tall as its body measures: {content} for {measured}"); + + let rects = Rc::new(RefCell::new(Vec::new())); + let seen = Rc::clone(&rects); + let spec = docked_tall(FlyoutHeight::Content); + let mut fixture = Fixture::new(move |ui| { + let column = Column::new(vec![Group::new(vec![0], 0), Group::new(vec![1], 0)]); + let mut shown = Vec::new(); + DockColumn::new("Panels", global("dock column", "flyout height"), &column, &spec).show_groups(ui, |group, rect, _, _| { + shown.push((group.panels.first().copied(), rect)); + }); + *seen.borrow_mut() = shown; + }); + fixture.room(SCREEN).settle(); + let group = rects.borrow().iter().find(|(panel, _)| *panel == Some(0)).map(|(_, rect)| *rect).expect("the docked group shows"); + assert!(near(group.height(), docked), "docked in a column the group keeps its docked height: {group:?} for {docked}"); +} + /// The names of the panels of the tall-body trials, which set no heights. const TALL: [&str; 8] = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"]; /// What the body of a flyout in the tall-body trial measures. diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index dc9c5c4e2e..77cc4da605 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -45,7 +45,7 @@ pub use panels::{close_requests, open_requests}; pub use placed::{Placing, placed_rect, with_area_rules}; pub use root::{DockRoot, DockRootOutput, DockRootStyle}; pub use sources::{DividerKind, DockSource, SourceKind}; -pub use spec::{DockGrid, DockHeights, PanelDocument, PanelSpec}; +pub use spec::{DockGrid, DockHeights, FlyoutHeight, PanelDocument, PanelSpec}; pub use splitter::{Splitter, SplitterStyle}; pub use targets::{CardInset, ColumnCards, DockSizes, DockSpot, DockTargets, GroupDrag, ZoneRule}; pub use words::DockWords; diff --git a/crates/ui-panels/src/docking/native.rs b/crates/ui-panels/src/docking/native.rs index 2af9145811..f7b43d95a5 100644 --- a/crates/ui-panels/src/docking/native.rs +++ b/crates/ui-panels/src/docking/native.rs @@ -129,7 +129,7 @@ pub fn waited(ctx: &Context, opening: &Opening, output: &FloatingGroupOutput) { /// app window's is recorded, with the rect `kept` gives for the rect the OS shows the window at (outer top-left corner /// and inner size, in desktop points), so a collapsed window keeps its expanded rect /// ([`WindowColumn::kept`](super::WindowColumn::kept)). `None` while the model already holds what the OS reports, so a -/// window at rest costs no action. +/// window at rest costs no action. A caller skips it while the window's move runs ([`FloatingGroupOutput::moving`]). #[doc(hidden)] pub fn reported(ctx: &Context, window: &Floating

, viewport: ViewportId, kept: impl FnOnce(Rect) -> Rect) -> Option> { let panel = window.panels().next()?; diff --git a/crates/ui-panels/src/docking/spec.rs b/crates/ui-panels/src/docking/spec.rs index ca5093842f..db97a87305 100644 --- a/crates/ui-panels/src/docking/spec.rs +++ b/crates/ui-panels/src/docking/spec.rs @@ -52,6 +52,19 @@ impl DockHeights { } } +/// How tall the flyout of a panel in a column collapsed to icons opens while the user has not resized its group. Either +/// way the flyout is at least as tall as its body measures, within the room below its top. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum FlyoutHeight { + /// At least the panel's [`DockHeights::default`], the height its group takes docked in a column. + #[default] + Docked, + /// As tall as the body measures, at least the dock's least group height: the panel's [`DockHeights`] size its + /// group docked in a column only. + Content, +} + /// How a panel that lays its content in a grid of equal columns (a toolbar) sizes its dock column. The column is a /// whole number of content columns wide, its steps ([`Column::steps`](craft_behavior::dock::Column::steps)), and as /// tall as the content measures at that width: docked from the top of the dock, floating under the title row. A drag @@ -211,9 +224,12 @@ pub struct PanelSpec { pub icon: Option>, /// Body size limits. pub limits: SizeLimits, - /// How the panel's group sizes itself in a dock column until the user resizes it. `None` shares the column's - /// free height with the column's last open group, which fills it, and with the other groups that have none. + /// How the panel's group sizes itself in a dock column until the user resizes it, and under + /// [`FlyoutHeight::Docked`] the least height of its flyout. `None` shares the column's free height with the + /// column's last open group, which fills it, and with the other groups that have none. pub heights: Option, + /// How tall the panel's flyout opens: at least its docked default height, or as tall as its body measures. + pub flyout_height: FlyoutHeight, /// The size the panel floats at: its width and the most height it takes. `None`: the size of the group it floats /// out of, else `FloatSpace`'s default size. pub float_size: Option, @@ -266,6 +282,7 @@ impl PanelSpec { icon: None, limits: SizeLimits::default(), heights: None, + flyout_height: FlyoutHeight::Docked, float_size: None, allow_native: true, allow_float_resize: true, @@ -352,6 +369,13 @@ impl PanelSpec { self } + /// How tall the panel's flyout opens. + #[must_use] + pub fn flyout_height(mut self, height: FlyoutHeight) -> Self { + self.flyout_height = height; + self + } + /// The size the panel floats at. #[must_use] pub fn float_size(mut self, size: Vec2) -> Self { diff --git a/crates/ui-panels/tests/it/dialogs.rs b/crates/ui-panels/tests/it/dialogs.rs index 8a485cf952..767ee1cb93 100644 --- a/crates/ui-panels/tests/it/dialogs.rs +++ b/crates/ui-panels/tests/it/dialogs.rs @@ -166,6 +166,35 @@ fn a_child_a_dialog_asks_for_opens_over_it_once() { assert!(host.is_empty(), "a dialog that finished does not leave its child open"); } +/// A child that asks for a child of its own in a later pass opens it over itself: the new dialog holds no dialog, the +/// asking child keeps its own parent, and both stay shown under it. +#[trial] +fn a_child_that_asks_for_a_child_in_a_later_pass_keeps_its_own_parent() { + let mut frames = Frames::new(); + let mut host = DialogHost::new(); + let below = host.open(Probe::<1>::new("below")); + let asker = host.open_child(Asker { ask: false, child: None, finish: None }, below); + run(&mut host, &mut frames); + + host.get_mut::().unwrap().ask = true; + run(&mut host, &mut frames); + let asked = dialog_id("asked"); + let parents = |host: &DialogHost| host.open_dialogs().into_iter().map(|open| (open.id, open.parent)).collect::>(); + assert_eq!(parents(&host), [(below, None), (asker, Some(below)), (asked, Some(asker))], "each dialog sits over the one it was opened from"); + assert!(!host.stack().has_child(asked), "the new dialog holds no dialog"); + + let shown = host.get::>().unwrap().shows; + run(&mut host, &mut frames); + let (below_probe, asked_probe) = (host.get::>().unwrap(), host.get::>().unwrap()); + assert_eq!(below_probe.shows, shown + 1, "the dialog under the asking child still shows"); + assert!(asked_probe.top && !below_probe.top, "the new dialog is on top"); + + assert!(host.cancel::>(&frames.ctx)); + run(&mut host, &mut frames); + assert_eq!(parents(&host), [(below, None), (asker, Some(below))], "closing the new dialog leaves the asking child over its parent"); + assert!(host.stack().is_top(asker)); +} + /// A story of a hosted alert whose title is the story's `title` knob. fn titled_alert(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let title = *data.value("title", "Could not open"); diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index cff0113967..803a4e9fb3 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -64,6 +64,20 @@ pub struct WindowFiles

{ pub files: Vec, } +/// The key, text and clipboard events one floating OS window of the dock left this pass, with the modifiers held in that +/// window. One batch per window that left any, in the order the windows were drawn. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct WindowEvents

{ + /// The panel the area names the window by: its first, as in [`DockAreaOutput::windows`]. + pub panel: P, + /// The modifiers held in that window while its events arrived. A clipboard event stands for its chord without the + /// key, so these tell Ctrl+C in this window from the keyboard's own Copy key, and from another window's Ctrl+C. + pub modifiers: egui::Modifiers, + /// The events, in the order the window's pass left them. + pub events: Vec, +} + /// What a dock area reports in a pass: the actions it applied to the workspace and the events for the host. #[derive(Debug)] #[non_exhaustive] @@ -105,6 +119,24 @@ pub struct DockAreaOutput

{ /// The files dropped on the area's floating OS windows this pass that no target there took, one entry per drop, /// each with the panel it was dropped on, for the host to open. pub window_files: Vec>, + /// The key, text and clipboard events (`Key`, `Text`, `Copy`, `Cut`, `Paste`, `PasteImage`) of the area's floating windows in their + /// own OS windows that nothing took this pass, window by window, in the order of the windows: each batch with the + /// modifiers held in its own window. egui hands each OS window only its own input, so the app's main window never + /// sees these: an app that runs its shortcuts from its main window's input runs them on these too, to keep them + /// working while a floating window has the focus. The framework took its own keys in the window (Escape, Tab and + /// focus moves, claimed and edit chords, a command a shortcut fired), and the window's widgets theirs. A window + /// where a component has keyboard focus forwards nothing: its keys are that component's. A clipboard chord stands + /// for the `Copy`, `Cut` or `Paste` (or `PasteImage`) event without its key, so a host reads the chord's modifiers + /// from the batch: a clipboard event carries none of its own, and two floats can leave events in one pass under + /// different modifiers. Floating windows that show in the app window forward nothing: their keys are the app + /// window's own. + pub window_events: Vec>, + /// Every window's events of `window_events`, flattened in the same order, for a host with one floating window: the + /// modifiers of these are `forwarded_modifiers`, the modifiers held in the last window that left any. A host that + /// reads input from more than one float in a pass wants each window's, in `window_events`. + pub forwarded_events: Vec, + /// The modifiers held in the window that left the last of `forwarded_events`; `None` when no window left any. + pub forwarded_modifiers: Option, /// Every place the area drew this pass where a press starts a dock gesture: each tab, each group's drag bar, each /// floating window's grip and resize grips, and each divider, with its rect, its OS window and the id of its /// accessibility node. Nothing the area did not draw reports: a hidden panel, the groups of a column collapsed to @@ -339,6 +371,8 @@ struct Report

{ windows: Vec<(P, ViewportId)>, /// The files dropped on the floating windows that no target there took. files: Vec>, + /// The events the floating windows' own OS windows left, window by window, each with the modifiers held in it. + window_events: Vec>, /// The gesture sources the parts drew, in the order they showed. sources: Vec>, /// The groups shown this pass, in the order they showed. @@ -683,6 +717,7 @@ struct Passed

{ columns: Vec<(P, Rect)>, windows: Vec<(P, ViewportId)>, files: Vec>, + window_events: Vec>, sources: Vec>, } @@ -852,8 +887,8 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { passed = Some(result); }); let requested = close_requests::

(&ctx); - let Passed { geometry, actions, events, focused, pressed, picked, edit, space, columns, windows, files, sources } = - passed.unwrap_or_else(|| Passed { + let Passed { geometry, actions, events, focused, pressed, picked, edit, space, columns, windows, files, window_events, sources } = passed + .unwrap_or_else(|| Passed { geometry: Vec::new(), actions: Vec::new(), events: Vec::new(), @@ -865,6 +900,7 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { columns: Vec::new(), windows: Vec::new(), files: Vec::new(), + window_events: Vec::new(), sources: Vec::new(), }); if shown.output.dropped.is_some() { @@ -884,6 +920,10 @@ impl<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> DockArea<'a, P> { columns, windows, window_files: files, + // The one-window view of the batches, from them, so the two cannot disagree. + forwarded_events: window_events.iter().flat_map(|window| window.events.iter().cloned()).collect(), + forwarded_modifiers: window_events.last().map(|window| window.modifiers), + window_events, sources, response: shown.output.response, } @@ -1044,6 +1084,7 @@ fn show_area( placed: Vec::new(), windows: Vec::new(), files: Vec::new(), + window_events: Vec::new(), sources: Vec::new(), shown: Vec::new(), picks: Vec::new(), @@ -1138,6 +1179,7 @@ fn show_area( columns: report.placed.into_iter().map(|placed| (placed.panel, placed.rect)).collect(), windows: report.windows, files: report.files, + window_events: report.window_events, sources: report.sources, } } @@ -1899,7 +1941,7 @@ impl Pass<'_, P> { DockTargets::

::register_room(ui.ctx(), dock, cell); } let opens = if edge == DockEdge::Start { Side::End } else { Side::Start }; - // Only a docked column's icons are a rail; a floating window's open flyouts. + // Only a docked column's icons are a rail; a floating window's open flyouts, which stand in the windows' order. let mode = if in_window { IconicMode::Flyouts } else { scene.config.iconic_mode }; // The width the user gives a column by its inner edge leaves out its card's inset. let inset = card.map_or(0.0, |place| scene.sizes.inset(place)); @@ -2043,6 +2085,31 @@ impl Pass<'_, P> { } } + /// What a floating window handed back this pass besides its layout: the files dropped on it, for the group under + /// the drop, else its first group (a drop on the title row, or with no pointer known), from `first_group` on in the + /// shown groups, else `active`; and the keys nothing in it took, with the modifiers held in it, as that window's + /// own batch (`anchor` names the window as the area does). + fn take_window_input( + &mut self, + first_group: usize, + anchor: &P, + active: &P, + (files, files_at): (Vec, Option), + (forwarded, modifiers): (Vec, Option), + ) { + if !files.is_empty() { + let groups = &self.report.shown[first_group..]; + let under = files_at.and_then(|at| groups.iter().find(|group| group.rect.contains(at))); + let panel = under.or(groups.first()).map_or_else(|| active.clone(), |group| group.panel.clone()); + self.report.files.push(WindowFiles { panel, files }); + } + if !forwarded.is_empty() { + // One batch per window: its own modifiers travel with its events, whatever the windows drawn after it hold. + let modifiers = modifiers.unwrap_or_default(); + self.report.window_events.push(WindowEvents { panel: anchor.clone(), modifiers, events: forwarded }); + } + } + /// The floating windows of the pruned layout, each a `FloatingGroup` holding its one column, drawn as a dock /// column is with the window's title row as the column's bar, in an OS window where the config, the platform and /// its panels allow one. A window takes the drops over it on its own layer, from the spots its column registers in @@ -2207,13 +2274,13 @@ impl Pass<'_, P> { source.viewport = viewport; } } - if !output.files.is_empty() { - // The group under the drop, else the first group: a drop on the title row, or with no pointer known. - let groups = &self.report.shown[first_group..]; - let under = output.files_at.and_then(|at| groups.iter().find(|group| group.rect.contains(at))); - let panel = under.or(groups.first()).map_or_else(|| active.clone(), |group| group.panel.clone()); - self.report.files.push(WindowFiles { panel, files: output.files }); - } + self.take_window_input( + first_group, + &anchor, + &active, + (output.files, output.files_at), + (output.forwarded_events, output.forwarded_modifiers), + ); if let Some(dropped) = dropped.into_inner() { cross_window::accept_cross_window(&ctx); self.report.actions.push(dropped.action); @@ -2249,8 +2316,12 @@ impl Pass<'_, P> { kept.edge = keeps.unwrap_or(kept.edge); self.report.actions.push(Action::move_floating_with_edge(anchor.clone(), rect, keeps)); } - let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl)); - self.report.actions.extend(reported); + // The OS window's place changes in every pass of a move; the workspace records it once, when the move + // ends. + if !output.moving { + let reported = native::reported(&ctx, window, viewport, |shown| kept.kept(shown, opening.rect, chrome, scene.rtl)); + self.report.actions.extend(reported); + } } } else if let Some(mut change) = output.placed.filter(|change| change.kind != PlacementKind::Move || change.phase == GesturePhase::Commit) { diff --git a/crates/ui-patterns/src/patterns/dock/mod.rs b/crates/ui-patterns/src/patterns/dock/mod.rs index 8fe3517e3f..e37647db1f 100644 --- a/crates/ui-patterns/src/patterns/dock/mod.rs +++ b/crates/ui-patterns/src/patterns/dock/mod.rs @@ -9,7 +9,7 @@ pub(crate) mod workspace_dialogs; // Task panes: docked panes as shell panes, floating panes as floating frames. pub(crate) mod panes; -pub use area::{DockArea, DockAreaOutput, InvalidGeometry, WindowFiles}; +pub use area::{DockArea, DockAreaOutput, InvalidGeometry, WindowEvents, WindowFiles}; pub use panes::{ PaneArea, PaneAreaOutput, PaneCommands, PaneContent, PaneEdges, PaneFrame, PaneFrameOutput, PaneFrameStyle, PanePlace, PaneRequest, PaneSpec, PaneState, SidePolicy, diff --git a/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs b/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs index e55e0b01be..0d1a14559b 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/list_manager.rs @@ -2,6 +2,7 @@ use crate::contract::{ Bind, BodyCx, CollectionEvent, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, + Sizing, }; use crate::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog}; use crate::display::{Shade, Text}; @@ -321,6 +322,10 @@ impl StackDialog for HostedListManager { } } +/// The fewest rows the list is tall, and the most it shows before it scrolls. +const MIN_ROWS: u16 = 8; +const MAX_ROWS: u16 = 12; + /// The name box's text in `bind`: empty while a kept binding holds none. fn text_of(bind: &mut Bind<'_, String>, cx: &mut BodyCx<'_>) -> String { match bind.reborrow().read(cx) { @@ -556,6 +561,11 @@ impl<'a> ListManager<'a> { .id(list_id) .select(SelectMode::Single) .allow_empty(true) + // A capped list is sized from its rows: without a cap it takes no height in a dialog that sizes to its + // content, and the empty message or the first rows are drawn over the section under it. + .sizing(Sizing::Content) + .min_rows(MIN_ROWS) + .max_rows(MAX_ROWS) .deletable(true) .selection(Bind::bound(&mut selection)); if let Some(empty) = &empty { diff --git a/crates/ui-patterns/src/patterns/preferences/model.rs b/crates/ui-patterns/src/patterns/preferences/model.rs index 944993fa5a..dd729063ef 100644 --- a/crates/ui-patterns/src/patterns/preferences/model.rs +++ b/crates/ui-patterns/src/patterns/preferences/model.rs @@ -126,6 +126,8 @@ pub struct RowSpec<'a> { /// default a drop-down, and on a card ([`PreferencesLayout::Cards`](super::PreferencesLayout::Cards)) a short /// choice of up to five options is segmented. Ignored by other kinds. pub pills: Option, + /// A [`RowKind::Text`] row: the translated text shown while the field is empty. Ignored by other kinds. + pub placeholder: Option<&'a str>, /// The control and the value it shows. pub kind: RowKind<'a>, } @@ -133,7 +135,7 @@ pub struct RowSpec<'a> { impl<'a> RowSpec<'a> { /// A visible, enabled row with no keywords or help. pub fn new(key: &'a str, label: &'a str, kind: RowKind<'a>) -> Self { - Self { key, label, keywords: "", help: None, visible: true, enabled: true, step: None, pills: None, kind } + Self { key, label, keywords: "", help: None, visible: true, enabled: true, step: None, pills: None, placeholder: None, kind } } /// Sets extra search text for the row. @@ -171,6 +173,13 @@ impl<'a> RowSpec<'a> { self } + /// Sets the text a [`RowKind::Text`] row shows while empty. + #[must_use] + pub fn placeholder(mut self, placeholder: &'a str) -> Self { + self.placeholder = Some(placeholder); + self + } + /// Sets the step of a [`RowKind::Float`] row. #[must_use] pub fn step(mut self, step: f64) -> Self { diff --git a/crates/ui-patterns/src/patterns/preferences/rows.rs b/crates/ui-patterns/src/patterns/preferences/rows.rs index 82c66c8ec2..700848cb2e 100644 --- a/crates/ui-patterns/src/patterns/preferences/rows.rs +++ b/crates/ui-patterns/src/patterns/preferences/rows.rs @@ -39,7 +39,7 @@ pub(super) enum Kind { Int { value: i64, range: RangeInclusive, unit: Option, unit_text: Option

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect, edge: Option }, ResizeSplit { path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, SetColumnSteps { panel: P, steps: u16 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

} }`. Groups, columns and floating windows are named by a panel they contain. +- `craft_behavior::dock::Action`: `pub enum Action

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect, edge: Option }, ResizeSplit { path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, SetColumnSteps { panel: P, steps: u16 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

}, Restore { panel: P, location: Location

} }`. Groups, columns and floating windows are named by a panel they contain. - `pub fn move_beside(panel: P, anchor: P, placement: DockPlacement

) -> Self`. Builds [`Action::Move`]. - `pub fn float(panel: P, rect: Rect) -> Self`. Builds [`Action::Float`]. - `pub fn close(panel: P) -> Self`. Builds [`Action::Close`]. @@ -533,6 +533,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn resize_iconic(panel: P, width: Option) -> Self`. Builds [`Action::ResizeIconic`]. - `pub fn set_native(panel: P, placement: Option) -> Self`. Builds [`Action::SetNative`]. - `pub fn move_panel(panel: P, to: Target

) -> Self`. Builds [`Action::MovePanel`]. + - `pub fn restore(panel: P, location: Location

) -> Self`. Builds [`Action::Restore`]. - `craft_behavior::dock::Arrangement`: `pub enum Arrangement { TileAllVertically, TileAllHorizontally, TwoUpVertical, TwoUpHorizontal, ThreeUpVertical, ThreeUpHorizontal, ThreeUpStacked, FourUp, SixUp, ConsolidateAllToTabs, Cascade, Tile, FloatInWindow, FloatAllInWindows, NewWindowForDocument, MatchZoom, MatchLocation, MatchRotation, MatchAll }`. One Window › Arrange entry. The n-up entries split the document area into that many - `pub fn group_count(self, documents: usize) -> Option`. How many document groups an n-up or tile arrangement wants, `None` for the window and - `pub fn enabled(self, documents: usize, groups: usize, floating: usize) -> bool`. Whether the entry is enabled with `documents` open and `floating` floating windows: @@ -633,7 +634,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn version(&self) -> u32`. The format version the workspace was read with. - `pub fn layout(&self) -> &Layout

`. The current arrangement. - `pub fn hidden(&self) -> &[(P, Location

)]`. The closed panels, and panels the application does not register now, with where each one goes back. - - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels with the docked location each one left. + - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels, and the closed panels that were floating, with the docked location each one left. - `pub fn revision(&self) -> Revision`. The revision of this workspace value: it moves with every write, and no other value has it. - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a @@ -771,7 +772,7 @@ Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the f The step of one pass of motion: a Hand glide, a held Zoom press and an autoscroll integrate over it. - `craft_behavior::frame_step::FRAME_STEP_MAX`: `pub const FRAME_STEP_MAX: f64`. The longest step motion integrates, in seconds, so a stalled pass never jumps the view. -- `craft_behavior::frame_step::frame_step`: `pub fn frame_step(dt: f64) -> f64`. The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the +- `craft_behavior::frame_step::frame_step`: `pub fn frame_step(dt: f64) -> f64`. The step of a pass that came `dt` seconds after the previous one, kept within `0..=FRAME_STEP_MAX`. ## `craft_behavior::geometry` @@ -1585,7 +1586,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn new() -> Self`. A reader for plain numbers written with `.` as the decimal separator. - `pub fn bare(mut self, factor: f64) -> Self`. A number with no unit counts as `factor` of the reader's base unit (a picas field reads bare numbers as - `pub fn decimal(mut self, decimal: char) -> Self`. The decimal separator. - - `pub fn group(mut self, group: char) -> Self`. The digit-group separator, which the reader skips between digits. + - `pub fn group(mut self, group: char) -> Self`. The digit-group separator, which the reader skips between digits. A comma or point after zero reads as a - `pub fn unit(mut self, spelling: &str, factor: f64) -> Self`. A unit spelling (case-insensitive; letters or the symbols `%`, `°`) and its factor to the base unit. - `pub fn unit_tagged(mut self, spelling: &str, factor: f64, tag: u32) -> Self`. Like [`Reader::unit`], with a `tag` that [`Reader::read_tagged`] returns when the text names this spelling. - `pub fn split_unit(mut self, spelling: &str, factor: f64, rest: f64, tag: u32) -> Self`. Like [`Reader::unit_tagged`], where a number written right after the spelling adds that many of `rest`: picas @@ -1834,9 +1835,10 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. - `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. + - `pub const fn zoom_lines(mut self, lines: Vec2) -> Self`. The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`). - `pub const fn touch_zoom(mut self, zoom: f32) -> Self`. The same gesture with the two-finger touch zoom factor `zoom`. - `pub const fn rotation(mut self, radians: f32) -> Self`. The same gesture with rotation `radians`, clockwise on screen. - `pub const fn touch_rotation(mut self, radians: f32) -> Self`. The same gesture with the two-finger touch rotation `radians`. @@ -1904,6 +1906,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `type ItemEvent`. Events an item reports. - `const MEMBERS: bool`. Whether the items are members of the collection's run instead of runs of their own. Each visible item is then - `fn items(&self) -> &CollectionProps`. Plain data: selection mode, reorder, rename, columns. + - `fn shows_row_focus(&self) -> bool`. Whether keyboard focus shows a ring on the lead row, or on a populated rows viewport with no visible lead. - `fn selection(&mut self) -> Option>`. The selection binding; `None` keeps it in session memory. - `fn column_layout(&mut self) -> Option>`. The column arrangement binding; `None` keeps it in the header's own memory. The header starts each pass from - `fn cell_space<'s>(&'s self, space: CellSpace<'s, Self::Key>) -> CellSpace<'s, Self::Key>`. The grid a model of cells selects in (17.7). The item step passes the grid it knows, the source's rows and the @@ -1914,6 +1917,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn dress_inputs(&self) -> u64`. What `dress` reads of the collection, hashed: a kept measure of the items serves only while it is the same. - `fn ideal_width(&self, _item: Option, _rows: usize, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env, _kept: Option<&Self::Key>,) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. `kept` is the + - `fn rings_lead(&self) -> bool`. Whether the focus ring goes around the lead item while the collection has keyboard-visible focus: the item step - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this - `fn rename_editor(&mut self, _ui: &mut Ui, _draft: Bind<'_, String>, _label: Rect, _name: &str) -> Option>`. The rename editor at `label`: the label rect the renaming item reports (`ItemOutput::label_rect`), else its row. - `fn hosts_header(&self, _column: &ColumnKey) -> bool`. Whether the collection hosts a component in the header cell of `column`: the header then calls `header_cell` @@ -2417,6 +2421,8 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn open_request(&self) -> Option>`. The item asks to open or close its children, as a click on its disclosure does. The collection reports it - `fn menu_request(&self) -> Option`. The item asks for its menu from one of its parts (a row's "More" button): the part's rect, in the item's layer. - `fn label_rect(&self) -> Option`. The rect of the item's label, where a rename editor goes; `None` puts it over the whole row. + - `fn lead_fill(&self) -> Option`. The lead item's resolved fill, which the collection uses as the background of its focus ring. + - `fn lead_focus_bounds(&self) -> Option`. The lead item's focus ring bounds, in the item's layer. The default uses the item's full bounds. - `craft_ui::contract::Job`: re-export of `craft_ui::runtime::pending::Job`. - `craft_ui::contract::LabelKind`: `pub enum LabelKind { Text, Hidden, Glyph(GlyphLabel), Short(Label) }`. How a side label is shown. - `craft_ui::contract::LabelPress`: `pub enum LabelPress { Focus, Link }`. What a click on a control's side label does. @@ -2442,7 +2448,6 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component. - `pub fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above - `pub fn column_room(&self) -> Option`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the - - `pub fn in_row(&self) -> bool`. Whether the component is a direct child of a `Row` body, a bar's included. A component that could wrap into - `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a band picture sizes at (a plot, a strip), one whose height is its own whatever its width: it takes - `pub fn picture_size(&self, least: f32, most: f32, height: impl FnOnce(f32) -> f32) -> Vec2`. The size of a picture whose height follows from its width (a square graph, a wheel, an image at its aspect): - `pub fn label(&self) -> Label`. The label as given. @@ -2498,7 +2503,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn unshown(response: Response) -> Option where Self: Sized,`. The output of a layer-like container that shows nothing this pass (closed, past its exit fade): `response` is - `fn value_text(&self) -> Option<&str>`. The shown value as the component words it to assistive technology; `None` for a component that gives none. - `fn story_facts(&self) -> crate::testing::StoryOutput`. The facts a story reports about this output: its id, click, edit kinds, collection kinds and visible range. -- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. +- `craft_ui::contract::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub among_windows: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. @@ -2528,7 +2533,9 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn opacity(mut self, opacity: f32) -> Overlay`. Sets the layer's opacity, from 0 (invisible) to 1. - `pub fn min_width(mut self, min_width: MinWidth) -> Overlay`. Sets the narrowest width. - `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it. + - `pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay`. Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]): - `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]). + - `pub fn among_windows(mut self, on: bool) -> Overlay`. Sets whether the layer stands among the floating windows ([`Overlay::among_windows`]). - `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer. - `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]). - `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer @@ -2540,7 +2547,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn opener_anchor(mut self, anchor: Anchor) -> Overlay`. Sets where the layer hangs when the opener named last opened it. A rect or point is in that opener's layer - `craft_ui::contract::OverlayUi`: `pub struct OverlayUi<'a> { pub closed: Vec<(Id, CloseReason)> }`. What the `overlay` hook gets: one call per anchored popup of this component, built at step 10 with the open state - `pub fn closing(&self, popup: PopupHandle) -> Option`. Why `popup` closes at the end of this pass, as its `show` decided (its dismissal, or a close its body asked for); - - `pub fn is_rtl(&self) -> bool`. Whether the owner lays out right to left: a layer its caller places by position mirrors its own geometry by it, + - `pub fn is_rtl(&self) -> bool`. Whether a layer the owner opens lays out right to left (`Scoped::layer_direction`): a layer its caller places by - `pub fn anchor_part(&self, part: impl Into) -> Anchor`. The anchor at the rect of the toggling part `part` of the owner. The layer's placement mirrors the side and - `pub fn contain_popups_below(&mut self)`. Keeps the popups this component shows from here on, and every popup opened from them, below the component: - `pub fn show(&mut self, popup: PopupHandle, overlay: Overlay, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Option`. Shows the popup while its handle is open, on a popup surface, inside `POPUP_PAD`; the content is a body closure. @@ -2558,6 +2565,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn with_style(&self, variant: Variant, f: impl FnOnce(&StyleCx<'_>) -> R) -> R`. Runs `f` with the style context of this component's env, so app hooks called from `paint` pick colours and - `pub fn child(&mut self, key: impl Hash + Debug, rect: Rect, child: C) -> C::Output`. Shows a child component at a physical rect, with id `cx.key(key)`. The child `Ui` is pinned left to - `pub fn inner(&mut self, key: impl Hash + Debug, rect: Rect, child: C) -> C::Output`. Shows `child` as the owner's own control, such as a picker the owner draws its field with. The child's node + - `pub fn label_target(&mut self, key: impl Hash + Debug)`. Makes the child shown with `key` the one a click on the composite's label focuses, in place of the composite's - `pub fn child_with_tip(&mut self, key: impl Hash + Debug, rect: Rect, child: C, tip: impl FnOnce(&mut Ui)) -> C::Output`. Shows a child with rich tooltip content. - `pub fn labelled(&mut self, key: impl Hash + Debug, rect: Rect, label: Label, side: SideLabel, child: C) -> C::Output`. Runs the label step (B2) for one leaf child at `rect`: the label's placement beside or above the child, the - `pub fn face(&mut self, part: impl Into, face: C)`. Paints `face` as the look of `part`: its style, surface and state fill from the part's state merged with the @@ -2683,11 +2691,13 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn keep_view_open(&mut self, canvas: Id)`. Keeps the view of `canvas` (the canvas component's id) usable under the modal layer: the wheel scrolls and - `craft_ui::contract::Savable`: re-export of `craft_ui::runtime::memory::Savable`. - `craft_ui::contract::SaveKey`: re-export of `craft_ui::runtime::memory::SaveKey`. -- `craft_ui::contract::Scroll`: `pub struct Scroll { pub axes: ScrollAxes, pub anchor: ScrollAnchor, pub notch: Notch, pub indicator: ScrollIndicator }`. A scrolling body. +- `craft_ui::contract::Scroll`: `pub struct Scroll { pub axes: ScrollAxes, pub anchor: ScrollAnchor, pub notch: Notch, pub indicator: ScrollIndicator, pub at_rest: bool }`. A scrolling body. - `pub const fn strips(mut self) -> Scroll`. Shows the overflow along y as scroll strips instead of a bar. - `pub const fn has_strips(&self) -> bool`. Whether the overflow along y shows as scroll strips. - `pub const fn overlay(mut self) -> Scroll`. Shows the overflow as a bar in the container's padding that takes no room from the content and shows only - `pub const fn has_overlay(&self) -> bool`. Whether the overflow shows as an overlay bar. + - `pub const fn at_rest(mut self) -> Scroll`. Shows an overlay bar whenever the content overflows, also while the pointer is away from the container. A bar of + - `pub const fn overlay_hides_at_rest(&self) -> bool`. Whether the overlay bar shows only while the pointer is over the container or presses the bar. - `pub const fn vertical() -> Scroll`. Scrolls along y. - `pub const fn horizontal() -> Scroll`. Scrolls along x. - `pub const fn both() -> Scroll`. Scrolls along both axes. @@ -2736,7 +2746,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn content_width(self) -> bool`. Whether the width follows the content: `Content` and `FillHeight`. - `pub const fn fills_height(self) -> bool`. Whether the height is the available height: `Fill` and `FillHeight`. - `craft_ui::contract::Slot`: re-export of `craft_ui::runtime::memory::Slot`. -- `craft_ui::contract::SpaceAction`: `pub enum SpaceAction { Activate, ToggleCell, Preview, None }`. What Space does in a collection (Enter always activates the lead). +- `craft_ui::contract::SpaceAction`: `pub enum SpaceAction { Activate, ActivateLead, ToggleCell, Preview, None }`. What Space does in a collection (Enter always activates the lead). - `craft_ui::contract::Stateless`: `pub struct Stateless`. A callback in props: a fn item or a capture-free closure, which is zero-sized, so its type alone says what it - `pub const fn new(f: F) -> Stateless`. `f` as a prop; `f` must capture nothing. - `pub fn get(&self) -> F`. The callback. @@ -2792,6 +2802,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::clicked`: `pub fn clicked(response: &Response) -> bool`. Whether `response` reports a click, by pointer or by keyboard activation. - `craft_ui::contract::item_node`: `pub fn item_node(id: Id, key: &K) -> Id`. The access node of the item `key` of the members collection `id` (a tab strip, a swatch table): the sub-node of its - `craft_ui::contract::item_part_open`: `pub fn item_part_open(ctx: &Context, item: Id, part: impl Into) -> bool`. Whether a menu or popover hung from the part `part` of the item `item` (`ItemCx::part_opener`) is open: an item +- `craft_ui::contract::keep_inside`: `pub fn keep_inside(rect: Rect, bounds: Rect) -> Rect`. `rect` moved, at its size, the least distance that puts it inside `bounds`: the one keep rule for a layer's - `craft_ui::contract::measure_item`: `pub fn measure_item(ui: &mut Ui, item: &mut C, at: crate::runtime::access::SetPosition, proposal: craft_behavior::Proposal) -> Vec2 where C: super::Component + super::Props + super::Show,`. Measures `item` as the item at `at` of a set, under the id and the item facts [`show_item`] shows it with. - `craft_ui::contract::pressed`: `pub fn pressed(response: &Response) -> bool`. Whether a pointer press went down on `response`'s component and is still held. - `craft_ui::contract::register_contract`: re-export of `craft_ui_macros::register_contract` (outside these crates). @@ -2825,6 +2836,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub const fn on_activate(mut self, on: bool) -> Self`. Closes when a component inside is activated, except an opener toggling its popup. - `pub const fn commands(mut self, on: bool) -> Self`. Closes when a key, a native menu pick or the palette runs a command from outside it; off for a layer its host - `pub const fn timeout(mut self, seconds: Option) -> Self`. Closes after `seconds`. +- `craft_ui::contract::overlay::DragBounds`: `pub enum DragBounds { Inside, TitleVisible }`. How much of a floating layer stays inside the window: the whole layer (`Inside`, the default) or a strip of its title. - `craft_ui::contract::overlay::FloatPlace`: `pub struct FloatPlace { pub pos: Option, pub corner: Align2 }`. Where a floating layer sits. - `pub const fn centred() -> Self`. Centred in the viewport. - `pub const fn at(pos: Pos2) -> Self`. With its left-top at `pos`. @@ -2834,7 +2846,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `craft_ui::contract::overlay::OpenFilter`: re-export of `craft_ui::runtime::overlay::OpenFilter`. - `craft_ui::contract::overlay::Opener`: `pub struct Opener { pub id: Id, pub rect: Rect, pub layer: areas::Layer, pub trigger: Trigger, pub enabled: bool, pub anchor: Option, pub others: Vec }`. A component that opens a free-standing popup, and how. A layer with several openers keeps the first as its - `craft_ui::contract::overlay::Outside`: `pub enum Outside { Close, Keep, Absorb }`. What a press outside the layer and its anchor does. -- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. +- `craft_ui::contract::overlay::Overlay`: `pub struct Overlay { pub place: Place, pub fit: OverlayFit, pub min_width: MinWidth, pub movable: bool, pub drag_bounds: DragBounds, pub resize: Resize, pub rank: Rank, pub keys: OwnerClass, pub focus: FocusPolicy, pub dismiss: Dismiss, pub motion: MotionSpec, pub opener: Option, pub popup: PopupKind, pub size: Option, pub size_limits: SizeLimits, pub placed: Option, pub placed_at: Option, pub bounds: Option, pub opacity: f32, pub body_scroll: bool, pub moves_window: bool, pub moved_by_app: bool, pub continue_move: Option, pub role: LayerRole, pub among_windows: bool }`. Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. - `pub fn popover() -> Overlay`. A popover: a popup anchored below, from its content, at least as wide as its anchor and capped by the window, - `pub fn dropdown() -> Overlay`. A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - `pub fn menu() -> Overlay`. A menu: a popup the arrow keys move through. A press outside closes it and goes no further. @@ -2864,7 +2876,9 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `pub fn opacity(mut self, opacity: f32) -> Overlay`. Sets the layer's opacity, from 0 (invisible) to 1. - `pub fn min_width(mut self, min_width: MinWidth) -> Overlay`. Sets the narrowest width. - `pub fn movable(mut self, on: bool) -> Overlay`. Sets whether the user may move it. + - `pub fn drag_bounds(mut self, bounds: DragBounds) -> Overlay`. Sets how much of the layer stays inside the window when the user moves it ([`DragBounds`]): - `pub fn role(mut self, role: LayerRole) -> Overlay`. Sets what the layer is for ([`Overlay::role`]). + - `pub fn among_windows(mut self, on: bool) -> Overlay`. Sets whether the layer stands among the floating windows ([`Overlay::among_windows`]). - `pub fn moves_window(mut self, on: bool) -> Overlay`. Sets whether the move band moves the OS window the layer is shown in, in place of the layer. - `pub fn moved_by_app(mut self) -> Overlay`. The app moves the OS window from the move band ([`Overlay::moved_by_app`]). - `pub fn continue_move(mut self, grab: Vec2) -> Overlay`. The move band takes over the held primary press in this pass, with the pointer at `grab` inside the layer @@ -2877,7 +2891,7 @@ Chapter 15: the `Overlay` data, its presets, popup handles, `OverlayUi` and the - `craft_ui::contract::overlay::OverlayFit`: `pub enum OverlayFit { Content, Resizable, ContentCapped(ViewportShare) }`. How an egui layer sizes. - `craft_ui::contract::overlay::OverlayUi`: `pub struct OverlayUi<'a> { pub closed: Vec<(Id, CloseReason)> }`. What the `overlay` hook gets: one call per anchored popup of this component, built at step 10 with the open state - `pub fn closing(&self, popup: PopupHandle) -> Option`. Why `popup` closes at the end of this pass, as its `show` decided (its dismissal, or a close its body asked for); - - `pub fn is_rtl(&self) -> bool`. Whether the owner lays out right to left: a layer its caller places by position mirrors its own geometry by it, + - `pub fn is_rtl(&self) -> bool`. Whether a layer the owner opens lays out right to left (`Scoped::layer_direction`): a layer its caller places by - `pub fn anchor_part(&self, part: impl Into) -> Anchor`. The anchor at the rect of the toggling part `part` of the owner. The layer's placement mirrors the side and - `pub fn contain_popups_below(&mut self)`. Keeps the popups this component shows from here on, and every popup opened from them, below the component: - `pub fn show(&mut self, popup: PopupHandle, overlay: Overlay, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Option`. Shows the popup while its handle is open, on a popup surface, inside `POPUP_PAD`; the content is a body closure. @@ -3153,6 +3167,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `craft_ui::primitives::Glyph`: `pub trait Glyph: Any + MemoProps + Sync`. A value glyph: an icon drawn from a value. It is `Sync` because container props that show one are kept with a - `fn directional(&self) -> bool`. Whether the glyph has a reading direction (an arrow) and so flips under right-to-left. - `fn paint(&self, painter: &Painter, tokens: &UiTokens, rect: Rect, color: Color32, mirrored: bool)`. Paints the glyph into `rect` in `color`, with the strokes of `tokens`. `mirrored` is set when a directional + - `fn paint_draw(&self, draw: &Draw<'_>, rect: Rect, color: Color32, mirrored: bool)`. Paints the glyph into `rect` in `color` with `draw`, the content painter of the component that shows the icon - `craft_ui::primitives::GridAxis`: `pub struct GridAxis { pub minor: Vec, pub major: Vec }`. The lines of one axis: positions along it, in the grid's space. - `craft_ui::primitives::GridCrowding`: `pub enum GridCrowding { Hide, Thin }`. What a grid does when its lines come closer than the minimum step. - `craft_ui::primitives::GridInk`: `pub struct GridInk { pub major: Option, pub minor: Option, pub stroke: GridStroke }`. The colours a grid's lines take; an unset one is the theme's. @@ -3297,7 +3312,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `pub fn row_lines(&self) -> Vec<(String, egui::Rect, Vec)>`. Every row as its text, its rect from the galley's origin and its bidi runs: the one per-row geometry, read by - `pub fn size(&self) -> egui::Vec2`. The galley size. - `pub fn char_x(&self, chars: usize) -> f32`. Where a caret before character `chars` (counted from the start of the text) stands, from the layout's left edge: -- `craft_ui::primitives::TextOptions`: `pub struct TextOptions { pub placeholder: Option

+ +# Kurbo + +**A Rust 2D curves library** + +[![Linebender Zulip, #kurbo channel](https://img.shields.io/badge/Linebender-%23kurbo-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/260979-kurbo) +[![dependency status](https://deps.rs/repo/github/linebender/kurbo/status.svg)](https://deps.rs/repo/github/linebender/kurbo) +[![Apache 2.0 or MIT license.](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](#license) +[![Build status](https://github.com/linebender/kurbo/workflows/CI/badge.svg)](https://github.com/linebender/kurbo/actions) +[![Crates.io](https://img.shields.io/crates/v/kurbo.svg)](https://crates.io/crates/kurbo) +[![Docs](https://docs.rs/kurbo/badge.svg)](https://docs.rs/kurbo) + +
+ +The Kurbo library contains data structures and algorithms for curves and vector paths. +It is probably most appropriate for creative tools, but is general enough it might be useful for other applications. + +The name "kurbo" is Esperanto for "curve". + +There is a focus on accuracy and good performance in high-accuracy conditions. +Thus, the library might be useful in engineering and science contexts as well, as opposed to visual arts where rough approximations are often sufficient. +Many approximate functions come with an accuracy parameter, and analytical solutions are used where they are practical. +An example is area calculation, which is done using Green's theorem. + +The library is still in fairly early development stages. +There are traits intended to be useful for general curves (not just Béziers), but these will probably be reorganized. + +## Minimum supported Rust Version (MSRV) + +This version of Kurbo has been verified to compile with **Rust 1.85** and later. + +Future versions of Kurbo might increase the Rust version requirement. +It will not be treated as a breaking change and as such can even happen with small patch releases. + +
+Click here if compiling fails. + +As time has passed, some of Kurbo's dependencies could have released versions with a higher Rust requirement. +If you encounter a compilation issue due to a dependency and don't want to upgrade your Rust toolchain, then you could downgrade the dependency. + +```sh +# Use the problematic dependency's name and version +cargo update -p package_name --precise 0.1.1 +``` + +
+ +## Similar crates + +Here we mention a few other curves libraries and touch on some of the decisions made differently here. + +* [lyon_geom] has a lot of very good vector algorithms. It's most focused on rendering. + +* [flo_curves] has good Bézier primitives, and seems tuned for animation. It's generic on the coordinate type, while we use `f64` for everything. + +* [vek] has both 2D and 3D Béziers among other things, and is tuned for game engines. + +Some code has been copied from lyon_geom with adaptation, thus the author of lyon_geom, Nicolas Silva, is credited in the [AUTHORS] file. + +## More info + +To learn more about Bézier curves, [A Primer on Bézier Curves] by Pomax is indispensable. + +## Community + +[![Linebender Zulip](https://img.shields.io/badge/Linebender-%23kurbo-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/260979-kurbo) + +Discussion of Kurbo development happens in the [Linebender Zulip](https://xi.zulipchat.com/), specifically the [#kurbo channel](https://xi.zulipchat.com/#narrow/channel/260979-kurbo). +All public content can be read without logging in. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. + +## Contribution + +Contributions are welcome by pull request. The [Rust code of conduct] applies. +Please feel free to add your name to the [AUTHORS] file in any substantive pull request. + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. + +[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct +[lyon_geom]: https://crates.io/crates/lyon_geom +[flo_curves]: https://crates.io/crates/flo_curves +[vek]: https://crates.io/crates/vek +[A Primer on Bézier Curves]: https://pomax.github.io/bezierinfo/ +[AUTHORS]: ./AUTHORS +[CHANGELOG.md]: ./CHANGELOG.md diff --git a/vendor/kurbo/SOURCE.json b/vendor/kurbo/SOURCE.json new file mode 100644 index 0000000000..e381d32cb7 --- /dev/null +++ b/vendor/kurbo/SOURCE.json @@ -0,0 +1,70 @@ +{ + "crate": "kurbo", + "source_repository": "https://crates.io/api/v1/crates/kurbo/0.13.1/download", + "source_revision": "0.13.1", + "source_directory": "kurbo-0.13.1", + "source_archive_sha256": "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2", + "upstream_repository": "https://github.com/linebender/kurbo", + "upstream_revision": "838b69ef35f3381cefc007d86aa8364f5a6dc673", + "upstream_directory": "kurbo", + "local_patches": [ + "In `src/stroke.rs`, `StrokeCtx::do_linear` skips a cusp, or the end point, whose tangent from the point before it is exactly zero, instead of passing the tangent to `do_join` and `do_line`, which divide by its length, so a collinear cubic whose cusps round onto the point before them or onto its end point no longer gives NaN coordinates. The test `stroke::tests::linear_cubic_with_coincident_cusps` covers it.", + "In `src/stroke.rs`, the stroker skips a quadratic or cubic whose start or end tangent from `PathSeg::tangents` is zero, as it skips a zero-length line, so a closed loop with control arms shorter than 1e-6 no longer gives NaN coordinates; a quadratic's own tangents are passed on to `do_cubic` and `do_linear`, since the cubic it raises to has control arms 2/3 as long. The test `stroke::tests::tiny_closed_loops` covers it." + ], + "files": [ + { "path": ".cargo_vcs_info.json", "source_sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66", "source_git_blob": null, "sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66" }, + { "path": "Cargo.lock", "source_sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90", "source_git_blob": null, "sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90" }, + { "path": "Cargo.toml", "source_sha256": "3c5b41c42b588b750fbca3109b48438288586c2b22fdda571ea0fc188b6e08b0", "source_git_blob": null, "sha256": "3c5b41c42b588b750fbca3109b48438288586c2b22fdda571ea0fc188b6e08b0" }, + { "path": "Cargo.toml.orig", "source_sha256": "20e9fc1c17fd24b20c7eba09b657f999cc503999b18051dcdf7770e581fab175", "source_git_blob": null, "sha256": "20e9fc1c17fd24b20c7eba09b657f999cc503999b18051dcdf7770e581fab175" }, + { "path": "LICENSE-APACHE", "source_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", "source_git_blob": null, "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" }, + { "path": "LICENSE-MIT", "source_sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e", "source_git_blob": null, "sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e" }, + { "path": "README.md", "source_sha256": "d731f0edd82b188d9156cfbd909a1fdce6dd7424299b5d9ab540135d20693aab", "source_git_blob": null, "sha256": "d731f0edd82b188d9156cfbd909a1fdce6dd7424299b5d9ab540135d20693aab" }, + { "path": "benches/cubic.rs", "source_sha256": "753d2822c69a8684032a3b4a5f40e3b03ea4b4553cd8aba39fe6afd159711ab9", "source_git_blob": null, "sha256": "753d2822c69a8684032a3b4a5f40e3b03ea4b4553cd8aba39fe6afd159711ab9" }, + { "path": "benches/cubic_arclen.rs", "source_sha256": "93ad92e94f421ef9b7ee60ed3b59909a59554ade76a18279ccacf8bfcd715477", "source_git_blob": null, "sha256": "93ad92e94f421ef9b7ee60ed3b59909a59554ade76a18279ccacf8bfcd715477" }, + { "path": "benches/nearest.rs", "source_sha256": "8cbf5ead45bce5ea79d1234f72fae704042162a934228b3af9611cf0932ef5fd", "source_git_blob": null, "sha256": "8cbf5ead45bce5ea79d1234f72fae704042162a934228b3af9611cf0932ef5fd" }, + { "path": "benches/quad_arclen.rs", "source_sha256": "f447a066c32703cbbba14bed66f419841cca1cb83e01ca7511e6f09a5d115e20", "source_git_blob": null, "sha256": "f447a066c32703cbbba14bed66f419841cca1cb83e01ca7511e6f09a5d115e20" }, + { "path": "benches/quartic.rs", "source_sha256": "3535c44734c559992b3f62077e5d933300777e248251b883b1451457280df1f3", "source_git_blob": null, "sha256": "3535c44734c559992b3f62077e5d933300777e248251b883b1451457280df1f3" }, + { "path": "benches/rect_expand.rs", "source_sha256": "496b987a239680b61b2d65b0ab91cbfab55c807cc1831476bcb08129c092f8de", "source_git_blob": null, "sha256": "496b987a239680b61b2d65b0ab91cbfab55c807cc1831476bcb08129c092f8de" }, + { "path": "examples/arclen_accuracy.rs", "source_sha256": "7bf354d4d34b42e915e082774d74177209b2997b09ee6972a38cb32dfaf385b2", "source_git_blob": null, "sha256": "7bf354d4d34b42e915e082774d74177209b2997b09ee6972a38cb32dfaf385b2" }, + { "path": "examples/circle.rs", "source_sha256": "1416fe74c7a82b15b1d2ee4166d09a75cf8cc9ac6744dddc7df338881258ded3", "source_git_blob": null, "sha256": "1416fe74c7a82b15b1d2ee4166d09a75cf8cc9ac6744dddc7df338881258ded3" }, + { "path": "examples/cubic_arclen.rs", "source_sha256": "467bcf52b26e3480ad05dddbd06374ce219df54b7dc1fa7fb96367eed41e1d5b", "source_git_blob": null, "sha256": "467bcf52b26e3480ad05dddbd06374ce219df54b7dc1fa7fb96367eed41e1d5b" }, + { "path": "examples/ellipse.rs", "source_sha256": "22db083067328d2d4f80a2be1ba1cf7e5478950ecde99142563a4cd9fa6dfaca", "source_git_blob": null, "sha256": "22db083067328d2d4f80a2be1ba1cf7e5478950ecde99142563a4cd9fa6dfaca" }, + { "path": "examples/fit_poly.rs", "source_sha256": "ed1d8adaf2e0adcee445cfd4fd06a110f064455ef382354ec2a99d3450442654", "source_git_blob": null, "sha256": "ed1d8adaf2e0adcee445cfd4fd06a110f064455ef382354ec2a99d3450442654" }, + { "path": "examples/quad_intersect.rs", "source_sha256": "56becf3a522316e1c54eaae7d2d75365fa275bbfc17bb2bf6884d63bf887d88a", "source_git_blob": null, "sha256": "56becf3a522316e1c54eaae7d2d75365fa275bbfc17bb2bf6884d63bf887d88a" }, + { "path": "examples/simplify.rs", "source_sha256": "7bd3fdcfd60fe9094b9f5da51be4a70061f3df760a62a0ae62e7e8c77f649558", "source_git_blob": null, "sha256": "7bd3fdcfd60fe9094b9f5da51be4a70061f3df760a62a0ae62e7e8c77f649558" }, + { "path": "examples/stroke.rs", "source_sha256": "f055edc18fc05c55c2a3f9ad2e3caa6b997e2d9cd7c5781959d752182afe1b90", "source_git_blob": null, "sha256": "f055edc18fc05c55c2a3f9ad2e3caa6b997e2d9cd7c5781959d752182afe1b90" }, + { "path": "src/affine.rs", "source_sha256": "7288c89bb5ce16acd7d1b046f189df5855cfafa0454d667fc7b0dc4454fa2663", "source_git_blob": null, "sha256": "7288c89bb5ce16acd7d1b046f189df5855cfafa0454d667fc7b0dc4454fa2663" }, + { "path": "src/arc.rs", "source_sha256": "f1479f3e54c7e4717424920f128ebfda59ea2984c08b43291411072072eb1475", "source_git_blob": null, "sha256": "f1479f3e54c7e4717424920f128ebfda59ea2984c08b43291411072072eb1475" }, + { "path": "src/axis.rs", "source_sha256": "6ccf1f4cca904fa43f54d9d71a6511927fdab171a8d00382ab311cd2776ef781", "source_git_blob": null, "sha256": "6ccf1f4cca904fa43f54d9d71a6511927fdab171a8d00382ab311cd2776ef781" }, + { "path": "src/bezpath.rs", "source_sha256": "6d9d5769715dfc4c10f90c1de500fca7a2ca35c0d673d2e05d7ddd615a987be4", "source_git_blob": null, "sha256": "6d9d5769715dfc4c10f90c1de500fca7a2ca35c0d673d2e05d7ddd615a987be4" }, + { "path": "src/circle.rs", "source_sha256": "434d23a89e13ad22be300c383cdf027e41a9ccfbd8a3f9152c1e97a5ad330491", "source_git_blob": null, "sha256": "434d23a89e13ad22be300c383cdf027e41a9ccfbd8a3f9152c1e97a5ad330491" }, + { "path": "src/common.rs", "source_sha256": "5d32994b9832dc34738a0d34464d9b2435398404bfd576c838584c301359d062", "source_git_blob": null, "sha256": "5d32994b9832dc34738a0d34464d9b2435398404bfd576c838584c301359d062" }, + { "path": "src/cubicbez.rs", "source_sha256": "de793f84444c55467a4669de64b4a06209f97540362c2da1fe0ad2b2367f5b80", "source_git_blob": null, "sha256": "de793f84444c55467a4669de64b4a06209f97540362c2da1fe0ad2b2367f5b80" }, + { "path": "src/ellipse.rs", "source_sha256": "991e9830a32643d2aa5c34c57330323e65f3b15231c80b086eb715b0665fc41d", "source_git_blob": null, "sha256": "991e9830a32643d2aa5c34c57330323e65f3b15231c80b086eb715b0665fc41d" }, + { "path": "src/expand.rs", "source_sha256": "f0ef21c91790097498bfacd2cc624f6ac86b32bc2600aa78c57583e46c5d0ae6", "source_git_blob": null, "sha256": "f0ef21c91790097498bfacd2cc624f6ac86b32bc2600aa78c57583e46c5d0ae6" }, + { "path": "src/fit.rs", "source_sha256": "3d7dace4a4452ce6a5eff3186a48f8dc0d0d625029feae78c24017fb5b68695b", "source_git_blob": null, "sha256": "3d7dace4a4452ce6a5eff3186a48f8dc0d0d625029feae78c24017fb5b68695b" }, + { "path": "src/insets.rs", "source_sha256": "cf6019c2ab0783ede641ef61677b60d4c2cf4f721317024a0944e8c66373dc98", "source_git_blob": null, "sha256": "cf6019c2ab0783ede641ef61677b60d4c2cf4f721317024a0944e8c66373dc98" }, + { "path": "src/interop_euclid.rs", "source_sha256": "bc94da5023b455df685b74cd942d569e1ee5025191c64ff4217f068d845b9418", "source_git_blob": null, "sha256": "bc94da5023b455df685b74cd942d569e1ee5025191c64ff4217f068d845b9418" }, + { "path": "src/lib.rs", "source_sha256": "f513dc1a758bc061cc2a177fa98a1d566003d6c83e36d3befbc9bbea2e4349e7", "source_git_blob": null, "sha256": "f513dc1a758bc061cc2a177fa98a1d566003d6c83e36d3befbc9bbea2e4349e7" }, + { "path": "src/line.rs", "source_sha256": "66fba2df6d9653aa03adfda457a5059a7cbdd1ae29fa2c2db4ba5aefb1d4db28", "source_git_blob": null, "sha256": "66fba2df6d9653aa03adfda457a5059a7cbdd1ae29fa2c2db4ba5aefb1d4db28" }, + { "path": "src/mindist.rs", "source_sha256": "3f6e98e5cc25395e042bcd3138abd237176034cbddb13d48a11b66f581d724e4", "source_git_blob": null, "sha256": "3f6e98e5cc25395e042bcd3138abd237176034cbddb13d48a11b66f581d724e4" }, + { "path": "src/moments.rs", "source_sha256": "decf10b9116aacab2bab47c8b331a6a5e3ba16b3c63527710289cedc5df930a0", "source_git_blob": null, "sha256": "decf10b9116aacab2bab47c8b331a6a5e3ba16b3c63527710289cedc5df930a0" }, + { "path": "src/offset.rs", "source_sha256": "8999fdb31334a6c08c260f2ae360aba3b091652e26454b735ea985c99a545cd9", "source_git_blob": null, "sha256": "8999fdb31334a6c08c260f2ae360aba3b091652e26454b735ea985c99a545cd9" }, + { "path": "src/param_curve.rs", "source_sha256": "5cac1495643a9cb5f4af7ea618265a9deb87e7f82ee9628fdb46c49fd970a553", "source_git_blob": null, "sha256": "5cac1495643a9cb5f4af7ea618265a9deb87e7f82ee9628fdb46c49fd970a553" }, + { "path": "src/point.rs", "source_sha256": "4311047b9497b4fbd38022eb62ebaa9771c05e55e1bafb9431f2243949515ca7", "source_git_blob": null, "sha256": "4311047b9497b4fbd38022eb62ebaa9771c05e55e1bafb9431f2243949515ca7" }, + { "path": "src/quadbez.rs", "source_sha256": "37ab1037750d32eed6b3664b250a8c14c78419a1567e790695c0e46544263bbd", "source_git_blob": null, "sha256": "37ab1037750d32eed6b3664b250a8c14c78419a1567e790695c0e46544263bbd" }, + { "path": "src/quadspline.rs", "source_sha256": "cfa129dd52d23a7852be3a1103e8022cc792cb2bd481440d3ebc1221a635e28d", "source_git_blob": null, "sha256": "cfa129dd52d23a7852be3a1103e8022cc792cb2bd481440d3ebc1221a635e28d" }, + { "path": "src/rect.rs", "source_sha256": "20c0bca0e79ab1b69321bf5d7e2db618cb4582bb29f47854faa5979a38a9ff2a", "source_git_blob": null, "sha256": "20c0bca0e79ab1b69321bf5d7e2db618cb4582bb29f47854faa5979a38a9ff2a" }, + { "path": "src/rounded_rect.rs", "source_sha256": "495d08f409456a97cd8c228f84624383922c4ef01e4d2edf624a40765a12b3c4", "source_git_blob": null, "sha256": "495d08f409456a97cd8c228f84624383922c4ef01e4d2edf624a40765a12b3c4" }, + { "path": "src/rounded_rect_radii.rs", "source_sha256": "ac42ee920ff31c6b5524ea9ae22e9da8ad2a8d17572e9ade1c369d827b8004d7", "source_git_blob": null, "sha256": "ac42ee920ff31c6b5524ea9ae22e9da8ad2a8d17572e9ade1c369d827b8004d7" }, + { "path": "src/shape.rs", "source_sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae", "source_git_blob": null, "sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae" }, + { "path": "src/simplify.rs", "source_sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684", "source_git_blob": null, "sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684" }, + { "path": "src/size.rs", "source_sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950", "source_git_blob": null, "sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950" }, + { "path": "src/stroke.rs", "source_sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498", "source_git_blob": null, "sha256": "18f6f59a8935516f42c8790cda61f6e0993c33dc0d9db8fbe1b6b3bb4c6a6cf0" }, + { "path": "src/svg.rs", "source_sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be", "source_git_blob": null, "sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be" }, + { "path": "src/translate_scale.rs", "source_sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a", "source_git_blob": null, "sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a" }, + { "path": "src/triangle.rs", "source_sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e", "source_git_blob": null, "sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e" }, + { "path": "src/vec2.rs", "source_sha256": "05b37bf834417a040012fef380aa9eb10925324ea1a07fba3328839a56c9a060", "source_git_blob": null, "sha256": "05b37bf834417a040012fef380aa9eb10925324ea1a07fba3328839a56c9a060" } + ], + "omitted_files": [] +} diff --git a/vendor/kurbo/benches/cubic.rs b/vendor/kurbo/benches/cubic.rs new file mode 100644 index 0000000000..17ad29b9f4 --- /dev/null +++ b/vendor/kurbo/benches/cubic.rs @@ -0,0 +1,25 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of the cubic equation solver. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::common::solve_cubic; + +fn bench_cubic(cc: &mut Criterion) { + let (x1, x2, x3) = (1.0, 2.0, 3.0); + let a = -(x1 + x2 + x3); + let b = x1 * x2 + x1 * x3 + x2 * x3; + let c = -x1 * x2 * x3; + + cc.bench_function("cubic roots", |bb| { + bb.iter(|| solve_cubic(black_box(c), black_box(b), black_box(a), 1.0)); + }); +} + +criterion_group!(benches, bench_cubic); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/cubic_arclen.rs b/vendor/kurbo/benches/cubic_arclen.rs new file mode 100644 index 0000000000..c8c93a02b3 --- /dev/null +++ b/vendor/kurbo/benches/cubic_arclen.rs @@ -0,0 +1,36 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of cubic arclength approaches. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::{CubicBez, ParamCurveArclen}; + +fn bench_cubic_arclen(cc: &mut Criterion) { + { + let mut group = cc.benchmark_group("cubic_arclen"); + for accuracy in [1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9] { + group.bench_with_input( + BenchmarkId::from_parameter(accuracy), + &accuracy, + |b, &accuracy| { + let c = + CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0), (1.0, 1.0)); + b.iter(|| black_box(c).arclen(accuracy)); + }, + ); + } + } + + cc.bench_function("cubic_arclen degenerate", |b| { + let c = CubicBez::new((0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)); + b.iter(|| black_box(c).arclen(1e-6)); + }); +} + +criterion_group!(benches, bench_cubic_arclen); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/nearest.rs b/vendor/kurbo/benches/nearest.rs new file mode 100644 index 0000000000..73e9fcbb59 --- /dev/null +++ b/vendor/kurbo/benches/nearest.rs @@ -0,0 +1,53 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of the quartic equation solver. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::{CubicBez, ParamCurveNearest as _, Point, QuadBez}; + +fn bench_nearest_quadratic(cc: &mut Criterion) { + let q = QuadBez { + p0: (-1.0, -1.0).into(), + p1: (0.0, 2.0).into(), + p2: (1.0, -1.0).into(), + }; + let p = Point::new(0.0, 0.0); + + for acc in [1e-3, 1e-6, 1e-12] { + cc.bench_with_input( + BenchmarkId::new("quadratic nearest point", acc), + &acc, + |bb, acc| { + bb.iter(|| black_box(q).nearest(black_box(p), *acc)); + }, + ); + } +} + +fn bench_nearest_cubic(cc: &mut Criterion) { + let c = CubicBez { + p0: (-1.0, -1.0).into(), + p1: (0.0, 2.0).into(), + p2: (1.0, -1.0).into(), + p3: (2.0, 2.0).into(), + }; + let p = Point::new(0.0, 0.0); + + for acc in [1e-3, 1e-6, 1e-12] { + cc.bench_with_input( + BenchmarkId::new("cubic nearest point", acc), + &acc, + |bb, acc| { + bb.iter(|| black_box(c).nearest(black_box(p), *acc)); + }, + ); + } +} + +criterion_group!(benches, bench_nearest_quadratic, bench_nearest_cubic); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/quad_arclen.rs b/vendor/kurbo/benches/quad_arclen.rs new file mode 100644 index 0000000000..208c8ce2ab --- /dev/null +++ b/vendor/kurbo/benches/quad_arclen.rs @@ -0,0 +1,170 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of quadratic arclength approaches. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +// TODO: organize so there's less cut'n'paste from arclen_accuracy example. + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv, QuadBez}; + +// Based on http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/ +fn quad_arclen_analytical(q: QuadBez) -> f64 { + let d2 = q.p0.to_vec2() - 2.0 * q.p1.to_vec2() + q.p2.to_vec2(); + let a = d2.hypot2(); + let d1 = q.p1 - q.p0; + let b = 2.0 * d2.dot(d1); + let c = d1.hypot2(); + + let sabc = (a + b + c).sqrt(); + let a2 = a.powf(-0.5); + let a32 = a2.powi(3); + let c2 = 2.0 * c.sqrt(); + let ba = b * a2; + + sabc + 0.25 + * (a2 * a2 * b * (2.0 * sabc - c2) + + a32 * (4.0 * c * a - b * b) * (((2.0 * a + b) * a2 + 2.0 * sabc) / (ba + c2)).ln()) +} + +/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad +/// in +fn gauss_arclen_3(q: QuadBez) -> f64 { + let v0 = (-0.492943519233745 * q.p0.to_vec2() + + 0.430331482911935 * q.p1.to_vec2() + + 0.0626120363218102 * q.p2.to_vec2()) + .hypot(); + let v1 = ((q.p2 - q.p0) * 0.4444444444444444).hypot(); + let v2 = (-0.0626120363218102 * q.p0.to_vec2() - 0.430331482911935 * q.p1.to_vec2() + + 0.492943519233745 * q.p2.to_vec2()) + .hypot(); + v0 + v1 + v2 +} + +fn awesome_quad_arclen3(q: QuadBez, accuracy: f64, depth: usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 0.06 * (lp - lc) * (x * x + y * y).powf(2.0); + if est_err < accuracy || depth == 16 { + gauss_arclen_3(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen3(q0, accuracy * 0.5, depth + 1) + + awesome_quad_arclen3(q1, accuracy * 0.5, depth + 1) + } +} + +/// Another implementation, using weights from +/// +fn gauss_arclen_n(q: QuadBez, coeffs: &[(f64, f64)]) -> f64 { + let d = q.deriv(); + coeffs + .iter() + .map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot()) + .sum::() + * 0.5 +} + +fn gauss_arclen_7(q: QuadBez) -> f64 { + gauss_arclen_n( + q, + &[ + (0.4179591836734694, 0.0000000000000000), + (0.3818300505051189, 0.4058451513773972), + (0.3818300505051189, -0.4058451513773972), + (0.2797053914892766, -0.7415311855993945), + (0.2797053914892766, 0.7415311855993945), + (0.1294849661688697, -0.9491079123427585), + (0.1294849661688697, 0.9491079123427585), + ], + ) +} + +fn gauss_arclen_24(q: QuadBez) -> f64 { + gauss_arclen_n( + q, + &[ + (0.1279381953467522, -0.0640568928626056), + (0.1279381953467522, 0.0640568928626056), + (0.1258374563468283, -0.1911188674736163), + (0.1258374563468283, 0.1911188674736163), + (0.1216704729278034, -0.3150426796961634), + (0.1216704729278034, 0.3150426796961634), + (0.1155056680537256, -0.4337935076260451), + (0.1155056680537256, 0.4337935076260451), + (0.1074442701159656, -0.5454214713888396), + (0.1074442701159656, 0.5454214713888396), + (0.0976186521041139, -0.6480936519369755), + (0.0976186521041139, 0.6480936519369755), + (0.0861901615319533, -0.7401241915785544), + (0.0861901615319533, 0.7401241915785544), + (0.0733464814110803, -0.820001985973903), + (0.0733464814110803, 0.820001985973903), + (0.0592985849154368, -0.8864155270044011), + (0.0592985849154368, 0.8864155270044011), + (0.0442774388174198, -0.9382745520027328), + (0.0442774388174198, 0.9382745520027328), + (0.0285313886289337, -0.9747285559713095), + (0.0285313886289337, 0.9747285559713095), + (0.0123412297999872, -0.9951872199970213), + (0.0123412297999872, 0.9951872199970213), + ], + ) +} + +fn awesome_quad_arclen7(q: QuadBez, accuracy: f64, depth: usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = dhypot2.sqrt(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 2.5e-2 * (lp - lc) * (x * x + y * y).powf(8.0).tanh(); + if est_err < accuracy || depth == 16 { + gauss_arclen_7(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen7(q0, accuracy * 0.5, depth + 1) + + awesome_quad_arclen7(q1, accuracy * 0.5, depth + 1) + } +} + +const ACCURACY: f64 = 1e-6; +fn bench_quad_arclen(cc: &mut Criterion) { + let q = QuadBez::new((0.0, 0.0), (1.0, 0.0), (1.0, 1.0)); + + cc.bench_function("quad_arclen_analytical", |b| { + b.iter(|| quad_arclen_analytical(black_box(q))); + }); + cc.bench_function("quad_arclen", |b| b.iter(|| black_box(q).arclen(ACCURACY))); + cc.bench_function("quad_arclen_gauss3", |b| { + b.iter(|| awesome_quad_arclen3(black_box(q), ACCURACY, 0)); + }); + cc.bench_function("quad_arclen_gauss7", |b| { + b.iter(|| awesome_quad_arclen7(black_box(q), ACCURACY, 0)); + }); + cc.bench_function("quad_arclen_gauss3_one", |b| { + b.iter(|| gauss_arclen_3(black_box(q))); + }); + cc.bench_function("quad_arclen_gauss7_one", |b| { + b.iter(|| gauss_arclen_7(black_box(q))); + }); + cc.bench_function("quad_arclen_gauss24_one", |b| { + b.iter(|| gauss_arclen_24(black_box(q))); + }); +} + +criterion_group!(benches, bench_quad_arclen); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/quartic.rs b/vendor/kurbo/benches/quartic.rs new file mode 100644 index 0000000000..b75bff3a58 --- /dev/null +++ b/vendor/kurbo/benches/quartic.rs @@ -0,0 +1,26 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of the quartic equation solver. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::common::solve_quartic; + +fn bench_quartic(cc: &mut Criterion) { + let (x1, x2, x3, x4) = (1.0, 2.0, 3.0, 4.0); + let a = -(x1 + x2 + x3 + x4); + let b = x1 * (x2 + x3) + x2 * (x3 + x4) + x4 * (x1 + x3); + let c = -x1 * x2 * (x3 + x4) - x3 * x4 * (x1 + x2); + let d = x1 * x2 * x3 * x4; + + cc.bench_function("quartic roots", |bb| { + bb.iter(|| solve_quartic(black_box(d), black_box(c), black_box(b), black_box(a), 1.0)); + }); +} + +criterion_group!(benches, bench_quartic); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/rect_expand.rs b/vendor/kurbo/benches/rect_expand.rs new file mode 100644 index 0000000000..0b9d51a0d3 --- /dev/null +++ b/vendor/kurbo/benches/rect_expand.rs @@ -0,0 +1,56 @@ +// Copyright 2020 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of rect expansion. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::Rect; + +// In positive space +static RECT_POS: Rect = Rect::new(3.3, 3.6, 5.6, 4.1); +// In both positive and negative space +static RECT_PAN: Rect = Rect::new(-3.3, -3.6, 5.6, 4.1); +// In negative space +static RECT_NEG: Rect = Rect::new(-5.6, -4.1, -3.3, -3.6); +// In positive space reverse +static RECT_POR: Rect = Rect::new(5.6, 4.1, 3.3, 3.6); +// In both positive and negative space reverse +static RECT_PNR: Rect = Rect::new(5.6, 4.1, -3.3, -3.6); +// In negative space reverse +static RECT_NER: Rect = Rect::new(-3.3, -3.6, -5.6, -4.1); +// In positive space mixed +static RECT_POM: Rect = Rect::new(3.3, 4.1, 5.6, 3.6); +// In both positive and negative space mixed +static RECT_PNM: Rect = Rect::new(-3.3, 4.1, 5.6, -3.6); +// In negative space mixed +static RECT_NEM: Rect = Rect::new(-5.6, -3.6, -3.3, -4.1); + +#[inline] +fn expand(rects: &[Rect; 9]) { + black_box(rects[0].expand()); + black_box(rects[1].expand()); + black_box(rects[2].expand()); + + black_box(rects[3].expand()); + black_box(rects[4].expand()); + black_box(rects[5].expand()); + + black_box(rects[6].expand()); + black_box(rects[7].expand()); + black_box(rects[8].expand()); +} + +fn bench_expand(c: &mut Criterion) { + // Creating the array here to prevent the compiler from optimizing all of it to NOP. + let rects: [Rect; 9] = [ + RECT_POS, RECT_PAN, RECT_NEG, RECT_POR, RECT_PNR, RECT_NER, RECT_POM, RECT_PNM, RECT_NEM, + ]; + c.bench_function("expand", |b| b.iter(|| expand(&rects))); +} + +criterion_group!(benches, bench_expand); +criterion_main!(benches); diff --git a/vendor/kurbo/examples/arclen_accuracy.rs b/vendor/kurbo/examples/arclen_accuracy.rs new file mode 100644 index 0000000000..7c47d87ce3 --- /dev/null +++ b/vendor/kurbo/examples/arclen_accuracy.rs @@ -0,0 +1,248 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A test program to plot the error of arclength approximation. + +#![allow(unused, reason = "a bunch of experiments in the code")] + +// TODO: make more functionality accessible from command line rather than uncommenting. + +use std::env; +use std::time::{Duration, Instant}; + +use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv, QuadBez}; + +use kurbo::common::{GAUSS_LEGENDRE_COEFFS_5, GAUSS_LEGENDRE_COEFFS_7, GAUSS_LEGENDRE_COEFFS_24}; + +/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad +/// in +fn gauss_arclen_3(q: QuadBez) -> f64 { + let v0 = (-0.492943519233745 * q.p0.to_vec2() + + 0.430331482911935 * q.p1.to_vec2() + + 0.0626120363218102 * q.p2.to_vec2()) + .hypot(); + let v1 = ((q.p2 - q.p0) * 0.4444444444444444).hypot(); + let v2 = (-0.0626120363218102 * q.p0.to_vec2() - 0.430331482911935 * q.p1.to_vec2() + + 0.492943519233745 * q.p2.to_vec2()) + .hypot(); + v0 + v1 + v2 +} + +fn awesome_quad_arclen(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 0.06 * (lp - lc) * (x * x + y * y).powf(2.0); + if est_err < accuracy || depth == 16 { + *count += 1; + gauss_arclen_3(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen(q0, accuracy * 0.5, depth + 1, count) + + awesome_quad_arclen(q1, accuracy * 0.5, depth + 1, count) + } +} + +const MAX_DEPTH: usize = 16; +fn gravesen_rec(q: &QuadBez, l0: f64, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let (q0, q1) = q.subdivide(); + let l0_q0 = calc_l0(q0); + let l0_q1 = calc_l0(q1); + let l1 = l0_q0 + l0_q1; + let error = (l0 - l1) * (1.0 / 15.0); + if error.abs() < accuracy || depth == MAX_DEPTH { + *count += 1; + l1 - error + } else { + gravesen_rec(&q0, l0_q0, accuracy * 0.5, depth + 1, count) + + gravesen_rec(&q1, l0_q1, accuracy * 0.5, depth + 1, count) + } +} + +fn gauss_arclen_5(q: QuadBez) -> f64 { + q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_5) +} + +fn gauss_arclen_7(q: QuadBez) -> f64 { + q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_7) +} + +fn gauss_arclen_24(q: QuadBez) -> f64 { + q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_24) +} + +fn awesome_quad_arclen7(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 2.5e-2 * (lp - lc) * (x * x + y * y).powf(8.0).tanh(); + // Increase depth, so we can be an accurate baseline for comparison. + if est_err < accuracy || depth == 22 { + *count += 1; + gauss_arclen_7(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen7(q0, accuracy * 0.5, depth + 1, count) + + awesome_quad_arclen7(q1, accuracy * 0.5, depth + 1, count) + } +} + +fn awesome_quad_arclen24(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + // This isn't quite right near (1.1, 0) + let est_err = 1.0 * (lp - lc) * (0.5 * x * x + 0.1 * y * y).powf(16.0).tanh(); + if est_err < accuracy || depth == 16 { + *count += 1; + gauss_arclen_24(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen24(q0, accuracy * 0.5, depth + 1, count) + + awesome_quad_arclen24(q1, accuracy * 0.5, depth + 1, count) + } +} + +// Based on http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/ +fn quad_arclen_analytical(q: QuadBez) -> f64 { + let d2 = q.p0.to_vec2() - 2.0 * q.p1.to_vec2() + q.p2.to_vec2(); + let a = d2.hypot2(); + let d1 = q.p1 - q.p0; + let c = d1.hypot2(); + if a < 5e-4 * c { + return gauss_arclen_3(q); + } + let b = 2.0 * d2.dot(d1); + + let sabc = (a + b + c).sqrt(); + let a2 = a.powf(-0.5); + let a32 = a2.powi(3); + let c2 = 2.0 * c.sqrt(); + let ba_c2 = b * a2 + c2; + + let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc; + // TODO: justify and fine-tune this exact constant. + if ba_c2 < 1e-13 { + // This case happens for Béziers with a sharp kink. + v0 + } else { + v0 + 0.25 * a32 * (4.0 * c * a - b * b) * (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln() + } +} + +/// Calculate the L0 metric from "Adaptive subdivision and the length and +/// energy of Bézier curves" by Jens Gravesen. +fn calc_l0(q: QuadBez) -> f64 { + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + (2.0 / 3.0) * lc + (1.0 / 3.0) * lp +} + +fn with_subdiv(q: QuadBez, f: &dyn Fn(QuadBez) -> f64, depth: usize) -> f64 { + if depth == 0 { + f(q) + } else { + let (q0, q1) = q.subdivide(); + with_subdiv(q0, f, depth - 1) + with_subdiv(q1, f, depth - 1) + } +} + +fn duration_to_time(d: Duration) -> f64 { + 1e-9 * (d.subsec_nanos() as f64) + (d.as_secs() as f64) +} + +fn run_simple() { + let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0)); + let true_len = q.arclen(1e-13); + for i in 0..20 { + let n = 1 << i; + let start_time = Instant::now(); + let mut est = 0.0; + let mut last = q.start(); + let dt = (n as f64).recip(); + for j in 0..n { + let t = ((j + 1) as f64) * dt; + let p = q.eval(t); + est += (p - last).hypot(); + last = p; + } + let elapsed = duration_to_time(start_time.elapsed()); + let err = true_len - est; + if i > 0 { + println!("{elapsed} {err}"); + } + } +} + +/// Generate map data suitable for plotting in Gnuplot. +fn main() { + let mut n_subdiv = 0; + let mut func: &dyn Fn(QuadBez) -> f64 = &gauss_arclen_3; + for arg in env::args().skip(1) { + if arg == "gauss3" { + func = &gauss_arclen_3; + } else if arg == "gauss5" { + func = &gauss_arclen_5; + } else if arg == "gauss7" { + func = &gauss_arclen_7; + } else if arg == "gauss24" { + func = &gauss_arclen_24; + } else if arg == "l0" { + func = &calc_l0; + } else if arg == "simple" { + run_simple(); + return; + } else if let Ok(n) = arg.parse() { + n_subdiv = n; + } else { + println!("usage: arclen_accuracy [func] n_subdiv"); + std::process::exit(1); + } + } + let n = 400; + let accuracy = 1e-6; + for i in 0..=n { + let x = 2.0 * (i as f64) * (n as f64).recip(); + for j in 0..=n { + let y = 2.0 * (j as f64) * (n as f64).recip(); + let q = QuadBez::new((-1.0, 0.0), (x, y), (1.0, 0.0)); + let mut count = 0; + let accurate_arclen = awesome_quad_arclen7(q, 1e-15, 0, &mut count); + //count = 0; + let start_time = Instant::now(); + //let est = awesome_quad_arclen7(q, accuracy, 0, &mut count); + let est = quad_arclen_analytical(q); + let elapsed = start_time.elapsed(); + //let est = gravesen_rec(&q, calc_l0(q), accuracy, 0, &mut count); + //let est = with_subdiv(q, func, n_subdiv); + let error = est - accurate_arclen; + println!("{} {} {}", x, y, (error.abs() + 1e-18).log10()); + //println!("{} {} {}", x, y, count); + //println!("{} {} {}", x, y, elapsed.subsec_nanos()); + //let accurate_arclen = with_subdiv(q, &gauss_arclen_5, 8); + //let error = est - accurate_arclen; + /* + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 1.0 * (lp - lc) * (0.5 * x * x + 0.1 * y * y).powf(16.0).tanh(); + println!("{} {} {}", x, y, (est_err/error.abs() + 1e-15).log10()); + */ + } + println!(); + } +} diff --git a/vendor/kurbo/examples/circle.rs b/vendor/kurbo/examples/circle.rs new file mode 100644 index 0000000000..207eaa37aa --- /dev/null +++ b/vendor/kurbo/examples/circle.rs @@ -0,0 +1,27 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Example of circle + +#[cfg(feature = "std")] +fn main() { + use kurbo::{Circle, Shape}; + + let circle = Circle::new((400.0, 400.0), 380.0); + println!(""); + println!(""); + println!(""); + println!(""); + let black_path = circle.to_path(1e-3).to_svg(); + println!(" "); + let red_path = circle.to_path(1.0).to_svg(); + println!(" "); + println!(""); + println!(""); + println!(""); +} + +#[cfg(not(feature = "std"))] +fn main() { + println!("This example requires the standard library"); +} diff --git a/vendor/kurbo/examples/cubic_arclen.rs b/vendor/kurbo/examples/cubic_arclen.rs new file mode 100644 index 0000000000..b019884d7f --- /dev/null +++ b/vendor/kurbo/examples/cubic_arclen.rs @@ -0,0 +1,256 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Research testbed for arclengths of cubic Bézier segments. + +#![allow(unused, reason = "a bunch of experiments in the code")] + +use kurbo::common::{GAUSS_LEGENDRE_COEFFS_7, GAUSS_LEGENDRE_COEFFS_9, GAUSS_LEGENDRE_COEFFS_11}; +use kurbo::{ + CubicBez, ParamCurve, ParamCurveArclen, ParamCurveCurvature, ParamCurveDeriv, Point, Vec2, +}; + +/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad +/// in +fn gauss_arclen_5(c: CubicBez) -> f64 { + let v0 = (c.p1 - c.p0).hypot() * 0.15; + let v1 = (-0.558983582205757 * c.p0.to_vec2() + + 0.325650248872424 * c.p1.to_vec2() + + 0.208983582205757 * c.p2.to_vec2() + + 0.024349751127576 * c.p3.to_vec2()) + .hypot(); + let v2 = (c.p3 - c.p0 + (c.p2 - c.p1)).hypot() * 0.26666666666666666; + let v3 = (-0.024349751127576 * c.p0.to_vec2() + - 0.208983582205757 * c.p1.to_vec2() + - 0.325650248872424 * c.p2.to_vec2() + + 0.558983582205757 * c.p3.to_vec2()) + .hypot(); + let v4 = (c.p3 - c.p2).hypot() * 0.15; + + v0 + v1 + v2 + v3 + v4 +} + +fn gauss_arclen_7(c: C) -> f64 { + c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_7) +} + +fn est_gauss5_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + let d2 = c.deriv().deriv(); + let d3 = d2.deriv(); + let lmi = 2.0 / (lp + lc); + 7e-8 * (d3.eval(0.5).to_vec2().hypot() * lmi + 5.0 * d2.eval(0.5).to_vec2().hypot() * lmi) + .powi(5) + * lp +} + +fn gauss_errnorm_n(c: C, coeffs: &[(f64, f64)]) -> f64 +where + C::DerivResult: ParamCurveDeriv, +{ + let d = c.deriv().deriv(); + coeffs + .iter() + .map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot2()) + .sum::() +} + +// Squared L2 norm of the second derivative of the cubic. +fn cubic_errnorm(c: CubicBez) -> f64 { + let d = c.deriv().deriv(); + let dd = d.end() - d.start(); + d.start().to_vec2().hypot2() + d.start().to_vec2().dot(dd) + dd.hypot2() * (1.0 / 3.0) +} + +fn est_gauss7_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + 8e-9 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(6) * lp +} + +fn gauss_arclen_9(c: C) -> f64 { + c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_9) +} + +fn gauss_arclen_11(c: C) -> f64 { + c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_11) +} + +fn est_gauss9_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + 1e-10 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(8) * lp +} + +fn est_gauss11_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + 1e-12 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(11) * lp +} + +// A new approach based on integrating local error. +fn est_gauss11_error_2(c: CubicBez) -> f64 { + let d = c.deriv(); + let d2 = d.deriv(); + GAUSS_LEGENDRE_COEFFS_11 + .iter() + .map(|(wi, xi)| { + wi * { + let t = 0.5 * (xi + 1.0); + let v = d.eval(t).to_vec2().hypot(); + let a2 = d2.eval(t).to_vec2().hypot2(); + a2.powi(3) / v.powi(5) + } + }) + .sum::() +} + +#[expect( + clippy::neg_cmp_op_on_partial_ord, + reason = "probably IEEE semantics nuance" +)] +fn est_max_curvature(c: CubicBez) -> f64 { + let n = 100; + let mut max = 0.0; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let k = c.curvature(t).abs(); + if !(k < max) { + max = k; + } + } + max +} + +fn est_min_deriv_norm2(c: CubicBez) -> f64 { + let d = c.deriv(); + let n = 100; + let mut min = d.eval(1.0).to_vec2().hypot2(); + for i in 0..n { + let t = (i as f64) * (n as f64).recip(); + min = min.min(d.eval(t).to_vec2().hypot2()); + } + min +} + +fn est_gauss11_error_3(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let pc_err = (lp - lc) * 0.02; + let ks = est_max_curvature(c) * lp; + let est = ks.powi(3) * lp * 8e-9; + if est < pc_err { est } else { pc_err } +} + +fn est_gauss9_error_3(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let pc_err = (lp - lc) * 0.02; + let ks = est_max_curvature(c) * lp; + let est = ks.powi(3) * lp * 5e-8; + if est < pc_err { est } else { pc_err } +} + +// A new approach based on integrating local error; the cost of evaluating the +// error metric is likely to dominate unless the accuracy buys a lot of subdivisions. +fn est_gauss9_error_2(c: CubicBez) -> f64 { + let d = c.deriv(); + let d2 = d.deriv(); + let p = 10; + GAUSS_LEGENDRE_COEFFS_9 + .iter() + .map(|(wi, xi)| { + wi * { + let t = 0.5 * (xi + 1.0); + let v = d.eval(t).to_vec2().hypot(); + let a = d2.eval(t).to_vec2().hypot(); + (1.0e-1 * a / v).tanh().powi(p) * v + } + }) + .sum::() + * 3.0 +} + +fn my_arclen(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss5_error(c) < accuracy { + *count += 1; + gauss_arclen_5(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen(c0, accuracy * 0.5, depth + 1, count) + + my_arclen(c1, accuracy * 0.5, depth + 1, count) + } +} + +fn my_arclen7(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss7_error(c) < accuracy { + *count += 1; + gauss_arclen_7(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen7(c0, accuracy * 0.5, depth + 1, count) + + my_arclen7(c1, accuracy * 0.5, depth + 1, count) + } +} + +// Should make this generic instead of copy+paste, but we need only one when we're done. +fn my_arclen9(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss9_error(c) < accuracy { + *count += 1; + gauss_arclen_9(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen9(c0, accuracy * 0.5, depth + 1, count) + + my_arclen9(c1, accuracy * 0.5, depth + 1, count) + } +} + +// This doesn't help; we can't really get a more accurate error bound, so all this +// does is overkill the accuracy. +fn my_arclen11(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss9_error(c) < accuracy { + *count += 1; + gauss_arclen_11(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen11(c0, accuracy * 0.5, depth + 1, count) + + my_arclen11(c1, accuracy * 0.5, depth + 1, count) + } +} + +fn randpt() -> Point { + Point::new(rand::random(), rand::random()) +} + +fn randbez() -> CubicBez { + CubicBez::new(randpt(), randpt(), randpt(), randpt()) +} + +fn main() { + let accuracy = 1e-4; + for _ in 0..10_000 { + let c = randbez(); + let t: f64 = rand::random(); + let c = c.subsegment(0.0..t); + //let accurate_arclen = c.arclen(1e-12); + let mut count = 0; + let accurate_arclen = my_arclen9(c, 1e-15, 0, &mut count); + + let est = gauss_arclen_9(c); + let est_err = est_gauss9_error_3(c); + let err = (accurate_arclen - est).abs(); + println!("{est_err} {err}"); + + /* + let mut count = 0; + let est = my_arclen9(c, accuracy, 0, &mut count); + let err = (accurate_arclen - est).abs(); + println!("{err} {count}"); + */ + } +} diff --git a/vendor/kurbo/examples/ellipse.rs b/vendor/kurbo/examples/ellipse.rs new file mode 100644 index 0000000000..62ad0def5f --- /dev/null +++ b/vendor/kurbo/examples/ellipse.rs @@ -0,0 +1,28 @@ +// Copyright 2020 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Example of ellipse + +#[cfg(feature = "std")] +fn main() { + use kurbo::{Ellipse, Shape}; + use std::f64::consts::PI; + + let ellipse = Ellipse::new((400.0, 400.0), (200.0, 100.0), 0.25 * PI); + println!(""); + println!(""); + println!(""); + println!(""); + let black_path = ellipse.to_path(1e-3).to_svg(); + println!(" "); + let red_path = ellipse.to_path(1.0).to_svg(); + println!(" "); + println!(""); + println!(""); + println!(""); +} + +#[cfg(not(feature = "std"))] +fn main() { + println!("This example requires the standard library"); +} diff --git a/vendor/kurbo/examples/fit_poly.rs b/vendor/kurbo/examples/fit_poly.rs new file mode 100644 index 0000000000..4fba08380d --- /dev/null +++ b/vendor/kurbo/examples/fit_poly.rs @@ -0,0 +1,76 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A test case for the cubic Bézier path simplifier, generating a very +//! efficient and accurate SVG file to plot a quartic polynomial. This +//! file was used to generate the image for the Wikipedia article on +//! quartic polynomials. + +use std::{io::Write, ops::Range}; + +use kurbo::{BezPath, CurveFitSample, ParamCurveFit, PathEl, Point, Vec2}; + +struct MyPoly; + +fn eval_mypoly(x: f64) -> f64 { + (x + 4.) * (x + 1.) * (x - 1.) * (x - 3.) / 14. + 0.5 +} + +fn eval_mypoly_deriv(x: f64) -> f64 { + (((4. * x + 3.) * x - 26.) * x - 1.) / 14. +} + +impl ParamCurveFit for MyPoly { + fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2) { + const S: f64 = 336.; + let x = 37. + t * S; + let math_x = (x - 220.) / 40.; + let y = -eval_mypoly(math_x) * 40. + 260.; + let dx = S; + let dy = -dx * eval_mypoly_deriv(math_x); + (Point::new(x, y), Vec2::new(dx, dy)) + } + + fn sample_pt_tangent(&self, t: f64, _: f64) -> CurveFitSample { + let (p, tangent) = self.sample_pt_deriv(t); + CurveFitSample { p, tangent } + } + + fn break_cusp(&self, _: Range) -> Option { + None + } +} + +fn to_svg_economical(path: &BezPath) -> String { + let mut buffer = Vec::new(); + write_to(path, &mut buffer).unwrap(); + String::from_utf8(buffer).unwrap() +} + +/// Write the SVG representation of this path to the provided buffer. +fn write_to(path: &BezPath, mut writer: W) -> std::io::Result<()> { + for el in path.elements() { + match *el { + PathEl::MoveTo(p) => write!(writer, "M{:.2} {:.2}", p.x, p.y)?, + PathEl::LineTo(p) => write!(writer, "L{} {}", p.x, p.y)?, + PathEl::QuadTo(p1, p2) => write!(writer, "Q{} {} {} {}", p1.x, p1.y, p2.x, p2.y)?, + PathEl::CurveTo(p1, p2, p3) => write!( + writer, + "C{:.2} {:.2} {:.2} {:.2} {:.2} {:.2}", + p1.x, p1.y, p2.x, p2.y, p3.x, p3.y + )?, + PathEl::ClosePath => write!(writer, "Z")?, + } + } + Ok(()) +} + +fn main() { + println!(""); + let path = kurbo::fit_to_bezpath_opt(&MyPoly, 0.1); + println!( + " ", + to_svg_economical(&path) + ); + println!(""); +} diff --git a/vendor/kurbo/examples/quad_intersect.rs b/vendor/kurbo/examples/quad_intersect.rs new file mode 100644 index 0000000000..8911d787ec --- /dev/null +++ b/vendor/kurbo/examples/quad_intersect.rs @@ -0,0 +1,92 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Test case that demonstrates quadratic/quadratic intersection using +//! new quartic solver. + +use arrayvec::ArrayVec; +use kurbo::{ParamCurve, Point, QuadBez, Shape, common::solve_quartic}; +use rand::Rng; + +fn rand_point() -> Point { + let mut rng = rand::rng(); + Point::new(rng.random_range(0.0..500.0), rng.random_range(0.0..500.0)) +} + +fn rand_quad() -> QuadBez { + QuadBez::new(rand_point(), rand_point(), rand_point()) +} + +struct ImplicitQuad { + x2: f64, + xy: f64, + y2: f64, + x: f64, + y: f64, + c: f64, +} + +impl ImplicitQuad { + fn from_quad(q: QuadBez) -> Self { + let Point { x: ax, y: ay } = q.p0; + let Point { x: bx, y: by } = q.p1; + let Point { x: cx, y: cy } = q.p2; + let (u0, u1, u2) = (by - cy, cx - bx, bx * cy - by * cx); + let (v0, v1, v2) = (cy - ay, ax - cx, cx * ay - cy * ax); + let (w0, w1, w2) = (ay - by, bx - ax, ax * by - ay * bx); + Self { + x2: 4. * u0 * w0 - v0 * v0, + xy: 4. * (u0 * w1 + u1 * w0) - 2. * v0 * v1, + y2: 4. * u1 * w1 - v1 * v1, + x: 4. * (u0 * w2 + u2 * w0) - 2. * v0 * v2, + y: 4. * (u1 * w2 + u2 * w1) - 2. * v1 * v2, + c: 4. * u2 * w2 - v2 * v2, + } + } + + fn eval(&self, x: f64, y: f64) -> f64 { + self.x2 * x * x + self.xy * x * y + self.y2 * y * y + self.x * x + self.y * y + self.c + } +} + +fn intersect_quads(q0: QuadBez, q1: QuadBez) -> ArrayVec { + let iq = ImplicitQuad::from_quad(q0); + let c = q1.p0.to_vec2(); + let b = (q1.p1 - q1.p0) * 2.0; + let a = c - q1.p1.to_vec2() * 2.0 + q1.p2.to_vec2(); + let c0 = iq.eval(c.x, c.y); + let c1 = iq.x * b.x + + iq.y * b.y + + 2. * iq.x2 * (b.x * c.x) + + 2. * iq.y2 * (b.y * c.y) + + iq.xy * (b.x * c.y + b.y * c.x); + let c2 = iq.x * a.x + + iq.y * a.y + + iq.x2 * (2. * a.x * c.x + b.x * b.x) + + iq.xy * (a.x * c.y + b.x * b.y + a.y * c.x) + + iq.y2 * (2. * a.y * c.y + b.y * b.y); + let c3 = iq.x2 * 2. * a.x * b.x + iq.xy * (a.x * b.y + b.x * a.y) + iq.y2 * 2. * a.y * b.y; + let c4 = iq.x2 * a.x * a.x + iq.xy * a.x * a.y + iq.y2 * a.y * a.y; + let ts = solve_quartic(c0, c1, c2, c3, c4); + println!("ts: {ts:?}"); + ts +} + +fn main() { + let q0 = rand_quad(); + let q1 = rand_quad(); + println!( + " ", + q0.to_path(1e-9).to_svg() + ); + println!( + " ", + q1.to_path(1e-9).to_svg() + ); + for t in intersect_quads(q0, q1) { + if (0.0..=1.0).contains(&t) { + let p = q1.eval(t); + println!(" ", p.x, p.y); + } + } +} diff --git a/vendor/kurbo/examples/simplify.rs b/vendor/kurbo/examples/simplify.rs new file mode 100644 index 0000000000..1227f7e5bb --- /dev/null +++ b/vendor/kurbo/examples/simplify.rs @@ -0,0 +1,52 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Test case showing simplification of a Bézier path. In this case, the +//! source path is a simple mathematical function, but it should work for +//! more general cases as well. + +use kurbo::{BezPath, Point}; + +fn plot_fn(f: &dyn Fn(f64) -> f64, d: &dyn Fn(f64) -> f64, xa: f64, xb: f64, n: usize) -> BezPath { + let width = 800.; + let dx = (xb - xa) / n as f64; + let xs = width / (xb - xa); + let ys = 250.; + let y_origin = 300.; + let plot = |x, y| Point::new((x - xa) * xs, y_origin - y * ys); + let mut x0 = xa; + let mut y0 = f(xa); + let mut d0 = d(xa); + let mut path = BezPath::new(); + path.move_to(plot(x0, y0)); + for i in 0..n { + let x3 = xa + dx * (i + 1) as f64; + let y3 = f(x3); + let d3 = d(x3); + let x1 = x0 + (1. / 3.) * dx; + let x2 = x3 - (1. / 3.) * dx; + let y1 = y0 + d0 * (1. / 3.) * dx; + let y2 = y3 - d3 * (1. / 3.) * dx; + path.curve_to(plot(x1, y1), plot(x2, y2), plot(x3, y3)); + x0 = x3; + y0 = y3; + d0 = d3; + } + path +} + +fn main() { + println!(""); + let path = plot_fn(&|x| x.sin(), &|x| x.cos(), -8., 8., 20); + println!( + " ", + path.to_svg() + ); + let simpl = kurbo::simplify::SimplifyBezPath::new(path); + let simplified_path = kurbo::fit_to_bezpath_opt(&simpl, 0.1); + println!( + " ", + simplified_path.to_svg() + ); + println!(""); +} diff --git a/vendor/kurbo/examples/stroke.rs b/vendor/kurbo/examples/stroke.rs new file mode 100644 index 0000000000..f6b7170390 --- /dev/null +++ b/vendor/kurbo/examples/stroke.rs @@ -0,0 +1,183 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Stroke example. +//! +//! This example has been lightly adapted from Vello, which in turn has +//! been adapted from the Skia "tricky stroke" test. + +use kurbo::{Affine, BezPath, Cap, Join, Rect, Shape, Stroke, StrokeOpts, stroke}; + +fn tricky_strokes() { + const CELL_SIZE: f64 = 200.; + const STROKE_WIDTH: f64 = 30.; + const NUM_COLS: usize = 5; + + fn stroke_bounds(pts: &[(f64, f64); 4]) -> Rect { + use kurbo::CubicBez; + CubicBez::new(pts[0], pts[1], pts[2], pts[3]) + .bounding_box() + .inflate(STROKE_WIDTH, STROKE_WIDTH) + } + + fn map_rect_to_rect(src: &Rect, dst: &Rect) -> (Affine, f64) { + let (scale, x_larger) = { + let sx = dst.width() / src.width(); + let sy = dst.height() / src.height(); + (sx.min(sy), sx > sy) + }; + let tx = dst.x0 - src.x0 * scale; + let ty = dst.y0 - src.y0 * scale; + let (tx, ty) = if x_larger { + (tx + 0.5 * (dst.width() - src.width() * scale), ty) + } else { + (tx, ty + 0.5 * (dst.height() - src.height() * scale)) + }; + (Affine::new([scale, 0.0, 0.0, scale, tx, ty]), scale) + } + + let tricky_cubics = [ + [(122., 737.), (348., 553.), (403., 761.), (400., 760.)], + [(244., 520.), (244., 518.), (1141., 634.), (394., 688.)], + [(550., 194.), (138., 130.), (1035., 246.), (288., 300.)], + [(226., 733.), (556., 779.), (-43., 471.), (348., 683.)], + [(268., 204.), (492., 304.), (352., 23.), (433., 412.)], + [(172., 480.), (396., 580.), (256., 299.), (338., 677.)], + [(731., 340.), (318., 252.), (1026., -64.), (367., 265.)], + [(475., 708.), (62., 620.), (770., 304.), (220., 659.)], + [(0., 0.), (128., 128.), (128., 0.), (0., 128.)], // Perfect cusp + [(0., 0.01), (128., 127.999), (128., 0.01), (0., 127.99)], // Near-cusp + [(0., -0.01), (128., 128.001), (128., -0.01), (0., 128.001)], // Near-cusp + [(0., 0.), (0., -10.), (0., -10.), (0., 10.)], // Flat line with 180 + [(10., 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(39., -39.), (40., -40.), (40., -40.), (0., 0.)], // Flat diagonal with 180 + [(40., 40.), (0., 0.), (200., 200.), (0., 0.)], // Diag w/ an internal 180 + [(0., 0.), (1e-2, 0.), (-1e-2, 0.), (0., 0.)], // Circle + // Flat line with no turns: + [ + (400.75, 100.05), + (400.75, 100.05), + (100.05, 300.95), + (100.05, 300.95), + ], + [(0.5, 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(10., 0.), (0., 0.), (10., 0.), (10., 0.)], // Flat line with a 180 + ]; + + // Flat conic with a cusp: (1,1) (2,1) (1,1), weight: 1 + let flat_quad = [ + // moveTo(1., 1.), + [(2., 1.), (1., 1.)], + ]; + // Flat conic with a cusp: (1,1) (100,1) (25,1), weight: 0.3 + let flat_conic_as_quads = [ + // moveTo(1., 1.), + [(2.232486, 1.000000), (3.471740, 1.000000)], + [(4.710995, 1.000000), (5.949262, 1.000000)], + [(7.187530, 1.000000), (8.417061, 1.000000)], + [(9.646591, 1.000000), (10.859690, 1.000000)], + [(12.072789, 1.000000), (13.261865, 1.000000)], + [(14.450940, 1.000000), (15.608549, 1.000000)], + [(16.766161, 1.000000), (17.885059, 1.000000)], + [(19.003958, 1.000000), (20.077141, 1.000000)], + [(21.150328, 1.000000), (22.171083, 1.000000)], + [(23.191839, 1.000000), (24.153776, 1.000000)], + [(25.115715, 1.000000), (26.012812, 1.000000)], + [(26.909912, 1.000000), (27.736557, 1.000000)], + [(28.563202, 1.000000), (29.314220, 1.000000)], + [(30.065239, 1.000000), (30.735928, 1.000000)], + [(31.406620, 1.000000), (31.992788, 1.000000)], + [(32.578957, 1.000000), (33.076927, 1.000000)], + [(33.574905, 1.000000), (33.981567, 1.000000)], + [(34.388233, 1.000000), (34.701038, 1.000000)], + [(35.013851, 1.000000), (35.230850, 1.000000)], + [(35.447845, 1.000000), (35.567669, 1.000000)], + [(35.687500, 1.000000), (35.709404, 1.000000)], + [(35.731312, 1.000000), (35.655155, 1.000000)], + [(35.579006, 1.000000), (35.405273, 1.000000)], + [(35.231541, 1.000000), (34.961311, 1.000000)], + [(34.691086, 1.000000), (34.326057, 1.000000)], + [(33.961029, 1.000000), (33.503479, 1.000000)], + [(33.045937, 1.000000), (32.498734, 1.000000)], + [(31.951530, 1.000000), (31.318098, 1.000000)], + [(30.684669, 1.000000), (29.968971, 1.000000)], + [(29.253277, 1.000000), (28.459791, 1.000000)], + [(27.666309, 1.000000), (26.800005, 1.000000)], + [(25.933704, 1.000000), (25.000000, 1.000000)], + ]; + // Flat conic with a cusp: (1,1) (100,1) (25,1), weight: 1.5 + let bigger_flat_conic_as_quads = [ + // moveTo(1., 1.), + [(8.979845, 1.000000), (15.795975, 1.000000)], + [(22.612104, 1.000000), (28.363287, 1.000000)], + [(34.114471, 1.000000), (38.884045, 1.000000)], + [(43.653618, 1.000000), (47.510696, 1.000000)], + [(51.367767, 1.000000), (54.368233, 1.000000)], + [(57.368698, 1.000000), (59.556030, 1.000000)], + [(61.743366, 1.000000), (63.149269, 1.000000)], + [(64.555168, 1.000000), (65.200005, 1.000000)], + [(65.844841, 1.000000), (65.737961, 1.000000)], + [(65.631073, 1.000000), (64.770912, 1.000000)], + [(63.910763, 1.000000), (62.284878, 1.000000)], + [(60.658997, 1.000000), (58.243816, 1.000000)], + [(55.828640, 1.000000), (52.589172, 1.000000)], + [(49.349705, 1.000000), (45.239006, 1.000000)], + [(41.128315, 1.000000), (36.086826, 1.000000)], + [(31.045338, 1.000000), (25.000000, 1.000000)], + ]; + + let mut idx = 0; + let tolerance = 0.25; + for cubic in &tricky_cubics { + let x = (idx % NUM_COLS) as f64 * CELL_SIZE; + let y = (idx / NUM_COLS) as f64 * CELL_SIZE; + let cell = Rect::new(x, y, x + CELL_SIZE, y + CELL_SIZE); + let bounds = stroke_bounds(cubic); + let (t, s) = map_rect_to_rect(&bounds, &cell); + let style = Stroke::new(STROKE_WIDTH / s) + .with_caps(Cap::Butt) + .with_join(Join::Miter); + let mut path = BezPath::new(); + path.move_to(cubic[0]); + path.curve_to(cubic[1], cubic[2], cubic[3]); + let stroked = stroke(path, &style, &StrokeOpts::default(), tolerance); + println!( + " ", + (t * stroked).to_svg() + ); + idx += 1; + } + + let flat_curves = [ + flat_quad.as_slice(), + flat_conic_as_quads.as_slice(), + bigger_flat_conic_as_quads.as_slice(), + ]; + for quads in flat_curves.iter() { + let mut path = BezPath::new(); + path.move_to((1., 1.)); + for quad in quads.iter() { + path.quad_to(quad[0], quad[1]); + } + let x = (idx % NUM_COLS) as f64 * CELL_SIZE; + let y = (idx / NUM_COLS) as f64 * CELL_SIZE; + let cell = Rect::new(x, y, x + CELL_SIZE, y + CELL_SIZE); + let bounds = path.bounding_box().inflate(STROKE_WIDTH, STROKE_WIDTH); + let (t, s) = map_rect_to_rect(&bounds, &cell); + let style = Stroke::new(STROKE_WIDTH / s) + .with_caps(Cap::Butt) + .with_join(Join::Miter); + let stroked = stroke(path, &style, &StrokeOpts::default(), tolerance); + println!( + " ", + (t * stroked).to_svg() + ); + idx += 1; + } +} + +fn main() { + println!(""); + tricky_strokes(); + println!(""); +} diff --git a/vendor/kurbo/src/affine.rs b/vendor/kurbo/src/affine.rs new file mode 100644 index 0000000000..80b25430e3 --- /dev/null +++ b/vendor/kurbo/src/affine.rs @@ -0,0 +1,865 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Affine transforms. + +use core::ops::{Mul, MulAssign}; + +use crate::{Point, Rect, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D affine transform. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Affine([f64; 6]); + +impl Affine { + /// The identity transform. + pub const IDENTITY: Affine = Affine::scale(1.0); + + /// A transform that is flipped on the y-axis. Useful for converting between + /// y-up and y-down spaces. + pub const FLIP_Y: Affine = Affine::new([1.0, 0., 0., -1.0, 0., 0.]); + + /// A transform that is flipped on the x-axis. + pub const FLIP_X: Affine = Affine::new([-1.0, 0., 0., 1.0, 0., 0.]); + + /// Construct an affine transform from coefficients. + /// + /// If the coefficients are `(a, b, c, d, e, f)`, then the resulting + /// transformation represents this augmented matrix: + /// + /// ```text + /// | a c e | + /// | b d f | + /// | 0 0 1 | + /// ``` + /// + /// Note that this convention is transposed from PostScript and + /// Direct2D, but is consistent with the + /// [Wikipedia](https://en.wikipedia.org/wiki/Affine_transformation) + /// formulation of affine transformation as augmented matrix. The + /// idea is that `(A * B) * v == A * (B * v)`, where `*` is the + /// [`Mul`] trait. + #[inline(always)] + pub const fn new(c: [f64; 6]) -> Affine { + Affine(c) + } + + /// An affine transform representing uniform scaling. + #[inline(always)] + pub const fn scale(s: f64) -> Affine { + Affine([s, 0.0, 0.0, s, 0.0, 0.0]) + } + + /// An affine transform representing non-uniform scaling + /// with different scale values for x and y + #[inline(always)] + pub const fn scale_non_uniform(s_x: f64, s_y: f64) -> Affine { + Affine([s_x, 0.0, 0.0, s_y, 0.0, 0.0]) + } + + /// An affine transform representing a scale of `scale` about `center`. + /// + /// Useful for a view transform that zooms at a specific point, + /// while keeping that point fixed in the result space. + /// + /// See [`Affine::scale()`] for more info. + #[inline] + pub fn scale_about(s: f64, center: impl Into) -> Affine { + let center = center.into().to_vec2(); + Self::translate(-center) + .then_scale(s) + .then_translate(center) + } + + /// An affine transform representing rotation. + /// + /// The convention for rotation is that a positive angle rotates a + /// positive X direction into positive Y. Thus, in a Y-down coordinate + /// system (as is common for graphics), it is a clockwise rotation, and + /// in Y-up (traditional for math), it is anti-clockwise. + /// + /// The angle, `th`, is expressed in radians. + #[inline] + pub fn rotate(th: f64) -> Affine { + let (s, c) = th.sin_cos(); + Affine([c, s, -s, c, 0.0, 0.0]) + } + + /// An affine transform representing a rotation of `th` radians about `center`. + /// + /// See [`Affine::rotate()`] for more info. + #[inline] + pub fn rotate_about(th: f64, center: impl Into) -> Affine { + let center = center.into().to_vec2(); + Self::translate(-center) + .then_rotate(th) + .then_translate(center) + } + + /// An affine transform representing translation. + #[inline(always)] + pub fn translate>(p: V) -> Affine { + let p = p.into(); + Affine([1.0, 0.0, 0.0, 1.0, p.x, p.y]) + } + + /// An affine transformation representing a skew. + /// + /// The `skew_x` and `skew_y` parameters represent skew factors for the + /// horizontal and vertical directions, respectively. + /// + /// This is commonly used to generate a faux oblique transform for + /// font rendering. In this case, you can slant the glyph 20 degrees + /// clockwise in the horizontal direction (assuming a Y-up coordinate + /// system): + /// + /// ``` + /// let oblique_transform = kurbo::Affine::skew(20f64.to_radians().tan(), 0.0); + /// ``` + #[inline(always)] + pub const fn skew(skew_x: f64, skew_y: f64) -> Affine { + Affine([1.0, skew_y, skew_x, 1.0, 0.0, 0.0]) + } + + /// Create an affine transform that represents reflection about the line `point + direction * t, t in (-infty, infty)` + /// + /// # Examples + /// + /// ``` + /// # use kurbo::{Point, Vec2, Affine}; + /// # fn assert_near(p0: Point, p1: Point) { + /// # assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + /// # } + /// let point = Point::new(1., 0.); + /// let vec = Vec2::new(1., 1.); + /// let map = Affine::reflect(point, vec); + /// assert_near(map * Point::new(1., 0.), Point::new(1., 0.)); + /// assert_near(map * Point::new(2., 1.), Point::new(2., 1.)); + /// assert_near(map * Point::new(2., 2.), Point::new(3., 1.)); + /// ``` + #[inline] + #[must_use] + pub fn reflect(point: impl Into, direction: impl Into) -> Self { + let point = point.into(); + let direction = direction.into(); + + let n = Vec2 { + x: direction.y, + y: -direction.x, + } + .normalize(); + + // Compute Householder reflection matrix + let x2 = n.x * n.x; + let xy = n.x * n.y; + let y2 = n.y * n.y; + // Here we also add in the post translation, because it doesn't require any further calc. + let aff = Affine::new([ + 1. - 2. * x2, + -2. * xy, + -2. * xy, + 1. - 2. * y2, + point.x, + point.y, + ]); + aff.pre_translate(-point.to_vec2()) + } + + /// A [rotation] by `th` followed by `self`. + /// + /// Equivalent to `self * Affine::rotate(th)` + /// + /// [rotation]: Affine::rotate + #[inline] + #[must_use] + pub fn pre_rotate(self, th: f64) -> Self { + self * Affine::rotate(th) + } + + /// A [rotation] by `th` about `center` followed by `self`. + /// + /// Equivalent to `self * Affine::rotate_about(th, center)` + /// + /// [rotation]: Affine::rotate_about + #[inline] + #[must_use] + pub fn pre_rotate_about(self, th: f64, center: impl Into) -> Self { + self * Affine::rotate_about(th, center) + } + + /// A [scale] by `scale` followed by `self`. + /// + /// Equivalent to `self * Affine::scale(scale)` + /// + /// [scale]: Affine::scale + #[inline] + #[must_use] + pub fn pre_scale(self, scale: f64) -> Self { + self * Affine::scale(scale) + } + + /// A [scale] by `(scale_x, scale_y)` followed by `self`. + /// + /// Equivalent to `self * Affine::scale_non_uniform(scale_x, scale_y)` + /// + /// [scale]: Affine::scale_non_uniform + #[inline] + #[must_use] + pub fn pre_scale_non_uniform(self, scale_x: f64, scale_y: f64) -> Self { + self * Affine::scale_non_uniform(scale_x, scale_y) + } + + /// A [translation] of `trans` followed by `self`. + /// + /// Equivalent to `self * Affine::translate(trans)` + /// + /// [translation]: Affine::translate + #[inline] + #[must_use] + pub fn pre_translate(self, trans: Vec2) -> Self { + self * Affine::translate(trans) + } + + /// A [skew] of `(skew_x, skew_y)` followed by `self`. + /// + /// Equivalent to `self * Affine::skew(skew_x, skew_y)` + /// + /// [skew]: Affine::skew + #[inline] + #[must_use] + pub fn pre_skew(self, skew_x: f64, skew_y: f64) -> Self { + self * Affine::skew(skew_x, skew_y) + } + + /// A [reflection] about the line through `point` in `direction` followed by `self`. + /// + /// Equivalent to `self * Affine::reflect(point, direction)` + /// + /// [reflection]: Affine::reflect + #[inline] + #[must_use] + pub fn pre_reflect(self, point: impl Into, direction: impl Into) -> Self { + self * Affine::reflect(point, direction) + } + + /// `self` followed by a [rotation] of `th`. + /// + /// Equivalent to `Affine::rotate(th) * self` + /// + /// [rotation]: Affine::rotate + #[inline] + #[must_use] + pub fn then_rotate(self, th: f64) -> Self { + Affine::rotate(th) * self + } + + /// `self` followed by a [rotation] of `th` about `center`. + /// + /// Equivalent to `Affine::rotate_about(th, center) * self` + /// + /// [rotation]: Affine::rotate_about + #[inline] + #[must_use] + pub fn then_rotate_about(self, th: f64, center: impl Into) -> Self { + Affine::rotate_about(th, center) * self + } + + /// `self` followed by a [scale] of `scale`. + /// + /// Equivalent to `Affine::scale(scale) * self` + /// + /// [scale]: Affine::scale + #[inline] + #[must_use] + pub fn then_scale(self, scale: f64) -> Self { + Affine::scale(scale) * self + } + + /// `self` followed by a [scale] of `(scale_x, scale_y)`. + /// + /// Equivalent to `Affine::scale_non_uniform(scale_x, scale_y) * self` + /// + /// [scale]: Affine::scale_non_uniform + #[inline] + #[must_use] + pub fn then_scale_non_uniform(self, scale_x: f64, scale_y: f64) -> Self { + Affine::scale_non_uniform(scale_x, scale_y) * self + } + + /// `self` followed by a [scale] of `scale` about `center`. + /// + /// Equivalent to `Affine::scale_about(scale) * self` + /// + /// [scale]: Affine::scale_about + #[inline] + #[must_use] + pub fn then_scale_about(self, scale: f64, center: impl Into) -> Self { + Affine::scale_about(scale, center) * self + } + + /// `self` followed by a [skew] of `(skew_x, skew_y)`. + /// + /// Equivalent to `Affine::skew(skew_x, skew_y) * self` + /// + /// [skew]: Affine::skew + #[inline] + #[must_use] + pub fn then_skew(self, skew_x: f64, skew_y: f64) -> Self { + Affine::skew(skew_x, skew_y) * self + } + + /// `self` followed by a [reflection] about the line through `point` in `direction`. + /// + /// Equivalent to `Affine::reflect(point, direction) * self` + /// + /// [reflection]: Affine::reflect + #[inline] + #[must_use] + pub fn then_reflect(self, point: impl Into, direction: impl Into) -> Self { + Affine::reflect(point, direction) * self + } + + /// `self` followed by a translation of `trans`. + /// + /// Equivalent to `Affine::translate(trans) * self` + /// + /// [translation]: Affine::translate + #[inline] + #[must_use] + pub const fn then_translate(mut self, trans: Vec2) -> Self { + self.0[4] += trans.x; + self.0[5] += trans.y; + self + } + + /// Creates an affine transformation that takes the unit square to the given rectangle. + /// + /// Useful when you want to draw into the unit square but have your output fill any rectangle. + /// In this case push the `Affine` onto the transform stack. + pub const fn map_unit_square(rect: Rect) -> Affine { + Affine([rect.width(), 0., 0., rect.height(), rect.x0, rect.y0]) + } + + /// Get the coefficients of the transform. + #[inline(always)] + pub const fn as_coeffs(self) -> [f64; 6] { + self.0 + } + + /// Compute the determinant of this transform. + /// + /// # Geometric interpretation + /// + /// Consider a region transformed by this affine. The transformed region's area is the area of + /// the original region scaled by the absolute value of the determinant. A negative determinant + /// indicates orientation reversal. + #[inline] + pub const fn determinant(self) -> f64 { + self.0[0] * self.0[3] - self.0[1] * self.0[2] + } + + /// Compute the square of the nuclear norm of this transform. + /// + /// This is the square of the [Schatten p-norm][schatten] with `p=1`, also known as the "trace norm." + /// + /// Returns the squared norm for efficiency; take the square root as necessary. + /// + /// # Geometric interpretation + /// + /// Consider a unit circle transformed by this affine. The nuclear norm is the sum of the + /// resulting ellipse's radii (semi axes). That sum multiplied by π is a first-order + /// approximation of the ellipse's perimeter. + /// + /// [schatten]: + #[inline] + pub const fn nuclear_norm_squared(self) -> f64 { + self.frobenius_norm_squared() + 2. * self.determinant().abs() + } + + /// Compute the square of the Frobenius norm of this transform. + /// + /// This is the square of the [Schatten p-norm][schatten] with `p=2`. + /// + /// Returns the squared norm for efficiency; take the square root as necessary. + /// + /// # Geometric interpretation + /// + /// Consider a unit circle transformed by this affine. The squared Frobenius norm is twice the + /// mean squared radius of the resulting ellipse. Alternatively, it is equal to the squared + /// distance from the ellipse's center to a corner of the rectangle spanned by the ellipse's + /// axes. + /// + /// [schatten]: + #[inline] + pub const fn frobenius_norm_squared(self) -> f64 { + let [a, b, c, d, _, _] = self.as_coeffs(); + a * a + b * b + c * c + d * d + } + + /// Compute the spectral norm of this transform. + /// + /// This is the [Schatten p-norm][schatten] with `p=∞`. + /// + /// # Geometric interpretation + /// + /// Consider a unit circle transformed by this affine. The spectral norm is the major radius + /// (semi-major axis) of the Ellipse. + /// + /// [schatten]: + #[inline] + pub fn spectral_norm(self) -> f64 { + // Note a different calculation, returning the `_squared` form like our nuclear and + // Frobenius norms, could be `0.5 (frob^2 + sqrt(frob^4 - 4 det^2))`. In terms of operations + // it's a wash: one fewer sqrt if the user actually wants the squared form, but it uses more + // muls. More importantly, that form has worse numeric conditioning. + self.svd().0.x + } + + /// Compute the inverse transform. + /// + /// Produces NaN values when the determinant is zero. + pub const fn inverse(self) -> Affine { + let inv_det = self.determinant().recip(); + Affine([ + inv_det * self.0[3], + -inv_det * self.0[1], + -inv_det * self.0[2], + inv_det * self.0[0], + inv_det * (self.0[2] * self.0[5] - self.0[3] * self.0[4]), + inv_det * (self.0[1] * self.0[4] - self.0[0] * self.0[5]), + ]) + } + + /// Compute the bounding box of a transformed rectangle. + /// + /// Returns the minimal `Rect` that encloses the given `Rect` after affine transformation. + /// If the transform is axis-aligned, then this bounding box is "tight", in other words the + /// returned `Rect` is the transformed rectangle. + /// + /// The returned rectangle always has non-negative width and height. + pub fn transform_rect_bbox(self, rect: Rect) -> Rect { + let p00 = self * Point::new(rect.x0, rect.y0); + let p01 = self * Point::new(rect.x0, rect.y1); + let p10 = self * Point::new(rect.x1, rect.y0); + let p11 = self * Point::new(rect.x1, rect.y1); + Rect::from_points(p00, p01).union(Rect::from_points(p10, p11)) + } + + /// Is this map [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.0[0].is_finite() + && self.0[1].is_finite() + && self.0[2].is_finite() + && self.0[3].is_finite() + && self.0[4].is_finite() + && self.0[5].is_finite() + } + + /// Is this map [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.0[0].is_nan() + || self.0[1].is_nan() + || self.0[2].is_nan() + || self.0[3].is_nan() + || self.0[4].is_nan() + || self.0[5].is_nan() + } + + /// Compute the singular value decomposition of the linear transformation (ignoring the + /// translation). + /// + /// All non-degenerate linear transformations can be represented as + /// + /// 1. a rotation about the origin. + /// 2. a scaling along the x and y axes + /// 3. another rotation about the origin + /// + /// composed together. Decomposing a 2x2 matrix in this way is called a "singular value + /// decomposition" and is written `U Σ V^T`, where U and V^T are orthogonal (rotations) and Σ + /// is a diagonal matrix (a scaling). + /// + /// Since currently this function is used to calculate ellipse radii and rotation from an + /// affine map on the unit circle, we don't calculate V^T, since a rotation of the unit (or + /// any) circle about its center always results in the same circle. This is the reason that an + /// ellipse mapped using an affine map is always an ellipse. + /// + /// Will return NaNs if the matrix (or equivalently the linear map) is non-finite. + /// + /// The first part of the returned tuple is the scaling, the second part is the angle of + /// rotation (in radians). The scaling along the x-axis is guaranteed to be greater than or + /// equal to the scaling along the y-axis. + // + // Note: though this does quite some computation, we are often interested only in specific + // components of the result. Hence this is marked `#[inline(always)]`, to give the compiler a + // good chance at eliminating dead code. + #[inline(always)] + pub(crate) fn svd(self) -> (Vec2, f64) { + let [a, b, c, d, _, _] = self.0; + let a2 = a * a; + let b2 = b * b; + let c2 = c * c; + let d2 = d * d; + let ab = a * b; + let cd = c * d; + let angle = 0.5 * (2.0 * (ab + cd)).atan2(a2 - b2 + c2 - d2); + + // Given matrix A = [ a c ] + // [ b d ] + // + // The two singular values σ1, σ2 of A are the square roots of the two eigen values λ1, λ2 + // of M = A^T A. The common formula for 2x2 eigenvalues requires evaluating a square root, + // but we'd like to compute the singular values of the matrix without nested square roots. + // + // M = A^T A = [ aa+cc ab+cd ] + // [ ab+cd bb+dd ] + // + // We have + // λ = 1/2 (tr(M) ± sqrt(tr(M)^2 - 4 det(M))). + // + // Note det(M) = det(A^T A) = det(A)^2. + // => 2λ = tr(M) ± sqrt(tr(M)^2 - 4 det(A)^2) + // => 2λ = tr(M) ± sqrt[(a^2+b^2+c^2+d^2)^2 - 4 (ad-bc)^2] + // By factorizing the inner term, + // => 2λ = tr(M) ± sqrt[((a+d)^2 + (b-c)^2) ((a-d)^2 + (b+c)^2)] + // => 2λ = tr(M) ± sqrt[(a+d)^2 + (b-c)^2] sqrt[(a-d)^2 + (b+c)^2] + // + // Define S1 = sqrt[(a+d)^2 + (b-c)^2] + // S2 = sqrt[(a-d)^2 + (b+c)^2]. + // + // => 2λ = tr(M) ± S1 S2 + // => 2λ = 1/2 (S1^2 + S2^2) ± S1 S2 + // => λ = 1/4 (S1^2 + S2^2 ± 2 S1 S2) + // => λ = 1/4 (S1 ± S2)^2 + // + // Note we're interested in + // σ = sqrt(λ). + // + // => σ1 = 1/2 (S1 + S2) + // and similarly σ2 = 1/2 |S1 - S2| + let s1 = ((a + d).powi(2) + (b - c).powi(2)).sqrt(); + let s2 = ((a - d).powi(2) + (b + c).powi(2)).sqrt(); + ( + Vec2 { + x: 0.5 * (s1 + s2), + y: 0.5 * (s1 - s2).abs(), + }, + angle, + ) + } + + /// Returns the translation part of this affine map (`(self.0[4], self.0[5])`). + #[inline(always)] + pub const fn translation(self) -> Vec2 { + Vec2 { + x: self.0[4], + y: self.0[5], + } + } + + /// Replaces the translation portion of this affine map + /// + /// The translation can be seen as being applied after the linear part of the map. + #[must_use] + #[inline(always)] + pub const fn with_translation(mut self, trans: Vec2) -> Affine { + self.0[4] = trans.x; + self.0[5] = trans.y; + self + } +} + +impl Default for Affine { + #[inline(always)] + fn default() -> Affine { + Affine::IDENTITY + } +} + +impl Mul for Affine { + type Output = Point; + + #[inline] + fn mul(self, other: Point) -> Point { + Point::new( + self.0[0] * other.x + self.0[2] * other.y + self.0[4], + self.0[1] * other.x + self.0[3] * other.y + self.0[5], + ) + } +} + +impl Mul for Affine { + type Output = Affine; + + #[inline] + fn mul(self, other: Affine) -> Affine { + Affine([ + self.0[0] * other.0[0] + self.0[2] * other.0[1], + self.0[1] * other.0[0] + self.0[3] * other.0[1], + self.0[0] * other.0[2] + self.0[2] * other.0[3], + self.0[1] * other.0[2] + self.0[3] * other.0[3], + self.0[0] * other.0[4] + self.0[2] * other.0[5] + self.0[4], + self.0[1] * other.0[4] + self.0[3] * other.0[5] + self.0[5], + ]) + } +} + +impl MulAssign for Affine { + #[inline] + fn mul_assign(&mut self, other: Affine) { + *self = self.mul(other); + } +} + +impl Mul for f64 { + type Output = Affine; + + #[inline] + fn mul(self, other: Affine) -> Affine { + Affine([ + self * other.0[0], + self * other.0[1], + self * other.0[2], + self * other.0[3], + self * other.0[4], + self * other.0[5], + ]) + } +} + +// Conversions to and from mint +#[cfg(feature = "mint")] +impl From for mint::ColumnMatrix2x3 { + #[inline(always)] + fn from(a: Affine) -> mint::ColumnMatrix2x3 { + mint::ColumnMatrix2x3 { + x: mint::Vector2 { + x: a.0[0], + y: a.0[1], + }, + y: mint::Vector2 { + x: a.0[2], + y: a.0[3], + }, + z: mint::Vector2 { + x: a.0[4], + y: a.0[5], + }, + } + } +} + +#[cfg(feature = "mint")] +impl From> for Affine { + #[inline(always)] + fn from(m: mint::ColumnMatrix2x3) -> Affine { + Affine([m.x.x, m.x.y, m.y.x, m.y.y, m.z.x, m.z.y]) + } +} + +#[cfg(test)] +mod tests { + use crate::{Affine, Point, Vec2}; + use std::f64::consts::PI; + + fn assert_near(p0: Point, p1: Point) { + assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + } + + fn affine_assert_near(a0: Affine, a1: Affine) { + for i in 0..6 { + assert!((a0.0[i] - a1.0[i]).abs() < 1e-9, "{a0:?} != {a1:?}"); + } + } + + #[test] + fn affine_basic() { + let p = Point::new(3.0, 4.0); + + assert_near(Affine::default() * p, p); + assert_near(Affine::scale(2.0) * p, Point::new(6.0, 8.0)); + assert_near(Affine::rotate(0.0) * p, p); + assert_near(Affine::rotate(PI / 2.0) * p, Point::new(-4.0, 3.0)); + assert_near(Affine::translate((5.0, 6.0)) * p, Point::new(8.0, 10.0)); + assert_near(Affine::skew(0.0, 0.0) * p, p); + assert_near(Affine::skew(2.0, 4.0) * p, Point::new(11.0, 16.0)); + } + + #[test] + fn affine_mul() { + let a1 = Affine::new([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]); + let a2 = Affine::new([0.1, 1.2, 2.3, 3.4, 4.5, 5.6]); + + let px = Point::new(1.0, 0.0); + let py = Point::new(0.0, 1.0); + let pxy = Point::new(1.0, 1.0); + assert_near(a1 * (a2 * px), (a1 * a2) * px); + assert_near(a1 * (a2 * py), (a1 * a2) * py); + assert_near(a1 * (a2 * pxy), (a1 * a2) * pxy); + } + + #[test] + fn affine_inv() { + let a = Affine::new([0.1, 1.2, 2.3, 3.4, 4.5, 5.6]); + let a_inv = a.inverse(); + + let px = Point::new(1.0, 0.0); + let py = Point::new(0.0, 1.0); + let pxy = Point::new(1.0, 1.0); + assert_near(a * (a_inv * px), px); + assert_near(a * (a_inv * py), py); + assert_near(a * (a_inv * pxy), pxy); + assert_near(a_inv * (a * px), px); + assert_near(a_inv * (a * py), py); + assert_near(a_inv * (a * pxy), pxy); + } + + #[test] + fn reflection() { + affine_assert_near( + Affine::reflect(Point::ZERO, (1., 0.)), + Affine::new([1., 0., 0., -1., 0., 0.]), + ); + affine_assert_near( + Affine::reflect(Point::ZERO, (0., 1.)), + Affine::new([-1., 0., 0., 1., 0., 0.]), + ); + // y = x + affine_assert_near( + Affine::reflect(Point::ZERO, (1., 1.)), + Affine::new([0., 1., 1., 0., 0., 0.]), + ); + + // no translate + let point = Point::new(0., 0.); + let vec = Vec2::new(1., 1.); + let map = Affine::reflect(point, vec); + assert_near(map * Point::new(0., 0.), Point::new(0., 0.)); + assert_near(map * Point::new(1., 1.), Point::new(1., 1.)); + assert_near(map * Point::new(1., 2.), Point::new(2., 1.)); + + // with translate + let point = Point::new(1., 0.); + let vec = Vec2::new(1., 1.); + let map = Affine::reflect(point, vec); + assert_near(map * Point::new(1., 0.), Point::new(1., 0.)); + assert_near(map * Point::new(2., 1.), Point::new(2., 1.)); + assert_near(map * Point::new(2., 2.), Point::new(3., 1.)); + } + + #[test] + fn svd() { + let a = Affine::new([1., 2., 3., 4., 5., 6.]); + let a_no_translate = a.with_translation(Vec2::ZERO); + + // translation should have no effect + let (scale, rotation) = a.svd(); + let (scale_no_translate, rotation_no_translate) = a_no_translate.svd(); + assert_near(scale.to_point(), scale_no_translate.to_point()); + assert!((rotation - rotation_no_translate).abs() <= 1e-9); + + assert_near( + scale.to_point(), + Point::new(5.4649857042190427, 0.36596619062625782), + ); + assert!((rotation - 0.95691013360780001).abs() <= 1e-9); + + // singular affine + let a = Affine::new([0., 0., 0., 0., 5., 6.]); + assert_eq!(a.determinant(), 0.); + let (scale, rotation) = a.svd(); + assert_eq!(scale, Vec2::new(0., 0.)); + assert_eq!(rotation, 0.); + } + + #[test] + fn svd_singular_values() { + // Test a few known singular values. + let mat = |a, b, c, d| Affine::new([a, b, c, d, 0., 0.]); + + let s = mat(1., 0., 0., 1.).svd().0; + assert_near(s.to_point(), Point::new(1., 1.)); + + let s = mat(1., 0., 0., -1.).svd().0; + assert_near(s.to_point(), Point::new(1., 1.)); + + let s = mat(1., 1., 1., 1.).svd().0; + assert_near(s.to_point(), Point::new(2., 0.)); + + let s = mat(1., 1., 1., 1.).svd().0; + assert_near(s.to_point(), Point::new(2., 0.)); + + let s = mat(0., 0., 1., 0.).svd().0; + assert_near(s.to_point(), Point::new(1., 0.)); + + // The singular values are the scaling of the affine map. So let's test that. + let s = Affine::scale_non_uniform(4., 8.) + .then_rotate_about(42_f64.to_radians(), (-2., 50.)) + .svd() + .0; + assert_near(s.to_point(), Point::new(8., 4.)); + + // Correctly handles negative scaling (singular values are necessarily non-negative). + let s = Affine::scale_non_uniform(-20., 3.).svd().0; + assert_near(s.to_point(), Point::new(20., 3.)); + let s = Affine::scale_non_uniform(-20., -3.).svd().0; + assert_near(s.to_point(), Point::new(20., 3.)); + let s = Affine::scale_non_uniform(20., -3.).svd().0; + assert_near(s.to_point(), Point::new(20., 3.)); + + // One more property: given a full-rank transform, the product of its singular values + // should be equal to its absolute determinant. + let m = mat(10., 9., -2.5, 3.3333); + let s = m.svd().0; + let prod = s.x * s.y; + let det = m.determinant().abs(); + assert!( + (prod - det) < 1e-9, + "The product of the singular values {s:?} ({prod}) should be equal to the absolute determinant {det}.", + ); + } + + #[test] + fn rotate_about_composition() { + let theta = core::f64::consts::FRAC_PI_2; + let center = Point::new(-1., 0.); + let translation = Vec2::new(0., 1.); + let probe = Point::ORIGIN; + + let rotate_about = Affine::rotate_about(theta, center); + let translate = Affine::translate(translation); + + // Establish baselines with raw matrix composition + // (also a sanity check to ensure the order of ops matters for this contrived test) + let rotate_then_translate = translate * rotate_about; + let translate_then_rotate = rotate_about * translate; + assert_near(rotate_then_translate * probe, Point::new(-1., 2.)); + assert_near(translate_then_rotate * probe, Point::new(-2., 1.)); + + // Check .then_* semantics + affine_assert_near( + rotate_about.then_translate(translation), + rotate_then_translate, + ); + affine_assert_near( + translate.then_rotate_about(theta, center), + translate_then_rotate, + ); + + // Check .pre_rotate_about semantics + affine_assert_near( + translate.pre_rotate_about(theta, center), + rotate_then_translate, + ); + } +} diff --git a/vendor/kurbo/src/arc.rs b/vendor/kurbo/src/arc.rs new file mode 100644 index 0000000000..0704deb156 --- /dev/null +++ b/vendor/kurbo/src/arc.rs @@ -0,0 +1,341 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! An ellipse arc. + +use crate::{Affine, Ellipse, ParamCurve, PathEl, Point, Rect, Shape, Vec2}; +use core::{ + f64::consts::{FRAC_PI_2, PI}, + iter, + ops::{Mul, Range}, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A single elliptical arc segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Arc { + /// The arc's centre point. + pub center: Point, + /// The arc's radii, where the vector's x-component is the radius in the + /// positive x direction after applying `x_rotation`. + pub radii: Vec2, + /// The start angle in radians. + pub start_angle: f64, + /// The angle between the start and end of the arc, in radians. + pub sweep_angle: f64, + /// How much the arc is rotated, in radians. + pub x_rotation: f64, +} + +impl Arc { + /// Create a new `Arc`. + #[inline(always)] + pub fn new( + center: impl Into, + radii: impl Into, + start_angle: f64, + sweep_angle: f64, + x_rotation: f64, + ) -> Self { + Self { + center: center.into(), + radii: radii.into(), + start_angle, + sweep_angle, + x_rotation, + } + } + + /// Returns a copy of this `Arc` in the opposite direction. + /// + /// The new `Arc` will sweep towards the original `Arc`s + /// start angle. + #[must_use] + #[inline] + pub fn reversed(&self) -> Arc { + Self { + center: self.center, + radii: self.radii, + start_angle: self.start_angle + self.sweep_angle, + sweep_angle: -self.sweep_angle, + x_rotation: self.x_rotation, + } + } + + #[inline] + fn angle_at(&self, t: f64) -> f64 { + self.start_angle + self.sweep_angle * t + } + + /// Create an iterator generating Bezier path elements. + /// + /// The generated elements can be appended to an existing bezier path. + pub fn append_iter(&self, tolerance: f64) -> ArcAppendIter { + let sign = self.sweep_angle.signum(); + let scaled_err = self.radii.x.max(self.radii.y) / tolerance; + // Number of subdivisions per ellipse based on error tolerance. + // Note: this may slightly underestimate the error for quadrants. + let n_err = (1.1163 * scaled_err).powf(1.0 / 6.0).max(3.999_999); + let n = (n_err * self.sweep_angle.abs() * (1.0 / (2.0 * PI))).ceil(); + let angle_step = self.sweep_angle / n; + let n = n as usize; + let arm_len = (4.0 / 3.0) * (0.25 * angle_step).abs().tan() * sign; + let angle0 = self.start_angle; + let p0 = sample_ellipse(self.radii, self.x_rotation, angle0); + + ArcAppendIter { + idx: 0, + + center: self.center, + radii: self.radii, + x_rotation: self.x_rotation, + n, + arm_len, + angle_step, + + p0, + angle0, + } + } + + /// Converts an `Arc` into a series of cubic bezier segments. + /// + /// The closure `p` will be invoked with the control points for each segment. + pub fn to_cubic_beziers

(self, tolerance: f64, mut p: P) + where + P: FnMut(Point, Point, Point), + { + let mut path = self.append_iter(tolerance); + while let Some(PathEl::CurveTo(p1, p2, p3)) = path.next() { + p(p1, p2, p3); + } + } +} + +#[doc(hidden)] +pub struct ArcAppendIter { + idx: usize, + + center: Point, + radii: Vec2, + x_rotation: f64, + n: usize, + arm_len: f64, + angle_step: f64, + + p0: Vec2, + angle0: f64, +} + +impl Iterator for ArcAppendIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + if self.idx >= self.n { + return None; + } + + let angle1 = self.angle0 + self.angle_step; + let p0 = self.p0; + let p1 = p0 + + self.arm_len * sample_ellipse(self.radii, self.x_rotation, self.angle0 + FRAC_PI_2); + let p3 = sample_ellipse(self.radii, self.x_rotation, angle1); + let p2 = + p3 - self.arm_len * sample_ellipse(self.radii, self.x_rotation, angle1 + FRAC_PI_2); + + self.angle0 = angle1; + self.p0 = p3; + self.idx += 1; + + Some(PathEl::CurveTo( + self.center + p1, + self.center + p2, + self.center + p3, + )) + } +} + +/// Take the ellipse radii, how the radii are rotated, and the sweep angle, and return a point on +/// the ellipse. +fn sample_ellipse(radii: Vec2, x_rotation: f64, angle: f64) -> Vec2 { + let (angle_sin, angle_cos) = angle.sin_cos(); + let u = radii.x * angle_cos; + let v = radii.y * angle_sin; + rotate_pt(Vec2::new(u, v), x_rotation) +} + +/// Rotate `pt` about the origin by `angle` radians. +fn rotate_pt(pt: Vec2, angle: f64) -> Vec2 { + let (angle_sin, angle_cos) = angle.sin_cos(); + Vec2::new( + pt.x * angle_cos - pt.y * angle_sin, + pt.x * angle_sin + pt.y * angle_cos, + ) +} + +impl ParamCurve for Arc { + fn eval(&self, t: f64) -> Point { + self.center + sample_ellipse(self.radii, self.x_rotation, self.angle_at(t)) + } + + fn subsegment(&self, range: Range) -> Self { + Self { + center: self.center, + radii: self.radii, + start_angle: self.angle_at(range.start), + sweep_angle: self.sweep_angle * (range.end - range.start), + x_rotation: self.x_rotation, + } + } +} + +impl Shape for Arc { + type PathElementsIter<'iter> = iter::Chain, ArcAppendIter>; + + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> { + iter::once(PathEl::MoveTo(self.start())).chain(self.append_iter(tolerance)) + } + + /// Note: shape isn't closed so area is not well defined. + #[inline] + fn area(&self) -> f64 { + let Vec2 { x, y } = self.radii; + PI * x * y + } + + /// The perimeter of the arc. + /// + /// For now we just approximate by using the bezier curve representation. + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.path_segments(0.1).perimeter(accuracy) + } + + /// Note: shape isn't closed, so a point's winding number is not well defined. + #[inline] + fn winding(&self, pt: Point) -> i32 { + self.path_segments(0.1).winding(pt) + } + + #[inline] + fn bounding_box(&self) -> Rect { + self.path_segments(0.1).bounding_box() + } +} + +impl Mul for Affine { + type Output = Arc; + + fn mul(self, arc: Arc) -> Self::Output { + let ellipse = self * Ellipse::new(arc.center, arc.radii, arc.x_rotation); + let center = ellipse.center(); + let (radii, rotation) = ellipse.radii_and_rotation(); + Arc { + center, + radii, + x_rotation: rotation, + start_angle: arc.start_angle, + sweep_angle: arc.sweep_angle, + } + } +} + +#[cfg(test)] +mod tests { + use core::f64::consts::{FRAC_PI_4, FRAC_PI_6}; + + use crate::ParamCurve; + + use super::*; + + fn assert_point_near(actual: Point, expected: Point) { + let epsilon = 1e-12; + assert!( + actual.distance(expected) <= epsilon, + "expected {expected:?}, got {actual:?}" + ); + } + + fn assert_subsegment_matches(arc: Arc, range: Range) { + let subsegment = arc.subsegment(range.clone()); + for t in [0.0, 0.25, 0.5, 1.0] { + let expected_t = range.start + (range.end - range.start) * t; + assert_point_near(subsegment.eval(t), arc.eval(expected_t)); + } + assert_point_near(subsegment.start(), arc.eval(range.start)); + assert_point_near(subsegment.end(), arc.eval(range.end)); + } + + #[test] + fn reversed_arc() { + let a = Arc::new((0., 0.), (1., 0.), 0., PI, 0.); + let f = a.reversed(); + + // Most fields should be unchanged: + assert_eq!(a.center, f.center); + assert_eq!(a.radii, f.radii); + assert_eq!(a.x_rotation, f.x_rotation); + + // Sweep angle should be in reverse + assert_eq!(a.sweep_angle, -f.sweep_angle); + + // Reversing it again should result in the original arc + assert_eq!(a, f.reversed()); + } + + #[test] + fn eval_endpoints_and_midpoint() { + let arc = Arc::new((3.0, -2.0), (4.0, 1.5), FRAC_PI_6, PI, 0.0); + assert_point_near(arc.eval(0.0), arc.start()); + assert_point_near(arc.eval(1.0), arc.end()); + assert_point_near( + arc.eval(0.5), + arc.center + sample_ellipse(arc.radii, arc.x_rotation, arc.angle_at(0.5)), + ); + } + + #[test] + fn eval_rotated_ellipse() { + let arc = Arc::new((5.0, 7.0), (3.0, 2.0), FRAC_PI_6, PI / 3.0, FRAC_PI_4); + assert_point_near( + arc.start(), + arc.center + sample_ellipse(arc.radii, arc.x_rotation, arc.start_angle), + ); + assert_point_near( + arc.end(), + arc.center + + sample_ellipse(arc.radii, arc.x_rotation, arc.start_angle + arc.sweep_angle), + ); + } + + #[test] + fn eval_reversed_arc() { + let arc = Arc::new((2.0, 3.0), (4.0, 1.0), FRAC_PI_6, PI / 2.0, FRAC_PI_4); + let reversed = arc.reversed(); + assert_point_near(reversed.start(), arc.end()); + assert_point_near(reversed.end(), arc.start()); + assert_point_near(reversed.eval(0.5), arc.eval(0.5)); + } + + #[test] + fn subsegment_matches_original() { + let arc = Arc::new((1.0, -4.0), (3.0, 2.0), -FRAC_PI_4, PI, FRAC_PI_6); + assert_subsegment_matches(arc, 0.2..0.7); + } + + #[test] + fn subsegment_negative_sweep_matches_original() { + let arc = Arc::new((1.0, 2.0), (5.0, 3.0), PI, -0.75 * PI, FRAC_PI_6); + assert_subsegment_matches(arc, 0.1..0.8); + } + + #[test] + fn subsegment_tiny_sweep_matches_original() { + let arc = Arc::new((0.0, 0.0), (2.0, 1.0), 1.0, 1e-9, FRAC_PI_4); + assert_subsegment_matches(arc, 0.25..0.75); + } +} diff --git a/vendor/kurbo/src/axis.rs b/vendor/kurbo/src/axis.rs new file mode 100644 index 0000000000..91a802e1b8 --- /dev/null +++ b/vendor/kurbo/src/axis.rs @@ -0,0 +1,72 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use crate::{Point, Size, Vec2}; + +/// An axis in the plane. +#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] +pub enum Axis { + /// The x axis. + Horizontal, + /// The y axis. + Vertical, +} + +impl Axis { + /// Get the axis perpendicular to this one. + #[inline] + pub const fn cross(self) -> Self { + match self { + Self::Horizontal => Self::Vertical, + Self::Vertical => Self::Horizontal, + } + } + + /// Create a new [`Point`] by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_point(self, axis_value: f64, cross_value: f64) -> Point { + match self { + Self::Horizontal => Point::new(axis_value, cross_value), + Self::Vertical => Point::new(cross_value, axis_value), + } + } + + /// Create a new [`Size`] by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `height` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_size(self, axis_value: f64, cross_value: f64) -> Size { + match self { + Self::Horizontal => Size::new(axis_value, cross_value), + Self::Vertical => Size::new(cross_value, axis_value), + } + } + + /// Create a new [`Vec2`] by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_vec2(self, axis_value: f64, cross_value: f64) -> Vec2 { + match self { + Self::Horizontal => Vec2::new(axis_value, cross_value), + Self::Vertical => Vec2::new(cross_value, axis_value), + } + } + + /// Create a new `(x, y)` pair by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_xy(self, axis_value: f64, cross_value: f64) -> (f64, f64) { + match self { + Self::Horizontal => (axis_value, cross_value), + Self::Vertical => (cross_value, axis_value), + } + } +} diff --git a/vendor/kurbo/src/bezpath.rs b/vendor/kurbo/src/bezpath.rs new file mode 100644 index 0000000000..a290df1f4e --- /dev/null +++ b/vendor/kurbo/src/bezpath.rs @@ -0,0 +1,2311 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Bézier paths (up to cubic). + +#![allow(clippy::many_single_char_names)] + +use core::iter::{Extend, FromIterator}; +use core::mem; +use core::ops::{Mul, Range}; + +use alloc::vec::Vec; + +use arrayvec::ArrayVec; + +use crate::MAX_EXTREMA; +use crate::common::{solve_cubic, solve_quadratic}; +use crate::{ + Affine, CubicBez, Line, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, Rect, Shape, TranslateScale, Vec2, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A Bézier path. +/// +/// These docs assume basic familiarity with Bézier curves; for an introduction, +/// see Pomax's wonderful [A Primer on Bézier Curves]. +/// +/// This path can contain lines, quadratics ([`QuadBez`]) and cubics +/// ([`CubicBez`]), and may contain multiple subpaths. +/// +/// # Elements and Segments +/// +/// A Bézier path can be represented in terms of either 'elements' ([`PathEl`]) +/// or 'segments' ([`PathSeg`]). Elements map closely to how Béziers are +/// generally used in PostScript-style drawing APIs; they can be thought of as +/// instructions for drawing the path. Segments more directly describe the +/// path itself, with each segment being an independent line or curve. +/// +/// These different representations are useful in different contexts. +/// For tasks like drawing, elements are a natural fit, but when doing +/// hit-testing or subdividing, we need to have access to the segments. +/// +/// Conceptually, a `BezPath` contains zero or more subpaths. Each subpath +/// *always* begins with a `MoveTo`, then has zero or more `LineTo`, `QuadTo`, +/// and `CurveTo` elements, and optionally ends with a `ClosePath`. +/// +/// Internally, a `BezPath` is a list of [`PathEl`]s; as such it implements +/// [`FromIterator`] and [`Extend`]: +/// +/// ``` +/// use kurbo::{BezPath, Rect, Shape, Vec2}; +/// let accuracy = 0.1; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.)); +/// // these are equivalent +/// let path1 = rect.to_path(accuracy); +/// let path2: BezPath = rect.path_elements(accuracy).collect(); +/// +/// // extend a path with another path: +/// let mut path = rect.to_path(accuracy); +/// let shifted_rect = rect + Vec2::new(5.0, 10.0); +/// path.extend(shifted_rect.to_path(accuracy)); +/// ``` +/// +/// You can iterate the elements of a `BezPath` with the [`iter`] method, +/// and the segments with the [`segments`] method: +/// +/// ``` +/// use kurbo::{BezPath, Line, PathEl, PathSeg, Point, Rect, Shape}; +/// let accuracy = 0.1; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.)); +/// // these are equivalent +/// let path = rect.to_path(accuracy); +/// let first_el = PathEl::MoveTo(Point::ZERO); +/// let first_seg = PathSeg::Line(Line::new((0., 0.), (10., 0.))); +/// assert_eq!(path.iter().next(), Some(first_el)); +/// assert_eq!(path.segments().next(), Some(first_seg)); +/// ``` +/// In addition, if you have some other type that implements +/// `Iterator`, you can adapt that to an iterator of segments with +/// the [`segments` free function]. +/// +/// # Advanced functionality +/// +/// In addition to the basic API, there are several useful pieces of advanced +/// functionality available on `BezPath`: +/// +/// - [`flatten`] does Bézier flattening, converting a curve to a series of +/// line segments +/// - [`intersect_line`] computes intersections of a path with a line, useful +/// for things like subdividing +/// +/// [A Primer on Bézier Curves]: https://pomax.github.io/bezierinfo/ +/// [`iter`]: BezPath::iter +/// [`segments`]: BezPath::segments +/// [`flatten`]: flatten +/// [`intersect_line`]: PathSeg::intersect_line +/// [`segments` free function]: segments +/// [`FromIterator`]: std::iter::FromIterator +/// [`Extend`]: std::iter::Extend +#[derive(Clone, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct BezPath(Vec); + +/// The element of a Bézier path. +/// +/// A valid path has `MoveTo` at the beginning of each subpath. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum PathEl { + /// Move directly to the point without drawing anything, starting a new + /// subpath. + MoveTo(Point), + /// Draw a line from the current location to the point. + LineTo(Point), + /// Draw a quadratic Bézier using the current location and the two points. + /// + /// The first point is the Bézier's control point, the second is its end point. + QuadTo(Point, Point), + /// Draw a cubic Bézier using the current location and the three points. + /// + /// The first two points are the Bézier's control points, the last point is its end point. + CurveTo(Point, Point, Point), + /// Close off the path. + ClosePath, +} + +/// A segment of a Bézier path. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum PathSeg { + /// A line segment. + Line(Line), + /// A quadratic Bézier segment. + Quad(QuadBez), + /// A cubic Bézier segment. + Cubic(CubicBez), +} + +/// An intersection of a [`Line`] and a [`PathSeg`]. +/// +/// This can be generated with the [`PathSeg::intersect_line`] method. +#[derive(Debug, Clone, Copy)] +pub struct LineIntersection { + /// The 'time' that the intersection occurs, on the line. + /// + /// This value is in the range 0..1. + pub line_t: f64, + + /// The 'time' that the intersection occurs, on the path segment. + /// + /// This value is nominally in the range 0..1, although it may slightly exceed + /// that range at the boundaries of segments. + pub segment_t: f64, +} + +/// The minimum distance between two Bézier curves. +pub struct MinDistance { + /// The shortest distance between any two points on the two curves. + pub distance: f64, + /// The position of the nearest point on the first curve, as a parameter. + /// + /// To resolve this to a [`Point`], use [`ParamCurve::eval`]. + /// + /// [`ParamCurve::eval`]: crate::ParamCurve::eval + pub t1: f64, + /// The position of the nearest point on the second curve, as a parameter. + /// + /// To resolve this to a [`Point`], use [`ParamCurve::eval`]. + /// + /// [`ParamCurve::eval`]: crate::ParamCurve::eval + pub t2: f64, +} + +impl BezPath { + /// Create a new path. + #[inline(always)] + pub fn new() -> BezPath { + BezPath::default() + } + + /// Create a new path with the specified capacity. + /// + /// This can be useful if you already know how many path elements the path + /// will consist of, to prevent reallocations. + pub fn with_capacity(capacity: usize) -> BezPath { + BezPath(Vec::with_capacity(capacity)) + } + + /// Create a path from a vector of path elements. + /// + /// `BezPath` also implements `FromIterator`, so it works with `collect`: + /// + /// ``` + /// // a very contrived example: + /// use kurbo::{BezPath, PathEl}; + /// + /// let path = BezPath::new(); + /// let as_vec: Vec = path.into_iter().collect(); + /// let back_to_path: BezPath = as_vec.into_iter().collect(); + /// ``` + pub fn from_vec(v: Vec) -> BezPath { + debug_assert!( + v.is_empty() || matches!(v.first(), Some(PathEl::MoveTo(_))), + "BezPath must begin with MoveTo" + ); + BezPath(v) + } + + /// Removes the last [`PathEl`] from the path and returns it, or `None` if the path is empty. + pub fn pop(&mut self) -> Option { + self.0.pop() + } + + /// Push a generic path element onto the path. + pub fn push(&mut self, el: PathEl) { + self.0.push(el); + debug_assert!( + matches!(self.0.first(), Some(PathEl::MoveTo(_))), + "BezPath must begin with MoveTo" + ); + } + + /// Push a "move to" element onto the path. + pub fn move_to>(&mut self, p: P) { + self.push(PathEl::MoveTo(p.into())); + } + + /// Push a "line to" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + /// + /// If `line_to` is called immediately after `close_path` then the current + /// subpath starts at the initial point of the previous subpath. + pub fn line_to>(&mut self, p: P) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::LineTo(p.into())); + } + + /// Push a "quad to" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + /// + /// If `quad_to` is called immediately after `close_path` then the current + /// subpath starts at the initial point of the previous subpath. + pub fn quad_to>(&mut self, p1: P, p2: P) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::QuadTo(p1.into(), p2.into())); + } + + /// Push a "curve to" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + /// + /// If `curve_to` is called immediately after `close_path` then the current + /// subpath starts at the initial point of the previous subpath. + pub fn curve_to>(&mut self, p1: P, p2: P, p3: P) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::CurveTo(p1.into(), p2.into(), p3.into())); + } + + /// Push a "close path" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + pub fn close_path(&mut self) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::ClosePath); + } + + /// Consumes the `BezPath` and returns a vector of [`PathEl`]s. + #[inline(always)] + pub fn into_elements(self) -> Vec { + self.0 + } + + /// Get the path elements. + /// + /// For owned elements, see [`into_elements`]. + /// + /// [`into_elements`]: Self::into_elements + #[inline(always)] + pub fn elements(&self) -> &[PathEl] { + &self.0 + } + + /// Get the path elements (mut version). + #[inline(always)] + pub fn elements_mut(&mut self) -> &mut [PathEl] { + &mut self.0 + } + + /// Returns an iterator over the path's elements. + pub fn iter(&self) -> impl Iterator + Clone + '_ { + self.0.iter().copied() + } + + /// Iterate over the path segments. + pub fn segments(&self) -> impl Iterator + Clone + '_ { + segments(self.iter()) + } + + /// Shorten the path, keeping the first `len` elements. + pub fn truncate(&mut self, len: usize) { + self.0.truncate(len); + } + + /// Get the segment at the given element index. + /// + /// If you need to access all segments, [`segments`] provides a better + /// API. This is intended for random access of specific elements, for clients + /// that require this specifically. + /// + /// **note**: This returns the segment that ends at the provided element + /// index. In effect this means it is *1-indexed*: since no segment ends at + /// the first element (which is presumed to be a `MoveTo`) `get_seg(0)` will + /// always return `None`. + pub fn get_seg(&self, ix: usize) -> Option { + if ix == 0 || ix >= self.0.len() { + return None; + } + let last = match self.0[ix - 1] { + PathEl::MoveTo(p) => p, + PathEl::LineTo(p) => p, + PathEl::QuadTo(_, p2) => p2, + PathEl::CurveTo(_, _, p3) => p3, + PathEl::ClosePath => return None, + }; + match self.0[ix] { + PathEl::LineTo(p) => Some(PathSeg::Line(Line::new(last, p))), + PathEl::QuadTo(p1, p2) => Some(PathSeg::Quad(QuadBez::new(last, p1, p2))), + PathEl::CurveTo(p1, p2, p3) => Some(PathSeg::Cubic(CubicBez::new(last, p1, p2, p3))), + PathEl::ClosePath => self.0[..ix].iter().rev().find_map(|el| match *el { + PathEl::MoveTo(start) if start != last => { + Some(PathSeg::Line(Line::new(last, start))) + } + _ => None, + }), + PathEl::MoveTo(_) => None, + } + } + + /// Returns `true` if the path contains no segments. + pub fn is_empty(&self) -> bool { + self.0 + .iter() + .all(|el| matches!(el, PathEl::MoveTo(..) | PathEl::ClosePath)) + } + + /// Apply an affine transform to the path. + pub fn apply_affine(&mut self, affine: Affine) { + for el in self.0.iter_mut() { + *el = affine * (*el); + } + } + + /// Is this path finite? + #[inline] + pub fn is_finite(&self) -> bool { + self.0.iter().all(|v| v.is_finite()) + } + + /// Is this path NaN? + #[inline] + pub fn is_nan(&self) -> bool { + self.0.iter().any(|v| v.is_nan()) + } + + /// Returns a rectangle that conservatively encloses the path. + /// + /// Unlike the `bounding_box` method, this uses control points directly + /// rather than computing tight bounds for curve elements. + pub fn control_box(&self) -> Rect { + let mut cbox: Option = None; + let mut add_pts = |pts: &[Point]| { + for pt in pts { + cbox = match cbox { + Some(cbox) => Some(cbox.union_pt(*pt)), + _ => Some(Rect::from_points(*pt, *pt)), + }; + } + }; + for &el in self.elements() { + match el { + PathEl::MoveTo(p0) | PathEl::LineTo(p0) => add_pts(&[p0]), + PathEl::QuadTo(p0, p1) => add_pts(&[p0, p1]), + PathEl::CurveTo(p0, p1, p2) => add_pts(&[p0, p1, p2]), + PathEl::ClosePath => {} + } + } + cbox.unwrap_or_default() + } + + /// Returns current position in the path, if path is not empty. + /// + /// This is different from calling [`PathEl::end_point`] on the last entry of [`BezPath::elements`]: + /// this method handles [`PathEl::ClosePath`], + /// by finding the first point of our last subpath, hence the time complexity is O(n). + pub fn current_position(&self) -> Option { + match self.0.last()? { + PathEl::MoveTo(p) => Some(*p), + PathEl::LineTo(p1) => Some(*p1), + PathEl::QuadTo(_, p2) => Some(*p2), + PathEl::CurveTo(_, _, p3) => Some(*p3), + PathEl::ClosePath => self + .elements() + .iter() + .rev() + .skip(1) + .take_while(|el| !matches!(el, PathEl::ClosePath)) + .last() + .and_then(|el| el.end_point()), + } + } + + /// Returns an iterator over the subpaths of this path. See [Elements and Segments](#elements-and-segments) for more information. + pub fn subpaths(&self) -> impl Iterator { + let elements = self.elements(); + let mut i = 0; + + core::iter::from_fn(move || { + if i >= elements.len() { + return None; + } + let start = i; + i += 1; + while i < elements.len() && !matches!(elements[i], PathEl::MoveTo(_)) { + i += 1; + } + Some(&elements[start..i]) + }) + } + + /// Returns a new path with the winding direction of all subpaths reversed. + pub fn reverse_subpaths(&self) -> BezPath { + let elements = self.elements(); + let mut start_ix = 1; + let mut start_pt = Point::default(); + let mut reversed = BezPath(Vec::with_capacity(elements.len())); + // Pending move is used to capture degenerate subpaths that should + // remain in the reversed output. + let mut pending_move = false; + for (ix, el) in elements.iter().enumerate() { + match el { + PathEl::MoveTo(pt) => { + if pending_move { + reversed.push(PathEl::MoveTo(start_pt)); + } + if start_ix < ix { + reverse_subpath(start_pt, &elements[start_ix..ix], &mut reversed); + } + pending_move = true; + start_pt = *pt; + start_ix = ix + 1; + } + PathEl::ClosePath => { + if start_ix <= ix { + reverse_subpath(start_pt, &elements[start_ix..ix], &mut reversed); + } + reversed.push(PathEl::ClosePath); + start_ix = ix + 1; + pending_move = false; + } + _ => { + pending_move = false; + } + } + } + if start_ix < elements.len() { + reverse_subpath(start_pt, &elements[start_ix..], &mut reversed); + } else if pending_move { + reversed.push(PathEl::MoveTo(start_pt)); + } + reversed + } +} + +/// Helper for reversing a subpath. +/// +/// The `els` parameter must not contain any `MoveTo` or `ClosePath` elements. +fn reverse_subpath(start_pt: Point, els: &[PathEl], reversed: &mut BezPath) { + let end_pt = els.last().and_then(|el| el.end_point()).unwrap_or(start_pt); + reversed.push(PathEl::MoveTo(end_pt)); + for (ix, el) in els.iter().enumerate().rev() { + let end_pt = if ix > 0 { + els[ix - 1].end_point().unwrap() + } else { + start_pt + }; + match el { + PathEl::LineTo(_) => reversed.push(PathEl::LineTo(end_pt)), + PathEl::QuadTo(c0, _) => reversed.push(PathEl::QuadTo(*c0, end_pt)), + PathEl::CurveTo(c0, c1, _) => reversed.push(PathEl::CurveTo(*c1, *c0, end_pt)), + _ => panic!("reverse_subpath expects MoveTo and ClosePath to be removed"), + } + } +} + +impl FromIterator for BezPath { + fn from_iter>(iter: T) -> Self { + let el_vec: Vec<_> = iter.into_iter().collect(); + BezPath::from_vec(el_vec) + } +} + +/// Allow iteration over references to `BezPath`. +/// +/// Note: the semantics are slightly different from simply iterating over the +/// slice, as it returns `PathEl` items, rather than references. +impl<'a> IntoIterator for &'a BezPath { + type Item = PathEl; + type IntoIter = core::iter::Cloned>; + + fn into_iter(self) -> Self::IntoIter { + self.elements().iter().cloned() + } +} + +impl IntoIterator for BezPath { + type Item = PathEl; + type IntoIter = alloc::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl Extend for BezPath { + /// Add the items from the iterator to this path. + /// + ///

+ /// + /// Note that if you're attempting to make a continuous path, you will generally + /// want to ensure that the iterator does not contain any [`MoveTo`](PathEl::MoveTo) + /// or [`ClosePath`](PathEl::ClosePath) elements. + /// Note especially that many (open) [shapes](Shape) will start with a `MoveTo` if + /// you use their [`path_elements`](Shape::path_elements) function. + /// Some shapes have alternatives for this use case, such as [`Arc::append_iter`](crate::Arc::append_iter). + /// + ///
+ fn extend>(&mut self, iter: I) { + self.0.extend(iter); + } +} + +/// Proportion of tolerance budget that goes to cubic to quadratic conversion. +const TO_QUAD_TOL: f64 = 0.1; + +/// Flatten the path, invoking the callback repeatedly. +/// +/// Flattening is the action of approximating a curve with a succession of line segments. +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// → +/// +/// +/// +/// The tolerance value controls the maximum distance between the curved input +/// segments and their polyline approximations. (In technical terms, this is the +/// Hausdorff distance). The algorithm attempts to bound this distance between +/// by `tolerance` but this is not absolutely guaranteed. The appropriate value +/// depends on the use, but for antialiased rendering, a value of 0.25 has been +/// determined to give good results. The number of segments tends to scale as the +/// inverse square root of tolerance. +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// The callback will be called in order with each element of the generated +/// path. Because the result is made of polylines, these will be straight-line +/// path elements only, no curves. +/// +/// This algorithm is based on the blog post [Flattening quadratic Béziers] +/// but with some refinements. For one, there is a more careful approximation +/// at cusps. For two, the algorithm is extended to work with cubic Béziers +/// as well, by first subdividing into quadratics and then computing the +/// subdivision of each quadratic. However, as a clever trick, these quadratics +/// are subdivided fractionally, and their endpoints are not included. +/// +/// TODO: write a paper explaining this in more detail. +/// +/// [Flattening quadratic Béziers]: https://raphlinus.github.io/graphics/curves/2019/12/23/flatten-quadbez.html +pub fn flatten( + path: impl IntoIterator, + tolerance: f64, + mut callback: impl FnMut(PathEl), +) { + let sqrt_tol = tolerance.sqrt(); + let mut last_pt = None; + let mut quad_buf = Vec::new(); + for el in path { + match el { + PathEl::MoveTo(p) => { + last_pt = Some(p); + callback(PathEl::MoveTo(p)); + } + PathEl::LineTo(p) => { + last_pt = Some(p); + callback(PathEl::LineTo(p)); + } + PathEl::QuadTo(p1, p2) => { + if let Some(p0) = last_pt { + let q = QuadBez::new(p0, p1, p2); + let params = q.estimate_subdiv(sqrt_tol); + let n = ((0.5 * params.val / sqrt_tol).ceil() as usize).max(1); + let step = 1.0 / (n as f64); + for i in 1..n { + let u = (i as f64) * step; + let t = q.determine_subdiv_t(¶ms, u); + let p = q.eval(t); + callback(PathEl::LineTo(p)); + } + callback(PathEl::LineTo(p2)); + } + last_pt = Some(p2); + } + PathEl::CurveTo(p1, p2, p3) => { + if let Some(p0) = last_pt { + let c = CubicBez::new(p0, p1, p2, p3); + + // Subdivide into quadratics, and estimate the number of + // subdivisions required for each, summing to arrive at an + // estimate for the number of subdivisions for the cubic. + // Also retain these parameters for later. + let iter = c.to_quads(tolerance * TO_QUAD_TOL); + quad_buf.clear(); + quad_buf.reserve(iter.size_hint().0); + let sqrt_remain_tol = sqrt_tol * (1.0 - TO_QUAD_TOL).sqrt(); + let mut sum = 0.0; + for (_, _, q) in iter { + let params = q.estimate_subdiv(sqrt_remain_tol); + sum += params.val; + quad_buf.push((q, params)); + } + let n = ((0.5 * sum / sqrt_remain_tol).ceil() as usize).max(1); + + // Iterate through the quadratics, outputting the points of + // subdivisions that fall within that quadratic. + let step = sum / (n as f64); + let mut i = 1; + let mut val_sum = 0.0; + for (q, params) in &quad_buf { + let mut target = (i as f64) * step; + let recip_val = params.val.recip(); + while target < val_sum + params.val { + let u = (target - val_sum) * recip_val; + let t = q.determine_subdiv_t(params, u); + let p = q.eval(t); + callback(PathEl::LineTo(p)); + i += 1; + if i == n + 1 { + break; + } + target = (i as f64) * step; + } + val_sum += params.val; + } + callback(PathEl::LineTo(p3)); + } + last_pt = Some(p3); + } + PathEl::ClosePath => { + last_pt = None; + callback(PathEl::ClosePath); + } + } + } +} + +impl Mul for Affine { + type Output = PathEl; + + // TODO: Inlining this leads to a huge performance benefit, perhaps the same should be done for + // other methods. + #[inline(always)] + fn mul(self, other: PathEl) -> PathEl { + match other { + PathEl::MoveTo(p) => PathEl::MoveTo(self * p), + PathEl::LineTo(p) => PathEl::LineTo(self * p), + PathEl::QuadTo(p1, p2) => PathEl::QuadTo(self * p1, self * p2), + PathEl::CurveTo(p1, p2, p3) => PathEl::CurveTo(self * p1, self * p2, self * p3), + PathEl::ClosePath => PathEl::ClosePath, + } + } +} + +impl Mul for Affine { + type Output = PathSeg; + + fn mul(self, other: PathSeg) -> PathSeg { + match other { + PathSeg::Line(line) => PathSeg::Line(self * line), + PathSeg::Quad(quad) => PathSeg::Quad(self * quad), + PathSeg::Cubic(cubic) => PathSeg::Cubic(self * cubic), + } + } +} + +impl Mul for Affine { + type Output = BezPath; + + fn mul(self, other: BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +impl Mul<&BezPath> for Affine { + type Output = BezPath; + + fn mul(self, other: &BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +impl Mul for TranslateScale { + type Output = PathEl; + + fn mul(self, other: PathEl) -> PathEl { + match other { + PathEl::MoveTo(p) => PathEl::MoveTo(self * p), + PathEl::LineTo(p) => PathEl::LineTo(self * p), + PathEl::QuadTo(p1, p2) => PathEl::QuadTo(self * p1, self * p2), + PathEl::CurveTo(p1, p2, p3) => PathEl::CurveTo(self * p1, self * p2, self * p3), + PathEl::ClosePath => PathEl::ClosePath, + } + } +} + +impl Mul for TranslateScale { + type Output = PathSeg; + + fn mul(self, other: PathSeg) -> PathSeg { + match other { + PathSeg::Line(line) => PathSeg::Line(self * line), + PathSeg::Quad(quad) => PathSeg::Quad(self * quad), + PathSeg::Cubic(cubic) => PathSeg::Cubic(self * cubic), + } + } +} + +impl Mul for TranslateScale { + type Output = BezPath; + + fn mul(self, other: BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +impl Mul<&BezPath> for TranslateScale { + type Output = BezPath; + + fn mul(self, other: &BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +/// Close all open subpaths in a path, expressed as iterator transform. +pub(crate) fn close_subpaths(elements: I) -> CloseSubpaths +where + I: IntoIterator, +{ + CloseSubpaths { + elements: elements.into_iter(), + state: CloseSubpathState::Start, + } +} + +/// An iterator that closes all open subpaths. +/// +/// This struct is created by the [`close_subpaths`] function. +#[derive(Clone)] +pub(crate) struct CloseSubpaths> { + elements: I, + state: CloseSubpathState, +} + +#[derive(Clone)] +enum CloseSubpathState { + Start, + InSubpath, + ClosedLast, + PendingMoveTo(Point), +} + +impl> Iterator for CloseSubpaths { + type Item = PathEl; + + fn next(&mut self) -> Option { + match self.state { + CloseSubpathState::Start => { + let el = self.elements.next(); + if !matches!(el, Some(PathEl::ClosePath) | None) { + self.state = CloseSubpathState::InSubpath; + } + el + } + CloseSubpathState::InSubpath => { + let el = self.elements.next(); + match el { + None => { + self.state = CloseSubpathState::ClosedLast; + Some(PathEl::ClosePath) + } + Some(PathEl::MoveTo(point)) => { + self.state = CloseSubpathState::PendingMoveTo(point); + Some(PathEl::ClosePath) + } + Some(PathEl::ClosePath) => { + self.state = CloseSubpathState::Start; + el + } + _ => el, + } + } + CloseSubpathState::ClosedLast => None, + CloseSubpathState::PendingMoveTo(point) => { + self.state = CloseSubpathState::Start; + Some(PathEl::MoveTo(point)) + } + } + } +} + +/// Transform an iterator over path elements into one over path +/// segments. +/// +/// See also [`BezPath::segments`]. +/// This signature is a bit more general, allowing `&[PathEl]` slices +/// and other iterators yielding `PathEl`. +pub fn segments(elements: I) -> Segments +where + I: IntoIterator, +{ + Segments { + elements: elements.into_iter(), + start_last: None, + } +} + +/// An iterator that transforms path elements to path segments. +/// +/// This struct is created by the [`segments`] function. +#[derive(Clone)] +pub struct Segments> { + elements: I, + start_last: Option<(Point, Point)>, +} + +impl> Iterator for Segments { + type Item = PathSeg; + + #[inline] + fn next(&mut self) -> Option { + for el in &mut self.elements { + // We first need to check whether this is the first + // path element we see to fill in the start position. + let (start, last) = self.start_last.get_or_insert_with(|| { + let point = match el { + PathEl::MoveTo(p) => p, + PathEl::LineTo(p) => p, + PathEl::QuadTo(_, p2) => p2, + PathEl::CurveTo(_, _, p3) => p3, + PathEl::ClosePath => panic!("Can't start a segment on a ClosePath"), + }; + (point, point) + }); + + return Some(match el { + PathEl::MoveTo(p) => { + *start = p; + *last = p; + continue; + } + PathEl::LineTo(p) => PathSeg::Line(Line::new(mem::replace(last, p), p)), + PathEl::QuadTo(p1, p2) => { + PathSeg::Quad(QuadBez::new(mem::replace(last, p2), p1, p2)) + } + PathEl::CurveTo(p1, p2, p3) => { + PathSeg::Cubic(CubicBez::new(mem::replace(last, p3), p1, p2, p3)) + } + PathEl::ClosePath => { + if *last != *start { + PathSeg::Line(Line::new(mem::replace(last, *start), *start)) + } else { + continue; + } + } + }); + } + + None + } +} + +impl> Segments { + /// Here, `accuracy` specifies the accuracy for each Bézier segment. At worst, + /// the total error is `accuracy` times the number of Bézier segments. + // TODO: pub? Or is this subsumed by method of &[PathEl]? + pub(crate) fn perimeter(self, accuracy: f64) -> f64 { + self.map(|seg| seg.arclen(accuracy)).sum() + } + + // Same + pub(crate) fn area(self) -> f64 { + self.map(|seg| seg.signed_area()).sum() + } + + // Same + pub(crate) fn winding(self, p: Point) -> i32 { + self.map(|seg| seg.winding(p)).sum() + } + + // Same + pub(crate) fn bounding_box(self) -> Rect { + let mut bbox: Option = None; + for seg in self { + let seg_bb = ParamCurveExtrema::bounding_box(&seg); + if let Some(bb) = bbox { + bbox = Some(bb.union(seg_bb)); + } else { + bbox = Some(seg_bb); + } + } + bbox.unwrap_or_default() + } +} + +impl ParamCurve for PathSeg { + fn eval(&self, t: f64) -> Point { + match *self { + PathSeg::Line(line) => line.eval(t), + PathSeg::Quad(quad) => quad.eval(t), + PathSeg::Cubic(cubic) => cubic.eval(t), + } + } + + fn subsegment(&self, range: Range) -> PathSeg { + match *self { + PathSeg::Line(line) => PathSeg::Line(line.subsegment(range)), + PathSeg::Quad(quad) => PathSeg::Quad(quad.subsegment(range)), + PathSeg::Cubic(cubic) => PathSeg::Cubic(cubic.subsegment(range)), + } + } + + fn start(&self) -> Point { + match *self { + PathSeg::Line(line) => line.start(), + PathSeg::Quad(quad) => quad.start(), + PathSeg::Cubic(cubic) => cubic.start(), + } + } + + fn end(&self) -> Point { + match *self { + PathSeg::Line(line) => line.end(), + PathSeg::Quad(quad) => quad.end(), + PathSeg::Cubic(cubic) => cubic.end(), + } + } +} + +impl ParamCurveArclen for PathSeg { + fn arclen(&self, accuracy: f64) -> f64 { + match *self { + PathSeg::Line(line) => line.arclen(accuracy), + PathSeg::Quad(quad) => quad.arclen(accuracy), + PathSeg::Cubic(cubic) => cubic.arclen(accuracy), + } + } + + fn inv_arclen(&self, arclen: f64, accuracy: f64) -> f64 { + match *self { + PathSeg::Line(line) => line.inv_arclen(arclen, accuracy), + PathSeg::Quad(quad) => quad.inv_arclen(arclen, accuracy), + PathSeg::Cubic(cubic) => cubic.inv_arclen(arclen, accuracy), + } + } +} + +impl ParamCurveArea for PathSeg { + fn signed_area(&self) -> f64 { + match *self { + PathSeg::Line(line) => line.signed_area(), + PathSeg::Quad(quad) => quad.signed_area(), + PathSeg::Cubic(cubic) => cubic.signed_area(), + } + } +} + +impl ParamCurveNearest for PathSeg { + fn nearest(&self, p: Point, accuracy: f64) -> Nearest { + match *self { + PathSeg::Line(line) => line.nearest(p, accuracy), + PathSeg::Quad(quad) => quad.nearest(p, accuracy), + PathSeg::Cubic(cubic) => cubic.nearest(p, accuracy), + } + } +} + +impl ParamCurveExtrema for PathSeg { + fn extrema(&self) -> ArrayVec { + match *self { + PathSeg::Line(line) => line.extrema(), + PathSeg::Quad(quad) => quad.extrema(), + PathSeg::Cubic(cubic) => cubic.extrema(), + } + } +} + +impl PathSeg { + /// Get the [`PathEl`] that is equivalent to discarding the segment start point. + pub fn as_path_el(&self) -> PathEl { + match self { + PathSeg::Line(line) => PathEl::LineTo(line.p1), + PathSeg::Quad(q) => PathEl::QuadTo(q.p1, q.p2), + PathSeg::Cubic(c) => PathEl::CurveTo(c.p1, c.p2, c.p3), + } + } + + /// Returns a new `PathSeg` describing the same path as `self`, but with + /// the points reversed. + pub fn reverse(&self) -> PathSeg { + match self { + PathSeg::Line(Line { p0, p1 }) => PathSeg::Line(Line::new(*p1, *p0)), + PathSeg::Quad(q) => PathSeg::Quad(QuadBez::new(q.p2, q.p1, q.p0)), + PathSeg::Cubic(c) => PathSeg::Cubic(CubicBez::new(c.p3, c.p2, c.p1, c.p0)), + } + } + + /// Convert this segment to a cubic Bézier. + pub fn to_cubic(&self) -> CubicBez { + match *self { + PathSeg::Line(Line { p0, p1 }) => CubicBez::new(p0, p0, p1, p1), + PathSeg::Cubic(c) => c, + PathSeg::Quad(q) => q.raise(), + } + } + + /// A single-segment "winding" number. + /// + /// Assume that `self` is monotonic in `y`, and take a ray pointing + /// left from `p`. If `self` crosses that ray, returns 1 (if we're + /// decreasing in y) or -1 (if we're increasing in y). Otherwise, returns 0. + /// + /// Handling of endpoints is a little subtle, just to make sure that + /// we correctly handle consecutive segments: we consider `self` to + /// contain the endpoint with smaller y, and not contain the endpoint + /// with larger y. + fn winding_inner(&self, p: Point) -> i32 { + let start = self.start(); + let end = self.end(); + let sign = if end.y > start.y { + if p.y < start.y || p.y >= end.y { + return 0; + } + -1 + } else if end.y < start.y { + if p.y < end.y || p.y >= start.y { + return 0; + } + 1 + } else { + return 0; + }; + match *self { + PathSeg::Line(_line) => { + if p.x < start.x.min(end.x) { + return 0; + } + if p.x >= start.x.max(end.x) { + return sign; + } + // line equation ax + by = c + let a = end.y - start.y; + let b = start.x - end.x; + let c = a * start.x + b * start.y; + if (a * p.x + b * p.y - c) * (sign as f64) <= 0.0 { + sign + } else { + 0 + } + } + PathSeg::Quad(quad) => { + let p1 = quad.p1; + if p.x < start.x.min(end.x).min(p1.x) { + return 0; + } + if p.x >= start.x.max(end.x).max(p1.x) { + return sign; + } + let t = quad.solve_monotonic_for_y(p.y); + let x = quad.eval(t).x; + if p.x >= x { sign } else { 0 } + } + PathSeg::Cubic(cubic) => { + let p1 = cubic.p1; + let p2 = cubic.p2; + if p.x < start.x.min(end.x).min(p1.x).min(p2.x) { + return 0; + } + if p.x >= start.x.max(end.x).max(p1.x).max(p2.x) { + return sign; + } + let t = cubic.solve_monotonic_for_y(p.y); + let x = cubic.eval(t).x; + if p.x >= x { sign } else { 0 } + } + } + } + + /// Compute the winding number contribution of a single segment. + /// + /// Cast a ray to the left and count intersections. + fn winding(&self, p: Point) -> i32 { + self.extrema_ranges() + .into_iter() + .map(|range| self.subsegment(range).winding_inner(p)) + .sum() + } + + /// Compute intersections against a line. + /// + /// Returns a vector of the intersections. For each intersection, + /// the `t` value of the segment and line are given. + /// + /// Note: This test is designed to be inclusive of points near the endpoints + /// of the segment. This is so that testing a line against multiple + /// contiguous segments of a path will be guaranteed to catch at least one + /// of them. In such cases, use higher level logic to coalesce the hits + /// (the `t` value may be slightly outside the range of 0..1). + /// + /// # Examples + /// + /// ``` + /// # use kurbo::*; + /// let seg = PathSeg::Line(Line::new((0.0, 0.0), (2.0, 0.0))); + /// let line = Line::new((1.0, 2.0), (1.0, -2.0)); + /// let intersection = seg.intersect_line(line); + /// assert_eq!(intersection.len(), 1); + /// let intersection = intersection[0]; + /// assert_eq!(intersection.segment_t, 0.5); + /// assert_eq!(intersection.line_t, 0.5); + /// + /// let point = seg.eval(intersection.segment_t); + /// assert_eq!(point, Point::new(1.0, 0.0)); + /// ``` + pub fn intersect_line(&self, line: Line) -> ArrayVec { + const EPSILON: f64 = 1e-9; + let p0 = line.p0; + let p1 = line.p1; + let dx = p1.x - p0.x; + let dy = p1.y - p0.y; + let mut result = ArrayVec::new(); + match self { + PathSeg::Line(l) => { + let det = dx * (l.p1.y - l.p0.y) - dy * (l.p1.x - l.p0.x); + if det.abs() < EPSILON { + // Lines are coincident (or nearly so). + return result; + } + let t = dx * (p0.y - l.p0.y) - dy * (p0.x - l.p0.x); + // t = position on self + let t = t / det; + if (-EPSILON..=(1.0 + EPSILON)).contains(&t) { + // u = position on probe line + let u = + (l.p0.x - p0.x) * (l.p1.y - l.p0.y) - (l.p0.y - p0.y) * (l.p1.x - l.p0.x); + let u = u / det; + if (0.0..=1.0).contains(&u) { + result.push(LineIntersection::new(u, t)); + } + } + } + PathSeg::Quad(q) => { + // The basic technique here is to determine x and y as a quadratic polynomial + // as a function of t. Then plug those values into the line equation for the + // probe line (giving a sort of signed distance from the probe line) and solve + // that for t. + let (px0, px1, px2) = quadratic_bez_coefs(q.p0.x, q.p1.x, q.p2.x); + let (py0, py1, py2) = quadratic_bez_coefs(q.p0.y, q.p1.y, q.p2.y); + let c0 = dy * (px0 - p0.x) - dx * (py0 - p0.y); + let c1 = dy * px1 - dx * py1; + let c2 = dy * px2 - dx * py2; + let invlen2 = (dx * dx + dy * dy).recip(); + for t in solve_quadratic(c0, c1, c2) { + if (-EPSILON..=(1.0 + EPSILON)).contains(&t) { + let x = px0 + t * px1 + t * t * px2; + let y = py0 + t * py1 + t * t * py2; + let u = ((x - p0.x) * dx + (y - p0.y) * dy) * invlen2; + if (0.0..=1.0).contains(&u) { + result.push(LineIntersection::new(u, t)); + } + } + } + } + PathSeg::Cubic(c) => { + // Same technique as above, but cubic polynomial. + let (px0, px1, px2, px3) = cubic_bez_coefs(c.p0.x, c.p1.x, c.p2.x, c.p3.x); + let (py0, py1, py2, py3) = cubic_bez_coefs(c.p0.y, c.p1.y, c.p2.y, c.p3.y); + let c0 = dy * (px0 - p0.x) - dx * (py0 - p0.y); + let c1 = dy * px1 - dx * py1; + let c2 = dy * px2 - dx * py2; + let c3 = dy * px3 - dx * py3; + let invlen2 = (dx * dx + dy * dy).recip(); + for t in solve_cubic(c0, c1, c2, c3) { + if (-EPSILON..=(1.0 + EPSILON)).contains(&t) { + let x = px0 + t * px1 + t * t * px2 + t * t * t * px3; + let y = py0 + t * py1 + t * t * py2 + t * t * t * py3; + let u = ((x - p0.x) * dx + (y - p0.y) * dy) * invlen2; + if (0.0..=1.0).contains(&u) { + result.push(LineIntersection::new(u, t)); + } + } + } + } + } + result + } + + /// Is this Bézier path finite? + #[inline] + pub fn is_finite(&self) -> bool { + match self { + PathSeg::Line(line) => line.is_finite(), + PathSeg::Quad(quad_bez) => quad_bez.is_finite(), + PathSeg::Cubic(cubic_bez) => cubic_bez.is_finite(), + } + } + + /// Is this Bézier path NaN? + #[inline] + pub fn is_nan(&self) -> bool { + match self { + PathSeg::Line(line) => line.is_nan(), + PathSeg::Quad(quad_bez) => quad_bez.is_nan(), + PathSeg::Cubic(cubic_bez) => cubic_bez.is_nan(), + } + } + + #[inline] + fn as_vec2_vec(&self) -> ArrayVec { + let mut a = ArrayVec::new(); + match self { + PathSeg::Line(l) => { + a.push(l.p0.to_vec2()); + a.push(l.p1.to_vec2()); + } + PathSeg::Quad(q) => { + a.push(q.p0.to_vec2()); + a.push(q.p1.to_vec2()); + a.push(q.p2.to_vec2()); + } + PathSeg::Cubic(c) => { + a.push(c.p0.to_vec2()); + a.push(c.p1.to_vec2()); + a.push(c.p2.to_vec2()); + a.push(c.p3.to_vec2()); + } + } + a + } + + /// Minimum distance between two [`PathSeg`]s. + /// + /// Returns a tuple of the distance, the path time `t1` of the closest point + /// on the first `PathSeg`, and the path time `t2` of the closest point on the + /// second `PathSeg`. + pub fn min_dist(&self, other: PathSeg, accuracy: f64) -> MinDistance { + let (distance, t1, t2) = crate::mindist::min_dist_param( + &self.as_vec2_vec(), + &other.as_vec2_vec(), + (0.0, 1.0), + (0.0, 1.0), + accuracy, + None, + ); + MinDistance { + distance: distance.sqrt(), + t1, + t2, + } + } + + /// Compute endpoint tangents of a path segment. + /// + /// This version is robust to the path segment not being a regular curve. + pub(crate) fn tangents(&self) -> (Vec2, Vec2) { + const EPS: f64 = 1e-12; + match self { + PathSeg::Line(l) => { + let d = l.p1 - l.p0; + (d, d) + } + PathSeg::Quad(q) => { + let d01 = q.p1 - q.p0; + let d0 = if d01.hypot2() > EPS { d01 } else { q.p2 - q.p0 }; + let d12 = q.p2 - q.p1; + let d1 = if d12.hypot2() > EPS { d12 } else { q.p2 - q.p0 }; + (d0, d1) + } + PathSeg::Cubic(c) => { + let d01 = c.p1 - c.p0; + let d0 = if d01.hypot2() > EPS { + d01 + } else { + let d02 = c.p2 - c.p0; + if d02.hypot2() > EPS { d02 } else { c.p3 - c.p0 } + }; + let d23 = c.p3 - c.p2; + let d1 = if d23.hypot2() > EPS { + d23 + } else { + let d13 = c.p3 - c.p1; + if d13.hypot2() > EPS { d13 } else { c.p3 - c.p0 } + }; + (d0, d1) + } + } + } +} + +impl LineIntersection { + #[inline(always)] + fn new(line_t: f64, segment_t: f64) -> Self { + LineIntersection { line_t, segment_t } + } + + /// Is this line intersection finite? + #[inline] + pub fn is_finite(self) -> bool { + self.line_t.is_finite() && self.segment_t.is_finite() + } + + /// Is this line intersection NaN? + #[inline] + pub fn is_nan(self) -> bool { + self.line_t.is_nan() || self.segment_t.is_nan() + } +} + +// Return polynomial coefficients given cubic Bézier coordinates. +fn quadratic_bez_coefs(x0: f64, x1: f64, x2: f64) -> (f64, f64, f64) { + let p0 = x0; + let p1 = 2.0 * x1 - 2.0 * x0; + let p2 = x2 - 2.0 * x1 + x0; + (p0, p1, p2) +} + +// Return polynomial coefficients given cubic Bézier coordinates. +fn cubic_bez_coefs(x0: f64, x1: f64, x2: f64, x3: f64) -> (f64, f64, f64, f64) { + let p0 = x0; + let p1 = 3.0 * x1 - 3.0 * x0; + let p2 = 3.0 * x2 - 6.0 * x1 + 3.0 * x0; + let p3 = x3 - 3.0 * x2 + 3.0 * x1 - x0; + (p0, p1, p2, p3) +} + +impl From for PathSeg { + #[inline(always)] + fn from(cubic_bez: CubicBez) -> PathSeg { + PathSeg::Cubic(cubic_bez) + } +} + +impl From for PathSeg { + #[inline(always)] + fn from(line: Line) -> PathSeg { + PathSeg::Line(line) + } +} + +impl From for PathSeg { + #[inline(always)] + fn from(quad_bez: QuadBez) -> PathSeg { + PathSeg::Quad(quad_bez) + } +} + +impl Shape for BezPath { + type PathElementsIter<'iter> = core::iter::Copied>; + + fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> { + self.0.iter().copied() + } + + fn to_path(&self, _tolerance: f64) -> BezPath { + self.clone() + } + + #[inline(always)] + fn into_path(self, _tolerance: f64) -> BezPath { + self + } + + /// Signed area. + fn area(&self) -> f64 { + self.elements().area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + self.elements().perimeter(accuracy) + } + + /// Winding number of point. + fn winding(&self, pt: Point) -> i32 { + self.elements().winding(pt) + } + + fn bounding_box(&self) -> Rect { + self.elements().bounding_box() + } + + #[inline(always)] + fn as_path_slice(&self) -> Option<&[PathEl]> { + Some(&self.0) + } +} + +impl PathEl { + /// Is this path element finite? + #[inline] + pub fn is_finite(&self) -> bool { + match self { + PathEl::MoveTo(p) => p.is_finite(), + PathEl::LineTo(p) => p.is_finite(), + PathEl::QuadTo(p, p2) => p.is_finite() && p2.is_finite(), + PathEl::CurveTo(p, p2, p3) => p.is_finite() && p2.is_finite() && p3.is_finite(), + PathEl::ClosePath => true, + } + } + + /// Is this path element NaN? + #[inline] + pub fn is_nan(&self) -> bool { + match self { + PathEl::MoveTo(p) => p.is_nan(), + PathEl::LineTo(p) => p.is_nan(), + PathEl::QuadTo(p, p2) => p.is_nan() || p2.is_nan(), + PathEl::CurveTo(p, p2, p3) => p.is_nan() || p2.is_nan() || p3.is_nan(), + PathEl::ClosePath => false, + } + } + + /// Get the end point of the path element, if it exists. + pub fn end_point(&self) -> Option { + match self { + PathEl::MoveTo(p) => Some(*p), + PathEl::LineTo(p1) => Some(*p1), + PathEl::QuadTo(_, p2) => Some(*p2), + PathEl::CurveTo(_, _, p3) => Some(*p3), + PathEl::ClosePath => None, + } + } +} + +/// Implements [`Shape`] for a slice of [`PathEl`], provided that the first element of the slice is +/// not a `PathEl::ClosePath`. If it is, several of these functions will panic. +/// +/// If the slice starts with `LineTo`, `QuadTo`, or `CurveTo`, it will be treated as a `MoveTo`. +impl<'a> Shape for &'a [PathEl] { + type PathElementsIter<'iter> + = core::iter::Copied> + where + 'a: 'iter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> { + self.iter().copied() + } + + fn to_path(&self, _tolerance: f64) -> BezPath { + BezPath::from_vec(self.to_vec()) + } + + /// Signed area. + fn area(&self) -> f64 { + segments(self.iter().copied()).area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + segments(self.iter().copied()).perimeter(accuracy) + } + + /// Winding number of point. + fn winding(&self, pt: Point) -> i32 { + segments(self.iter().copied()).winding(pt) + } + + fn bounding_box(&self) -> Rect { + segments(self.iter().copied()).bounding_box() + } + + #[inline(always)] + fn as_path_slice(&self) -> Option<&[PathEl]> { + Some(self) + } +} + +/// Implements [`Shape`] for an array of [`PathEl`], provided that the first element of the array is +/// not a `PathEl::ClosePath`. If it is, several of these functions will panic. +/// +/// If the array starts with `LineTo`, `QuadTo`, or `CurveTo`, it will be treated as a `MoveTo`. +impl Shape for [PathEl; N] { + type PathElementsIter<'iter> = core::iter::Copied>; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> { + self.iter().copied() + } + + fn to_path(&self, _tolerance: f64) -> BezPath { + BezPath::from_vec(self.to_vec()) + } + + /// Signed area. + fn area(&self) -> f64 { + segments(self.iter().copied()).area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + segments(self.iter().copied()).perimeter(accuracy) + } + + /// Winding number of point. + fn winding(&self, pt: Point) -> i32 { + segments(self.iter().copied()).winding(pt) + } + + fn bounding_box(&self) -> Rect { + segments(self.iter().copied()).bounding_box() + } + + #[inline(always)] + fn as_path_slice(&self) -> Option<&[PathEl]> { + Some(self) + } +} + +/// An iterator for path segments. +pub struct PathSegIter { + seg: PathSeg, + ix: usize, +} + +impl Shape for PathSeg { + type PathElementsIter<'iter> = PathSegIter; + + #[inline(always)] + fn path_elements(&self, _tolerance: f64) -> PathSegIter { + PathSegIter { seg: *self, ix: 0 } + } + + /// The area under the curve. + /// + /// We could just return `0`, but this seems more useful. + fn area(&self) -> f64 { + self.signed_area() + } + + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.arclen(accuracy) + } + + #[inline(always)] + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline] + fn bounding_box(&self) -> Rect { + ParamCurveExtrema::bounding_box(self) + } + + fn as_line(&self) -> Option { + if let PathSeg::Line(line) = self { + Some(*line) + } else { + None + } + } +} + +impl Iterator for PathSegIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match (self.ix, self.seg) { + // yes I could do some fancy bindings thing here but... :shrug: + (1, PathSeg::Line(seg)) => Some(PathEl::MoveTo(seg.p0)), + (1, PathSeg::Quad(seg)) => Some(PathEl::MoveTo(seg.p0)), + (1, PathSeg::Cubic(seg)) => Some(PathEl::MoveTo(seg.p0)), + (2, PathSeg::Line(seg)) => Some(PathEl::LineTo(seg.p1)), + (2, PathSeg::Quad(seg)) => Some(PathEl::QuadTo(seg.p1, seg.p2)), + (2, PathSeg::Cubic(seg)) => Some(PathEl::CurveTo(seg.p1, seg.p2, seg.p3)), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use crate::{Circle, DEFAULT_ACCURACY}; + + use super::*; + + fn assert_approx_eq(x: f64, y: f64) { + assert!((x - y).abs() < 1e-8, "{x} != {y}"); + } + + #[test] + #[should_panic(expected = "uninitialized subpath")] + fn test_elements_to_segments_starts_on_closepath() { + let mut path = BezPath::new(); + path.close_path(); + path.segments().next(); + } + + #[test] + fn test_elements_to_segments_closepath_refers_to_last_moveto() { + let mut path = BezPath::new(); + path.move_to((5.0, 5.0)); + path.line_to((15.0, 15.0)); + path.move_to((10.0, 10.0)); + path.line_to((15.0, 15.0)); + path.close_path(); + assert_eq!( + path.segments().collect::>().last(), + Some(&Line::new((15.0, 15.0), (10.0, 10.0)).into()), + ); + } + + #[test] + #[should_panic(expected = "uninitialized subpath")] + fn test_must_not_start_on_quad() { + let mut path = BezPath::new(); + path.quad_to((5.0, 5.0), (10.0, 10.0)); + path.line_to((15.0, 15.0)); + path.close_path(); + } + + #[test] + fn test_intersect_line() { + let h_line = Line::new((0.0, 0.0), (100.0, 0.0)); + let v_line = Line::new((10.0, -10.0), (10.0, 10.0)); + let intersection = PathSeg::Line(h_line).intersect_line(v_line)[0]; + assert_approx_eq(intersection.segment_t, 0.1); + assert_approx_eq(intersection.line_t, 0.5); + + let v_line = Line::new((-10.0, -10.0), (-10.0, 10.0)); + assert!(PathSeg::Line(h_line).intersect_line(v_line).is_empty()); + + let v_line = Line::new((10.0, 10.0), (10.0, 20.0)); + assert!(PathSeg::Line(h_line).intersect_line(v_line).is_empty()); + } + + #[test] + fn test_intersect_qad() { + let q = QuadBez::new((0.0, -10.0), (10.0, 20.0), (20.0, -10.0)); + let v_line = Line::new((10.0, -10.0), (10.0, 10.0)); + assert_eq!(PathSeg::Quad(q).intersect_line(v_line).len(), 1); + let intersection = PathSeg::Quad(q).intersect_line(v_line)[0]; + assert_approx_eq(intersection.segment_t, 0.5); + assert_approx_eq(intersection.line_t, 0.75); + + let h_line = Line::new((0.0, 0.0), (100.0, 0.0)); + assert_eq!(PathSeg::Quad(q).intersect_line(h_line).len(), 2); + } + + #[test] + fn test_intersect_cubic() { + let c = CubicBez::new((0.0, -10.0), (10.0, 20.0), (20.0, -20.0), (30.0, 10.0)); + let v_line = Line::new((10.0, -10.0), (10.0, 10.0)); + assert_eq!(PathSeg::Cubic(c).intersect_line(v_line).len(), 1); + let intersection = PathSeg::Cubic(c).intersect_line(v_line)[0]; + assert_approx_eq(intersection.segment_t, 0.333333333); + assert_approx_eq(intersection.line_t, 0.592592592); + + let h_line = Line::new((0.0, 0.0), (100.0, 0.0)); + assert_eq!(PathSeg::Cubic(c).intersect_line(h_line).len(), 3); + } + + #[test] + fn test_contains() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((1.0, 1.0)); + path.line_to((2.0, 0.0)); + path.close_path(); + assert_eq!(path.winding(Point::new(1.0, 0.5)), -1); + assert!(path.contains(Point::new(1.0, 0.5))); + } + + // get_seg(i) should produce the same results as path_segments().nth(i - 1). + #[test] + fn test_get_seg() { + let circle = Circle::new((10.0, 10.0), 2.0).to_path(DEFAULT_ACCURACY); + let segments = circle.path_segments(DEFAULT_ACCURACY).collect::>(); + let get_segs = (1..usize::MAX) + .map_while(|i| circle.get_seg(i)) + .collect::>(); + assert_eq!(segments, get_segs); + } + + #[test] + fn test_control_box() { + // a sort of map ping looking thing drawn with a single cubic + // cbox is wildly different than tight box + let path = BezPath::from_svg("M200,300 C50,50 350,50 200,300").unwrap(); + assert_eq!(Rect::new(50.0, 50.0, 350.0, 300.0), path.control_box()); + assert!(path.control_box().area() > path.bounding_box().area()); + } + + #[test] + fn test_subpaths() { + let path = BezPath::from_svg("M10,10 L0,10 L0,0 L10,0 Z M100,100 M30,0 Q35,10,40,0 L30,0") + .unwrap(); + assert_eq!( + vec![ + BezPath::from_svg("M10,10 L0,10 L0,0 L10,0 Z").unwrap(), + BezPath::from_svg("M100,100").unwrap(), + BezPath::from_svg("M30,0 Q35,10,40,0 L30,0").unwrap(), + ], + path.subpaths() + .map(|sp| BezPath::from_vec(sp.to_vec())) + .collect::>() + ); + } + + #[test] + fn test_reverse_unclosed() { + let path = BezPath::from_svg("M10,10 Q40,40 60,10 L100,10 C125,10 150,50 125,60").unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!( + "M125,60 C150,50 125,10 100,10 L60,10 Q40,40 10,10", + reversed.to_svg() + ); + } + + #[test] + fn test_reverse_closed_triangle() { + let path = BezPath::from_svg("M100,100 L150,200 L50,200 Z").unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!("M50,200 L150,200 L100,100 Z", reversed.to_svg()); + } + + #[test] + fn test_reverse_closed_shape() { + let path = BezPath::from_svg( + "M125,100 Q200,150 175,300 C150,150 50,150 25,300 Q0,150 75,100 L100,50 Z", + ) + .unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!( + "M100,50 L75,100 Q0,150 25,300 C50,150 150,150 175,300 Q200,150 125,100 Z", + reversed.to_svg() + ); + } + + #[test] + fn test_reverse_multiple_subpaths() { + let svg = "M10,10 Q40,40 60,10 L100,10 C125,10 150,50 125,60 M100,100 L150,200 L50,200 Z M125,100 Q200,150 175,300 C150,150 50,150 25,300 Q0,150 75,100 L100,50 Z"; + let expected_svg = "M125,60 C150,50 125,10 100,10 L60,10 Q40,40 10,10 M50,200 L150,200 L100,100 Z M100,50 L75,100 Q0,150 25,300 C50,150 150,150 175,300 Q200,150 125,100 Z"; + let path = BezPath::from_svg(svg).unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!(expected_svg, reversed.to_svg()); + } + + // https://github.com/fonttools/fonttools/blob/bf265ce49e0cae6f032420a4c80c31d8e16285b8/Tests/pens/reverseContourPen_test.py#L7 + #[test] + fn test_reverse_lines() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((1.0, 1.0)); + path.line_to((2.0, 2.0)); + path.line_to((3.0, 3.0)); + path.close_path(); + let rev = path.reverse_subpaths(); + assert_eq!("M3,3 L2,2 L1,1 L0,0 Z", rev.to_svg()); + } + + #[test] + fn test_reverse_multiple_moves() { + reverse_test_helper( + vec![ + PathEl::MoveTo((2.0, 2.0).into()), + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((4.0, 4.0).into()), + ], + vec![ + PathEl::MoveTo((2.0, 2.0).into()), + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((4.0, 4.0).into()), + ], + ); + } + + // The following are direct port of fonttools' + // reverseContourPen_test.py::test_reverse_pen, adapted to rust, excluding + // test cases that don't apply because we don't implement + // outputImpliedClosingLine=False. + // https://github.com/fonttools/fonttools/blob/85c80be/Tests/pens/reverseContourPen_test.py#L6-L467 + + #[test] + fn test_reverse_closed_last_line_not_on_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((3.0, 3.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // closing line NOT implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_line_overlaps_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // closing line NOT implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_duplicate_line_following_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((2.0, 2.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // duplicate line retained + PathEl::LineTo((0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_two_lines() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // closing line NOT implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_curve_overlaps_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((4.0, 4.0).into(), (5.0, 5.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 0.0).into()), // no extra lineTo added here + PathEl::CurveTo((5.0, 5.0).into(), (4.0, 4.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_curve_not_on_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((4.0, 4.0).into(), (5.0, 5.0).into(), (6.0, 6.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((6.0, 6.0).into()), // the previously implied line + PathEl::CurveTo((5.0, 5.0).into(), (4.0, 4.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_line_curve_line() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), // this line... + PathEl::CurveTo((2.0, 2.0).into(), (3.0, 3.0).into(), (4.0, 4.0).into()), + PathEl::CurveTo((5.0, 5.0).into(), (6.0, 6.0).into(), (7.0, 7.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((7.0, 7.0).into()), + PathEl::CurveTo((6.0, 6.0).into(), (5.0, 5.0).into(), (4.0, 4.0).into()), + PathEl::CurveTo((3.0, 3.0).into(), (2.0, 2.0).into(), (1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // ... does NOT become implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_quad_overlaps_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((3.0, 3.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 0.0).into()), // no extra lineTo added here + PathEl::QuadTo((3.0, 3.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_quad_not_on_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((3.0, 3.0).into(), (4.0, 4.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((4.0, 4.0).into()), // the previously implied line + PathEl::QuadTo((3.0, 3.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_line_quad_line() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), // this line... + PathEl::QuadTo((2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::QuadTo((2.0, 2.0).into(), (1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // ... does NOT become implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_empty() { + reverse_test_helper(vec![], vec![]); + } + + #[test] + fn test_reverse_single_point() { + reverse_test_helper( + vec![PathEl::MoveTo((0.0, 0.0).into())], + vec![PathEl::MoveTo((0.0, 0.0).into())], + ); + } + + #[test] + fn test_reverse_single_point_closed() { + reverse_test_helper( + vec![PathEl::MoveTo((0.0, 0.0).into()), PathEl::ClosePath], + vec![PathEl::MoveTo((0.0, 0.0).into()), PathEl::ClosePath], + ); + } + + #[test] + fn test_reverse_single_line_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + ], + vec![ + PathEl::MoveTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_single_curve_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + ], + vec![ + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_curve_line_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::LineTo((4.0, 4.0).into()), + ], + vec![ + PathEl::MoveTo((4.0, 4.0).into()), + PathEl::LineTo((3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_line_curve_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (3.0, 3.0).into(), (4.0, 4.0).into()), + ], + vec![ + PathEl::MoveTo((4.0, 4.0).into()), + PathEl::CurveTo((3.0, 3.0).into(), (2.0, 2.0).into(), (1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_duplicate_point_after_move() { + // Test case from: https://github.com/googlei18n/cu2qu/issues/51#issue-179370514 + // Simplified to only use atomic PathEl::QuadTo (no QuadSplines). + reverse_test_helper( + vec![ + PathEl::MoveTo((848.0, 348.0).into()), + PathEl::LineTo((848.0, 348.0).into()), + PathEl::QuadTo((848.0, 526.0).into(), (449.0, 704.0).into()), + PathEl::QuadTo((848.0, 171.0).into(), (848.0, 348.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((848.0, 348.0).into()), + PathEl::QuadTo((848.0, 171.0).into(), (449.0, 704.0).into()), + PathEl::QuadTo((848.0, 526.0).into(), (848.0, 348.0).into()), + PathEl::LineTo((848.0, 348.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_duplicate_point_at_end() { + // Test case from: https://github.com/googlefonts/fontmake/issues/572 + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::ClosePath, + ], + ); + } + + fn reverse_test_helper(contour: Vec, expected: Vec) { + assert_eq!(BezPath(contour).reverse_subpaths().0, expected); + } + + #[test] + fn test_rect_segments() { + // Ensure that `from_path_segments` does not insert spurious MoveTos in + // the middle of a path. + let x0 = 25.189500810000002; + let x1 = 568.18950081; + let y0 = -105.0; + let y1 = 176.0; + let r = Rect::from_points((x0, y0), (x1, y1)); + + let path0 = r.into_path(0.0); + assert!( + path0 + .elements() + .iter() + .skip(1) + .all(|el| !matches!(el, PathEl::MoveTo(_))) + ); + + let path1 = BezPath::from_path_segments(path0.segments()); + assert!( + path1 + .elements() + .iter() + .skip(1) + .all(|el| !matches!(el, PathEl::MoveTo(_))) + ); + } + + #[test] + fn test_current_position() { + let mut path = BezPath::new(); + assert_eq!(path.current_position(), None); + path.move_to((0., 0.)); + assert_eq!(path.current_position(), Some(Point::new(0., 0.))); + path.line_to((10., 10.)); + assert_eq!(path.current_position(), Some(Point::new(10., 10.))); + path.line_to((10., 0.)); + assert_eq!(path.current_position(), Some(Point::new(10., 0.))); + path.close_path(); + assert_eq!(path.current_position(), Some(Point::new(0., 0.))); + + path.close_path(); + assert_eq!(path.current_position(), None); + + path.move_to((0., 10.)); + assert_eq!(path.current_position(), Some(Point::new(0., 10.))); + path.close_path(); + assert_eq!(path.current_position(), Some(Point::new(0., 10.))); + path.close_path(); + assert_eq!(path.current_position(), None); + } + + // Regression test for #531 + // + // When testing the winding number of a point whose y coordinate is very + // close (or equal to) the y coordinate of a segment's start or end, we need + // to be consistent about how we treat it. In particular, in #531 we noticed + // that the point was within the y range of a monotonic segment, but because + // of rounding errors the cubic solver disagreed. + #[test] + fn winding_endpoints() { + let bez = BezPath::from_vec(vec![ + PathEl::MoveTo((200.0, 410.0).into()), + PathEl::CurveTo( + (139.0, 410.0).into(), + (90.0, 360.8772277832031).into(), + (90.0, 300.0).into(), + ), + PathEl::CurveTo( + (90.0, 239.0).into(), + (139.0, 190.0).into(), + (200.0, 190.0).into(), + ), + PathEl::CurveTo( + (150.0, 210.0).into(), + (110.0, 250.0).into(), + (110.0, 300.0).into(), + ), + PathEl::CurveTo( + (110.0, 349.0).into(), + (150.0, 390.0).into(), + (200.0, 390.0).into(), + ), + PathEl::ClosePath, + ]); + + assert!(bez.contains((100.0, 300.1).into())); + assert!(bez.contains((100.0, 299.9).into())); + assert!(bez.contains((100.0, 300.0).into())); + } + + #[test] + fn check_close_subpaths() { + let mut bez = BezPath::new(); + bez.move_to((10.0, 10.0)); + bez.line_to((100.0, 20.0)); + bez.line_to((60.0, 100.0)); + let elements = close_subpaths(&bez).collect::>(); + bez.close_path(); + assert_eq!(&elements, bez.elements()); + + // Test implicit closepath in middle of path + let mut bez2 = BezPath::new(); + bez2.move_to((10.0, 10.0)); + bez2.line_to((100.0, 20.0)); + bez2.line_to((60.0, 100.0)); + bez2.move_to((110.0, 10.0)); + bez2.line_to((200.0, 20.0)); + bez2.line_to((160.0, 100.0)); + let elements2 = close_subpaths(&bez2).collect::>(); + let mut bez3 = BezPath::new(); + bez3.move_to((10.0, 10.0)); + bez3.line_to((100.0, 20.0)); + bez3.line_to((60.0, 100.0)); + bez3.close_path(); + bez3.move_to((110.0, 10.0)); + bez3.line_to((200.0, 20.0)); + bez3.line_to((160.0, 100.0)); + bez3.close_path(); + assert_eq!(&elements2, bez3.elements()); + } + + #[test] + fn close_subpaths_does_not_duplicate_existing_closepath() { + let path = BezPath::from_vec(vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((10.0, 0.0).into()), + PathEl::LineTo((10.0, 10.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((20.0, 0.0).into()), + PathEl::LineTo((30.0, 0.0).into()), + ]); + + let closed = close_subpaths(path.iter()).collect::>(); + + assert_eq!( + closed, + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((10.0, 0.0).into()), + PathEl::LineTo((10.0, 10.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((20.0, 0.0).into()), + PathEl::LineTo((30.0, 0.0).into()), + PathEl::ClosePath, + ] + ); + } +} diff --git a/vendor/kurbo/src/circle.rs b/vendor/kurbo/src/circle.rs new file mode 100644 index 0000000000..046d22b54c --- /dev/null +++ b/vendor/kurbo/src/circle.rs @@ -0,0 +1,428 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Implementation of circle shape. + +use core::{ + f64::consts::{FRAC_PI_2, PI}, + iter, + ops::{Add, Mul, Sub}, +}; + +use crate::{Affine, Arc, ArcAppendIter, Ellipse, PathEl, Point, Rect, Shape, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A circle. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Circle { + /// The center. + pub center: Point, + /// The radius. + pub radius: f64, +} + +impl Circle { + /// A new circle from center and radius. + #[inline(always)] + pub fn new(center: impl Into, radius: f64) -> Circle { + Circle { + center: center.into(), + radius, + } + } + + /// Create a [`CircleSegment`] by cutting out parts of this circle. + #[inline(always)] + pub fn segment(self, inner_radius: f64, start_angle: f64, sweep_angle: f64) -> CircleSegment { + CircleSegment { + center: self.center, + outer_radius: self.radius, + inner_radius, + start_angle, + sweep_angle, + } + } + + /// Is this circle [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub fn is_finite(&self) -> bool { + self.center.is_finite() && self.radius.is_finite() + } + + /// Is this circle [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub fn is_nan(&self) -> bool { + self.center.is_nan() || self.radius.is_nan() + } +} + +impl Add for Circle { + type Output = Circle; + + #[inline] + fn add(self, v: Vec2) -> Circle { + Circle { + center: self.center + v, + radius: self.radius, + } + } +} + +impl Sub for Circle { + type Output = Circle; + + #[inline] + fn sub(self, v: Vec2) -> Circle { + Circle { + center: self.center - v, + radius: self.radius, + } + } +} + +impl Mul for Affine { + type Output = Ellipse; + fn mul(self, other: Circle) -> Self::Output { + self * Ellipse::from(other) + } +} + +#[doc(hidden)] +pub struct CirclePathIter { + circle: Circle, + delta_th: f64, + arm_len: f64, + ix: usize, + n: usize, +} + +impl Shape for Circle { + type PathElementsIter<'iter> = CirclePathIter; + + fn path_elements(&self, tolerance: f64) -> CirclePathIter { + let scaled_err = self.radius.abs() / tolerance; + let (n, arm_len) = if scaled_err < 1.0 / 1.9608e-4 { + // Solution from http://spencermortensen.com/articles/bezier-circle/ + (4, 0.551915024494) + } else { + // This is empirically determined to fall within error tolerance. + let n = (1.1163 * scaled_err).powf(1.0 / 6.0).ceil() as usize; + // Note: this isn't minimum error, but it is simple and we can easily + // estimate the error. + let arm_len = (4.0 / 3.0) * (FRAC_PI_2 / (n as f64)).tan(); + (n, arm_len) + }; + CirclePathIter { + circle: *self, + delta_th: 2.0 * PI / (n as f64), + arm_len, + ix: 0, + n, + } + } + + #[inline] + fn area(&self) -> f64 { + PI * self.radius.powi(2) + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + (2.0 * PI * self.radius).abs() + } + + fn winding(&self, pt: Point) -> i32 { + if (pt - self.center).hypot2() < self.radius.powi(2) { + 1 + } else { + 0 + } + } + + #[inline] + fn bounding_box(&self) -> Rect { + let r = self.radius.abs(); + let (x, y) = self.center.into(); + Rect::new(x - r, y - r, x + r, y + r) + } + + #[inline(always)] + fn as_circle(&self) -> Option { + Some(*self) + } +} + +impl Iterator for CirclePathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + let a = self.arm_len; + let r = self.circle.radius; + let (x, y) = self.circle.center.into(); + let ix = self.ix; + self.ix += 1; + if ix == 0 { + Some(PathEl::MoveTo(Point::new(x + r, y))) + } else if ix <= self.n { + let th1 = self.delta_th * (ix as f64); + let th0 = th1 - self.delta_th; + let (s0, c0) = th0.sin_cos(); + let (s1, c1) = if ix == self.n { + (0.0, 1.0) + } else { + th1.sin_cos() + }; + Some(PathEl::CurveTo( + Point::new(x + r * (c0 - a * s0), y + r * (s0 + a * c0)), + Point::new(x + r * (c1 + a * s1), y + r * (s1 - a * c1)), + Point::new(x + r * c1, y + r * s1), + )) + } else if ix == self.n + 1 { + Some(PathEl::ClosePath) + } else { + None + } + } +} + +/// A segment of a circle. +/// +/// If `inner_radius > 0`, then the shape will be a doughnut segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct CircleSegment { + /// The center. + pub center: Point, + /// The outer radius. + pub outer_radius: f64, + /// The inner radius. + pub inner_radius: f64, + /// The angle to start drawing the segment (in radians). + pub start_angle: f64, + /// The arc length of the segment (in radians). + pub sweep_angle: f64, +} + +impl CircleSegment { + /// Create a `CircleSegment` out of its constituent parts. + #[inline(always)] + pub fn new( + center: impl Into, + outer_radius: f64, + inner_radius: f64, + start_angle: f64, + sweep_angle: f64, + ) -> Self { + CircleSegment { + center: center.into(), + outer_radius, + inner_radius, + start_angle, + sweep_angle, + } + } + + /// Return an arc representing the outer radius. + #[must_use] + #[inline(always)] + pub fn outer_arc(&self) -> Arc { + Arc { + center: self.center, + radii: Vec2::new(self.outer_radius, self.outer_radius), + start_angle: self.start_angle, + sweep_angle: self.sweep_angle, + x_rotation: 0.0, + } + } + + /// Return an arc representing the inner radius. + /// + /// This is [reversed] from the outer arc, so that it is in the + /// same direction as the arc that would be drawn (as the path + /// elements for this circle segment produce a closed path). + /// + /// [reversed]: Arc::reversed + #[must_use] + #[inline] + pub fn inner_arc(&self) -> Arc { + Arc { + center: self.center, + radii: Vec2::new(self.inner_radius, self.inner_radius), + start_angle: self.start_angle + self.sweep_angle, + sweep_angle: -self.sweep_angle, + x_rotation: 0.0, + } + } + + /// Is this circle segment [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.center.is_finite() + && self.outer_radius.is_finite() + && self.inner_radius.is_finite() + && self.start_angle.is_finite() + && self.sweep_angle.is_finite() + } + + /// Is this circle segment [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.center.is_nan() + || self.outer_radius.is_nan() + || self.inner_radius.is_nan() + || self.start_angle.is_nan() + || self.sweep_angle.is_nan() + } +} + +impl Add for CircleSegment { + type Output = CircleSegment; + + #[inline] + fn add(self, v: Vec2) -> Self { + Self { + center: self.center + v, + ..self + } + } +} + +impl Sub for CircleSegment { + type Output = CircleSegment; + + #[inline] + fn sub(self, v: Vec2) -> Self { + Self { + center: self.center - v, + ..self + } + } +} + +type CircleSegmentPathIter = iter::Chain< + iter::Chain< + iter::Chain, iter::Once>, ArcAppendIter>, + iter::Once, + >, + ArcAppendIter, +>; + +impl Shape for CircleSegment { + type PathElementsIter<'iter> = CircleSegmentPathIter; + + fn path_elements(&self, tolerance: f64) -> CircleSegmentPathIter { + iter::once(PathEl::MoveTo(point_on_circle( + self.center, + self.inner_radius, + self.start_angle, + ))) + // First radius + .chain(iter::once(PathEl::LineTo(point_on_circle( + self.center, + self.outer_radius, + self.start_angle, + )))) + // outer arc + .chain(self.outer_arc().append_iter(tolerance)) + // second radius + .chain(iter::once(PathEl::LineTo(point_on_circle( + self.center, + self.inner_radius, + self.start_angle + self.sweep_angle, + )))) + // inner arc + .chain(self.inner_arc().append_iter(tolerance)) + } + + #[inline] + fn area(&self) -> f64 { + 0.5 * (self.outer_radius.powi(2) - self.inner_radius.powi(2)).abs() * self.sweep_angle + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + 2.0 * (self.outer_radius - self.inner_radius).abs() + + self.sweep_angle * (self.inner_radius + self.outer_radius) + } + + fn winding(&self, pt: Point) -> i32 { + let angle = (pt - self.center).atan2(); + if angle < self.start_angle || angle > self.start_angle + self.sweep_angle { + return 0; + } + let dist2 = (pt - self.center).hypot2(); + if (dist2 < self.outer_radius.powi(2) && dist2 > self.inner_radius.powi(2)) || + // case where outer_radius < inner_radius + (dist2 < self.inner_radius.powi(2) && dist2 > self.outer_radius.powi(2)) + { + 1 + } else { + 0 + } + } + + #[inline] + fn bounding_box(&self) -> Rect { + // todo this is currently not tight + let r = self.inner_radius.max(self.outer_radius); + let (x, y) = self.center.into(); + Rect::new(x - r, y - r, x + r, y + r) + } +} + +#[inline] +fn point_on_circle(center: Point, radius: f64, angle: f64) -> Point { + let (angle_sin, angle_cos) = angle.sin_cos(); + center + + Vec2 { + x: angle_cos * radius, + y: angle_sin * radius, + } +} + +#[cfg(test)] +mod tests { + use crate::{Circle, Point, Shape}; + use std::f64::consts::PI; + + fn assert_approx_eq(x: f64, y: f64) { + // Note: we might want to be more rigorous in testing the accuracy + // of the conversion into Béziers. But this seems good enough. + assert!((x - y).abs() < 1e-7, "{x} != {y}"); + } + + #[test] + fn area_sign() { + let center = Point::new(5.0, 5.0); + let c = Circle::new(center, 5.0); + assert_approx_eq(c.area(), 25.0 * PI); + + assert_eq!(c.winding(center), 1); + + let p = c.to_path(1e-9); + assert_approx_eq(c.area(), p.area()); + assert_eq!(c.winding(center), p.winding(center)); + + let c_neg_radius = Circle::new(center, -5.0); + assert_approx_eq(c_neg_radius.area(), 25.0 * PI); + + assert_eq!(c_neg_radius.winding(center), 1); + + let p_neg_radius = c_neg_radius.to_path(1e-9); + assert_approx_eq(c_neg_radius.area(), p_neg_radius.area()); + assert_eq!(c_neg_radius.winding(center), p_neg_radius.winding(center)); + } +} diff --git a/vendor/kurbo/src/common.rs b/vendor/kurbo/src/common.rs new file mode 100644 index 0000000000..9df3fc7914 --- /dev/null +++ b/vendor/kurbo/src/common.rs @@ -0,0 +1,1121 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Common mathematical operations + +#![allow(missing_docs)] + +#[cfg(not(feature = "std"))] +mod sealed { + /// A [sealed trait](https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/) + /// which stops [`super::FloatFuncs`] from being implemented outside kurbo. This could + /// be relaxed in the future if there is are good reasons to allow external impls. + /// The benefit from being sealed is that we can add methods without breaking downstream + /// implementations. + pub trait FloatFuncsSealed {} +} + +use arrayvec::ArrayVec; + +/// Defines a trait that chooses between libstd or libm implementations of float methods. +/// +/// Some methods will eventually became available in core by +/// [`core_float_math`](https://github.com/rust-lang/rust/issues/137578) +macro_rules! define_float_funcs { + ($( + fn $name:ident(self $(,$arg:ident: $arg_ty:ty)*) -> $ret:ty + => $lname:ident/$lfname:ident; + )+) => { + + /// Since core doesn't depend upon libm, this provides libm implementations + /// of float functions which are typically provided by the std library, when + /// the `std` feature is not enabled. + /// + /// For documentation see the respective functions in the std library. + #[cfg(not(feature = "std"))] + pub trait FloatFuncs : Sized + sealed::FloatFuncsSealed { + /// For documentation see + /// + /// Special implementation, because libm doesn't have it. + fn signum(self) -> Self; + + /// For documentation see + /// + /// Special implementation, because libm doesn't have it. + fn rem_euclid(self, rhs: Self) -> Self; + + $(fn $name(self $(,$arg: $arg_ty)*) -> $ret;)+ + } + + #[cfg(not(feature = "std"))] + impl sealed::FloatFuncsSealed for f32 {} + + #[cfg(not(feature = "std"))] + impl FloatFuncs for f32 { + #[inline] + fn signum(self) -> f32 { + if self.is_nan() { + f32::NAN + } else { + 1.0_f32.copysign(self) + } + } + + #[inline] + fn rem_euclid(self, rhs: Self) -> Self { + let r = self % rhs; + if r < 0.0 { + r + rhs.abs() + } else { + r + } + } + + $(fn $name(self $(,$arg: $arg_ty)*) -> $ret { + #[cfg(feature = "libm")] + return libm::$lfname(self $(,$arg as _)*); + + #[cfg(not(feature = "libm"))] + compile_error!("kurbo requires either the `std` or `libm` feature") + })+ + } + + #[cfg(not(feature = "std"))] + impl sealed::FloatFuncsSealed for f64 {} + #[cfg(not(feature = "std"))] + impl FloatFuncs for f64 { + #[inline] + fn signum(self) -> f64 { + if self.is_nan() { + f64::NAN + } else { + 1.0_f64.copysign(self) + } + } + + #[inline] + fn rem_euclid(self, rhs: Self) -> Self { + let r = self % rhs; + if r < 0.0 { + r + rhs.abs() + } else { + r + } + } + + $(fn $name(self $(,$arg: $arg_ty)*) -> $ret { + #[cfg(feature = "libm")] + return libm::$lname(self $(,$arg as _)*); + + #[cfg(not(feature = "libm"))] + compile_error!("kurbo requires either the `std` or `libm` feature") + })+ + } + } +} + +define_float_funcs! { + fn abs(self) -> Self => fabs/fabsf; + fn acos(self) -> Self => acos/acosf; + fn atan2(self, other: Self) -> Self => atan2/atan2f; + fn cbrt(self) -> Self => cbrt/cbrtf; + fn ceil(self) -> Self => ceil/ceilf; + fn cos(self) -> Self => cos/cosf; + fn copysign(self, sign: Self) -> Self => copysign/copysignf; + fn floor(self) -> Self => floor/floorf; + fn hypot(self, other: Self) -> Self => hypot/hypotf; + fn ln(self) -> Self => log/logf; + fn log2(self) -> Self => log2/log2f; + fn mul_add(self, a: Self, b: Self) -> Self => fma/fmaf; + fn powi(self, n: i32) -> Self => pow/powf; + fn powf(self, n: Self) -> Self => pow/powf; + fn round(self) -> Self => round/roundf; + fn sin(self) -> Self => sin/sinf; + fn sin_cos(self) -> (Self, Self) => sincos/sincosf; + fn sqrt(self) -> Self => sqrt/sqrtf; + fn tan(self) -> Self => tan/tanf; + fn trunc(self) -> Self => trunc/truncf; +} + +/// Adds convenience methods to `f32` and `f64`. +pub trait FloatExt { + /// Rounds to the nearest integer away from zero, + /// unless the provided value is already an integer. + /// + /// It is to `ceil` what `trunc` is to `floor`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::common::FloatExt; + /// + /// let f = 3.7_f64; + /// let g = 3.0_f64; + /// let h = -3.7_f64; + /// let i = -5.1_f32; + /// + /// assert_eq!(f.expand(), 4.0); + /// assert_eq!(g.expand(), 3.0); + /// assert_eq!(h.expand(), -4.0); + /// assert_eq!(i.expand(), -6.0); + /// ``` + fn expand(&self) -> T; +} + +impl FloatExt for f64 { + #[inline] + fn expand(&self) -> f64 { + self.abs().ceil().copysign(*self) + } +} + +impl FloatExt for f32 { + #[inline] + fn expand(&self) -> f32 { + self.abs().ceil().copysign(*self) + } +} + +/// Find real roots of cubic equation. +/// +/// The implementation is not (yet) fully robust, but it does handle the case +/// where `c3` is zero (in that case, solving the quadratic equation). +/// +/// See: +/// +/// That implementation is in turn based on Jim Blinn's "How to Solve a Cubic +/// Equation", which is masterful. +/// +/// Return values of x for which c0 + c1 x + c2 x² + c3 x³ = 0. +pub fn solve_cubic(c0: f64, c1: f64, c2: f64, c3: f64) -> ArrayVec { + let mut result = ArrayVec::new(); + let c3_recip = c3.recip(); + const ONETHIRD: f64 = 1. / 3.; + let scaled_c2 = c2 * (ONETHIRD * c3_recip); + let scaled_c1 = c1 * (ONETHIRD * c3_recip); + let scaled_c0 = c0 * c3_recip; + if !(scaled_c0.is_finite() && scaled_c1.is_finite() && scaled_c2.is_finite()) { + // cubic coefficient is zero or nearly so. + return solve_quadratic(c0, c1, c2).iter().copied().collect(); + } + let (c0, c1, c2) = (scaled_c0, scaled_c1, scaled_c2); + // (d0, d1, d2) is called "Delta" in article + let d0 = (-c2).mul_add(c2, c1); + let d1 = (-c1).mul_add(c2, c0); + let d2 = c2 * c0 - c1 * c1; + // d is called "Discriminant" + let d = 4.0 * d0 * d2 - d1 * d1; + // de is called "Depressed.x", Depressed.y = d0 + let de = (-2.0 * c2).mul_add(d0, d1); + // TODO: handle the cases where these intermediate results overflow. + if d < 0.0 { + let sq = (-0.25 * d).sqrt(); + let r = -0.5 * de; + let t1 = (r + sq).cbrt() + (r - sq).cbrt(); + result.push(t1 - c2); + } else if d == 0.0 { + let t1 = (-d0).sqrt().copysign(de); + result.push(t1 - c2); + result.push(-2.0 * t1 - c2); + } else { + let th = d.sqrt().atan2(-de) * ONETHIRD; + // (th_cos, th_sin) is called "CubicRoot" + let (th_sin, th_cos) = th.sin_cos(); + // (r0, r1, r2) is called "Root" + let r0 = th_cos; + let ss3 = th_sin * 3.0f64.sqrt(); + let r1 = 0.5 * (-th_cos + ss3); + let r2 = 0.5 * (-th_cos - ss3); + let t = 2.0 * (-d0).sqrt(); + result.push(t.mul_add(r0, -c2)); + result.push(t.mul_add(r1, -c2)); + result.push(t.mul_add(r2, -c2)); + } + result +} + +/// Find real roots of quadratic equation. +/// +/// Return values of x for which c0 + c1 x + c2 x² = 0. +/// +/// This function tries to be quite numerically robust. If the equation +/// is nearly linear, it will return the root ignoring the quadratic term; +/// the other root might be out of representable range. In the degenerate +/// case where all coefficients are zero, so that all values of x satisfy +/// the equation, a single `0.0` is returned. +pub fn solve_quadratic(c0: f64, c1: f64, c2: f64) -> ArrayVec { + let mut result = ArrayVec::new(); + let sc0 = c0 * c2.recip(); + let sc1 = c1 * c2.recip(); + if !sc0.is_finite() || !sc1.is_finite() { + // c2 is zero or very small, treat as linear eqn + let root = -c0 / c1; + if root.is_finite() { + result.push(root); + } else if c0 == 0.0 && c1 == 0.0 { + // Degenerate case + result.push(0.0); + } + return result; + } + let arg = sc1 * sc1 - 4. * sc0; + let root1 = if !arg.is_finite() { + // Likely, calculation of sc1 * sc1 overflowed. Find one root + // using sc1 x + x² = 0, other root as sc0 / root1. + -sc1 + } else { + if arg < 0.0 { + return result; + } else if arg == 0.0 { + result.push(-0.5 * sc1); + return result; + } + // See https://math.stackexchange.com/questions/866331 + -0.5 * (sc1 + arg.sqrt().copysign(sc1)) + }; + let root2 = sc0 / root1; + if root2.is_finite() { + // Sort just to be friendly and make results deterministic. + if root2 > root1 { + result.push(root1); + result.push(root2); + } else { + result.push(root2); + result.push(root1); + } + } else { + result.push(root1); + } + result +} + +/// Compute epsilon relative to coefficient. +/// +/// A helper function from the Orellana and De Michele paper. +fn eps_rel(raw: f64, a: f64) -> f64 { + if a == 0.0 { + raw.abs() + } else { + ((raw - a) / a).abs() + } +} + +/// Find real roots of a quartic equation. +/// +/// This is a fairly literal implementation of the method described in: +/// Algorithm 1010: Boosting Efficiency in Solving Quartic Equations with +/// No Compromise in Accuracy, Orellana and De Michele, ACM +/// Transactions on Mathematical Software, Vol. 46, No. 2, May 2020. +pub fn solve_quartic(c0: f64, c1: f64, c2: f64, c3: f64, c4: f64) -> ArrayVec { + if c4 == 0.0 { + return solve_cubic(c0, c1, c2, c3).iter().copied().collect(); + } + if c0 == 0.0 { + // Note: appends 0 root at end, doesn't sort. We might want to do that. + return solve_cubic(c1, c2, c3, c4) + .iter() + .copied() + .chain(Some(0.0)) + .collect(); + } + let a = c3 / c4; + let b = c2 / c4; + let c = c1 / c4; + let d = c0 / c4; + if let Some(result) = solve_quartic_inner(a, b, c, d, false) { + return result; + } + // Do polynomial rescaling + const K_Q: f64 = 7.16e76; + for rescale in [false, true] { + if let Some(result) = solve_quartic_inner( + a / K_Q, + b / K_Q.powi(2), + c / K_Q.powi(3), + d / K_Q.powi(4), + rescale, + ) { + return result.iter().map(|x| x * K_Q).collect(); + } + } + // Overflow happened, just return no roots. + //println!("overflow, no roots returned"); + ArrayVec::default() +} + +fn solve_quartic_inner(a: f64, b: f64, c: f64, d: f64, rescale: bool) -> Option> { + factor_quartic_inner(a, b, c, d, rescale).map(|quadratics| { + quadratics + .iter() + .flat_map(|(a, b)| solve_quadratic(*b, *a, 1.0)) + .collect() + }) +} + +/// Factor a quartic into two quadratics. +/// +/// Attempt to factor a quartic equation into two quadratic equations. Returns `None` either if there +/// is overflow (in which case rescaling might succeed) or the factorization would result in +/// complex coefficients. +/// +/// Discussion question: distinguish the two cases in return value? +pub fn factor_quartic_inner( + a: f64, + b: f64, + c: f64, + d: f64, + rescale: bool, +) -> Option> { + let calc_eps_q = |a1, b1, a2, b2| { + let eps_a = eps_rel(a1 + a2, a); + let eps_b = eps_rel(b1 + a1 * a2 + b2, b); + let eps_c = eps_rel(b1 * a2 + a1 * b2, c); + eps_a + eps_b + eps_c + }; + let calc_eps_t = |a1, b1, a2, b2| calc_eps_q(a1, b1, a2, b2) + eps_rel(b1 * b2, d); + let disc = 9. * a * a - 24. * b; + let s = if disc >= 0.0 { + -2. * b / (3. * a + disc.sqrt().copysign(a)) + } else { + -0.25 * a + }; + let a_prime = a + 4. * s; + let b_prime = b + 3. * s * (a + 2. * s); + let c_prime = c + s * (2. * b + s * (3. * a + 4. * s)); + let d_prime = d + s * (c + s * (b + s * (a + s))); + let g_prime; + let h_prime; + const K_C: f64 = 3.49e102; + if rescale { + let a_prime_s = a_prime / K_C; + let b_prime_s = b_prime / K_C; + let c_prime_s = c_prime / K_C; + let d_prime_s = d_prime / K_C; + g_prime = a_prime_s * c_prime_s - (4. / K_C) * d_prime_s - (1. / 3.) * b_prime_s.powi(2); + h_prime = (a_prime_s * c_prime_s + (8. / K_C) * d_prime_s - (2. / 9.) * b_prime_s.powi(2)) + * (1. / 3.) + * b_prime_s + - c_prime_s * (c_prime_s / K_C) + - a_prime_s.powi(2) * d_prime_s; + } else { + g_prime = a_prime * c_prime - 4. * d_prime - (1. / 3.) * b_prime.powi(2); + h_prime = + (a_prime * c_prime + 8. * d_prime - (2. / 9.) * b_prime.powi(2)) * (1. / 3.) * b_prime + - c_prime.powi(2) + - a_prime.powi(2) * d_prime; + } + if !(g_prime.is_finite() && h_prime.is_finite()) { + return None; + } + let phi = depressed_cubic_dominant(g_prime, h_prime); + let phi = if rescale { phi * K_C } else { phi }; + let l_1 = a * 0.5; + let l_3 = (1. / 6.) * b + 0.5 * phi; + let delt_2 = c - a * l_3; + let d_2_cand_1 = (2. / 3.) * b - phi - l_1 * l_1; + let l_2_cand_1 = 0.5 * delt_2 / d_2_cand_1; + let l_2_cand_2 = 2. * (d - l_3 * l_3) / delt_2; + let d_2_cand_2 = 0.5 * delt_2 / l_2_cand_2; + let d_2_cand_3 = d_2_cand_1; + let l_2_cand_3 = l_2_cand_2; + let mut d_2_best = 0.0; + let mut l_2_best = 0.0; + let mut eps_l_best = 0.0; + for (i, (d_2, l_2)) in [ + (d_2_cand_1, l_2_cand_1), + (d_2_cand_2, l_2_cand_2), + (d_2_cand_3, l_2_cand_3), + ] + .iter() + .enumerate() + { + let eps_0 = eps_rel(d_2 + l_1 * l_1 + 2. * l_3, b); + let eps_1 = eps_rel(2. * (d_2 * l_2 + l_1 * l_3), c); + let eps_2 = eps_rel(d_2 * l_2 * l_2 + l_3 * l_3, d); + let eps_l = eps_0 + eps_1 + eps_2; + if i == 0 || eps_l < eps_l_best { + d_2_best = *d_2; + l_2_best = *l_2; + eps_l_best = eps_l; + } + } + let d_2 = d_2_best; + let l_2 = l_2_best; + let mut alpha_1; + let mut beta_1; + let mut alpha_2; + let mut beta_2; + //println!("phi = {}, d_2 = {}", phi, d_2); + if d_2 < 0.0 { + let sq = (-d_2).sqrt(); + alpha_1 = l_1 + sq; + beta_1 = l_3 + sq * l_2; + alpha_2 = l_1 - sq; + beta_2 = l_3 - sq * l_2; + if beta_2.abs() < beta_1.abs() { + beta_2 = d / beta_1; + } else if beta_2.abs() > beta_1.abs() { + beta_1 = d / beta_2; + } + let cands; + if alpha_1.abs() != alpha_2.abs() { + if alpha_1.abs() < alpha_2.abs() { + let a1_cand_1 = (c - beta_1 * alpha_2) / beta_2; + let a1_cand_2 = (b - beta_2 - beta_1) / alpha_2; + let a1_cand_3 = a - alpha_2; + // Note: cand 3 is first because it is infallible, simplifying logic + cands = [ + (a1_cand_3, alpha_2), + (a1_cand_1, alpha_2), + (a1_cand_2, alpha_2), + ]; + } else { + let a2_cand_1 = (c - alpha_1 * beta_2) / beta_1; + let a2_cand_2 = (b - beta_2 - beta_1) / alpha_1; + let a2_cand_3 = a - alpha_1; + cands = [ + (alpha_1, a2_cand_3), + (alpha_1, a2_cand_1), + (alpha_1, a2_cand_2), + ]; + } + let mut eps_q_best = 0.0; + for (i, (a1, a2)) in cands.iter().enumerate() { + if a1.is_finite() && a2.is_finite() { + let eps_q = calc_eps_q(*a1, beta_1, *a2, beta_2); + if i == 0 || eps_q < eps_q_best { + alpha_1 = *a1; + alpha_2 = *a2; + eps_q_best = eps_q; + } + } + } + } + } else if d_2 == 0.0 { + let d_3 = d - l_3 * l_3; + alpha_1 = l_1; + beta_1 = l_3 + (-d_3).sqrt(); + alpha_2 = l_1; + beta_2 = l_3 - (-d_3).sqrt(); + if beta_1.abs() > beta_2.abs() { + beta_2 = d / beta_1; + } else if beta_2.abs() > beta_1.abs() { + beta_1 = d / beta_2; + } + // TODO: handle case d_2 is very small? + } else { + // This case means no real roots; in the most general case we might want + // to factor into quadratic equations with complex coefficients. + return None; + } + // Newton-Raphson iteration on alpha/beta coeff's. + let mut eps_t = calc_eps_t(alpha_1, beta_1, alpha_2, beta_2); + for _ in 0..8 { + //println!("a1 {} b1 {} a2 {} b2 {}", alpha_1, beta_1, alpha_2, beta_2); + //println!("eps_t = {:e}", eps_t); + if eps_t == 0.0 { + break; + } + let f_0 = beta_1 * beta_2 - d; + let f_1 = beta_1 * alpha_2 + alpha_1 * beta_2 - c; + let f_2 = beta_1 + alpha_1 * alpha_2 + beta_2 - b; + let f_3 = alpha_1 + alpha_2 - a; + let c_1 = alpha_1 - alpha_2; + let det_j = beta_1 * beta_1 - beta_1 * (alpha_2 * c_1 + 2. * beta_2) + + beta_2 * (alpha_1 * c_1 + beta_2); + if det_j == 0.0 { + break; + } + let inv = det_j.recip(); + let c_2 = beta_2 - beta_1; + let c_3 = beta_1 * alpha_2 - alpha_1 * beta_2; + let dz_0 = c_1 * f_0 + c_2 * f_1 + c_3 * f_2 - (beta_1 * c_2 + alpha_1 * c_3) * f_3; + let dz_1 = (alpha_1 * c_1 + c_2) * f_0 + - beta_1 * c_1 * f_1 + - beta_1 * c_2 * f_2 + - beta_1 * c_3 * f_3; + let dz_2 = -c_1 * f_0 - c_2 * f_1 - c_3 * f_2 + (alpha_2 * c_3 + beta_2 * c_2) * f_3; + let dz_3 = -(alpha_2 * c_1 + c_2) * f_0 + + beta_2 * c_1 * f_1 + + beta_2 * c_2 * f_2 + + beta_2 * c_3 * f_3; + let a1 = alpha_1 - inv * dz_0; + let b1 = beta_1 - inv * dz_1; + let a2 = alpha_2 - inv * dz_2; + let b2 = beta_2 - inv * dz_3; + let new_eps_t = calc_eps_t(a1, b1, a2, b2); + // We break if the new eps is equal, paper keeps going + if new_eps_t < eps_t { + alpha_1 = a1; + beta_1 = b1; + alpha_2 = a2; + beta_2 = b2; + eps_t = new_eps_t; + } else { + //println!("new_eps_t got worse: {:e}", new_eps_t); + break; + } + } + Some([(alpha_1, beta_1), (alpha_2, beta_2)].into()) +} + +/// Dominant root of depressed cubic x^3 + gx + h = 0. +/// +/// Section 2.2 of Orellana and De Michele. +// Note: some of the techniques in here might be useful to improve the +// cubic solver, and vice versa. +fn depressed_cubic_dominant(g: f64, h: f64) -> f64 { + let q = (-1. / 3.) * g; + let r = 0.5 * h; + let phi_0; + let k = if q.abs() < 1e102 && r.abs() < 1e154 { + None + } else if q.abs() < r.abs() { + Some(1. - q * (q / r).powi(2)) + } else { + Some(q.signum() * ((r / q).powi(2) / q - 1.0)) + }; + if k.is_some() && r == 0.0 { + if g > 0.0 { + phi_0 = 0.0; + } else { + phi_0 = (-g).sqrt(); + } + } else if k.map(|k| k < 0.0).unwrap_or_else(|| r * r < q.powi(3)) { + let t = if k.is_some() { + r / q / q.sqrt() + } else { + r / q.powi(3).sqrt() + }; + phi_0 = -2. * q.sqrt() * (t.abs().acos() * (1. / 3.)).cos().copysign(t); + } else { + let a = if let Some(k) = k { + if q.abs() < r.abs() { + -r * (1. + k.sqrt()) + } else { + -r - (q.abs().sqrt() * q * k.sqrt()).copysign(r) + } + } else { + -r - (r * r - q.powi(3)).sqrt().copysign(r) + } + .cbrt(); + let b = if a == 0.0 { 0.0 } else { q / a }; + phi_0 = a + b; + } + // Refine with Newton-Raphson iteration + let mut x = phi_0; + let mut f = (x * x + g) * x + h; + //println!("g = {:e}, h = {:e}, x = {:e}, f = {:e}", g, h, x, f); + const EPS_M: f64 = 2.22045e-16; + if f.abs() < EPS_M * x.powi(3).max(g * x).max(h) { + return x; + } + for _ in 0..8 { + let delt_f = 3. * x * x + g; + if delt_f == 0.0 { + break; + } + let new_x = x - f / delt_f; + let new_f = (new_x * new_x + g) * new_x + h; + //println!("delt_f = {:e}, new_f = {:e}", delt_f, new_f); + if new_f == 0.0 { + return new_x; + } + if new_f.abs() >= f.abs() { + break; + } + x = new_x; + f = new_f; + } + x +} + +/// Solve an arbitrary function for a zero-crossing. +/// +/// This uses the [ITP method], as described in the paper +/// [An Enhancement of the Bisection Method Average Performance Preserving Minmax Optimality]. +/// +/// The values of `ya` and `yb` are given as arguments rather than +/// computed from `f`, as the values may already be known, or they may +/// be less expensive to compute as special cases. +/// +/// It is assumed that `ya < 0.0` and `yb > 0.0`, otherwise unexpected +/// results may occur. +/// +/// The value of `epsilon` must be larger than 2^-63 times `b - a`, +/// otherwise integer overflow may occur. The `a` and `b` parameters +/// represent the lower and upper bounds of the bracket searched for a +/// solution. +/// +/// The ITP method has tuning parameters. This implementation hardwires +/// k2 to 2, both because it avoids an expensive floating point +/// exponentiation, and because this value has been tested to work well +/// with curve fitting problems. +/// +/// The `n0` parameter controls the relative impact of the bisection and +/// secant components. When it is 0, the number of iterations is +/// guaranteed to be no more than the number required by bisection (thus, +/// this method is strictly superior to bisection). However, when the +/// function is smooth, a value of 1 gives the secant method more of a +/// chance to engage, so the average number of iterations is likely +/// lower, though there can be one more iteration than bisection in the +/// worst case. +/// +/// The `k1` parameter is harder to characterize, and interested users +/// are referred to the paper, as well as encouraged to do empirical +/// testing. To match the paper, a value of `0.2 / (b - a)` is +/// suggested, and this is confirmed to give good results. +/// +/// When the function is monotonic, the returned result is guaranteed to +/// be within `epsilon` of the zero crossing. For more detailed analysis, +/// again see the paper. +/// +/// [ITP method]: https://en.wikipedia.org/wiki/ITP_Method +/// [An Enhancement of the Bisection Method Average Performance Preserving Minmax Optimality]: https://dl.acm.org/doi/10.1145/3423597 +#[allow(clippy::too_many_arguments)] +pub fn solve_itp( + mut f: impl FnMut(f64) -> f64, + a: f64, + b: f64, + epsilon: f64, + n0: usize, + k1: f64, + ya: f64, + yb: f64, +) -> f64 { + use core::convert::Infallible; + let (a, b) = solve_itp_fallible(|x| Ok::<_, Infallible>(f(x)), a, b, epsilon, n0, k1, ya, yb) + .expect("Infallible `f` never returns `Err`"); + + // Return the midpoint of the bracket returned by `solve_itp_fallible`. If that found an exact + // zero, it returns `(a, a)`, and the following will result in exactly `a` (except for harmless + // negative zero subtlety or when `a + b` overflows ~1e308). + 0.5 * (a + b) +} + +/// A variant ITP solver that allows fallible functions. +/// +/// Another difference: it returns the bracket that contains the root, +/// which may be important if the function has a discontinuity. +#[allow(clippy::too_many_arguments)] +pub(crate) fn solve_itp_fallible( + mut f: impl FnMut(f64) -> Result, + mut a: f64, + mut b: f64, + epsilon: f64, + n0: usize, + k1: f64, + mut ya: f64, + mut yb: f64, +) -> Result<(f64, f64), E> { + let n1_2 = (((b - a) / epsilon).log2().ceil() - 1.0).max(0.0) as usize; + let nmax = n0 + n1_2; + let mut scaled_epsilon = epsilon * (1u64 << nmax) as f64; + while b - a > 2.0 * epsilon { + let x1_2 = 0.5 * (a + b); + let r = scaled_epsilon - 0.5 * (b - a); + let xf = (yb * a - ya * b) / (yb - ya); + let sigma = x1_2 - xf; + // This has k2 = 2 hardwired for efficiency. + let delta = k1 * (b - a).powi(2); + let xt = if delta <= (x1_2 - xf).abs() { + xf + delta.copysign(sigma) + } else { + x1_2 + }; + let xitp = if (xt - x1_2).abs() <= r { + xt + } else { + x1_2 - r.copysign(sigma) + }; + let yitp = f(xitp)?; + if yitp > 0.0 { + b = xitp; + yb = yitp; + } else if yitp < 0.0 { + a = xitp; + ya = yitp; + } else { + return Ok((xitp, xitp)); + } + scaled_epsilon *= 0.5; + } + Ok((a, b)) +} + +// Tables of Legendre-Gauss quadrature coefficients, adapted from: +// + +pub const GAUSS_LEGENDRE_COEFFS_3: &[(f64, f64)] = &[ + (0.8888888888888888, 0.0000000000000000), + (0.5555555555555556, -0.7745966692414834), + (0.5555555555555556, 0.7745966692414834), +]; + +pub const GAUSS_LEGENDRE_COEFFS_4: &[(f64, f64)] = &[ + (0.6521451548625461, -0.3399810435848563), + (0.6521451548625461, 0.3399810435848563), + (0.3478548451374538, -0.8611363115940526), + (0.3478548451374538, 0.8611363115940526), +]; + +pub const GAUSS_LEGENDRE_COEFFS_5: &[(f64, f64)] = &[ + (0.5688888888888889, 0.0000000000000000), + (0.4786286704993665, -0.5384693101056831), + (0.4786286704993665, 0.5384693101056831), + (0.2369268850561891, -0.9061798459386640), + (0.2369268850561891, 0.9061798459386640), +]; + +pub const GAUSS_LEGENDRE_COEFFS_6: &[(f64, f64)] = &[ + (0.3607615730481386, 0.6612093864662645), + (0.3607615730481386, -0.6612093864662645), + (0.4679139345726910, -0.2386191860831969), + (0.4679139345726910, 0.2386191860831969), + (0.1713244923791704, -0.9324695142031521), + (0.1713244923791704, 0.9324695142031521), +]; + +pub const GAUSS_LEGENDRE_COEFFS_7: &[(f64, f64)] = &[ + (0.4179591836734694, 0.0000000000000000), + (0.3818300505051189, 0.4058451513773972), + (0.3818300505051189, -0.4058451513773972), + (0.2797053914892766, -0.7415311855993945), + (0.2797053914892766, 0.7415311855993945), + (0.1294849661688697, -0.9491079123427585), + (0.1294849661688697, 0.9491079123427585), +]; + +pub const GAUSS_LEGENDRE_COEFFS_8: &[(f64, f64)] = &[ + (0.3626837833783620, -0.1834346424956498), + (0.3626837833783620, 0.1834346424956498), + (0.3137066458778873, -0.5255324099163290), + (0.3137066458778873, 0.5255324099163290), + (0.2223810344533745, -0.7966664774136267), + (0.2223810344533745, 0.7966664774136267), + (0.1012285362903763, -0.9602898564975363), + (0.1012285362903763, 0.9602898564975363), +]; + +pub const GAUSS_LEGENDRE_COEFFS_8_HALF: &[(f64, f64)] = &[ + (0.3626837833783620, 0.1834346424956498), + (0.3137066458778873, 0.5255324099163290), + (0.2223810344533745, 0.7966664774136267), + (0.1012285362903763, 0.9602898564975363), +]; + +pub const GAUSS_LEGENDRE_COEFFS_9: &[(f64, f64)] = &[ + (0.3302393550012598, 0.0000000000000000), + (0.1806481606948574, -0.8360311073266358), + (0.1806481606948574, 0.8360311073266358), + (0.0812743883615744, -0.9681602395076261), + (0.0812743883615744, 0.9681602395076261), + (0.3123470770400029, -0.3242534234038089), + (0.3123470770400029, 0.3242534234038089), + (0.2606106964029354, -0.6133714327005904), + (0.2606106964029354, 0.6133714327005904), +]; + +pub const GAUSS_LEGENDRE_COEFFS_11: &[(f64, f64)] = &[ + (0.2729250867779006, 0.0000000000000000), + (0.2628045445102467, -0.2695431559523450), + (0.2628045445102467, 0.2695431559523450), + (0.2331937645919905, -0.5190961292068118), + (0.2331937645919905, 0.5190961292068118), + (0.1862902109277343, -0.7301520055740494), + (0.1862902109277343, 0.7301520055740494), + (0.1255803694649046, -0.8870625997680953), + (0.1255803694649046, 0.8870625997680953), + (0.0556685671161737, -0.9782286581460570), + (0.0556685671161737, 0.9782286581460570), +]; + +pub const GAUSS_LEGENDRE_COEFFS_16: &[(f64, f64)] = &[ + (0.1894506104550685, -0.0950125098376374), + (0.1894506104550685, 0.0950125098376374), + (0.1826034150449236, -0.2816035507792589), + (0.1826034150449236, 0.2816035507792589), + (0.1691565193950025, -0.4580167776572274), + (0.1691565193950025, 0.4580167776572274), + (0.1495959888165767, -0.6178762444026438), + (0.1495959888165767, 0.6178762444026438), + (0.1246289712555339, -0.7554044083550030), + (0.1246289712555339, 0.7554044083550030), + (0.0951585116824928, -0.8656312023878318), + (0.0951585116824928, 0.8656312023878318), + (0.0622535239386479, -0.9445750230732326), + (0.0622535239386479, 0.9445750230732326), + (0.0271524594117541, -0.9894009349916499), + (0.0271524594117541, 0.9894009349916499), +]; + +// Just the positive x_i values. +pub const GAUSS_LEGENDRE_COEFFS_16_HALF: &[(f64, f64)] = &[ + (0.1894506104550685, 0.0950125098376374), + (0.1826034150449236, 0.2816035507792589), + (0.1691565193950025, 0.4580167776572274), + (0.1495959888165767, 0.6178762444026438), + (0.1246289712555339, 0.7554044083550030), + (0.0951585116824928, 0.8656312023878318), + (0.0622535239386479, 0.9445750230732326), + (0.0271524594117541, 0.9894009349916499), +]; + +pub const GAUSS_LEGENDRE_COEFFS_24: &[(f64, f64)] = &[ + (0.1279381953467522, -0.0640568928626056), + (0.1279381953467522, 0.0640568928626056), + (0.1258374563468283, -0.1911188674736163), + (0.1258374563468283, 0.1911188674736163), + (0.1216704729278034, -0.3150426796961634), + (0.1216704729278034, 0.3150426796961634), + (0.1155056680537256, -0.4337935076260451), + (0.1155056680537256, 0.4337935076260451), + (0.1074442701159656, -0.5454214713888396), + (0.1074442701159656, 0.5454214713888396), + (0.0976186521041139, -0.6480936519369755), + (0.0976186521041139, 0.6480936519369755), + (0.0861901615319533, -0.7401241915785544), + (0.0861901615319533, 0.7401241915785544), + (0.0733464814110803, -0.8200019859739029), + (0.0733464814110803, 0.8200019859739029), + (0.0592985849154368, -0.8864155270044011), + (0.0592985849154368, 0.8864155270044011), + (0.0442774388174198, -0.9382745520027328), + (0.0442774388174198, 0.9382745520027328), + (0.0285313886289337, -0.9747285559713095), + (0.0285313886289337, 0.9747285559713095), + (0.0123412297999872, -0.9951872199970213), + (0.0123412297999872, 0.9951872199970213), +]; + +pub const GAUSS_LEGENDRE_COEFFS_24_HALF: &[(f64, f64)] = &[ + (0.1279381953467522, 0.0640568928626056), + (0.1258374563468283, 0.1911188674736163), + (0.1216704729278034, 0.3150426796961634), + (0.1155056680537256, 0.4337935076260451), + (0.1074442701159656, 0.5454214713888396), + (0.0976186521041139, 0.6480936519369755), + (0.0861901615319533, 0.7401241915785544), + (0.0733464814110803, 0.8200019859739029), + (0.0592985849154368, 0.8864155270044011), + (0.0442774388174198, 0.9382745520027328), + (0.0285313886289337, 0.9747285559713095), + (0.0123412297999872, 0.9951872199970213), +]; + +pub const GAUSS_LEGENDRE_COEFFS_32: &[(f64, f64)] = &[ + (0.0965400885147278, -0.0483076656877383), + (0.0965400885147278, 0.0483076656877383), + (0.0956387200792749, -0.1444719615827965), + (0.0956387200792749, 0.1444719615827965), + (0.0938443990808046, -0.2392873622521371), + (0.0938443990808046, 0.2392873622521371), + (0.0911738786957639, -0.3318686022821277), + (0.0911738786957639, 0.3318686022821277), + (0.0876520930044038, -0.4213512761306353), + (0.0876520930044038, 0.4213512761306353), + (0.0833119242269467, -0.5068999089322294), + (0.0833119242269467, 0.5068999089322294), + (0.0781938957870703, -0.5877157572407623), + (0.0781938957870703, 0.5877157572407623), + (0.0723457941088485, -0.6630442669302152), + (0.0723457941088485, 0.6630442669302152), + (0.0658222227763618, -0.7321821187402897), + (0.0658222227763618, 0.7321821187402897), + (0.0586840934785355, -0.7944837959679424), + (0.0586840934785355, 0.7944837959679424), + (0.0509980592623762, -0.8493676137325700), + (0.0509980592623762, 0.8493676137325700), + (0.0428358980222267, -0.8963211557660521), + (0.0428358980222267, 0.8963211557660521), + (0.0342738629130214, -0.9349060759377397), + (0.0342738629130214, 0.9349060759377397), + (0.0253920653092621, -0.9647622555875064), + (0.0253920653092621, 0.9647622555875064), + (0.0162743947309057, -0.9856115115452684), + (0.0162743947309057, 0.9856115115452684), + (0.0070186100094701, -0.9972638618494816), + (0.0070186100094701, 0.9972638618494816), +]; + +pub const GAUSS_LEGENDRE_COEFFS_32_HALF: &[(f64, f64)] = &[ + (0.0965400885147278, 0.0483076656877383), + (0.0956387200792749, 0.1444719615827965), + (0.0938443990808046, 0.2392873622521371), + (0.0911738786957639, 0.3318686022821277), + (0.0876520930044038, 0.4213512761306353), + (0.0833119242269467, 0.5068999089322294), + (0.0781938957870703, 0.5877157572407623), + (0.0723457941088485, 0.6630442669302152), + (0.0658222227763618, 0.7321821187402897), + (0.0586840934785355, 0.7944837959679424), + (0.0509980592623762, 0.8493676137325700), + (0.0428358980222267, 0.8963211557660521), + (0.0342738629130214, 0.9349060759377397), + (0.0253920653092621, 0.9647622555875064), + (0.0162743947309057, 0.9856115115452684), + (0.0070186100094701, 0.9972638618494816), +]; + +#[cfg(test)] +mod tests { + use crate::common::*; + use arrayvec::ArrayVec; + + fn verify(mut roots: ArrayVec, expected: &[f64]) { + assert_eq!(expected.len(), roots.len()); + let epsilon = 1e-12; + roots.sort_by(|a, b| a.partial_cmp(b).unwrap()); + for i in 0..expected.len() { + assert!((roots[i] - expected[i]).abs() < epsilon); + } + } + + #[test] + fn test_solve_cubic() { + verify(solve_cubic(-5.0, 0.0, 0.0, 1.0), &[5.0f64.cbrt()]); + verify(solve_cubic(-5.0, -1.0, 0.0, 1.0), &[1.90416085913492]); + verify(solve_cubic(0.0, -1.0, 0.0, 1.0), &[-1.0, 0.0, 1.0]); + verify(solve_cubic(-2.0, -3.0, 0.0, 1.0), &[-1.0, 2.0]); + verify(solve_cubic(2.0, -3.0, 0.0, 1.0), &[-2.0, 1.0]); + verify( + solve_cubic(2.0 - 1e-12, 5.0, 4.0, 1.0), + &[ + -1.9999999999989995, + -1.0000010000848456, + -0.9999989999161546, + ], + ); + verify(solve_cubic(2.0 + 1e-12, 5.0, 4.0, 1.0), &[-2.0]); + } + + #[test] + fn test_solve_quadratic() { + verify( + solve_quadratic(-5.0, 0.0, 1.0), + &[-(5.0f64.sqrt()), 5.0f64.sqrt()], + ); + verify(solve_quadratic(5.0, 0.0, 1.0), &[]); + verify(solve_quadratic(5.0, 1.0, 0.0), &[-5.0]); + verify(solve_quadratic(1.0, 2.0, 1.0), &[-1.0]); + } + + #[test] + fn test_solve_quartic() { + // These test cases are taken from Orellana and De Michele paper (Table 1). + fn test_with_roots(coeffs: [f64; 4], roots: &[f64], rel_err: f64) { + // Note: in paper, coefficients are in decreasing order. + let mut actual = solve_quartic(coeffs[3], coeffs[2], coeffs[1], coeffs[0], 1.0); + actual.sort_by(f64::total_cmp); + assert_eq!(actual.len(), roots.len()); + for (actual, expected) in actual.iter().zip(roots) { + assert!( + (actual - expected).abs() < rel_err * expected.abs(), + "actual {:e}, expected {:e}, err {:e}", + actual, + expected, + actual - expected + ); + } + } + + fn test_vieta_roots(x1: f64, x2: f64, x3: f64, x4: f64, roots: &[f64], rel_err: f64) { + let a = -(x1 + x2 + x3 + x4); + let b = x1 * (x2 + x3) + x2 * (x3 + x4) + x4 * (x1 + x3); + let c = -x1 * x2 * (x3 + x4) - x3 * x4 * (x1 + x2); + let d = x1 * x2 * x3 * x4; + test_with_roots([a, b, c, d], roots, rel_err); + } + + fn test_vieta(x1: f64, x2: f64, x3: f64, x4: f64, rel_err: f64) { + test_vieta_roots(x1, x2, x3, x4, &[x1, x2, x3, x4], rel_err); + } + + // case 1 + test_vieta(1., 1e3, 1e6, 1e9, 1e-16); + // case 2 + test_vieta(2., 2.001, 2.002, 2.003, 1e-6); + // case 3 + test_vieta(1e47, 1e49, 1e50, 1e53, 2e-16); + // case 4 + test_vieta(-1., 1., 2., 1e14, 1e-16); + // case 5 + test_vieta(-2e7, -1., 1., 1e7, 1e-16); + // case 6 + test_with_roots( + [-9000002.0, -9999981999998.0, 19999982e6, -2e13], + &[-1e6, 1e7], + 1e-16, + ); + // case 7 + test_with_roots( + [2000011.0, 1010022000028.0, 11110056e6, 2828e10], + &[-7., -4.], + 1e-16, + ); + // case 8 + test_with_roots( + [-100002011.0, 201101022001.0, -102200111000011.0, 11000011e8], + &[11., 1e8], + 1e-16, + ); + // cases 9-13 have no real roots + // case 14 + test_vieta_roots(1000., 1000., 1000., 1000., &[1000., 1000.], 1e-16); + // case 15 + test_vieta_roots(1e-15, 1000., 1000., 1000., &[1e-15, 1000., 1000.], 1e-15); + // case 16 no real roots + // case 17 + test_vieta(10000., 10001., 10010., 10100., 1e-6); + // case 19 + test_vieta_roots(1., 1e30, 1e30, 1e44, &[1., 1e30, 1e44], 1e-16); + // case 20 + // FAILS, error too big + test_vieta(1., 1e7, 1e7, 1e14, 1e-7); + // case 21 doesn't pick up double root + // case 22 + test_vieta(1., 10., 1e152, 1e154, 3e-16); + // case 23 + test_with_roots( + [1., 1., 3. / 8., 1e-3], + &[-0.497314148060048, -0.00268585193995149], + 2e-15, + ); + // case 24 + const S: f64 = 1e30; + test_with_roots( + [-(1. + 1. / S), 1. / S - S * S, S * S + S, -S], + &[-S, 1e-30, 1., S], + 2e-16, + ); + } + + #[test] + fn test_solve_itp() { + let f = |x: f64| x.powi(3) - x - 2.0; + let x = solve_itp(f, 1., 2., 1e-12, 0, 0.2, f(1.), f(2.)); + assert!(f(x).abs() < 6e-12); + } + + #[test] + fn test_inv_arclen() { + use crate::{ParamCurve, ParamCurveArclen}; + let c = crate::CubicBez::new( + (0.0, 0.0), + (100.0 / 3.0, 0.0), + (200.0 / 3.0, 100.0 / 3.0), + (100.0, 100.0), + ); + let target = 100.0; + let _ = solve_itp( + |t| c.subsegment(0.0..t).arclen(1e-9) - target, + 0., + 1., + 1e-6, + 1, + 0.2, + -target, + c.arclen(1e-9) - target, + ); + } +} diff --git a/vendor/kurbo/src/cubicbez.rs b/vendor/kurbo/src/cubicbez.rs new file mode 100644 index 0000000000..533256fb52 --- /dev/null +++ b/vendor/kurbo/src/cubicbez.rs @@ -0,0 +1,1257 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Cubic Bézier segments. + +use alloc::vec; +use alloc::vec::Vec; +use core::ops::{Mul, Range}; + +use crate::MAX_EXTREMA; +use crate::{Line, QuadSpline, Vec2}; +use arrayvec::ArrayVec; + +use crate::common::{ + GAUSS_LEGENDRE_COEFFS_8, GAUSS_LEGENDRE_COEFFS_8_HALF, GAUSS_LEGENDRE_COEFFS_16_HALF, + GAUSS_LEGENDRE_COEFFS_24_HALF, solve_cubic, solve_quadratic, solve_quartic, +}; +use crate::{ + Affine, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, + ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point, QuadBez, Rect, Shape, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +const MAX_SPLINE_SPLIT: usize = 100; + +/// A single cubic Bézier segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[allow(missing_docs)] +pub struct CubicBez { + pub p0: Point, + pub p1: Point, + pub p2: Point, + pub p3: Point, +} + +/// An iterator which produces quadratic Bézier segments. +struct ToQuads { + c: CubicBez, + i: usize, + n: usize, +} + +/// Classification result for cusp detection. +#[derive(Debug)] +pub enum CuspType { + /// Cusp is a loop. + Loop, + /// Cusp has two closely spaced inflection points. + DoubleInflection, +} + +impl CubicBez { + /// Create a new cubic Bézier segment. + #[inline(always)] + pub fn new>(p0: P, p1: P, p2: P, p3: P) -> CubicBez { + CubicBez { + p0: p0.into(), + p1: p1.into(), + p2: p2.into(), + p3: p3.into(), + } + } + + /// Convert to quadratic Béziers. + /// + /// The iterator returns the start and end parameter in the cubic of each quadratic + /// segment, along with the quadratic. + /// + /// Note that the resulting quadratic Béziers are not in general G1 continuous; + /// they are optimized for minimizing distance error. + /// + /// This iterator will always produce at least one `QuadBez`. + #[inline] + pub fn to_quads(&self, accuracy: f64) -> impl Iterator { + // The maximum error, as a vector from the cubic to the best approximating + // quadratic, is proportional to the third derivative, which is constant + // across the segment. Thus, the error scales down as the third power of + // the number of subdivisions. Our strategy then is to subdivide `t` evenly. + // + // This is an overestimate of the error because only the component + // perpendicular to the first derivative is important. But the simplicity is + // appealing. + + // This magic number is the square of 36 / sqrt(3). + // See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html + let max_hypot2 = 432.0 * accuracy * accuracy; + let p1x2 = 3.0 * self.p1.to_vec2() - self.p0.to_vec2(); + let p2x2 = 3.0 * self.p2.to_vec2() - self.p3.to_vec2(); + let err = (p2x2 - p1x2).hypot2(); + let n = ((err / max_hypot2).powf(1. / 6.0).ceil() as usize).max(1); + + ToQuads { c: *self, n, i: 0 } + } + + /// Return a [`QuadSpline`] approximating this cubic Bézier. + /// + /// Returns `None` if no suitable approximation is found within the given + /// tolerance. + pub fn approx_spline(&self, accuracy: f64) -> Option { + (1..=MAX_SPLINE_SPLIT).find_map(|n| self.approx_spline_n(n, accuracy)) + } + + // Approximate a cubic curve with a quadratic spline of `n` curves + fn approx_spline_n(&self, n: usize, accuracy: f64) -> Option { + if n == 1 { + return self + .try_approx_quadratic(accuracy) + .map(|quad| QuadSpline::new(vec![quad.p0, quad.p1, quad.p2])); + } + let mut cubics = self.split_into_n(n); + + // The above function guarantees that the iterator returns n items, + // which is why we're unwrapping things with wild abandon. + let mut next_cubic = cubics.next().unwrap(); + let mut next_q1: Point = next_cubic.approx_quad_control(0.0); + let mut q2 = self.p0; + let mut d1 = Vec2::ZERO; + let mut spline = vec![self.p0, next_q1]; + for i in 1..=n { + let current_cubic: CubicBez = next_cubic; + let q0 = q2; + let q1 = next_q1; + q2 = if i < n { + next_cubic = cubics.next().unwrap(); + next_q1 = next_cubic.approx_quad_control(i as f64 / (n - 1) as f64); + + spline.push(next_q1); + q1.midpoint(next_q1) + } else { + current_cubic.p3 + }; + let d0 = d1; + d1 = q2.to_vec2() - current_cubic.p3.to_vec2(); + + if d1.hypot() > accuracy + || !CubicBez::new( + d0.to_point(), + q0.lerp(q1, 2.0 / 3.0) - current_cubic.p1.to_vec2(), + q2.lerp(q1, 2.0 / 3.0) - current_cubic.p2.to_vec2(), + d1.to_point(), + ) + .fit_inside(accuracy) + { + return None; + } + } + spline.push(self.p3); + Some(QuadSpline::new(spline)) + } + + fn approx_quad_control(&self, t: f64) -> Point { + let p1 = self.p0 + (self.p1 - self.p0) * 1.5; + let p2 = self.p3 + (self.p2 - self.p3) * 1.5; + p1.lerp(p2, t) + } + + /// Approximate a cubic with a single quadratic + /// + /// Returns a quadratic approximating the given cubic that maintains + /// endpoint tangents if that is within tolerance, or `None` otherwise. + fn try_approx_quadratic(&self, accuracy: f64) -> Option { + if let Some(q1) = Line::new(self.p0, self.p1) + .crossing_point(Line::new(self.p2, self.p3)) + .or_else(|| { + // with 3 to 4 consecutive equal points (with no valid crossing_point), + // we can try to use the common point as the quadratic control point. + // This matches fonttools' cu2qu: https://github.com/fonttools/fonttools/pull/3904 + (self.p1 == self.p2 && (self.p0 == self.p1 || self.p2 == self.p3)) + .then_some(self.p1) + }) + { + let c1 = self.p0.lerp(q1, 2.0 / 3.0); + let c2 = self.p3.lerp(q1, 2.0 / 3.0); + if !CubicBez::new( + Point::ZERO, + c1 - self.p1.to_vec2(), + c2 - self.p2.to_vec2(), + Point::ZERO, + ) + .fit_inside(accuracy) + { + return None; + } + return Some(QuadBez::new(self.p0, q1, self.p3)); + } + None + } + + fn split_into_n(&self, n: usize) -> impl Iterator { + // for certain small values of `n` we precompute all our values. + // if we have six or fewer items we precompute them. + let mut storage = ArrayVec::<_, 6>::new(); + + match n { + 1 => storage.push(*self), + 2 => { + let (l, r) = self.subdivide(); + storage.try_extend_from_slice(&[r, l]).unwrap(); + } + 3 => { + let (left, mid, right) = self.subdivide_3(); + storage.try_extend_from_slice(&[right, mid, left]).unwrap(); + } + 4 => { + let (l, r) = self.subdivide(); + let (ll, lr) = l.subdivide(); + let (rl, rr) = r.subdivide(); + storage.try_extend_from_slice(&[rr, rl, lr, ll]).unwrap(); + } + 6 => { + let (l, r) = self.subdivide(); + let (l1, l2, l3) = l.subdivide_3(); + let (r1, r2, r3) = r.subdivide_3(); + storage + .try_extend_from_slice(&[r3, r2, r1, l3, l2, l1]) + .unwrap(); + } + _ => (), + } + + // a limitation of returning 'impl Trait' is that the implementation + // can only return a single concrete type; that is you cannot return + // Vec::into_iter() from one branch, and then HashSet::into_iter from + // another branch. + // + // This means we have to get a bit fancy, and have a single concrete + // type that represents both of our possible cases. + + let mut storage = if storage.is_empty() { + None + } else { + Some(storage) + }; + + // used in the fallback case + let mut i = 0; + let (a, b, c, d) = self.parameters(); + let dt = 1.0 / n as f64; + let delta_2 = dt * dt; + let delta_3 = dt * delta_2; + + core::iter::from_fn(move || { + // if storage exists, we use it exclusively + if let Some(storage) = storage.as_mut() { + return storage.pop(); + } + + // if storage does not exist, we are exclusively working down here. + if i >= n { + return None; + } + + let t1 = i as f64 * dt; + let t1_2 = t1 * t1; + let a1 = a * delta_3; + let b1 = (3.0 * a * t1 + b) * delta_2; + let c1 = (2.0 * b * t1 + c + 3.0 * a * t1_2) * dt; + let d1 = a * t1 * t1_2 + b * t1_2 + c * t1 + d; + let result = CubicBez::from_parameters(a1, b1, c1, d1); + i += 1; + Some(result) + }) + } + + fn parameters(&self) -> (Vec2, Vec2, Vec2, Vec2) { + let c = (self.p1 - self.p0) * 3.0; + let b = (self.p2 - self.p1) * 3.0 - c; + let d = self.p0.to_vec2(); + let a = self.p3.to_vec2() - d - c - b; + (a, b, c, d) + } + + /// Rust port of cu2qu [calc_cubic_points](https://github.com/fonttools/fonttools/blob/3b9a73ff8379ab49d3ce35aaaaf04b3a7d9d1655/Lib/fontTools/cu2qu/cu2qu.py#L63-L68) + fn from_parameters(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Self { + let p0 = d.to_point(); + let p1 = c.div_exact(3.0).to_point() + d; + let p2 = (b + c).div_exact(3.0).to_point() + p1.to_vec2(); + let p3 = (a + d + c + b).to_point(); + CubicBez::new(p0, p1, p2, p3) + } + + fn subdivide_3(&self) -> (CubicBez, CubicBez, CubicBez) { + let (p0, p1, p2, p3) = ( + self.p0.to_vec2(), + self.p1.to_vec2(), + self.p2.to_vec2(), + self.p3.to_vec2(), + ); + // The original Python cu2qu code here does not use division operator to divide by 27 but + // instead uses multiplication by the reciprocal 1 / 27. We want to match it exactly + // to avoid any floating point differences, hence in this particular case we do not use div_exact. + // I could directly use the Vec2 Div trait (also implemented as multiplication by reciprocal) + // but I prefer to be explicit here. + // Source: https://github.com/fonttools/fonttools/blob/85c80be/Lib/fontTools/cu2qu/cu2qu.py#L215-L218 + // See also: https://github.com/linebender/kurbo/issues/272 + let one_27th = 27.0_f64.recip(); + let mid1 = ((8.0 * p0 + 12.0 * p1 + 6.0 * p2 + p3) * one_27th).to_point(); + let deriv1 = (p3 + 3.0 * p2 - 4.0 * p0) * one_27th; + let mid2 = ((p0 + 6.0 * p1 + 12.0 * p2 + 8.0 * p3) * one_27th).to_point(); + let deriv2 = (4.0 * p3 - 3.0 * p1 - p0) * one_27th; + + let left = CubicBez::new( + self.p0, + (2.0 * p0 + p1).div_exact(3.0).to_point(), + mid1 - deriv1, + mid1, + ); + let mid = CubicBez::new(mid1, mid1 + deriv1, mid2 - deriv2, mid2); + let right = CubicBez::new( + mid2, + mid2 + deriv2, + (p2 + 2.0 * p3).div_exact(3.0).to_point(), + self.p3, + ); + (left, mid, right) + } + + /// Does this curve fit inside the given distance from the origin? + /// + /// Rust port of cu2qu [cubic_farthest_fit_inside](https://github.com/fonttools/fonttools/blob/3b9a73ff8379ab49d3ce35aaaaf04b3a7d9d1655/Lib/fontTools/cu2qu/cu2qu.py#L281) + fn fit_inside(&self, distance: f64) -> bool { + if self.p2.to_vec2().hypot() <= distance && self.p1.to_vec2().hypot() <= distance { + return true; + } + let mid = + (self.p0.to_vec2() + 3.0 * (self.p1.to_vec2() + self.p2.to_vec2()) + self.p3.to_vec2()) + * 0.125; + if mid.hypot() > distance { + return false; + } + // Split in two. Note that cu2qu here uses a 3/8 subdivision. I don't know why. + let (left, right) = self.subdivide(); + left.fit_inside(distance) && right.fit_inside(distance) + } + + /// Is this cubic Bezier curve finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.p0.is_finite() && self.p1.is_finite() && self.p2.is_finite() && self.p3.is_finite() + } + + /// Is this cubic Bezier curve NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.p0.is_nan() || self.p1.is_nan() || self.p2.is_nan() || self.p3.is_nan() + } + + /// Determine the inflection points. + /// + /// Return value is t parameter for the inflection points of the curve segment. + /// There are a maximum of two for a cubic Bézier. + /// + /// See + /// for the theory. + pub fn inflections(&self) -> ArrayVec { + let a = self.p1 - self.p0; + let b = (self.p2 - self.p1) - a; + let c = (self.p3 - self.p0) - 3. * (self.p2 - self.p1); + solve_quadratic(a.cross(b), a.cross(c), b.cross(c)) + .iter() + .copied() + .filter(|t| *t >= 0.0 && *t <= 1.0) + .collect() + } + + /// Find points on the curve where the tangent line passes through the + /// given point. + /// + /// Result is array of t values such that the tangent line from the curve + /// evaluated at that point goes through the argument point. + pub fn tangents_to_point(&self, p: Point) -> ArrayVec { + let (a, b, c, d_orig) = self.parameters(); + let d = d_orig - p.to_vec2(); + // coefficients of x(t) \cross x'(t) + let c4 = b.cross(a); + let c3 = 2.0 * c.cross(a); + let c2 = c.cross(b) + 3.0 * d.cross(a); + let c1 = 2.0 * d.cross(b); + let c0 = d.cross(c); + solve_quartic(c0, c1, c2, c3, c4) + .iter() + .copied() + .filter(|t| *t >= 0.0 && *t <= 1.0) + .collect() + } + + /// Preprocess a cubic Bézier to ease numerical robustness. + /// + /// If the cubic Bézier segment has zero or near-zero derivatives as an interior + /// cusp, perturb the control points to make curvature finite, avoiding + /// numerical robustness problems in offset and stroke. + pub(crate) fn regularize_cusp(&self, dimension: f64) -> CubicBez { + let mut c = *self; + // First step: if control point is too near the endpoint, nudge it away + // along the tangent. + if let Some(cusp_type) = self.detect_cusp(dimension) { + let d01 = c.p1 - c.p0; + let d01h = d01.hypot(); + let d23 = c.p3 - c.p2; + let d23h = d23.hypot(); + match cusp_type { + CuspType::Loop => { + c.p1 += (dimension / d01h) * d01; + c.p2 -= (dimension / d23h) * d23; + } + CuspType::DoubleInflection => { + // Avoid making control distance smaller than dimension + if d01h > 2.0 * dimension { + c.p1 -= (dimension / d01h) * d01; + } + if d23h > 2.0 * dimension { + c.p2 += (dimension / d23h) * d23; + } + } + } + } + c + } + + /// Detect whether there is a cusp. + /// + /// Return a cusp classification if there is a cusp with curvature greater than + /// the reciprocal of the given dimension. + fn detect_cusp(&self, dimension: f64) -> Option { + let d01 = self.p1 - self.p0; + let d02 = self.p2 - self.p0; + let d03 = self.p3 - self.p0; + let d12 = self.p2 - self.p1; + let d23 = self.p3 - self.p2; + let det_012 = d01.cross(d02); + let det_123 = d12.cross(d23); + let det_013 = d01.cross(d03); + let det_023 = d02.cross(d03); + if det_012 * det_123 > 0.0 && det_012 * det_013 < 0.0 && det_012 * det_023 < 0.0 { + let q = self.deriv(); + // accuracy isn't used for quadratic nearest + let nearest = q.nearest(Point::ORIGIN, 1e-9); + // detect whether curvature at minimum derivative exceeds 1/dimension, + // without division. + let d = q.eval(nearest.t); + let d2 = q.deriv().eval(nearest.t); + let cross = d.to_vec2().cross(d2.to_vec2()); + if nearest.distance_sq.powi(3) <= (cross * dimension).powi(2) { + let a = 3. * det_012 + det_023 - 2. * det_013; + let b = -3. * det_012 + det_013; + let c = det_012; + let d = b * b - 4. * a * c; + if d > 0.0 { + return Some(CuspType::DoubleInflection); + } else { + return Some(CuspType::Loop); + } + } + } + None + } + + /// Finds the value of `t` for which `self.eval(t)` is about `y`. + /// + /// Assumes that this segment is monotonic in `y` and that it crosses + /// the height `y`. (Under these assumptions, there is a unique answer.) + pub(crate) fn solve_monotonic_for_y(&self, y: f64) -> f64 { + let start = self.start(); + let end = self.end(); + + debug_assert!(start.y.min(end.y) <= y && y <= start.y.max(end.y)); + + let p1 = self.p1; + let p2 = self.p2; + let a = end.y - 3.0 * p2.y + 3.0 * p1.y - start.y; + let b = 3.0 * (p2.y - 2.0 * p1.y + start.y); + let c = 3.0 * (p1.y - start.y); + let d = start.y - y; + for t in solve_cubic(d, c, b, a) { + if (0.0..=1.0).contains(&t) { + return t; + } + } + + // Even though we asserted that our y range contains `y`, it's possible + // that we failed to find a solution numerically. (For example, rounding + // of a, b, or c might have pushed the root outside of [0.0, 1.0].) + // If we failed to find a solution, the real solution should be close + // to one of the endpoints. So just find whichever endpoint was closer. + if (start.y - y).abs() <= (end.y - y).abs() { + 0.0 + } else { + 1.0 + } + } +} + +/// An iterator for cubic beziers. +pub struct CubicBezIter { + cubic: CubicBez, + ix: usize, +} + +impl Shape for CubicBez { + type PathElementsIter<'iter> = CubicBezIter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> CubicBezIter { + CubicBezIter { + cubic: *self, + ix: 0, + } + } + + #[inline(always)] + fn area(&self) -> f64 { + 0.0 + } + + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.arclen(accuracy) + } + + #[inline(always)] + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline] + fn bounding_box(&self) -> Rect { + ParamCurveExtrema::bounding_box(self) + } +} + +impl Iterator for CubicBezIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.cubic.p0)), + 2 => Some(PathEl::CurveTo(self.cubic.p1, self.cubic.p2, self.cubic.p3)), + _ => None, + } + } +} + +impl ParamCurve for CubicBez { + #[inline] + fn eval(&self, t: f64) -> Point { + let mt = 1.0 - t; + let v = self.p0.to_vec2() * (mt * mt * mt) + + (self.p1.to_vec2() * (mt * mt * 3.0) + + (self.p2.to_vec2() * (mt * 3.0) + self.p3.to_vec2() * t) * t) + * t; + v.to_point() + } + + fn subsegment(&self, range: Range) -> CubicBez { + let (t0, t1) = (range.start, range.end); + let p0 = self.eval(t0); + let p3 = self.eval(t1); + let d = self.deriv(); + let scale = (t1 - t0) * (1.0 / 3.0); + let p1 = p0 + scale * d.eval(t0).to_vec2(); + let p2 = p3 - scale * d.eval(t1).to_vec2(); + CubicBez { p0, p1, p2, p3 } + } + + /// Subdivide into halves, using de Casteljau. + #[inline] + fn subdivide(&self) -> (CubicBez, CubicBez) { + let pm = self.eval(0.5); + ( + CubicBez::new( + self.p0, + self.p0.midpoint(self.p1), + ((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) + .to_point(), + pm, + ), + CubicBez::new( + pm, + ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) + .to_point(), + self.p2.midpoint(self.p3), + self.p3, + ), + ) + } + + #[inline(always)] + fn start(&self) -> Point { + self.p0 + } + + #[inline(always)] + fn end(&self) -> Point { + self.p3 + } +} + +impl ParamCurveDeriv for CubicBez { + type DerivResult = QuadBez; + + #[inline] + fn deriv(&self) -> QuadBez { + QuadBez::new( + (3.0 * (self.p1 - self.p0)).to_point(), + (3.0 * (self.p2 - self.p1)).to_point(), + (3.0 * (self.p3 - self.p2)).to_point(), + ) + } +} + +fn arclen_quadrature_core(coeffs: &[(f64, f64)], dm: Vec2, dm1: Vec2, dm2: Vec2) -> f64 { + coeffs + .iter() + .map(|&(wi, xi)| { + let d = dm + dm2 * (xi * xi); + let dpx = (d + dm1 * xi).hypot(); + let dmx = (d - dm1 * xi).hypot(); + (2.25f64.sqrt() * wi) * (dpx + dmx) + }) + .sum::() +} + +fn arclen_rec(c: &CubicBez, accuracy: f64, depth: usize) -> f64 { + let d03 = c.p3 - c.p0; + let d01 = c.p1 - c.p0; + let d12 = c.p2 - c.p1; + let d23 = c.p3 - c.p2; + let lp_lc = d01.hypot() + d12.hypot() + d23.hypot() - d03.hypot(); + let dd1 = d12 - d01; + let dd2 = d23 - d12; + // It might be faster to do direct multiplies, the data dependencies would be shorter. + // The following values don't have the factor of 3 for first deriv + let dm = 0.25 * (d01 + d23) + 0.5 * d12; // first derivative at midpoint + let dm1 = 0.5 * (dd2 + dd1); // second derivative at midpoint + let dm2 = 0.25 * (dd2 - dd1); // 0.5 * (third derivative at midpoint) + + let est = GAUSS_LEGENDRE_COEFFS_8 + .iter() + .map(|&(wi, xi)| { + wi * { + let d_norm2 = (dm + dm1 * xi + dm2 * (xi * xi)).hypot2(); + let dd_norm2 = (dm1 + dm2 * (2.0 * xi)).hypot2(); + dd_norm2 / d_norm2 + } + }) + .sum::(); + let est_gauss8_error = (est.powi(3) * 2.5e-6).min(3e-2) * lp_lc; + if est_gauss8_error < accuracy { + return arclen_quadrature_core(GAUSS_LEGENDRE_COEFFS_8_HALF, dm, dm1, dm2); + } + let est_gauss16_error = (est.powi(6) * 1.5e-11).min(9e-3) * lp_lc; + if est_gauss16_error < accuracy { + return arclen_quadrature_core(GAUSS_LEGENDRE_COEFFS_16_HALF, dm, dm1, dm2); + } + let est_gauss24_error = (est.powi(9) * 3.5e-16).min(3.5e-3) * lp_lc; + if est_gauss24_error < accuracy || depth >= 20 { + return arclen_quadrature_core(GAUSS_LEGENDRE_COEFFS_24_HALF, dm, dm1, dm2); + } + let (c0, c1) = c.subdivide(); + arclen_rec(&c0, accuracy * 0.5, depth + 1) + arclen_rec(&c1, accuracy * 0.5, depth + 1) +} + +impl ParamCurveArclen for CubicBez { + /// Arclength of a cubic Bézier segment. + /// + /// This is an adaptive subdivision approach using Legendre-Gauss quadrature + /// in the base case, and an error estimate to decide when to subdivide. + fn arclen(&self, accuracy: f64) -> f64 { + arclen_rec(self, accuracy, 0) + } +} + +impl ParamCurveArea for CubicBez { + #[inline] + fn signed_area(&self) -> f64 { + (self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y) + + 3.0 + * (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y) + - self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y)) + - self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y)) + * (1.0 / 20.0) + } +} + +impl ParamCurveNearest for CubicBez { + /// Find the nearest point using a quintic solver. + /// + /// The polynomial `|self - p|^2` has degree 6, so we find its critical + /// points and evaluate them all to find the best one. + fn nearest(&self, p: Point, accuracy: f64) -> Nearest { + fn eval_t(p: Point, t_best: &mut f64, r_best: &mut Option, t: f64, p0: Point) { + let r = (p0 - p).hypot2(); + if r_best.map(|r_best| r < r_best).unwrap_or(true) { + *r_best = Some(r); + *t_best = t; + } + } + + let mut r_best = None; + let mut t_best = 0.0; + + // Reparameterize `self - p` as q0 + q1 t + q2 t^2 + q3 t^3. + let q0 = self.p0 - p; + let q1 = 3.0 * (self.p1 - self.p0); + let q2 = 3.0 * (self.p0.to_vec2() - 2.0 * self.p1.to_vec2() + self.p2.to_vec2()); + let q3 = -self.p0.to_vec2() + 3.0 * self.p1.to_vec2() - 3.0 * self.p2.to_vec2() + + self.p3.to_vec2(); + + // Coefficients of the degree-5 polynomial (self - p) \cdot tangent. + let c0 = q0.dot(q1); + let c1 = q1.hypot2() + 2.0 * q2.dot(q0); + let c2 = 3.0 * (q2.dot(q1) + q3.dot(q0)); + let c3 = 4.0 * q3.dot(q1) + 2.0 * q2.hypot2(); + let c4 = 5.0 * q3.dot(q2); + let c5 = 3.0 * q3.hypot2(); + + let roots = polycool::Poly::new([c0, c1, c2, c3, c4, c5]).roots_between(0.0, 1.0, accuracy); + + for &t in &roots { + eval_t(p, &mut t_best, &mut r_best, t, self.eval(t)); + } + + // If we found all 5 critical points, we can skip evaluating the endpoints. + if roots.len() != 5 { + eval_t(p, &mut t_best, &mut r_best, 0.0, self.p0); + eval_t(p, &mut t_best, &mut r_best, 1.0, self.p3); + } + + Nearest { + t: t_best, + distance_sq: r_best.unwrap(), + } + } +} + +impl ParamCurveCurvature for CubicBez {} + +impl ParamCurveExtrema for CubicBez { + fn extrema(&self) -> ArrayVec { + fn one_coord(result: &mut ArrayVec, d0: f64, d1: f64, d2: f64) { + let a = d0 - 2.0 * d1 + d2; + let b = 2.0 * (d1 - d0); + let c = d0; + let roots = solve_quadratic(c, b, a); + for &t in &roots { + if t > 0.0 && t < 1.0 { + result.push(t); + } + } + } + let mut result = ArrayVec::new(); + let d0 = self.p1 - self.p0; + let d1 = self.p2 - self.p1; + let d2 = self.p3 - self.p2; + one_coord(&mut result, d0.x, d1.x, d2.x); + one_coord(&mut result, d0.y, d1.y, d2.y); + result.sort_by(|a, b| a.partial_cmp(b).unwrap()); + result + } +} + +impl Mul for Affine { + type Output = CubicBez; + + #[inline] + fn mul(self, c: CubicBez) -> CubicBez { + CubicBez { + p0: self * c.p0, + p1: self * c.p1, + p2: self * c.p2, + p3: self * c.p3, + } + } +} + +impl Iterator for ToQuads { + type Item = (f64, f64, QuadBez); + + #[inline] + fn next(&mut self) -> Option<(f64, f64, QuadBez)> { + if self.i == self.n { + return None; + } + let t0 = self.i as f64 / self.n as f64; + let t1 = (self.i + 1) as f64 / self.n as f64; + let seg = self.c.subsegment(t0..t1); + let p1x2 = 3.0 * seg.p1.to_vec2() - seg.p0.to_vec2(); + let p2x2 = 3.0 * seg.p2.to_vec2() - seg.p3.to_vec2(); + let result = QuadBez::new(seg.p0, ((p1x2 + p2x2) / 4.0).to_point(), seg.p3); + self.i += 1; + Some((t0, t1, result)) + } + + fn size_hint(&self) -> (usize, Option) { + let remaining = self.n - self.i; + (remaining, Some(remaining)) + } +} + +/// Convert multiple cubic Bézier curves to quadratic splines. +/// +/// Ensures that the resulting splines have the same number of control points. +/// +/// Rust port of cu2qu [cubic_approx_quadratic](https://github.com/fonttools/fonttools/blob/3b9a73ff8379ab49d3ce35aaaaf04b3a7d9d1655/Lib/fontTools/cu2qu/cu2qu.py#L322) +pub fn cubics_to_quadratic_splines(curves: &[CubicBez], accuracy: f64) -> Option> { + let mut result = Vec::new(); + let mut split_order = 0; + + while split_order <= MAX_SPLINE_SPLIT { + split_order += 1; + result.clear(); + + for curve in curves { + match curve.approx_spline_n(split_order, accuracy) { + Some(spline) => result.push(spline), + None => break, + } + } + + if result.len() == curves.len() { + return Some(result); + } + } + None +} +#[cfg(test)] +mod tests { + use crate::{ + Affine, CubicBez, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, + ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, QuadSpline, + cubics_to_quadratic_splines, + }; + + #[test] + fn cubicbez_deriv() { + // y = x^2 + let c = CubicBez::new( + (0.0, 0.0), + (1.0 / 3.0, 0.0), + (2.0 / 3.0, 1.0 / 3.0), + (1.0, 1.0), + ); + let deriv = c.deriv(); + + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let delta = 1e-6; + let p = c.eval(t); + let p1 = c.eval(t + delta); + let d_approx = (p1 - p) * delta.recip(); + let d = deriv.eval(t).to_vec2(); + assert!((d - d_approx).hypot() < delta * 2.0); + } + } + + #[test] + fn cubicbez_arclen() { + // y = x^2 + let c = CubicBez::new( + (0.0, 0.0), + (1.0 / 3.0, 0.0), + (2.0 / 3.0, 1.0 / 3.0), + (1.0, 1.0), + ); + let true_arclen = 0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln(); + for i in 0..12 { + let accuracy = 0.1f64.powi(i); + let error = c.arclen(accuracy) - true_arclen; + assert!(error.abs() < accuracy); + } + } + + #[test] + fn cubicbez_inv_arclen() { + // y = x^2 / 100 + let c = CubicBez::new( + (0.0, 0.0), + (100.0 / 3.0, 0.0), + (200.0 / 3.0, 100.0 / 3.0), + (100.0, 100.0), + ); + let true_arclen = 100.0 * (0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln()); + for i in 0..12 { + let accuracy = 0.1f64.powi(i); + let n = 10; + for j in 0..=n { + let arc = (j as f64) * ((n as f64).recip() * true_arclen); + let t = c.inv_arclen(arc, accuracy * 0.5); + let actual_arc = c.subsegment(0.0..t).arclen(accuracy * 0.5); + assert!( + (arc - actual_arc).abs() < accuracy, + "at accuracy {accuracy:e}, wanted {actual_arc} got {arc}" + ); + } + } + // corner case: user passes accuracy larger than total arc length + let accuracy = true_arclen * 1.1; + let arc = true_arclen * 0.5; + let t = c.inv_arclen(arc, accuracy); + let actual_arc = c.subsegment(0.0..t).arclen(accuracy); + assert!( + (arc - actual_arc).abs() < 2.0 * accuracy, + "at accuracy {accuracy:e}, want {actual_arc} got {arc}" + ); + } + + #[test] + fn cubicbez_inv_arclen_accuracy() { + let c = CubicBez::new((0.2, 0.73), (0.35, 1.08), (0.85, 1.08), (1.0, 0.73)); + let true_t = c.inv_arclen(0.5, 1e-12); + for i in 1..12 { + let accuracy = (0.1f64).powi(i); + let approx_t = c.inv_arclen(0.5, accuracy); + assert!((approx_t - true_t).abs() <= accuracy); + } + } + + #[test] + #[allow(clippy::float_cmp)] + fn cubicbez_signed_area_linear() { + // y = 1 - x + let c = CubicBez::new( + (1.0, 0.0), + (2.0 / 3.0, 1.0 / 3.0), + (1.0 / 3.0, 2.0 / 3.0), + (0.0, 1.0), + ); + let epsilon = 1e-12; + assert_eq!((Affine::rotate(0.5) * c).signed_area(), 0.5); + assert!(((Affine::rotate(0.5) * c).signed_area() - 0.5).abs() < epsilon); + assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.0).abs() < epsilon); + assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.0).abs() < epsilon); + } + + #[test] + fn cubicbez_signed_area() { + // y = 1 - x^3 + let c = CubicBez::new((1.0, 0.0), (2.0 / 3.0, 1.0), (1.0 / 3.0, 1.0), (0.0, 1.0)); + let epsilon = 1e-12; + assert!((c.signed_area() - 0.75).abs() < epsilon); + assert!(((Affine::rotate(0.5) * c).signed_area() - 0.75).abs() < epsilon); + assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.25).abs() < epsilon); + assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.25).abs() < epsilon); + } + + #[test] + fn cubicbez_nearest() { + fn verify(result: Nearest, expected: f64) { + assert!( + (result.t - expected).abs() < 1e-6, + "got {result:?} expected {expected}" + ); + } + // y = x^3 + let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); + verify(c.nearest((0.1, 0.001).into(), 1e-6), 0.1); + verify(c.nearest((0.2, 0.008).into(), 1e-6), 0.2); + verify(c.nearest((0.3, 0.027).into(), 1e-6), 0.3); + verify(c.nearest((0.4, 0.064).into(), 1e-6), 0.4); + verify(c.nearest((0.5, 0.125).into(), 1e-6), 0.5); + verify(c.nearest((0.6, 0.216).into(), 1e-6), 0.6); + verify(c.nearest((0.7, 0.343).into(), 1e-6), 0.7); + verify(c.nearest((0.8, 0.512).into(), 1e-6), 0.8); + verify(c.nearest((0.9, 0.729).into(), 1e-6), 0.9); + verify(c.nearest((1.0, 1.0).into(), 1e-6), 1.0); + verify(c.nearest((1.1, 1.1).into(), 1e-6), 1.0); + verify(c.nearest((-0.1, 0.0).into(), 1e-6), 0.0); + let a = Affine::rotate(0.5); + verify((a * c).nearest(a * Point::new(0.1, 0.001), 1e-6), 0.1); + + // Here's a case that tripped up the old solver because the start is close to + // degenerate and the end is actually degenerate; see #446. + let curve = CubicBez::new( + (461.0, 123.0), + (460.99999999999994, 123.00000000000004), + (111.0, 319.0), + (111.0, 319.0), + ); + let p = Point::new(282.0379003395483, 223.21877580985594); + let eps = 0.0005; + let nearest = curve.nearest(p, eps); + let q = curve.eval(nearest.t); + let r = curve.eval(0.5075474297354187); + + assert!((q - p).hypot() <= (r - p).hypot() + eps); + } + + // ensure to_quads returns something given collinear points + #[test] + fn degenerate_to_quads() { + let c = CubicBez::new((0., 9.), (6., 6.), (12., 3.0), (18., 0.0)); + let quads = c.to_quads(1e-6).collect::>(); + assert_eq!(quads.len(), 1, "{:?}", &quads); + } + + #[test] + fn cubicbez_extrema() { + // y = x^2 + let q = CubicBez::new((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 1); + assert!((extrema[0] - 0.5).abs() < 1e-6); + + let q = CubicBez::new((0.4, 0.5), (0.0, 1.0), (1.0, 0.0), (0.5, 0.4)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 4); + } + + #[test] + fn cubicbez_toquads() { + // y = x^3 + let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); + for i in 0..10 { + let accuracy = 0.1f64.powi(i); + let mut worst: f64 = 0.0; + for (t0, t1, q) in c.to_quads(accuracy) { + let epsilon = 1e-12; + assert!((q.start() - c.eval(t0)).hypot() < epsilon); + assert!((q.end() - c.eval(t1)).hypot() < epsilon); + let n = 4; + for j in 0..=n { + let t = (j as f64) * (n as f64).recip(); + let p = q.eval(t); + let err = (p.y - p.x.powi(3)).abs(); + worst = worst.max(err); + assert!(err < accuracy, "got {err} wanted {accuracy}"); + } + } + } + } + + #[test] + fn cubicbez_approx_spline() { + let c1 = CubicBez::new( + (550.0, 258.0), + (1044.0, 482.0), + (2029.0, 1841.0), + (1934.0, 1554.0), + ); + + let quad = c1.try_approx_quadratic(344.0); + let expected = QuadBez::new( + Point::new(550.0, 258.0), + Point::new(1673.665720592873, 767.5164401068898), + Point::new(1934.0, 1554.0), + ); + assert!(quad.is_some()); + assert_eq!(quad.unwrap(), expected); + + let quad = c1.try_approx_quadratic(343.0); + assert!(quad.is_none()); + + let spline = c1.approx_spline_n(2, 343.0); + assert!(spline.is_some()); + let spline = spline.unwrap(); + let expected = [ + Point::new(550.0, 258.0), + Point::new(920.5, 426.0), + Point::new(2005.25, 1769.25), + Point::new(1934.0, 1554.0), + ]; + assert_eq!(spline.points().len(), expected.len()); + for (got, &wanted) in spline.points().iter().zip(expected.iter()) { + assert!(got.distance(wanted) < 5.0); + } + + let spline = c1.approx_spline(5.0); + let expected = [ + Point::new(550.0, 258.0), + Point::new(673.5, 314.0), + Point::new(984.8777777777776, 584.2666666666667), + Point::new(1312.6305555555557, 927.825), + Point::new(1613.1194444444443, 1267.425), + Point::new(1842.7055555555555, 1525.8166666666666), + Point::new(1957.75, 1625.75), + Point::new(1934.0, 1554.0), + ]; + assert!(spline.is_some()); + let spline = spline.unwrap(); + assert_eq!(spline.points().len(), expected.len()); + for (got, &wanted) in spline.points().iter().zip(expected.iter()) { + assert!(got.distance(wanted) < 5.0); + } + } + + #[test] + fn cubicbez_cubics_to_quadratic_splines() { + let curves = vec![ + CubicBez::new( + (550.0, 258.0), + (1044.0, 482.0), + (2029.0, 1841.0), + (1934.0, 1554.0), + ), + CubicBez::new( + (859.0, 384.0), + (1998.0, 116.0), + (1596.0, 1772.0), + (8.0, 1824.0), + ), + CubicBez::new( + (1090.0, 937.0), + (418.0, 1300.0), + (125.0, 91.0), + (104.0, 37.0), + ), + ]; + let converted = cubics_to_quadratic_splines(&curves, 5.0); + assert!(converted.is_some()); + let converted = converted.unwrap(); + assert_eq!(converted[0].points().len(), 8); + assert_eq!(converted[1].points().len(), 8); + assert_eq!(converted[2].points().len(), 8); + assert!(converted[0].points()[1].distance(Point::new(673.5, 314.0)) < 0.0001); + assert!( + converted[0].points()[2].distance(Point::new(88639.0 / 90.0, 52584.0 / 90.0)) < 0.0001 + ); + } + + #[test] + fn cubicbez_approx_spline_div_exact() { + // Ensure rounding behavior for division matches fonttools + // cu2qu. + // See + let cubic = CubicBez::new( + Point::new(408.0, 321.0), + Point::new(408.0, 452.0), + Point::new(342.0, 560.0), + Point::new(260.0, 560.0), + ); + let spline = cubic.approx_spline(1.0).unwrap(); + assert_eq!( + spline.points(), + &[ + Point::new(408.0, 321.0), + // Previous behavior produced 386.49999999999994 for the + // y coordinate leading to inconsistent rounding. + Point::new(408.0, 386.5), + Point::new(368.16666666666663, 495.0833333333333), + Point::new(301.0, 560.0), + Point::new(260.0, 560.0) + ] + ); + } + + #[test] + fn cubicbez_inflections() { + let c = CubicBez::new((0., 0.), (0.8, 1.), (0.2, 1.), (1., 0.)); + let inflections = c.inflections(); + assert_eq!(inflections.len(), 2); + assert!((inflections[0] - 0.311018).abs() < 1e-6); + assert!((inflections[1] - 0.688982).abs() < 1e-6); + let c = CubicBez::new((0., 0.), (1., 1.), (2., -1.), (3., 0.)); + let inflections = c.inflections(); + assert_eq!(inflections.len(), 1); + assert!((inflections[0] - 0.5).abs() < 1e-6); + let c = CubicBez::new((0., 0.), (1., 1.), (2., 1.), (3., 0.)); + let inflections = c.inflections(); + assert_eq!(inflections.len(), 0); + } + + #[test] + fn cubic_to_quadratic_matches_python() { + // from https://github.com/googlefonts/fontmake-rs/issues/217 + let cubic = CubicBez { + p0: (796.0, 319.0).into(), + p1: (727.0, 314.0).into(), + p2: (242.0, 303.0).into(), + p3: (106.0, 303.0).into(), + }; + + // FontTools can approximate this curve successfully in 7 splits, we can too + assert!(cubic.approx_spline_n(7, 1.0).is_some()); + + // FontTools can solve this with accuracy 0.001, we can too + assert!(cubics_to_quadratic_splines(&[cubic], 0.001).is_some()); + } + + #[test] + fn cubic_to_quadratic_all_points_equal() { + let pt = Point::new(5.0, 5.0); + let cubic = CubicBez::new(pt, pt, pt, pt); + let quads = cubics_to_quadratic_splines(&[cubic], 0.1).unwrap(); + assert_eq!(quads, [QuadSpline::new(vec![pt, pt, pt])]); + } + + #[test] + fn cubic_to_quadratic_3_points_equal_single_quad_within_tolerance() { + let p0 = Point::new(5.0, 5.0); + let p1 = Point::new(5.0, 5.1); + let cubic = CubicBez::new(p0, p0, p0, p1); + let quads = cubics_to_quadratic_splines(&[cubic], 0.1).unwrap(); + // a single quadratic bezier approximates this cubic for the given tolerance + assert_eq!(quads, [QuadSpline::new(vec![p0, p0, p1])]); + } + + #[test] + fn cubic_to_quadratic_3_points_equal_exceeding_tolerance() { + let p0 = Point::new(5.0, 5.0); + let p1 = Point::new(5.0, 5.1); + let cubic = CubicBez::new(p0, p0, p0, p1); + let quads = cubics_to_quadratic_splines(&[cubic], 0.01).unwrap(); + // 2 quadratic off-curves are required to approximate the same cubic + // given the smaller tolerance + assert_eq!( + quads, + [QuadSpline::new(vec![p0, p0, (5.0, 5.025).into(), p1])] + ); + } + + #[test] + fn cubics_to_quadratic_splines_matches_python() { + // https://github.com/linebender/kurbo/pull/273 + let light = CubicBez::new((378., 608.), (378., 524.), (355., 455.), (266., 455.)); + let regular = CubicBez::new((367., 607.), (367., 511.), (338., 472.), (243., 472.)); + let bold = CubicBez::new( + (372.425, 593.05), + (372.425, 524.95), + (355.05, 485.95), + (274., 485.95), + ); + let qsplines = cubics_to_quadratic_splines(&[light, regular, bold], 1.0).unwrap(); + assert_eq!( + qsplines, + [ + QuadSpline::new(vec![ + (378.0, 608.0).into(), + (378.0, 566.0).into(), + (359.0833333333333, 496.5).into(), + (310.5, 455.0).into(), + (266.0, 455.0).into(), + ]), + QuadSpline::new(vec![ + (367.0, 607.0).into(), + (367.0, 559.0).into(), + // Previous behavior produced 496.5 for the y coordinate + (344.5833333333333, 499.49999999999994).into(), + (290.5, 472.0).into(), + (243.0, 472.0).into(), + ]), + QuadSpline::new(vec![ + (372.425, 593.05).into(), + (372.425, 559.0).into(), + (356.98333333333335, 511.125).into(), + (314.525, 485.95).into(), + (274.0, 485.95).into(), + ]), + ] + ); + } +} diff --git a/vendor/kurbo/src/ellipse.rs b/vendor/kurbo/src/ellipse.rs new file mode 100644 index 0000000000..7eea2b4906 --- /dev/null +++ b/vendor/kurbo/src/ellipse.rs @@ -0,0 +1,554 @@ +// Copyright 2020 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Implementation of ellipse shape. + +use core::f64::consts::PI; +use core::{ + iter, + ops::{Add, Mul, Sub}, +}; + +use crate::{Affine, Arc, ArcAppendIter, Circle, PathEl, Point, Rect, Shape, Size, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// An ellipse. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Ellipse { + /// All ellipses can be represented as an affine map of the unit circle, + /// centred at (0, 0). Therefore we can store the ellipse as an affine map, + /// with the implication that it be applied to the unit circle to recover the + /// actual shape. + inner: Affine, +} + +impl Ellipse { + /// Create A new ellipse with a given center, radii, and rotation. + /// + /// The returned ellipse will be the result of taking a circle, stretching + /// it by the `radii` along the x and y axes, then rotating it from the + /// x axis by `rotation` radians, before finally translating the center + /// to `center`. + /// + /// Rotation is clockwise in a y-down coordinate system. For more on + /// rotation, see [`Affine::rotate`]. + #[inline] + pub fn new(center: impl Into, radii: impl Into, x_rotation: f64) -> Ellipse { + let Point { x: cx, y: cy } = center.into(); + let Vec2 { x: rx, y: ry } = radii.into(); + Ellipse::private_new(Vec2 { x: cx, y: cy }, rx, ry, x_rotation) + } + + /// Returns the largest ellipse that can be bounded by this [`Rect`]. + /// + /// This uses the absolute width and height of the rectangle. + /// + /// This ellipse is always axis-aligned; to apply rotation you can call + /// [`with_rotation`] with the result. + /// + /// [`with_rotation`]: Ellipse::with_rotation + #[inline] + pub fn from_rect(rect: Rect) -> Self { + let center = rect.center().to_vec2(); + let Size { width, height } = rect.size() / 2.0; + Ellipse::private_new(center, width, height, 0.0) + } + + /// Create an ellipse from an affine transformation of the unit circle. + #[inline(always)] + pub const fn from_affine(affine: Affine) -> Self { + Ellipse { inner: affine } + } + + /// Create a new `Ellipse` centered on the provided point. + #[inline] + #[must_use] + pub fn with_center(self, new_center: impl Into) -> Ellipse { + let Point { x: cx, y: cy } = new_center.into(); + Ellipse { + inner: self.inner.with_translation(Vec2 { x: cx, y: cy }), + } + } + + /// Create a new `Ellipse` with the provided radii. + #[inline] + #[must_use] + pub fn with_radii(self, new_radii: Vec2) -> Ellipse { + let rotation = self.inner.svd().1; + let translation = self.inner.translation(); + Ellipse::private_new(translation, new_radii.x, new_radii.y, rotation) + } + + /// Create a new `Ellipse`, with the rotation replaced by `rotation` + /// radians. + /// + /// The rotation is clockwise, for a y-down coordinate system. For more + /// on rotation, See [`Affine::rotate`]. + #[inline] + #[must_use] + pub fn with_rotation(self, rotation: f64) -> Ellipse { + let scale = self.inner.svd().0; + let translation = self.inner.translation(); + Ellipse::private_new(translation, scale.x, scale.y, rotation) + } + + /// This gives us an internal method without any type conversions. + #[inline] + fn private_new(center: Vec2, scale_x: f64, scale_y: f64, x_rotation: f64) -> Ellipse { + // Since the circle is symmetric about the x and y axes, using absolute values for the + // radii results in the same ellipse. For simplicity we make this change here. + Ellipse { + inner: Affine::translate(center) + * Affine::rotate(x_rotation) + * Affine::scale_non_uniform(scale_x.abs(), scale_y.abs()), + } + } + + // Getters and setters. + + /// Returns the center of this ellipse. + #[inline(always)] + pub fn center(&self) -> Point { + self.inner.translation().to_point() + } + + /// Returns the two radii of this ellipse. + /// + /// The first number is the horizontal radius and the second is the vertical + /// radius, before rotation. + /// + /// If you are only interested in the value of the greatest or smallest radius of this ellipse, + /// consider using [`Ellipse::major_radius`] or [`Ellipse::minor_radius`] instead. + #[inline] + pub fn radii(&self) -> Vec2 { + self.inner.svd().0 + } + + /// Returns the major radius of this ellipse. + /// + /// This metric is also known as the semi-major axis. + #[inline] + pub fn major_radius(&self) -> f64 { + self.inner.svd().0.x + } + + /// Returns the minor radius of this ellipse. + /// + /// This metric is also known as the semi-minor axis. + #[inline] + pub fn minor_radius(&self) -> f64 { + self.inner.svd().0.y + } + + /// The ellipse's rotation, in radians. + /// + /// This allows all possible ellipses to be drawn by always starting with + /// an ellipse with the two radii on the x and y axes. + #[inline] + pub fn rotation(&self) -> f64 { + self.inner.svd().1 + } + + /// Returns the radii and the rotation of this ellipse. + /// + /// Equivalent to `(self.radii(), self.rotation())` but more efficient. + #[inline] + pub fn radii_and_rotation(&self) -> (Vec2, f64) { + self.inner.svd() + } + + /// Is this ellipse [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.inner.is_finite() + } + + /// Is this ellipse [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.inner.is_nan() + } +} + +impl Add for Ellipse { + type Output = Ellipse; + + /// In this context adding a `Vec2` applies the corresponding translation to the ellipse. + #[inline] + #[allow(clippy::suspicious_arithmetic_impl)] + fn add(self, v: Vec2) -> Ellipse { + Ellipse { + inner: Affine::translate(v) * self.inner, + } + } +} + +impl Sub for Ellipse { + type Output = Ellipse; + + /// In this context subtracting a `Vec2` applies the corresponding translation to the ellipse. + #[inline] + fn sub(self, v: Vec2) -> Ellipse { + Ellipse { + inner: Affine::translate(-v) * self.inner, + } + } +} + +impl Mul for Affine { + type Output = Ellipse; + #[inline] + fn mul(self, other: Ellipse) -> Self::Output { + Ellipse { + inner: self * other.inner, + } + } +} + +impl From for Ellipse { + #[inline] + fn from(circle: Circle) -> Self { + Ellipse::new(circle.center, Vec2::splat(circle.radius), 0.0) + } +} + +impl Shape for Ellipse { + type PathElementsIter<'iter> = iter::Chain, ArcAppendIter>; + + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> { + let (radii, x_rotation) = self.inner.svd(); + Arc { + center: self.center(), + radii, + start_angle: 0.0, + sweep_angle: 2.0 * PI, + x_rotation, + } + .path_elements(tolerance) + } + + /// The area of the ellipse. + /// + /// This is always positive if the result is finite. + /// + /// If non-finite, this will be [`f64::INFINITY`] or [`f64::NAN`] depending on whether the + /// inner affine's [determinant](Affine::determinant) is [`f64::INFINITY`] (either positive or + /// negative) or [`f64::NAN`]. + #[inline] + fn area(&self) -> f64 { + // `Ellipse` is represented as a unit circle transformed by `Affine`. The transformed area + // of a region is `area * |det(affine)|`, see + // . + // + // A unit circle has area `PI`. Therefore, the area of this ellipse is PI multiplied by the + // affine's determinant. + PI * self.inner.determinant().abs() + } + + /// Approximate the ellipse perimeter. + /// + /// This uses a numerical approximation. The absolute error between the calculated perimeter + /// and the true perimeter is bounded by `accuracy` (modulo floating point rounding errors). + /// + /// For circular ellipses (equal horizontal and vertical radii), the calculated perimeter is + /// exact. + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + let radii = self.radii(); + + // Note: the radii are calculated from an inner affine map (`self.inner`), and may be NaN. + // Currently, constructing an ellipse with infinite radii will produce an ellipse whose + // calculated radii are NaN. + if !radii.is_finite() { + return f64::NAN; + } + + // Check for the trivial case where the ellipse has one of its radii equal to 0, i.e., + // where it describes a line, as the numerical method used breaks down with this extreme. + if radii.x == 0. || radii.y == 0. { + return 4. * f64::max(radii.x, radii.y); + } + + // Evaluate an approximation based on a truncated infinite series. If it returns a good + // enough value, we do not need to iterate. + if kummer_elliptic_perimeter_range(radii) <= accuracy { + return kummer_elliptic_perimeter(radii); + } + + agm_elliptic_perimeter(accuracy, radii) + } + + #[inline] + fn winding(&self, pt: Point) -> i32 { + // Strategy here is to apply the inverse map to the point and see if it is in the unit + // circle. + let inv = self.inner.inverse(); + if (inv * pt).to_vec2().hypot2() < 1.0 { + 1 + } else { + 0 + } + } + + // Compute a tight bounding box of the ellipse. + // + // See https://www.iquilezles.org/www/articles/ellipses/ellipses.htm. We can get the two + // radius vectors by applying the affine map to the two impulses (1, 0) and (0, 1) which gives + // (a, b) and (c, d) if the affine map is + // + // a | c | e + // ----------- + // b | d | f + // + // We can then use the method in the link with the translation to get the bounding box. + #[inline] + fn bounding_box(&self) -> Rect { + let aff = self.inner.as_coeffs(); + let a2 = aff[0] * aff[0]; + let b2 = aff[1] * aff[1]; + let c2 = aff[2] * aff[2]; + let d2 = aff[3] * aff[3]; + let cx = aff[4]; + let cy = aff[5]; + let range_x = (a2 + c2).sqrt(); + let range_y = (b2 + d2).sqrt(); + Rect { + x0: cx - range_x, + y0: cy - range_y, + x1: cx + range_x, + y1: cy + range_y, + } + } +} + +/// Calculates circumference C of an ellipse with radii (x, y) as the infinite series +/// +/// C = pi (x+y) * ∑ binom(1/2, n)^2 * h^n from n = 0 to inf +/// with h = (x - y)^2 / (x + y)^2 +/// and binom(.,.) the binomial coefficient +/// +/// as described by Kummer ("Über die Hypergeometrische Reihe", 1837) and rediscovered by +/// Linderholm and Segal ("An Overlooked Series for the Elliptic Perimeter", 1995). +/// +/// The series converges very quickly for ellipses with only moderate eccentricity (`h` not close +/// to 1). +/// +/// The series is truncated to the sixth power, meaning a lower bound on the true value is +/// returned. Adding the value of [`kummer_elliptic_perimeter_range`] to the value returned by this +/// function calculates an upper bound on the true value. +#[inline] +fn kummer_elliptic_perimeter(radii: Vec2) -> f64 { + let Vec2 { x, y } = radii; + let h = ((x - y) / (x + y)).powi(2); + let h2 = h * h; + let h3 = h2 * h; + let h4 = h3 * h; + let h5 = h4 * h; + let h6 = h5 * h; + + let lower = PI + + h * (PI / 4.) + + h2 * (PI / 64.) + + h3 * (PI / 256.) + + h4 * (PI * 25. / 16384.) + + h5 * (PI * 49. / 65536.) + + h6 * (PI * 441. / 1048576.); + + (x + y) * lower +} + +/// This calculates the error range of [`kummer_elliptic_perimeter`]. That function returns a lower +/// bound on the true value, and though we do not know what the remainder of the infinite series +/// sums to, we can calculate an upper bound: +/// +/// ∑ binom(1/2, n)^2 for n = 0 to inf +/// = 1 + (1 / 2!!)^2 + (1!! / 4!!)^2 + (3!! / 6!!)^2 + (5!! / 8!!)^2 + .. +/// = 4 / pi +/// with !! the double factorial +/// (equation 274 in "Summation of Series", L. B. W. Jolley, 1961). +/// +/// This means the remainder of the infinite series for C, assuming the series was truncated to the +/// mth term and h = 1, sums to +/// 4 / pi - ∑ binom(1/2, n)^2 for n = 0 to m-1 +/// +/// As 0 ≤ h ≤ 1, this is an upper bound. +#[inline] +fn kummer_elliptic_perimeter_range(radii: Vec2) -> f64 { + let Vec2 { x, y } = radii; + let h = ((x - y) / (x + y)).powi(2); + + const BINOM_SQUARED_REMAINDER: f64 = 0.00101416479131503; + // = 4. / PI - (1. + 1. / 4. + 1. / 64. + 1. / 256. + 25. / 16384. + 49. / 65536. + 441. / 1048576.) + + PI * BINOM_SQUARED_REMAINDER * h.powi(7) * (x + y) +} + +/// Calculates circumference C of an ellipse with radii (x, y) using the arithmetic-geometric mean, +/// as described in equation 19.8.6 of +/// . +fn agm_elliptic_perimeter(accuracy: f64, radii: Vec2) -> f64 { + let Vec2 { x, y } = if radii.x >= radii.y { + radii + } else { + Vec2::new(radii.y, radii.x) + }; + + let accuracy = accuracy / (2. * PI * x); + + let mut sum = 1.; + let mut a = 1.; + let mut g = y / x; + let mut c = (1. - g.powi(2)).sqrt(); + let mut mul = 0.5; + + loop { + let c2 = c.powi(2); + // term = 2^(n-1) c_n^2 + let term = mul * c2; + sum -= term; + + // We have c_(n+1) ≤ 1/2 c_n + // (for a derivation, see e.g. section 2.1 of "Elliptic integrals, the + // arithmetic-geometric mean and the Brent-Salamin algorithm for π" by G.J.O. Jameson: + // ) + // + // Therefore + // ∑ 2^(i-1) c_i^2 from i = 1 ≤ ∑ 2^(i-1) ((1/2)^i c_0)^2 from i = 1 + // = ∑ 2^-(i+1) c_0^2 from i = 1 + // = 1/2 c_0^2 + // + // or, for arbitrary starting point i = n+1: + // ∑ 2^(i-1) c_i^2 from i = n+1 ≤ ∑ 2^(i-1) ((1/2)^(i-n) c_n)^2 from i = n+1 + // = ∑ 2^(2n - i - 1) c_n^2 from i = n+1 + // = 2^(2n) ∑ 2^(-(i+1)) c_n^2 from i = n+1 + // = 2^(2n) 2^(-(n+1)) c_n^2 + // = 2^(n-1) c_n^2 + // + // Therefore, the remainder of the series sums to less than or equal to 2^(n-1) c_n^2, + // which is exactly the value of the nth term. + // + // Furthermore, a_m ≥ g_n, and g_n ≤ 1, for all m, n. + if term <= accuracy * g { + // `sum` currently overestimates the true value - subtract the upper bound of the + // remaining series. We will then underestimate the true value, but by no more than + // `accuracy`. + sum -= term; + break; + } + + mul *= 2.; + // This is equal to c_next = c^2 / (4 * a_next) + c = (a - g) / 2.; + let a_next = (a + g) / 2.; + g = (a * g).sqrt(); + a = a_next; + } + + 2. * PI * x / a * sum +} + +#[cfg(test)] +mod tests { + use crate::{Circle, Ellipse, Point, Shape}; + use std::f64::consts::PI; + + fn assert_approx_eq(x: f64, y: f64) { + // Note: we might want to be more rigorous in testing the accuracy + // of the conversion into Béziers. But this seems good enough. + assert!((x - y).abs() < 1e-7, "{x} != {y}"); + } + + #[test] + fn circular_perimeter() { + for radius in [1.0, 0., 1.5, PI, 10.0, -1.0, 1_234_567_890.1] { + let circle = Circle::new((0., 0.), radius); + let ellipse = Ellipse::new((0., 0.), (radius, radius), 0.); + + let circle_p = circle.perimeter(0.); + let ellipse_p = ellipse.perimeter(0.1); + + // We expect the results to be identical, modulo potential roundoff errors. Compare + // with a very small relative epsilon. + let epsilon = f64::EPSILON * 8. * circle_p.max(ellipse_p); + assert!( + (circle_p - ellipse_p).abs() <= epsilon, + "Expected circular ellipse radius {ellipse_p} to be equal to circle radius {circle_p} for radius {radius}" + ); + } + } + + #[test] + fn compare_perimeter_with_bez() { + const EPSILON: f64 = 0.000_002; + + for radii in [ + (0.5, 1.), + (2., 1.), + (0.000_000_1, 1.), + (0., 1.), + (1., 0.), + (-0.5, 1.), + (-0.000_000_1, -1.), + ] { + let ellipse = Ellipse::new((0., 0.), radii, 0.); + + let ellipse_p = ellipse.perimeter(0.000_001); + let bez_p = ellipse.path_segments(0.000_000_25).perimeter(0.000_000_25); + + assert!( + (ellipse_p - bez_p).abs() < EPSILON, + "Numerically approximated ellipse perimeter ({ellipse_p}) does not match bezier segment perimeter length ({bez_p}) for radii {radii:?}" + ); + } + } + + #[test] + fn known_perimeter() { + const ACCURACY: f64 = 0.000_000_000_001; + + for (radii, perimeter) in [ + ((0.5, 1.), 4.844_224_110_273_838), + ((0.001, 1.), 4.000_015_588_104_688), + ] { + let ellipse = Ellipse::new((0., 0.), radii, 0.); + + let ellipse_p = ellipse.perimeter(ACCURACY); + assert!( + (ellipse_p - perimeter).abs() <= ACCURACY, + "Numerically approximated ellipse perimeter ({ellipse_p}) does not match known perimeter ({perimeter}) radii {radii:?}" + ); + } + } + + #[test] + fn area_sign() { + let center = Point::new(5.0, 5.0); + let e = Ellipse::new(center, (5.0, 5.0), 1.0); + assert_approx_eq(e.area(), 25.0 * PI); + let e = Ellipse::new(center, (5.0, 10.0), 1.0); + assert_approx_eq(e.area(), 50.0 * PI); + + assert_eq!(e.winding(center), 1); + + let p = e.to_path(1e-9); + assert_approx_eq(e.area(), p.area()); + assert_eq!(e.winding(center), p.winding(center)); + + let e_neg_radius = Ellipse::new(center, (-5.0, 10.0), 1.0); + assert_approx_eq(e_neg_radius.area(), 50.0 * PI); + + assert_eq!(e_neg_radius.winding(center), 1); + + let p_neg_radius = e_neg_radius.to_path(1e-9); + assert_approx_eq(e_neg_radius.area(), p_neg_radius.area()); + assert_eq!(e_neg_radius.winding(center), p_neg_radius.winding(center)); + } +} diff --git a/vendor/kurbo/src/expand.rs b/vendor/kurbo/src/expand.rs new file mode 100644 index 0000000000..284d7f1c7c --- /dev/null +++ b/vendor/kurbo/src/expand.rs @@ -0,0 +1,604 @@ +// Copyright 2026 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use crate::{ + Affine, Arc, BezPath, CubicBez, Join, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Point, + QuadBez, Shape, Vec2, bezpath::close_subpaths, segments, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A diagonal matrix, suitable for representing anisotropic scaling. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Diagonal2 { + /// The horizontal expansion factor. + pub xx: f64, + /// The vertical expansion factor. + pub yy: f64, +} + +struct ExpandCtx { + expand: Diagonal2, + join: Join, + miter_limit: f64, + tolerance: f64, + result: BezPath, + first_n: Option, + first_tan: Vec2, + last_pt: Point, + last_n: Option, + last_tan: Vec2, +} + +struct CubicCtx { + q: QuadBez, + utan0: Vec2, + utan1: Vec2, +} + +struct TwoPointSample { + a_n: f64, + b_n: f64, + c_n: f64, +} + +impl Diagonal2 { + /// Create a diagonal matrix. + pub const fn new(xx: f64, yy: f64) -> Self { + Self { xx, yy } + } + + /// Matrix inverse. + /// + /// Will of course produce infinities if a component is zero. + pub const fn inv(self) -> Self { + Diagonal2::new(1.0 / self.xx, 1.0 / self.yy) + } + + /// Absolute value of transform components. + pub const fn abs(self) -> Self { + Self::new(self.xx.abs(), self.yy.abs()) + } + + /// Scale a normal vector. + /// + /// This is mathematically equivalent to `self * (self * n).normalize()` + /// for positive transforms, but handles zeros and gets the sign correct + /// when negative. + /// + /// Note that `n` need not be unit length. + pub fn scale_normal(self, n: Vec2) -> Vec2 { + let z = self * n; + let z_hypot2 = z.hypot2(); + if z_hypot2 == 0.0 { + Vec2::ZERO + } else { + let inv_scale = 1.0 / z_hypot2.sqrt(); + self.abs() * z * inv_scale + } + } +} + +impl core::ops::Neg for Diagonal2 { + type Output = Self; + + fn neg(self) -> Self { + Diagonal2::new(-self.xx, -self.yy) + } +} + +impl core::ops::Mul for Diagonal2 { + type Output = Vec2; + + fn mul(self, rhs: Vec2) -> Vec2 { + Vec2::new(self.xx * rhs.x, self.yy * rhs.y) + } +} + +impl core::ops::Mul for Diagonal2 { + type Output = Point; + + fn mul(self, rhs: Point) -> Point { + Point::new(self.xx * rhs.x, self.yy * rhs.y) + } +} + +// Note: a bunch more ops on `Diagonal2` could be implemented, but for now we'll stick to what we need. + +/// Expand a path. +/// +/// Expands a filled path by the expansion, which allows separate x and y factors. The +/// path (and the result) is interpreted according to the nonzero winding rule. Both +/// factors should be positive. A negative expansion will shrink the path but is also +/// likely to leave intersection artifacts at corners. +/// +/// The direction of the expansion is based on the signed area of the overall path. +/// This should give expected results most of the time, but there are exceptions. For a +/// figure-eight path, one lobe will be expanded and the other shrunk. Similarly if +/// there are two disjoint subpaths with opposite winding. +/// +/// The tolerance is mostly for joins and robustness; it is not used to guide +/// subdivision. Rather, each Bézier segment in the input generally results in one +/// cubic Bézier in the output. Thus, it is not expected to work well when the +/// expansion factor is large compared with the radius of curvature on the input. +pub fn expand_path( + path: impl Shape, + mut expand: Diagonal2, + join: Join, + miter_limit: f64, + tolerance: f64, +) -> BezPath { + if segments(close_subpaths(path.path_elements(tolerance))).area() >= 0.0 { + expand = -expand; + } + expand_path_signed(path, expand, join, miter_limit, tolerance) +} + +/// Expand a path when the sign is known. +/// +/// Applies the expansion based on the path orientation, so that expansion happens +/// with positive `expand` values on subpaths with negative area, or vice versa. This +/// is backwards from the intuitive sign convention, but results from the choice of +/// convention for the offset primitives. +pub fn expand_path_signed( + path: impl Shape, + expand: Diagonal2, + join: Join, + miter_limit: f64, + tolerance: f64, +) -> BezPath { + let result = BezPath::new(); + let mut ctx = ExpandCtx { + expand, + join, + miter_limit, + tolerance, + result, + first_n: None, + first_tan: Vec2::default(), + last_pt: Point::default(), + last_n: None, + last_tan: Vec2::default(), + }; + let mut first_pt = Point::default(); + for el in path.path_elements(tolerance) { + match el { + PathEl::MoveTo(point) => { + ctx.do_close_path(first_pt); + first_pt = point; + ctx.last_pt = point; + } + PathEl::LineTo(p1) => ctx.do_line(p1), + PathEl::QuadTo(p1, p2) => ctx.do_quad(p1, p2), + PathEl::CurveTo(p1, p2, p3) => ctx.do_cubic(p1, p2, p3), + PathEl::ClosePath => ctx.do_close_path(first_pt), + } + } + // Treat all subpaths as closed; close if left open in input. + ctx.do_close_path(first_pt); + ctx.result +} + +impl ExpandCtx { + /// Helper function to determine if a distance is within tolerance. + fn in_tolerance(&self, v: Vec2) -> bool { + v.hypot2() < self.tolerance * self.tolerance + } + + /// Process a line segment. Includes initial join. + fn do_line(&mut self, p1: Point) { + if p1 == self.last_pt { + return; + } + let tan = p1 - self.last_pt; + let n = self.expand.scale_normal(tan.turn_90()); + self.do_join(n, tan, true); + let out_p1 = p1 + n; + self.result.line_to(out_p1); + self.last_n = Some(n); + self.last_tan = tan; + self.last_pt = p1; + } + + /// Process a quadratic Bézier segment. Includes initial join. + fn do_quad(&mut self, p1: Point, p2: Point) { + let q0 = p1 - self.last_pt; + let q1 = p2 - p1; + if self.in_tolerance(q0) || self.in_tolerance(q1) { + self.do_line(p2); + return; + } + let einv = self.expand.inv(); + let utan0 = (einv * q0).normalize(); + let utan1 = (einv * q1).normalize(); + let det = utan1.cross(utan0); + if det.abs() < 1e-10 { + self.do_line(p2); + return; + } + let utanm = (einv * (p2 - self.last_pt)).normalize(); + let n0 = self.expand.abs() * utan0.turn_90(); + let n1 = self.expand.abs() * utan1.turn_90(); + let mid_chord = self.last_pt.midpoint(p2); + let m = mid_chord.midpoint(p1) + self.expand.abs() * utanm.turn_90(); + let out_p0 = self.last_pt + n0; + let out_p3 = p2 + n1; + let rhs = einv * (m - out_p0.midpoint(out_p3)); + let idet = (8. / 3.) / det; + let a = (utan1.cross(rhs) * idet).max(0.0); + let b = (utan0.cross(rhs) * idet).max(0.0); + self.do_join(n0, q0, false); + let out_p1 = out_p0 + self.expand * (a * utan0); + let out_p2 = out_p3 - self.expand * (b * utan1); + self.result.curve_to(out_p1, out_p2, out_p3); + self.last_n = Some(n1); + self.last_tan = q1; + self.last_pt = p2; + } + + /// Process a cubic segment. Includes initial join. + fn do_cubic(&mut self, p1: Point, p2: Point, p3: Point) { + let einv = self.expand.inv(); + let c = CubicBez::new(einv * self.last_pt, einv * p1, einv * p2, einv * p3); + let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + let utan0 = tan0.normalize(); + let utan1 = tan1.normalize(); + let q = c.deriv(); + let p1xp0 = q.p1.to_vec2().cross(q.p0.to_vec2()); + let p2xp1 = q.p2.to_vec2().cross(q.p1.to_vec2()); + let cx = CubicCtx { q, utan0, utan1 }; + // First we try one-point, but only if there isn't one inflection point. + let mut soln = if p1xp0 * p2xp1 >= 0.0 { + try_one_point(&cx) + } else { + None + }; + if soln.is_none() { + // We try two-point linear if we don't have a one-point solution. A + // more sophisticated approach would be to evaluate error and pick a + // minimum, but that would be more complexity and take time. This is + // very likely good enough for the purpose. + soln = two_point_linear(&cx); + } + if let Some((a, b)) = soln { + let n0 = self.expand.abs() * utan0.turn_90(); + let n1 = self.expand.abs() * utan1.turn_90(); + self.do_join(n0, self.expand * utan0, false); + let out_p3 = p3 + n1; + // TODO: clamp to correct direction + let out_p1 = p1 + n0 + self.expand.abs() * (a * utan0); + let out_p2 = p2 + n1 + self.expand.abs() * (b * utan1); + self.result.curve_to(out_p1, out_p2, out_p3); + self.last_n = Some(n1); + self.last_tan = self.expand * utan1; + self.last_pt = p3; + } else { + self.do_line(p3); + } + } + + /// Do a join. + /// + /// The `tan` parameter is a vector tangent to the start of the new segment. + /// The `n` parameter is the normal vector (turned tangent) scaled by the expansion. + fn do_join(&mut self, n: Vec2, tan: Vec2, is_line: bool) { + // TODO: other join types etc + if let Some(last_n) = self.last_n { + let p = self.last_pt + n; + if !self.in_tolerance(n - last_n) { + if self.join != Join::Bevel { + let cross = self.last_tan.cross(tan); + if cross * self.expand.xx < 0.0 { + match self.join { + Join::Bevel => unreachable!(), + Join::Miter => { + let dot = self.last_tan.dot(tan); + let hypot = cross.hypot(dot); + if 2.0 * hypot < (hypot + dot) * self.miter_limit * self.miter_limit + { + let h = (n - last_n).cross(tan) / self.last_tan.cross(tan); + let miter_pt = self.last_pt + last_n + h * self.last_tan; + // A cheap optimization to reduce line segments with joins to lines + if let Some(PathEl::LineTo(p)) = + self.result.elements_mut().last_mut() + { + *p = miter_pt; + } else { + self.result.line_to(miter_pt); + } + if is_line { + return; + } + } + } + Join::Round => { + // Cheaper inverse; everything is normalized so we don't care about uniform scaling. + let einv = Diagonal2::new(self.expand.yy, self.expand.xx); + let last_tann = einv * self.last_tan; + let tann = einv * tan; + let crossn = (last_tann).cross(tann); + let dotn = (last_tann).dot(tann); + let angle = crossn.atan2(dotn).abs(); + let nt = self.expand * tann.normalize(); + let a = Affine::new([ + n.x, + n.y, + nt.x, + nt.y, + self.last_pt.x, + self.last_pt.y, + ]); + let arc: Arc = + Arc::new(Point::ORIGIN, (1.0, 1.0), -angle, angle, 0.0); + let tolerance = self.tolerance / einv.xx.abs().max(einv.yy.abs()); + arc.to_cubic_beziers(tolerance, |p1, p2, p3| { + self.result.curve_to(a * p1, a * p2, a * p3); + }); + return; + } + } + } + } + // Bevel case + self.result.line_to(p); + } + } else { + self.result.move_to(self.last_pt + n); + self.first_n = Some(n); + self.first_tan = tan; + } + } + + /// Close an open subpath if there is one; no-op if already closed. + fn do_close_path(&mut self, first_pt: Point) { + if let Some(first_n) = self.first_n.take() { + // could do this test inside do_line for all lines, but it already checks for 0-length + if first_pt.distance_squared(self.last_pt) > self.tolerance * self.tolerance { + self.do_line(first_pt); + } + self.do_join(first_n, self.first_tan, true); + self.result.close_path(); + } + self.last_n = None; + } +} + +// Note: here is our own copy of sophisticated cubic Bézier offset logic. We have +// the ability to apply anisotropic expansion, but not cusp detection or subdivision, +// and I've also stripped out all the error evaluation. At some point, we want to +// redo stroking, and there may be an opportunity to share code. + +/// Try to compute one-point shape control for a cubic. +/// +/// Result is (a, b) parameters. +fn try_one_point(cx: &CubicCtx) -> Option<(f64, f64)> { + // TODO: possibly reduce duplication with quadratic case. + let tan = cx.q.eval(0.5).to_vec2(); + let tan_hypot2 = tan.hypot2(); + if tan_hypot2 < 1e-12 { + return None; + } + let utan = tan / tan_hypot2.sqrt(); + let z = (utan - 0.5 * (cx.utan0 + cx.utan1)).turn_90(); + let cross = cx.utan0.cross(cx.utan1); + if cross.abs() < 1e-12 { + return None; + } + let idet = (8. / 3.) / cross; + let a = z.cross(cx.utan1) * idet; + let b = cx.utan0.cross(z) * idet; + //let delta_tan = 0.75 * (b * cx.utan1 - a * cx.utan0) + 1.5 * (cx.utan1 - cx.utan0).turn_90(); + //let angle_err = delta_tan.cross(utan); + //let err_est = 0.16 * angle_err.abs(); + Some((a, b)) +} + +fn two_point_linear(cx: &CubicCtx) -> Option<(f64, f64)> { + const T0: f64 = 0.35; + let s = [T0, 1.0 - T0].map(|t| { + let utan = cx.q.eval(t).to_vec2().normalize(); + let n = utan.turn_90(); + let utan0_n = cx.utan0.dot(n); + let utan1_n = cx.utan1.dot(n); + let utan0xn = cx.utan0.dot(utan); + let utan1xn = cx.utan1.dot(utan); + let mt = 1.0 - t; + let b0 = mt * mt * mt; + let b1 = 3.0 * mt * t * mt; + let b2 = 3.0 * mt * t * t; + let b3 = t * t * t; + let a_n = b1 * utan0_n; + let b_n = b2 * utan1_n; + let c_n = (b0 + b1) * utan0xn + (b2 + b3) * utan1xn - 1.0; + TwoPointSample { a_n, b_n, c_n } + }); + let det = s[0].a_n * s[1].b_n - s[1].a_n * s[0].b_n; + // Consider both near-zero and NaN determinants to be failures. + if det.abs().partial_cmp(&1e-12) != Some(core::cmp::Ordering::Greater) { + return None; + } + let idet = -1.0 / det; + let a = idet * (s[0].c_n * s[1].b_n - s[1].c_n * s[0].b_n); + let b = idet * (s[0].a_n * s[1].c_n - s[1].a_n * s[0].c_n); + Some((a, b)) +} + +#[cfg(test)] +mod tests { + use std::f64::consts::PI; + + use crate::{ + Affine, BezPath, Circle, Diagonal2, Join, ParamCurveMoments, PathEl, Point, Rect, Shape, + Size, Vec2, expand_path, + }; + + #[test] + fn expand_circle_basic() { + const CENTER: Point = Point::new(100., 100.); + const RADIUS: f64 = 10.0; + let circle = Circle::new(CENTER, RADIUS); + let expected_area = PI * RADIUS.powi(2); + let expected_perimeter = 2.0 * PI * RADIUS; + assert!((circle.area() - expected_area).abs() < 1e-9); + assert!((circle.perimeter(1e-12) - expected_perimeter).abs() < 1e-9); + const R_DELTA: f64 = 2.0; + const EXPAND: Diagonal2 = Diagonal2::new(R_DELTA, R_DELTA); + let expanded = expand_path(circle, EXPAND, Join::Bevel, 4.0, 1e-3); + let expected_area_expanded = PI * (RADIUS + R_DELTA).powi(2); + let expected_perimeter_expanded = 2.0 * PI * (RADIUS + R_DELTA); + assert!((expanded.area() - expected_area_expanded).abs() < 4e-2); + assert!((expanded.perimeter(1e-12) - expected_perimeter_expanded).abs() < 3e-3); + + let mirror = Affine::reflect(CENTER, Vec2::new(0.0, 1.0)); + // We have to convert to a path here as the circle type doesn't support negative area. + let circle_mirror = mirror * circle.to_path(1e-3); + let expanded_mirror = expand_path(circle_mirror, EXPAND, Join::Bevel, 4.0, 1e-3); + assert!((-expanded_mirror.area() - expected_area_expanded).abs() < 4e-2); + assert!((expanded_mirror.perimeter(1e-12) - expected_perimeter_expanded).abs() < 3e-3); + } + + #[test] + fn expand_ellipse_anisotropic() { + const CENTER: Point = Point::new(100., 100.); + const RADIUS: f64 = 10.0; + let circle = Circle::new(CENTER, RADIUS); + const STRETCH: f64 = 2.717; + let ellipse = Affine::scale_non_uniform(STRETCH, 1.0) * circle; + let expected_area = PI * RADIUS.powi(2) * STRETCH; + assert!((ellipse.area() - expected_area).abs() < 1e-9); + const R_DELTA: f64 = 2.0; + const EXPAND: Diagonal2 = Diagonal2::new(R_DELTA * STRETCH, R_DELTA); + let expanded = expand_path(ellipse, EXPAND, Join::Bevel, 4.0, 1e-3); + let expected_area_expanded = PI * (RADIUS + R_DELTA).powi(2) * STRETCH; + assert!((expanded.area() - expected_area_expanded).abs() < 4e-2); + } + + #[test] + fn expand_rect() { + const CENTER: Point = Point::new(100., 100.); + const SIZE: Size = Size::new(30., 20.); + let rect = Rect::from_center_size(CENTER, SIZE); + assert!((rect.area() - SIZE.area()).abs() < 1e-9); + const EXPAND: Diagonal2 = Diagonal2::new(10.0, 10.0); + let mitered = expand_path(rect, EXPAND, Join::Miter, 4.0, 1e-3); + let expected_area_mitered = + (SIZE.width + 2.0 * EXPAND.xx) * (SIZE.height + 2.0 * EXPAND.yy); + assert!((mitered.area() - expected_area_mitered).abs() < 1e-9); + + let beveled = expand_path(rect, EXPAND, Join::Bevel, 4.0, 1e-3); + let expected_area_beveled = expected_area_mitered - 2.0 * EXPAND.xx * EXPAND.yy; + assert!((beveled.area() - expected_area_beveled).abs() < 1e-9); + + let rounded = expand_path(rect, EXPAND, Join::Round, 4.0, 0.1); + let expected_area_rounded = expected_area_mitered - (4.0 - PI) * EXPAND.xx * EXPAND.yy; + assert!((rounded.area() - expected_area_rounded).abs() < 1e-1); + } + + #[test] + fn expand_rounding_tolerance() { + const CENTER: Point = Point::new(100., 100.); + const SIZE: Size = Size::new(30., 20.); + let rect = Rect::from_center_size(CENTER, SIZE); + const EXPAND: Diagonal2 = Diagonal2::new(10.0, 10.0); + let expected_area_mitered = + (SIZE.width + 2.0 * EXPAND.xx) * (SIZE.height + 2.0 * EXPAND.yy); + let expected_area_rounded = expected_area_mitered - (4.0 - PI) * EXPAND.xx * EXPAND.yy; + let rounded = expand_path(rect, EXPAND, Join::Round, 4.0, 1e-3); + assert!((rounded.area() - expected_area_rounded).abs() < 2e-3); + // Validate that a lower tolerance increases accuracy. + let rounded_fine = expand_path(rect, EXPAND, Join::Round, 4.0, 1e-6); + assert!((rounded_fine.area() - expected_area_rounded).abs() < 3e-5); + } + + #[test] + fn expand_glyph_shape() { + // WARNING: this test is fragile. If there is optimization to simplify inner joins by + // computing intersections, the measurements change. A properly written test would + // compare the result after path intersection, or alternatively probe for zero/nonzero + // winding number for a collection of sample points. But at least it is sensitive to + // regressions. + + // Roboto "e" glyph + let path = BezPath::from_svg( + "M10.359375,-0.359375 Q6.484375,-0.359375 4.0625,2.1875 Q1.640625,4.734375 1.640625,8.984375 \ + L1.640625,9.578125 Q1.640625,12.40625 2.71875,14.625 Q3.796875,16.859375 5.734375,18.109375 \ + Q7.6875,19.375 9.953125,19.375 Q13.65625,19.375 15.703125,16.921875 Q17.765625,14.484375 17.765625,9.9375 \ + L17.765625,8.578125 L4.890625,8.578125 Q4.953125,5.765625 6.53125,4.03125 Q8.109375,2.296875 10.53125,2.296875 \ + Q12.25,2.296875 13.4375,3 Q14.640625,3.703125 15.546875,4.875 L17.53125,3.328125 Q15.140625,-0.359375 10.359375,-0.359375 Z \ + M9.953125,16.703125 Q7.984375,16.703125 6.640625,15.265625 Q5.3125,13.828125 5,11.25 L14.515625,11.25 L14.515625,11.5 \ + Q14.375,13.96875 13.171875,15.328125 Q11.984375,16.703125 9.953125,16.703125 Z", + ) + .unwrap(); + const EXPAND: Diagonal2 = Diagonal2::new(1.5, 1.0); + let expanded = expand_path(&path, EXPAND, Join::Round, 4.0, 0.1); + //println!("{}", expanded.to_svg()); + // The outline has been visually verified, these are measurements taken from known-good. + const EXPECTED_AREA: f64 = -291.3217958410297; + const EXPECTED_PERIMETER: f64 = 120.89147879578239; + const EXPECTED_MOMENT_X: f64 = -2788.568539588466; + const EXPECTED_MOMENT_Y: f64 = -2801.3818805722685; + const EXPECTED_MOMENT_XX: f64 = -34280.940819978576; + const EXPECTED_MOMENT_XY: f64 = -26971.281063345254; + const EXPECTED_MOMENT_YY: f64 = -36722.298990246876; + assert!((expanded.area() - EXPECTED_AREA).abs() < 1e-3); + assert!((expanded.perimeter(1e-9) - EXPECTED_PERIMETER).abs() < 1e-3); + let moments = expanded.moments(); + assert!((moments.moment_x - EXPECTED_MOMENT_X).abs() < 1e-3); + assert!((moments.moment_y - EXPECTED_MOMENT_Y).abs() < 1e-3); + assert!((moments.moment_xx - EXPECTED_MOMENT_XX).abs() < 1e-3); + assert!((moments.moment_xy - EXPECTED_MOMENT_XY).abs() < 1e-3); + assert!((moments.moment_yy - EXPECTED_MOMENT_YY).abs() < 1e-3); + } + + #[test] + fn assert_expand_subpath_closed() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + path.line_to((100.0, 100.0)); + path.line_to((0.0, 100.0)); + + let expanded = expand_path(path, Diagonal2::new(10.0, 10.0), Join::Miter, 4.0, 1e-3); + assert_eq!(expanded.elements().last(), Some(&PathEl::ClosePath)); + } + + #[test] + fn expand_degenerate_input() { + let path = BezPath::from_svg("M0,0 C0,0 0,0 0,0 Z").unwrap(); + let expanded = expand_path(path, Diagonal2::new(10.0, 10.0), Join::Miter, 4.0, 1e-3); + assert!(expanded.is_empty()); + } + + #[test] + fn expand_degenerate_ghost() { + let mut path = BezPath::new(); + path.extend(Rect::new(0.0, 0.0, 10.0, 10.0).path_elements(1e-3)); + let expected = expand_path(&path, Diagonal2::new(1.0, 1.0), Join::Miter, 4.0, 1e-3); + + path.move_to((20.0, 20.0)); + path.close_path(); + let actual = expand_path(&path, Diagonal2::new(1.0, 1.0), Join::Miter, 4.0, 1e-3); + + assert_eq!(actual, expected); + } + + #[test] + fn expand_open_subpath_uses_implicit_close_for_area_sign() { + let mut open = BezPath::new(); + open.move_to((100.0, 100.0)); + open.line_to((110.0, 100.0)); + open.line_to((100.0, 110.0)); + + let mut closed = open.clone(); + closed.close_path(); + + let expand = Diagonal2::new(1.0, 1.0); + let open_expanded = expand_path(open, expand, Join::Miter, 4.0, 1e-3); + let closed_expanded = expand_path(closed, expand, Join::Miter, 4.0, 1e-3); + + assert_eq!(open_expanded, closed_expanded); + } +} diff --git a/vendor/kurbo/src/fit.rs b/vendor/kurbo/src/fit.rs new file mode 100644 index 0000000000..1f739cb868 --- /dev/null +++ b/vendor/kurbo/src/fit.rs @@ -0,0 +1,719 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! An implementation of cubic Bézier curve fitting based on a quartic +//! solver making signed area and moment match the source curve. + +use core::ops::Range; + +use alloc::vec::Vec; + +use arrayvec::ArrayVec; + +use crate::{ + Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2, + common::{ + GAUSS_LEGENDRE_COEFFS_16, factor_quartic_inner, solve_cubic, solve_itp_fallible, + solve_quadratic, + }, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// The source curve for curve fitting. +/// +/// This trait is a general representation of curves to be used as input to a curve +/// fitting process. It can represent source curves with cusps and corners, though +/// if the corners are known in advance, it may be better to run curve fitting on +/// subcurves bounded by the corners. +/// +/// The trait primarily works by sampling the source curve and computing the position +/// and derivative at each sample. Those derivatives are then used for multiple +/// sub-tasks, including ensuring G1 continuity at subdivision points, computing the +/// area and moment of the curve for curve fitting, and casting rays for evaluation +/// of a distance metric to test accuracy. +/// +/// A major motivation is computation of offset curves, which often have cusps, but +/// the presence and location of those cusps is not generally known. It is also +/// intended for conversion between curve types (for example, piecewise Euler spiral +/// or NURBS), and distortion effects such as perspective transform. +/// +/// Note general similarities to [`ParamCurve`] but also important differences. +/// Instead of separate [`eval`] and evaluation of derivative, have a single +/// [`sample_pt_deriv`] method which can be more efficient and also handles cusps more +/// robustly. Also there is no method for subsegment, as that is not needed and +/// would be annoying to implement. +/// +/// [`ParamCurve`]: crate::ParamCurve +/// [`eval`]: crate::ParamCurve::eval +/// [`sample_pt_deriv`]: ParamCurveFit::sample_pt_deriv +pub trait ParamCurveFit { + /// Evaluate the curve and its tangent at parameter `t`. + /// + /// For a regular curve (one not containing a cusp or corner), the + /// derivative is a good choice for the tangent vector and the `sign` + /// parameter can be ignored. Otherwise, the `sign` parameter selects which + /// side of the discontinuity the tangent will be sampled from. + /// + /// Generally `t` is in the range [0..1]. + fn sample_pt_tangent(&self, t: f64, sign: f64) -> CurveFitSample; + + /// Evaluate the point and derivative at parameter `t`. + /// + /// In curves with cusps, the derivative can go to zero. + fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2); + + /// Compute moment integrals. + /// + /// This method computes the integrals of y dx, x y dx, and y^2 dx over the + /// length of this curve. From these integrals it is fairly straightforward + /// to derive the moments needed for curve fitting. + /// + /// A default implementation is provided which does quadrature integration + /// with Green's theorem, in terms of samples evaluated with + /// [`sample_pt_deriv`]. + /// + /// [`sample_pt_deriv`]: ParamCurveFit::sample_pt_deriv + fn moment_integrals(&self, range: Range) -> (f64, f64, f64) { + let t0 = 0.5 * (range.start + range.end); + let dt = 0.5 * (range.end - range.start); + let (a, x, y) = GAUSS_LEGENDRE_COEFFS_16 + .iter() + .map(|(wi, xi)| { + let t = t0 + xi * dt; + let (p, d) = self.sample_pt_deriv(t); + let a = wi * d.x * p.y; + let x = p.x * a; + let y = p.y * a; + (a, x, y) + }) + .fold((0.0, 0.0, 0.0), |(a0, x0, y0), (a1, x1, y1)| { + (a0 + a1, x0 + x1, y0 + y1) + }); + (a * dt, x * dt, y * dt) + } + + /// Find a cusp or corner within the given range. + /// + /// If the range contains a corner or cusp, return it. If there is more + /// than one such discontinuity, any can be reported, as the function will + /// be called repeatedly after subdivision of the range. + /// + /// Do not report cusps at the endpoints of the range, as this may cause + /// potentially infinite subdivision. In particular, when a cusp is reported + /// and this method is called on a subdivided range bounded by the reported + /// cusp, then the subsequent call should not report a cusp there. + /// + /// The definition of what exactly constitutes a cusp is somewhat loose. + /// If a cusp is missed, then the curve fitting algorithm will attempt to + /// fit the curve with a smooth curve, which is generally not a disaster + /// will usually result in more subdivision. Conversely, it might be useful + /// to report near-cusps, specifically points of curvature maxima where the + /// curvature is large but still mathematically finite. + fn break_cusp(&self, range: Range) -> Option; +} + +/// A sample point of a curve for fitting. +pub struct CurveFitSample { + /// A point on the curve at the sample location. + pub p: Point, + /// A vector tangent to the curve at the sample location. + pub tangent: Vec2, +} + +impl CurveFitSample { + /// Intersect a ray orthogonal to the tangent with the given cubic. + /// + /// Returns a vector of `t` values on the cubic. + fn intersect(&self, c: CubicBez) -> ArrayVec { + let p1 = 3.0 * (c.p1 - c.p0); + let p2 = 3.0 * c.p2.to_vec2() - 6.0 * c.p1.to_vec2() + 3.0 * c.p0.to_vec2(); + let p3 = (c.p3 - c.p0) - 3.0 * (c.p2 - c.p1); + let c0 = (c.p0 - self.p).dot(self.tangent); + let c1 = p1.dot(self.tangent); + let c2 = p2.dot(self.tangent); + let c3 = p3.dot(self.tangent); + solve_cubic(c0, c1, c2, c3) + .into_iter() + .filter(|t| (0.0..=1.0).contains(t)) + .collect() + } +} + +/// Generate a Bézier path that fits the source curve. +/// +/// This function is still experimental and the signature might change; it's possible +/// it might become a method on the [`ParamCurveFit`] trait. +/// +/// This function recursively subdivides the curve in half by the parameter when the +/// accuracy is not met. That gives a reasonably optimized result but not necessarily +/// the minimum number of segments. +/// +/// In general, the resulting Bézier path should have a Fréchet distance less than +/// the provided `accuracy` parameter. However, this is not a rigorous guarantee, as +/// the error metric is computed approximately. +/// +/// This function is intended for use when the source curve is piecewise continuous, +/// with the discontinuities reported by the cusp method. In applications (such as +/// stroke expansion) where this property may not hold, it is up to the client to +/// detect and handle such cases. Even so, best effort is made to avoid infinite +/// subdivision. +/// +/// When a higher degree of optimization is desired (at considerably more runtime cost), +/// consider [`fit_to_bezpath_opt`] instead. +pub fn fit_to_bezpath(source: &impl ParamCurveFit, accuracy: f64) -> BezPath { + let mut path = BezPath::new(); + fit_to_bezpath_rec(source, 0.0..1.0, accuracy, &mut path); + path +} + +// Discussion question: possibly should take endpoint samples, to avoid +// duplication of that work. +fn fit_to_bezpath_rec( + source: &impl ParamCurveFit, + range: Range, + accuracy: f64, + path: &mut BezPath, +) { + let start = range.start; + let end = range.end; + let start_p = source.sample_pt_tangent(range.start, 1.0).p; + let end_p = source.sample_pt_tangent(range.end, -1.0).p; + if start_p.distance_squared(end_p) <= accuracy * accuracy { + if let Some((c, _)) = try_fit_line(source, accuracy, range, start_p, end_p) { + if path.is_empty() { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + return; + } + } + let t = if let Some(t) = source.break_cusp(start..end) { + t + } else if let Some((c, _)) = fit_to_cubic(source, start..end, accuracy) { + if path.is_empty() { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + return; + } else { + // A smarter approach is possible than midpoint subdivision, but would be + // a significant increase in complexity. + 0.5 * (start + end) + }; + if t == start || t == end { + // infinite recursion, just draw a line + let p1 = start_p.lerp(end_p, 1.0 / 3.0); + let p2 = end_p.lerp(start_p, 1.0 / 3.0); + if path.is_empty() { + path.move_to(start_p); + } + path.curve_to(p1, p2, end_p); + return; + } + fit_to_bezpath_rec(source, start..t, accuracy, path); + fit_to_bezpath_rec(source, t..end, accuracy, path); +} + +const N_SAMPLE: usize = 20; + +/// An acceleration structure for estimating curve distance +struct CurveDist { + samples: ArrayVec, + arcparams: ArrayVec, + range: Range, + /// A "spicy" curve is one with potentially extreme curvature variation, + /// so use arc length measurement for better accuracy. + spicy: bool, +} + +impl CurveDist { + fn from_curve(source: &impl ParamCurveFit, range: Range) -> Self { + let step = (range.end - range.start) * (1.0 / (N_SAMPLE + 1) as f64); + let mut last_tan = None; + let mut spicy = false; + const SPICY_THRESH: f64 = 0.2; + let mut samples = ArrayVec::new(); + for i in 0..N_SAMPLE + 2 { + let sample = source.sample_pt_tangent(range.start + i as f64 * step, 1.0); + if let Some(last_tan) = last_tan { + let cross = sample.tangent.cross(last_tan); + let dot = sample.tangent.dot(last_tan); + if cross.abs() > SPICY_THRESH * dot.abs() { + spicy = true; + } + } + last_tan = Some(sample.tangent); + if i > 0 && i < N_SAMPLE + 1 { + samples.push(sample); + } + } + CurveDist { + samples, + arcparams: ArrayVec::default(), + range, + spicy, + } + } + + fn compute_arc_params(&mut self, source: &impl ParamCurveFit) { + const N_SUBSAMPLE: usize = 10; + let (start, end) = (self.range.start, self.range.end); + let dt = (end - start) * (1.0 / ((N_SAMPLE + 1) * N_SUBSAMPLE) as f64); + let mut arclen = 0.0; + for i in 0..N_SAMPLE + 1 { + for j in 0..N_SUBSAMPLE { + let t = start + dt * ((i * N_SUBSAMPLE + j) as f64 + 0.5); + let (_, deriv) = source.sample_pt_deriv(t); + arclen += deriv.hypot(); + } + if i < N_SAMPLE { + self.arcparams.push(arclen); + } + } + let arclen_inv = arclen.recip(); + for x in &mut self.arcparams { + *x *= arclen_inv; + } + } + + /// Evaluate distance based on arc length parametrization + fn eval_arc(&self, c: CubicBez, acc2: f64) -> Option { + // TODO: this could perhaps be tuned. + const EPS: f64 = 1e-9; + let c_arclen = c.arclen(EPS); + let mut max_err2 = 0.0; + for (sample, s) in self.samples.iter().zip(&self.arcparams) { + let t = c.inv_arclen(c_arclen * s, EPS); + let err = sample.p.distance_squared(c.eval(t)); + max_err2 = err.max(max_err2); + if max_err2 > acc2 { + return None; + } + } + Some(max_err2) + } + + /// Evaluate distance to a cubic approximation. + /// + /// If distance exceeds stated accuracy, can return `None`. Note that + /// `acc2` is the square of the target. + /// + /// Returns the square of the error, which is intended to be a good + /// approximation of the Fréchet distance. + fn eval_ray(&self, c: CubicBez, acc2: f64) -> Option { + let mut max_err2 = 0.0; + for sample in &self.samples { + let mut best = acc2 + 1.0; + for t in sample.intersect(c) { + let err = sample.p.distance_squared(c.eval(t)); + best = best.min(err); + } + max_err2 = best.max(max_err2); + if max_err2 > acc2 { + return None; + } + } + Some(max_err2) + } + + fn eval_dist(&mut self, source: &impl ParamCurveFit, c: CubicBez, acc2: f64) -> Option { + // Always compute cheaper distance, hoping for early-out. + let ray_dist = self.eval_ray(c, acc2)?; + if !self.spicy { + return Some(ray_dist); + } + if self.arcparams.is_empty() { + self.compute_arc_params(source); + } + self.eval_arc(c, acc2) + } +} + +/// As described in [Simplifying Bézier paths], strictly optimizing for +/// Fréchet distance can create bumps. The problem is curves with long +/// control arms (distance from the control point to the corresponding +/// endpoint). We mitigate that by applying a penalty as a multiplier to +/// the measured error (approximate Fréchet distance). This is ReLU-like, +/// with a value of 1.0 below the elbow, and a given slope above it. The +/// values here have been determined empirically to give good results. +/// +/// [Simplifying Bézier paths]: +/// https://raphlinus.github.io/curves/2023/04/18/bezpath-simplify.html +const D_PENALTY_ELBOW: f64 = 0.65; +const D_PENALTY_SLOPE: f64 = 2.0; + +/// Try fitting a line. +/// +/// This is especially useful for very short chords, in which the standard +/// cubic fit is not numerically stable. The tangents are not considered, so +/// it's useful in cusp and near-cusp situations where the tangents are not +/// reliable, as well. +/// +/// Returns the line raised to a cubic and the error, if within tolerance. +fn try_fit_line( + source: &impl ParamCurveFit, + accuracy: f64, + range: Range, + start: Point, + end: Point, +) -> Option<(CubicBez, f64)> { + let acc2 = accuracy * accuracy; + let chord_l = Line::new(start, end); + const SHORT_N: usize = 7; + let mut max_err2 = 0.0; + let dt = (range.end - range.start) / (SHORT_N + 1) as f64; + for i in 0..SHORT_N { + let t = range.start + (i + 1) as f64 * dt; + let p = source.sample_pt_deriv(t).0; + let err2 = chord_l.nearest(p, accuracy).distance_sq; + if err2 > acc2 { + // Not in tolerance; likely subdivision will help. + return None; + } + max_err2 = err2.max(max_err2); + } + let p1 = start.lerp(end, 1.0 / 3.0); + let p2 = end.lerp(start, 1.0 / 3.0); + let c = CubicBez::new(start, p1, p2, end); + Some((c, max_err2)) +} + +/// Fit a single cubic to a range of the source curve. +/// +/// Returns the cubic segment and the square of the error. +/// Discussion question: should this be a method on the trait instead? +pub fn fit_to_cubic( + source: &impl ParamCurveFit, + range: Range, + accuracy: f64, +) -> Option<(CubicBez, f64)> { + let start = source.sample_pt_tangent(range.start, 1.0); + let end = source.sample_pt_tangent(range.end, -1.0); + let d = end.p - start.p; + let chord2 = d.hypot2(); + let acc2 = accuracy * accuracy; + if chord2 <= acc2 { + // Special case very short chords; try to fit a line. + return try_fit_line(source, accuracy, range, start.p, end.p); + } + let th = d.atan2(); + fn mod_2pi(th: f64) -> f64 { + let th_scaled = th * core::f64::consts::FRAC_1_PI * 0.5; + core::f64::consts::PI * 2.0 * (th_scaled - th_scaled.round()) + } + let th0 = mod_2pi(start.tangent.atan2() - th); + let th1 = mod_2pi(th - end.tangent.atan2()); + + let (mut area, mut x, mut y) = source.moment_integrals(range.clone()); + let (x0, y0) = (start.p.x, start.p.y); + let (dx, dy) = (d.x, d.y); + // Subtract off area of chord + area -= dx * (y0 + 0.5 * dy); + // `area` is signed area of closed curve segment. + // This quantity is invariant to translation and rotation. + + // Subtract off moment of chord + let dy_3 = dy * (1. / 3.); + x -= dx * (x0 * y0 + 0.5 * (x0 * dy + y0 * dx) + dy_3 * dx); + y -= dx * (y0 * y0 + y0 * dy + dy_3 * dy); + // Translate start point to origin; convert raw integrals to moments. + x -= x0 * area; + y = 0.5 * y - y0 * area; + // Rotate into place (this also scales up by chordlength for efficiency). + let moment = d.x * x + d.y * y; + // `moment` is the chordlength times the x moment of the curve translated + // so its start point is on the origin, and rotated so its end point is on the + // x axis. + + let chord2_inv = chord2.recip(); + let unit_area = area * chord2_inv; + let mx = moment * chord2_inv.powi(2); + // `unit_area` is signed area scaled to unit chord; `mx` is scaled x moment + + let chord = chord2.sqrt(); + let aff = Affine::translate(start.p.to_vec2()) * Affine::rotate(th) * Affine::scale(chord); + let mut curve_dist = CurveDist::from_curve(source, range); + let mut best_c = None; + let mut best_err2 = None; + for (cand, d0, d1) in cubic_fit(th0, th1, unit_area, mx) { + let c = aff * cand; + if let Some(err2) = curve_dist.eval_dist(source, c, acc2) { + fn scale_f(d: f64) -> f64 { + 1.0 + (d - D_PENALTY_ELBOW).max(0.0) * D_PENALTY_SLOPE + } + let scale = scale_f(d0).max(scale_f(d1)).powi(2); + let err2 = err2 * scale; + if err2 < acc2 && best_err2.map(|best| err2 < best).unwrap_or(true) { + best_c = Some(c); + best_err2 = Some(err2); + } + } + } + match (best_c, best_err2) { + (Some(c), Some(err2)) => Some((c, err2)), + _ => None, + } +} + +/// Returns curves matching area and moment, given unit chord. +fn cubic_fit(th0: f64, th1: f64, area: f64, mx: f64) -> ArrayVec<(CubicBez, f64, f64), 4> { + // Note: maybe we want to take unit vectors instead of angle? Shouldn't + // matter much either way though. + let (s0, c0) = th0.sin_cos(); + let (s1, c1) = th1.sin_cos(); + let a4 = -9. + * c0 + * (((2. * s1 * c1 * c0 + s0 * (2. * c1 * c1 - 1.)) * c0 - 2. * s1 * c1) * c0 + - c1 * c1 * s0); + let a3 = 12. + * ((((c1 * (30. * area * c1 - s1) - 15. * area) * c0 + 2. * s0 + - c1 * s0 * (c1 + 30. * area * s1)) + * c0 + + c1 * (s1 - 15. * area * c1)) + * c0 + - s0 * c1 * c1); + let a2 = 12. + * ((((70. * mx + 15. * area) * s1 * s1 + c1 * (9. * s1 - 70. * c1 * mx - 5. * c1 * area)) + * c0 + - 5. * s0 * s1 * (3. * s1 - 4. * c1 * (7. * mx + area))) + * c0 + - c1 * (9. * s1 - 70. * c1 * mx - 5. * c1 * area)); + let a1 = 16. + * (((12. * s0 - 5. * c0 * (42. * mx - 17. * area)) * s1 + - 70. * c1 * (3. * mx - area) * s0 + - 75. * c0 * c1 * area * area) + * s1 + - 75. * c1 * c1 * area * area * s0); + let a0 = 80. * s1 * (42. * s1 * mx - 25. * area * (s1 - c1 * area)); + // TODO: "roots" is not a good name for this variable, as it also contains + // the real part of complex conjugate pairs. + let mut roots = ArrayVec::::new(); + const EPS: f64 = 1e-12; + if a4.abs() > EPS { + let a = a3 / a4; + let b = a2 / a4; + let c = a1 / a4; + let d = a0 / a4; + if let Some(quads) = factor_quartic_inner(a, b, c, d, false) { + for (qc1, qc0) in quads { + let qroots = solve_quadratic(qc0, qc1, 1.0); + if qroots.is_empty() { + // Real part of pair of complex roots + roots.push(-0.5 * qc1); + } else { + roots.extend(qroots); + } + } + } + } else if a3.abs() > EPS { + roots.extend(solve_cubic(a0, a1, a2, a3)); + } else if a2.abs() > EPS || a1.abs() > EPS || a0.abs() > EPS { + roots.extend(solve_quadratic(a0, a1, a2)); + } else { + return [( + CubicBez::new((0.0, 0.0), (1. / 3., 0.0), (2. / 3., 0.0), (1., 0.0)), + 1f64 / 3., + 1f64 / 3., + )] + .into_iter() + .collect(); + } + + let s01 = s0 * c1 + s1 * c0; + roots + .iter() + .filter_map(|&d0| { + let (d0, d1) = if d0 > 0.0 { + let d1 = (d0 * s0 - area * (10. / 3.)) / (0.5 * d0 * s01 - s1); + if d1 > 0.0 { (d0, d1) } else { (s1 / s01, 0.0) } + } else { + (0.0, s0 / s01) + }; + // We could implement a maximum d value here. + if d0 >= 0.0 && d1 >= 0.0 { + Some(( + CubicBez::new( + (0.0, 0.0), + (d0 * c0, d0 * s0), + (1.0 - d1 * c1, d1 * s1), + (1.0, 0.0), + ), + d0, + d1, + )) + } else { + None + } + }) + .collect() +} + +/// Generate a highly optimized Bézier path that fits the source curve. +/// +/// This function is still experimental and the signature might change; it's possible +/// it might become a method on the [`ParamCurveFit`] trait. +/// +/// This function is considerably slower than [`fit_to_bezpath`], as it computes +/// optimal subdivision points. Its result is expected to be very close to the optimum +/// possible Bézier path for the source curve, in that it has a minimal number of curve +/// segments, and a minimal error over all paths with that number of segments. +/// +/// See [`fit_to_bezpath`] for an explanation of the `accuracy` parameter. +pub fn fit_to_bezpath_opt(source: &impl ParamCurveFit, accuracy: f64) -> BezPath { + let mut cusps = Vec::new(); + let mut path = BezPath::new(); + let mut t0 = 0.0; + loop { + let t1 = cusps.last().copied().unwrap_or(1.0); + match fit_to_bezpath_opt_inner(source, accuracy, t0..t1, &mut path) { + Some(t) => cusps.push(t), + None => match cusps.pop() { + Some(t) => t0 = t, + None => break, + }, + } + } + path +} + +/// Fit a range without cusps. +/// +/// On Ok return, range has been added to the path. On Err return, report a cusp (and don't +/// mutate path). +fn fit_to_bezpath_opt_inner( + source: &impl ParamCurveFit, + accuracy: f64, + range: Range, + path: &mut BezPath, +) -> Option { + if let Some(t) = source.break_cusp(range.clone()) { + return Some(t); + } + let err; + if let Some((c, err2)) = fit_to_cubic(source, range.clone(), accuracy) { + err = err2.sqrt(); + if err < accuracy { + if range.start == 0.0 { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + return None; + } + } else { + err = 2.0 * accuracy; + } + let (mut t0, t1) = (range.start, range.end); + let mut n = 0; + let last_err; + loop { + n += 1; + match fit_opt_segment(source, accuracy, t0..t1) { + FitResult::ParamVal(t) => t0 = t, + FitResult::SegmentError(err) => { + last_err = err; + break; + } + FitResult::CuspFound(t) => return Some(t), + } + } + t0 = range.start; + const EPS: f64 = 1e-9; + let f = |x| fit_opt_err_delta(source, x, accuracy, t0..t1, n); + let k1 = 0.2 / accuracy; + let ya = -err; + let yb = accuracy - last_err; + let (_, x) = match solve_itp_fallible(f, 0.0, accuracy, EPS, 1, k1, ya, yb) { + Ok(x) => x, + Err(t) => return Some(t), + }; + //println!("got fit with n={}, err={}", n, x); + let path_len = path.elements().len(); + for i in 0..n { + let t1 = if i < n - 1 { + match fit_opt_segment(source, x, t0..range.end) { + FitResult::ParamVal(t1) => t1, + FitResult::SegmentError(_) => range.end, + FitResult::CuspFound(t) => { + path.truncate(path_len); + return Some(t); + } + } + } else { + range.end + }; + let (c, _) = fit_to_cubic(source, t0..t1, accuracy).unwrap(); + if i == 0 && range.start == 0.0 { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + t0 = t1; + if t0 == range.end { + // This is unlikely but could happen when not monotonic. + break; + } + } + None +} + +fn measure_one_seg(source: &impl ParamCurveFit, range: Range, limit: f64) -> Option { + fit_to_cubic(source, range, limit).map(|(_, err2)| err2.sqrt()) +} + +enum FitResult { + /// The parameter (`t`) value that meets the desired accuracy. + ParamVal(f64), + /// Error of the measured segment. + SegmentError(f64), + /// The parameter value where a cusp was found. + CuspFound(f64), +} + +fn fit_opt_segment(source: &impl ParamCurveFit, accuracy: f64, range: Range) -> FitResult { + if let Some(t) = source.break_cusp(range.clone()) { + return FitResult::CuspFound(t); + } + let missing_err = accuracy * 2.0; + let err = measure_one_seg(source, range.clone(), accuracy).unwrap_or(missing_err); + if err <= accuracy { + return FitResult::SegmentError(err); + } + let (t0, t1) = (range.start, range.end); + let f = |x| { + if let Some(t) = source.break_cusp(range.clone()) { + return Err(t); + } + let err = measure_one_seg(source, t0..x, accuracy).unwrap_or(missing_err); + Ok(err - accuracy) + }; + const EPS: f64 = 1e-9; + let k1 = 2.0 / (t1 - t0); + match solve_itp_fallible(f, t0, t1, EPS, 1, k1, -accuracy, err - accuracy) { + Ok((t1, _)) => FitResult::ParamVal(t1), + Err(t) => FitResult::CuspFound(t), + } +} + +// Ok result is delta error (accuracy - error of last seg). +// Err result is a cusp. +fn fit_opt_err_delta( + source: &impl ParamCurveFit, + accuracy: f64, + limit: f64, + range: Range, + n: usize, +) -> Result { + let (mut t0, t1) = (range.start, range.end); + for _ in 0..n - 1 { + t0 = match fit_opt_segment(source, accuracy, t0..t1) { + FitResult::ParamVal(t0) => t0, + // In this case, n - 1 will work, which of course means the error is highly + // non-monotonic. We should probably harvest that solution. + FitResult::SegmentError(_) => return Ok(accuracy), + FitResult::CuspFound(t) => return Err(t), + } + } + let err = measure_one_seg(source, t0..t1, limit).unwrap_or(accuracy * 2.0); + Ok(accuracy - err) +} diff --git a/vendor/kurbo/src/insets.rs b/vendor/kurbo/src/insets.rs new file mode 100644 index 0000000000..a2d61e0183 --- /dev/null +++ b/vendor/kurbo/src/insets.rs @@ -0,0 +1,404 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A description of the distances between the edges of two rectangles. + +use core::ops::{Add, Div, Mul, Neg, Sub}; + +use crate::{Rect, Size}; + +/// Insets from the edges of a rectangle. +/// +/// +/// The inset value for each edge can be thought of as a delta computed from +/// the center of the rect to that edge. For instance, with an inset of `2.0` on +/// the x-axis, a rectangle with the origin `(0.0, 0.0)` with that inset added +/// will have the new origin at `(-2.0, 0.0)`. +/// +/// Put alternatively, a positive inset represents increased distance from center, +/// and a negative inset represents decreased distance from center. +/// +/// # Examples +/// +/// Positive insets added to a [`Rect`] produce a larger [`Rect`]: +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.,)); +/// let insets = Insets::uniform_xy(3., 0.,); +/// +/// let inset_rect = rect + insets; +/// assert_eq!(inset_rect.width(), 16.0, "10.0 + 3.0 × 2"); +/// assert_eq!(inset_rect.x0, -3.0); +/// ``` +/// +/// Negative insets added to a [`Rect`] produce a smaller [`Rect`]: +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.,)); +/// let insets = Insets::uniform_xy(-3., 0.,); +/// +/// let inset_rect = rect + insets; +/// assert_eq!(inset_rect.width(), 4.0, "10.0 - 3.0 × 2"); +/// assert_eq!(inset_rect.x0, 3.0); +/// ``` +/// +/// [`Insets`] operate on the absolute rectangle [`Rect::abs`], and so ignore +/// existing negative widths and heights. +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::new(7., 11., 0., 0.,); +/// let insets = Insets::uniform_xy(0., 1.,); +/// +/// assert_eq!(rect.width(), -7.0); +/// +/// let inset_rect = rect + insets; +/// assert_eq!(inset_rect.width(), 7.0); +/// assert_eq!(inset_rect.x0, 0.0); +/// assert_eq!(inset_rect.height(), 13.0); +/// ``` +/// +/// The width and height of an inset operation can still be negative if the +/// [`Insets`]' dimensions are greater than the dimensions of the original [`Rect`]. +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::new(0., 0., 3., 5.); +/// let insets = Insets::uniform_xy(0., 7.,); +/// +/// let inset_rect = rect - insets; +/// assert_eq!(inset_rect.height(), -9., "5 - 7 × 2") +/// ``` +/// +/// `Rect - Rect = Insets`: +/// +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::new(0., 0., 5., 11.); +/// let insets = Insets::uniform_xy(1., 7.,); +/// +/// let inset_rect = rect + insets; +/// let insets2 = inset_rect - rect; +/// +/// assert_eq!(insets2.x0, insets.x0); +/// assert_eq!(insets2.y1, insets.y1); +/// assert_eq!(insets2.x_value(), insets.x_value()); +/// assert_eq!(insets2.y_value(), insets.y_value()); +/// ``` +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Insets { + /// The minimum x coordinate (left edge). + pub x0: f64, + /// The minimum y coordinate (top edge in y-down spaces). + pub y0: f64, + /// The maximum x coordinate (right edge). + pub x1: f64, + /// The maximum y coordinate (bottom edge in y-down spaces). + pub y1: f64, +} + +impl Insets { + /// Zeroed insets. + pub const ZERO: Insets = Insets::uniform(0.); + + /// New uniform insets. + #[inline(always)] + pub const fn uniform(d: f64) -> Insets { + Insets { + x0: d, + y0: d, + x1: d, + y1: d, + } + } + + /// New insets with uniform values along each axis. + #[inline(always)] + pub const fn uniform_xy(x: f64, y: f64) -> Insets { + Insets { + x0: x, + y0: y, + x1: x, + y1: y, + } + } + + /// New insets. The ordering of the arguments is "left, top, right, bottom", + /// assuming a y-down coordinate space. + #[inline(always)] + pub const fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Insets { + Insets { x0, y0, x1, y1 } + } + + /// The total delta on the x-axis represented by these insets. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let insets = Insets::uniform_xy(3., 8.); + /// assert_eq!(insets.x_value(), 6.); + /// + /// let insets = Insets::new(5., 0., -12., 0.,); + /// assert_eq!(insets.x_value(), -7.); + /// ``` + #[inline] + pub const fn x_value(self) -> f64 { + self.x0 + self.x1 + } + + /// The total delta on the y-axis represented by these insets. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let insets = Insets::uniform_xy(3., 7.); + /// assert_eq!(insets.y_value(), 14.); + /// + /// let insets = Insets::new(5., 10., -12., 4.,); + /// assert_eq!(insets.y_value(), 14.); + /// ``` + #[inline] + pub const fn y_value(self) -> f64 { + self.y0 + self.y1 + } + + /// Returns the total delta represented by these insets as a [`Size`]. + /// + /// This is equivalent to creating a [`Size`] from the values returned by + /// [`x_value`] and [`y_value`]. + /// + /// This function may return a size with negative values. + /// + /// # Examples + /// + /// ``` + /// use kurbo::{Insets, Size}; + /// + /// let insets = Insets::new(11.1, -43.3, 3.333, -0.0); + /// assert_eq!(insets.size(), Size::new(insets.x_value(), insets.y_value())); + /// ``` + /// + /// [`x_value`]: Insets::x_value + /// [`y_value`]: Insets::y_value + pub const fn size(self) -> Size { + Size::new(self.x_value(), self.y_value()) + } + + /// Return `true` iff all values are nonnegative. + pub const fn are_nonnegative(self) -> bool { + let Insets { x0, y0, x1, y1 } = self; + x0 >= 0.0 && y0 >= 0.0 && x1 >= 0.0 && y1 >= 0.0 + } + + /// Return new `Insets` with all negative values replaced with `0.0`. + /// + /// This is provided as a convenience for applications where negative insets + /// are not meaningful. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let insets = Insets::new(-10., 3., -0.2, 4.); + /// let nonnegative = insets.nonnegative(); + /// assert_eq!(nonnegative.x_value(), 0.0); + /// assert_eq!(nonnegative.y_value(), 7.0); + /// ``` + pub const fn nonnegative(self) -> Insets { + let Insets { x0, y0, x1, y1 } = self; + Insets { + x0: x0.max(0.0), + y0: y0.max(0.0), + x1: x1.max(0.0), + y1: y1.max(0.0), + } + } + + /// Are these insets finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.x0.is_finite() && self.y0.is_finite() && self.x1.is_finite() && self.y1.is_finite() + } + + /// Are these insets NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.x0.is_nan() || self.y0.is_nan() || self.x1.is_nan() || self.y1.is_nan() + } + + /// Returns the component-wise minimum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let this = Insets::new(1., 2., 3., 4.); + /// let other = Insets::new(4., 3., 2., 1.); + /// + /// assert_eq!(this.min(other), Insets::new(1., 2., 2., 1.)); + /// ``` + pub const fn min(self, other: Insets) -> Self { + Self { + x0: self.x0.min(other.x0), + x1: self.x1.min(other.x1), + y0: self.y0.min(other.y0), + y1: self.y1.min(other.y1), + } + } + + /// Returns the component-wise maximum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let this = Insets::new(1., 2., 3., 4.); + /// let other = Insets::new(4., 3., 2., 1.); + /// + /// assert_eq!(this.max(other), Insets::new(4., 3., 3., 4.)); + /// ``` + pub const fn max(self, other: Insets) -> Self { + Self { + x0: self.x0.max(other.x0), + x1: self.x1.max(other.x1), + y0: self.y0.max(other.y0), + y1: self.y1.max(other.y1), + } + } +} + +impl Neg for Insets { + type Output = Insets; + + #[inline] + fn neg(self) -> Insets { + Insets::new(-self.x0, -self.y0, -self.x1, -self.y1) + } +} + +impl Add for Insets { + type Output = Insets; + + fn add(self, other: Insets) -> Self::Output { + Insets { + x0: self.x0 + other.x0, + x1: self.x1 + other.x1, + y0: self.y0 + other.y0, + y1: self.y1 + other.y1, + } + } +} + +impl Sub for Insets { + type Output = Insets; + + fn sub(self, other: Insets) -> Self::Output { + Insets { + x0: self.x0 - other.x0, + x1: self.x1 - other.x1, + y0: self.y0 - other.y0, + y1: self.y1 - other.y1, + } + } +} + +impl Add for Insets { + type Output = Rect; + + #[inline] + #[allow(clippy::suspicious_arithmetic_impl)] + fn add(self, other: Rect) -> Rect { + let other = other.abs(); + Rect::new( + other.x0 - self.x0, + other.y0 - self.y0, + other.x1 + self.x1, + other.y1 + self.y1, + ) + } +} + +impl Add for Rect { + type Output = Rect; + + #[inline] + fn add(self, other: Insets) -> Rect { + other + self + } +} + +impl Sub for Insets { + type Output = Rect; + + #[inline] + fn sub(self, other: Rect) -> Rect { + other + -self + } +} + +impl Mul for Insets { + type Output = Insets; + + fn mul(self, rhs: f64) -> Self::Output { + Self { + x0: self.x0 * rhs, + y0: self.y0 * rhs, + x1: self.x1 * rhs, + y1: self.y1 * rhs, + } + } +} + +impl Div for Insets { + type Output = Insets; + + fn div(self, rhs: f64) -> Self::Output { + Self { + x0: self.x0 / rhs, + y0: self.y0 / rhs, + x1: self.x1 / rhs, + y1: self.y1 / rhs, + } + } +} + +impl Sub for Rect { + type Output = Rect; + + #[inline] + fn sub(self, other: Insets) -> Rect { + other - self + } +} + +impl From for Insets { + #[inline(always)] + fn from(src: f64) -> Insets { + Insets::uniform(src) + } +} + +impl From<(f64, f64)> for Insets { + #[inline(always)] + fn from(src: (f64, f64)) -> Insets { + Insets::uniform_xy(src.0, src.1) + } +} + +impl From<(f64, f64, f64, f64)> for Insets { + #[inline(always)] + fn from(src: (f64, f64, f64, f64)) -> Insets { + Insets::new(src.0, src.1, src.2, src.3) + } +} diff --git a/vendor/kurbo/src/interop_euclid.rs b/vendor/kurbo/src/interop_euclid.rs new file mode 100644 index 0000000000..322bd43286 --- /dev/null +++ b/vendor/kurbo/src/interop_euclid.rs @@ -0,0 +1,91 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use euclid::UnknownUnit; + +impl From> for crate::Vec2 { + #[inline(always)] + fn from(value: euclid::Vector2D) -> Self { + Self::new(value.x, value.y) + } +} + +impl From for euclid::Vector2D { + #[inline(always)] + fn from(value: crate::Vec2) -> Self { + Self::new(value.x, value.y) + } +} + +impl From> for crate::Point { + #[inline(always)] + fn from(value: euclid::Point2D) -> Self { + Self::new(value.x, value.y) + } +} + +impl From for euclid::Point2D { + #[inline(always)] + fn from(value: crate::Point) -> Self { + Self::new(value.x, value.y) + } +} + +impl From> for crate::Size { + #[inline(always)] + fn from(value: euclid::Size2D) -> Self { + Self::new(value.width, value.height) + } +} + +impl From for euclid::Size2D { + #[inline(always)] + fn from(value: crate::Size) -> Self { + Self::new(value.width, value.height) + } +} + +impl From> for crate::Rect { + #[inline] + fn from(value: euclid::Rect) -> Self { + Self::from_origin_size(value.origin, value.size) + } +} + +impl From for euclid::Rect { + #[inline] + fn from(value: crate::Rect) -> Self { + Self::new(value.origin().into(), value.size().into()) + } +} + +impl From> for crate::Rect { + #[inline] + fn from(value: euclid::Box2D) -> Self { + Self::from_points(value.min, value.max) + } +} + +impl From for euclid::Box2D { + #[inline] + fn from(value: crate::Rect) -> Self { + Self::new( + euclid::Point2D::new(value.min_x(), value.min_y()), + euclid::Point2D::new(value.max_x(), value.max_y()), + ) + } +} + +impl From> for crate::Affine { + #[inline(always)] + fn from(t: euclid::Transform2D) -> Self { + Self::new(t.to_array()) + } +} + +impl From for euclid::Transform2D { + #[inline(always)] + fn from(a: crate::Affine) -> Self { + Self::from_array(a.as_coeffs()) + } +} diff --git a/vendor/kurbo/src/lib.rs b/vendor/kurbo/src/lib.rs new file mode 100644 index 0000000000..ae92bd3999 --- /dev/null +++ b/vendor/kurbo/src/lib.rs @@ -0,0 +1,189 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! 2D geometry, with a focus on curves. +//! +//! The kurbo library contains data structures and algorithms for curves and +//! vector paths. It was designed to serve the needs of 2D graphics applications, +//! but it is intended to be general enough to be useful for other applications. +//! It can be used as "vocabulary types" for representing curves and paths, and +//! also contains a number of computational geometry methods. +//! +//! # Examples +//! +//! Basic UI-style geometry: +//! ``` +//! use kurbo::{Insets, Point, Rect, Size, Vec2}; +//! +//! let pt = Point::new(10.0, 10.0); +//! let vector = Vec2::new(5.0, -5.0); +//! let pt2 = pt + vector; +//! assert_eq!(pt2, Point::new(15.0, 5.0)); +//! +//! let rect = Rect::from_points(pt, pt2); +//! assert_eq!(rect, Rect::from_origin_size((10.0, 5.0), (5.0, 5.0))); +//! +//! let insets = Insets::uniform(1.0); +//! let inset_rect = rect - insets; +//! assert_eq!(inset_rect.size(), Size::new(3.0, 3.0)); +//! ``` +//! +//! Finding the closest position on a [`Shape`]'s perimeter to a [`Point`]: +//! +//! ``` +//! use kurbo::{Circle, ParamCurve, ParamCurveNearest, Point, Shape}; +//! +//! const DESIRED_ACCURACY: f64 = 0.1; +//! +//! /// Given a shape and a point, returns the closest position on the shape's +//! /// perimeter, or `None` if the shape is malformed. +//! fn closest_perimeter_point(shape: impl Shape, pt: Point) -> Option { +//! let mut best: Option<(Point, f64)> = None; +//! for segment in shape.path_segments(DESIRED_ACCURACY) { +//! let nearest = segment.nearest(pt, DESIRED_ACCURACY); +//! if best.map(|(_, best_d)| nearest.distance_sq < best_d).unwrap_or(true) { +//! best = Some((segment.eval(nearest.t), nearest.distance_sq)) +//! } +//! } +//! best.map(|(point, _)| point) +//! } +//! +//! let circle = Circle::new((5.0, 5.0), 5.0); +//! let hit_point = Point::new(5.0, -2.0); +//! let expectation = Point::new(5.0, 0.0); +//! let hit = closest_perimeter_point(circle, hit_point).unwrap(); +//! assert!(hit.distance(expectation) <= DESIRED_ACCURACY); +//! ``` +//! +//! # Feature Flags +//! +//! The following crate [feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features) are available: +//! +//! - `std` (enabled by default): Get floating point functions from the standard library +//! (likely using your target's libc). +//! - `libm`: Use floating point implementations from [libm][]. +//! This is useful for `no_std` environments. +//! However, note that the `libm` crate is not as efficient as the standard library. +//! - `mint`: Enable `From`/`Into` conversion of Kurbo and [mint][] types, enabling interoperability +//! with other graphics libraries. +//! - `euclid`: Enable `From`/`Into` conversion of Kurbo and [euclid][] types. +//! Note that if you're using both Kurbo and euclid at the same time, you *must* +//! also enable one of euclid's `std` or `libm` features. +//! - `serde`: Implement `serde::Deserialize` and `serde::Serialize` on various types. +//! - `schemars`: Add best-effort support for using Kurbo types in JSON schemas using [schemars][]. +//! +//! At least one of `std` and `libm` is required; `std` overrides `libm`. +//! Note that Kurbo does require that an allocator is available (i.e. it uses [alloc]). + +// LINEBENDER LINT SET - lib.rs - v4 +// See https://linebender.org/wiki/canonical-lints/ +// These lints shouldn't apply to examples or tests. +#![cfg_attr(not(test), warn(unused_crate_dependencies))] +// These lints shouldn't apply to examples. +#![warn(clippy::print_stdout, clippy::print_stderr)] +// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit. +#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))] +// END LINEBENDER LINT SET +#![cfg_attr(docsrs, feature(doc_cfg))] +#![cfg_attr(all(not(feature = "std"), not(test)), no_std)] +#![allow( + clippy::unreadable_literal, + clippy::many_single_char_names, + clippy::excessive_precision, + clippy::bool_to_int_with_if +)] +// The following lints are part of the Linebender standard set, +// but resolving them has been deferred for now. +// Feel free to send a PR that solves one or more of these. +#![allow( + missing_debug_implementations, + elided_lifetimes_in_paths, + trivial_numeric_casts, + unnameable_types, + clippy::use_self, + clippy::cast_possible_truncation, + clippy::missing_assert_message, + clippy::unseparated_literal_suffix, + clippy::duplicated_attributes, + clippy::allow_attributes_without_reason +)] + +#[cfg(not(any(feature = "std", feature = "libm")))] +compile_error!("kurbo requires either the `std` or `libm` feature"); + +// Suppress the unused_crate_dependencies lint when both std and libm are specified. +#[cfg(all(feature = "std", feature = "libm"))] +use libm as _; + +extern crate alloc; + +mod affine; +mod arc; +mod axis; +mod bezpath; +mod circle; +pub mod common; +mod cubicbez; +mod ellipse; +mod expand; +mod fit; +mod insets; +mod line; +mod mindist; +mod moments; +pub mod offset; +mod param_curve; +mod point; +mod quadbez; +mod quadspline; +mod rect; +mod rounded_rect; +mod rounded_rect_radii; +mod shape; +pub mod simplify; +mod size; +mod stroke; +mod svg; +mod translate_scale; +mod triangle; +mod vec2; + +#[cfg(feature = "euclid")] +mod interop_euclid; + +pub use crate::affine::Affine; +pub use crate::arc::{Arc, ArcAppendIter}; +pub use crate::axis::Axis; +pub use crate::bezpath::{ + BezPath, LineIntersection, MinDistance, PathEl, PathSeg, PathSegIter, Segments, flatten, + segments, +}; +pub use crate::circle::{Circle, CirclePathIter, CircleSegment}; +pub use crate::cubicbez::{CubicBez, CubicBezIter, CuspType, cubics_to_quadratic_splines}; +pub use crate::ellipse::Ellipse; +pub use crate::expand::{Diagonal2, expand_path, expand_path_signed}; +pub use crate::fit::{ + CurveFitSample, ParamCurveFit, fit_to_bezpath, fit_to_bezpath_opt, fit_to_cubic, +}; +pub use crate::insets::Insets; +pub use crate::line::{ConstPoint, Line, LinePathIter}; +pub use crate::moments::{Moments, ParamCurveMoments}; +pub use crate::param_curve::{ + DEFAULT_ACCURACY, MAX_EXTREMA, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, +}; +pub use crate::point::Point; +pub use crate::quadbez::{QuadBez, QuadBezIter}; +pub use crate::quadspline::QuadSpline; +pub use crate::rect::{Rect, RectPathIter}; +pub use crate::rounded_rect::{RoundedRect, RoundedRectPathIter}; +pub use crate::rounded_rect_radii::RoundedRectRadii; +pub use crate::shape::Shape; +pub use crate::size::Size; +pub use crate::stroke::{ + Cap, Dashes, Join, Stroke, StrokeCtx, StrokeOptLevel, StrokeOpts, dash, stroke, stroke_with, +}; +pub use crate::svg::{SvgArc, SvgParseError}; +pub use crate::translate_scale::TranslateScale; +pub use crate::triangle::{Triangle, TrianglePathIter}; +pub use crate::vec2::Vec2; diff --git a/vendor/kurbo/src/line.rs b/vendor/kurbo/src/line.rs new file mode 100644 index 0000000000..8f8ee2a9b7 --- /dev/null +++ b/vendor/kurbo/src/line.rs @@ -0,0 +1,448 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Lines. + +use core::ops::{Add, Mul, Range, Sub}; + +use arrayvec::ArrayVec; + +use crate::{ + Affine, DEFAULT_ACCURACY, MAX_EXTREMA, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point, + Rect, Shape, Vec2, +}; + +/// A single line. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Line { + /// The line's start point. + pub p0: Point, + /// The line's end point. + pub p1: Point, +} + +impl Line { + /// Create a new line. + #[inline(always)] + pub fn new(p0: impl Into, p1: impl Into) -> Line { + Line { + p0: p0.into(), + p1: p1.into(), + } + } + + /// Returns a copy of this `Line` with the end points swapped so that it + /// points in the opposite direction. + #[must_use] + #[inline(always)] + pub const fn reversed(&self) -> Line { + Self { + p0: self.p1, + p1: self.p0, + } + } + + /// The length of the line. + #[inline] + pub fn length(self) -> f64 { + self.arclen(DEFAULT_ACCURACY) + } + + /// The midpoint of the line. + /// + /// This is the same as calling [`Point::midpoint`] with + /// the endpoints of this line. + #[must_use] + #[inline] + pub fn midpoint(&self) -> Point { + self.p0.midpoint(self.p1) + } + + /// Computes the point where two lines, if extended to infinity, would cross. + pub fn crossing_point(self, other: Line) -> Option { + let ab = self.p1 - self.p0; + let cd = other.p1 - other.p0; + let pcd = ab.cross(cd); + if pcd == 0.0 { + return None; + } + let h = ab.cross(self.p0 - other.p0) / pcd; + Some(other.p0 + cd * h) + } + + /// Is this line `finite`? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.p0.is_finite() && self.p1.is_finite() + } + + /// Is this line `NaN`? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.p0.is_nan() || self.p1.is_nan() + } +} + +impl From<(Point, Point)> for Line { + #[inline(always)] + fn from((from, to): (Point, Point)) -> Self { + Line::new(from, to) + } +} + +impl From<(Point, Vec2)> for Line { + #[inline(always)] + fn from((origin, displacement): (Point, Vec2)) -> Self { + Line::new(origin, origin + displacement) + } +} + +impl ParamCurve for Line { + #[inline] + fn eval(&self, t: f64) -> Point { + self.p0.lerp(self.p1, t) + } + + #[inline] + fn subsegment(&self, range: Range) -> Line { + Line { + p0: self.eval(range.start), + p1: self.eval(range.end), + } + } + + #[inline(always)] + fn start(&self) -> Point { + self.p0 + } + + #[inline(always)] + fn end(&self) -> Point { + self.p1 + } +} + +impl ParamCurveDeriv for Line { + type DerivResult = ConstPoint; + + #[inline] + fn deriv(&self) -> ConstPoint { + ConstPoint((self.p1 - self.p0).to_point()) + } +} + +impl ParamCurveArclen for Line { + #[inline] + fn arclen(&self, _accuracy: f64) -> f64 { + (self.p1 - self.p0).hypot() + } + + #[inline] + fn inv_arclen(&self, arclen: f64, _accuracy: f64) -> f64 { + arclen / (self.p1 - self.p0).hypot() + } +} + +impl ParamCurveArea for Line { + #[inline] + fn signed_area(&self) -> f64 { + self.p0.to_vec2().cross(self.p1.to_vec2()) * 0.5 + } +} + +impl ParamCurveNearest for Line { + #[inline] + fn nearest(&self, p: Point, _accuracy: f64) -> Nearest { + let d = self.p1 - self.p0; + let v = p - self.p0; + + // Calculate projection parameter `t` of the point onto the line segment s(t), with + // s(t) = (1-t) * p0 + t * p1. + // + // Note when the segment has 0 length, this will be positive or negative infinity or NaN; + // see the clamping below. + let t = d.dot(v) / d.hypot2(); + + // Clamp the parameter to be on the line segment. This clamps negative infinity and NaN to + // `0.`, and positive infinity to `1.`. + #[expect( + clippy::manual_clamp, + reason = "`clamp` uses slightly more instructions than chained `max` and `min` on x86 and aarch64" + )] + let t = { t.max(0.).min(1.) }; + + // Calculate ||p - s(t)||^2. + let distance_sq = (v - t * d).hypot2(); + + Nearest { distance_sq, t } + } +} + +impl ParamCurveCurvature for Line { + #[inline(always)] + fn curvature(&self, _t: f64) -> f64 { + 0.0 + } +} + +impl ParamCurveExtrema for Line { + #[inline] + fn extrema(&self) -> ArrayVec { + ArrayVec::new() + } +} + +/// A trivial "curve" that is just a constant. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct ConstPoint(Point); + +impl ConstPoint { + /// Is this point [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.0.is_finite() + } + + /// Is this point [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.0.is_nan() + } +} + +impl ParamCurve for ConstPoint { + #[inline(always)] + fn eval(&self, _t: f64) -> Point { + self.0 + } + + #[inline(always)] + fn subsegment(&self, _range: Range) -> ConstPoint { + *self + } +} + +impl ParamCurveDeriv for ConstPoint { + type DerivResult = ConstPoint; + + #[inline(always)] + fn deriv(&self) -> ConstPoint { + ConstPoint(Point::new(0.0, 0.0)) + } +} + +impl ParamCurveArclen for ConstPoint { + #[inline(always)] + fn arclen(&self, _accuracy: f64) -> f64 { + 0.0 + } + + #[inline(always)] + fn inv_arclen(&self, _arclen: f64, _accuracy: f64) -> f64 { + 0.0 + } +} + +impl Mul for Affine { + type Output = Line; + + #[inline] + fn mul(self, other: Line) -> Line { + Line { + p0: self * other.p0, + p1: self * other.p1, + } + } +} + +impl Add for Line { + type Output = Line; + + #[inline] + fn add(self, v: Vec2) -> Line { + Line::new(self.p0 + v, self.p1 + v) + } +} + +impl Sub for Line { + type Output = Line; + + #[inline] + fn sub(self, v: Vec2) -> Line { + Line::new(self.p0 - v, self.p1 - v) + } +} + +/// An iterator yielding the path for a single line. +#[doc(hidden)] +pub struct LinePathIter { + line: Line, + ix: usize, +} + +impl Shape for Line { + type PathElementsIter<'iter> = LinePathIter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> LinePathIter { + LinePathIter { line: *self, ix: 0 } + } + + /// Returning zero here is consistent with the contract (area is + /// only meaningful for closed shapes), but an argument can be made + /// that the contract should be tightened to include the Green's + /// theorem contribution. + #[inline(always)] + fn area(&self) -> f64 { + 0.0 + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + (self.p1 - self.p0).hypot() + } + + /// Same consideration as `area`. + #[inline(always)] + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline(always)] + fn bounding_box(&self) -> Rect { + Rect::from_points(self.p0, self.p1) + } + + #[inline(always)] + fn as_line(&self) -> Option { + Some(*self) + } +} + +impl Iterator for LinePathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.line.p0)), + 2 => Some(PathEl::LineTo(self.line.p1)), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use crate::{Line, ParamCurveArclen, Point}; + + #[test] + fn line_reversed() { + let l = Line::new((0.0, 0.0), (1.0, 1.0)); + let f = l.reversed(); + + assert_eq!(l.p0, f.p1); + assert_eq!(l.p1, f.p0); + + // Reversing it again should result in the original line + assert_eq!(l, f.reversed()); + } + + #[test] + fn line_arclen() { + let l = Line::new((0.0, 0.0), (1.0, 1.0)); + let true_len = 2.0f64.sqrt(); + let epsilon = 1e-9; + assert!(l.arclen(epsilon) - true_len < epsilon); + + let t = l.inv_arclen(true_len / 3.0, epsilon); + assert!((t - 1.0 / 3.0).abs() < epsilon); + } + + #[test] + fn line_midpoint() { + let l = Line::new((0.0, 0.0), (2.0, 4.0)); + assert_eq!(l.midpoint(), Point::new(1.0, 2.0)); + } + + #[test] + fn line_is_finite() { + assert!( + (Line { + p0: Point { x: 0., y: 0. }, + p1: Point { x: 1., y: 1. } + }) + .is_finite() + ); + + assert!( + !(Line { + p0: Point { x: 0., y: 0. }, + p1: Point { + x: f64::INFINITY, + y: 1. + } + }) + .is_finite() + ); + + assert!( + !(Line { + p0: Point { x: 0., y: 0. }, + p1: Point { + x: 0., + y: f64::INFINITY + } + }) + .is_finite() + ); + } + + #[test] + fn line_nearest() { + use crate::{ParamCurve, ParamCurveNearest}; + + const EPSILON: f64 = 1e-9; + + let line = Line::new((-4., 0.), (2., 1.)); + + // Projects onto the line segment end point. + let point = Point::new(4., 0.); + let nearest = line.nearest(point, 0.); + assert_eq!(nearest.t, 1.); + assert!((nearest.distance_sq - line.p1.distance_squared(point)).abs() < EPSILON); + + // Projects onto the line segment start point. + let point = Point::new(0., -50.); + let nearest = line.nearest(point, 0.); + assert_eq!(nearest.t, 0.); + assert!((nearest.distance_sq - line.p0.distance_squared(point)).abs() < EPSILON); + + // Projects onto the line segment proper (not just onto one of its extrema). + let point = Point::new(-1., 0.5); + let nearest = line.nearest(point, 0.); + assert!(nearest.t > 0. && nearest.t < 1.); + // Ensure evaluating and calculating distance manually has the same result. + assert!( + (line.eval(nearest.t).distance_squared(point) - nearest.distance_sq).abs() < EPSILON + ); + + // Test minimality while avoiding reimplementing projection in this test by checking that + // moving to a slightly different point on the segment increases the distance. + assert!(line.eval(nearest.t * 0.95).distance_squared(point) > nearest.distance_sq); + assert!(line.eval(nearest.t * 1.05).distance_squared(point) > nearest.distance_sq); + } +} diff --git a/vendor/kurbo/src/mindist.rs b/vendor/kurbo/src/mindist.rs new file mode 100644 index 0000000000..3c741aaa26 --- /dev/null +++ b/vendor/kurbo/src/mindist.rs @@ -0,0 +1,359 @@ +// Copyright 2021 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Minimum distance between two Bézier curves +//! +//! This implements the algorithm in "Computing the minimum distance between +//! two Bézier curves", Chen et al., *Journal of Computational and Applied +//! Mathematics* 229(2009), 294-301 + +use crate::Vec2; +use core::cmp::Ordering; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// Given the control points of n- and m-dimensional Bézier curves in `bez1` and `bez2` +/// respectively, calculate the minimum distance between the two curves. +/// +/// This should work for arbitrary Bézier curves up to and including degree 255, but only lines, +/// quadratics and cubics are tested. +/// +/// Returns a tuple of the distance, the path time `t1` of the closest point on the first Bézier, +/// and the path time `t2` of the closest point on the second Bézier. +/// +/// # Panics +/// +/// This panics if more than 256 control points are given in `bez1` or `bez2`, i.e., if either +/// Bézier is of degree greater than 255. +pub(crate) fn min_dist_param( + bez1: &[Vec2], + bez2: &[Vec2], + u: (f64, f64), + v: (f64, f64), + epsilon: f64, + best_alpha: Option, +) -> (f64, f64, f64) { + assert!(!bez1.is_empty() && !bez2.is_empty()); + let n = u8::try_from(bez1.len() - 1).expect("At most 256 control points"); + let m = u8::try_from(bez2.len() - 1).expect("At most 256 control points"); + let (umin, umax) = u; + let (vmin, vmax) = v; + let umid = (umin + umax) / 2.0; + let vmid = (vmin + vmax) / 2.0; + let svalues: [(f64, f64, f64); 4] = [ + (S(umin, vmin, bez1, bez2), umin, vmin), + (S(umin, vmax, bez1, bez2), umin, vmax), + (S(umax, vmin, bez1, bez2), umax, vmin), + (S(umax, vmax, bez1, bez2), umax, vmax), + ]; + let alpha: f64 = svalues.iter().map(|(a, _, _)| *a).reduce(f64::min).unwrap(); + if let Some(best) = best_alpha { + if alpha > best { + return (alpha, umid, vmid); + } + } + + if (umax - umin).abs() < epsilon || (vmax - vmin).abs() < epsilon { + return (alpha, umid, vmid); + } + + // Property one: D(r>k) > alpha + let mut is_outside = true; + let mut min_drk = None; + let mut min_ij = None; + for r in 0..(2 * n) { + for k in 0..(2 * m) { + let d_rk = D_rk(r, k, bez1, bez2); + if d_rk < alpha { + is_outside = false; + } + if min_drk.is_none() || Some(d_rk) < min_drk { + min_drk = Some(d_rk); + min_ij = Some((r, k)); + } + } + } + if is_outside { + return (alpha, umid, vmid); + } + + // Property two: boundary check + let mut at_boundary0on_bez1 = true; + let mut at_boundary1on_bez1 = true; + let mut at_boundary0on_bez2 = true; + let mut at_boundary1on_bez2 = true; + for i in 0..2 * n { + for j in 0..2 * m { + let dij = D_rk(i, j, bez1, bez2); + let dkj = D_rk(0, j, bez1, bez2); + if dij < dkj { + at_boundary0on_bez1 = false; + } + let dkj = D_rk(2 * n, j, bez1, bez2); + if dij < dkj { + at_boundary1on_bez1 = false; + } + let dkj = D_rk(i, 0, bez1, bez2); + if dij < dkj { + at_boundary0on_bez2 = false; + } + let dkj = D_rk(i, 2 * m, bez1, bez2); + if dij < dkj { + at_boundary1on_bez2 = false; + } + } + } + if at_boundary0on_bez1 && at_boundary0on_bez2 { + return svalues[0]; + } + if at_boundary0on_bez1 && at_boundary1on_bez2 { + return svalues[1]; + } + if at_boundary1on_bez1 && at_boundary0on_bez2 { + return svalues[2]; + } + if at_boundary1on_bez1 && at_boundary1on_bez2 { + return svalues[3]; + } + + let (min_i, min_j) = min_ij.unwrap(); + let new_umid = umin + (umax - umin) * (min_i as f64 / (2 * n) as f64); + let new_vmid = vmin + (vmax - vmin) * (min_j as f64 / (2 * m) as f64); + + // Subdivide + let results = [ + min_dist_param( + bez1, + bez2, + (umin, new_umid), + (vmin, new_vmid), + epsilon, + Some(alpha), + ), + min_dist_param( + bez1, + bez2, + (umin, new_umid), + (new_vmid, vmax), + epsilon, + Some(alpha), + ), + min_dist_param( + bez1, + bez2, + (new_umid, umax), + (vmin, new_vmid), + epsilon, + Some(alpha), + ), + min_dist_param( + bez1, + bez2, + (new_umid, umax), + (new_vmid, vmax), + epsilon, + Some(alpha), + ), + ]; + + *results + .iter() + .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Less)) + .unwrap() +} + +// $ S(u,v)=\sum_{r=0}^{2n} \sum _{k=0}^{2m} D_{r,k} B_{2n}^r(u) B_{2m}^k(v) $ + +#[allow(non_snake_case)] +fn S(u: f64, v: f64, bez1: &[Vec2], bez2: &[Vec2]) -> f64 { + #[expect( + clippy::cast_possible_truncation, + reason = "By the checks in `min_dist_param` we know `bez1.len()` and `bez2.len()` are less than or equal to 256" + )] + let (n, m) = { ((bez1.len() - 1) as u8, (bez2.len() - 1) as u8) }; + let mut summand = 0.0; + for r in 0..=2 * n { + for k in 0..=2 * m { + summand += + D_rk(r, k, bez1, bez2) * basis_function(2 * n, r, u) * basis_function(2 * m, k, v); + } + } + summand +} + +// $ C_{r,k} = ( \sum_{i=\theta}^\upsilon P_i C_n^i C_n^{r-i} / C_{2n}^r ) \cdot (\sum_{j=\sigma}^\varsigma Q_j C_m^j C_m^{k-j} / C_{2m}^k ) $ +#[allow(non_snake_case)] +fn C_rk(r: u8, k: u8, bez1: &[Vec2], bez2: &[Vec2]) -> f64 { + #[expect( + clippy::cast_possible_truncation, + reason = "By the checks in `min_dist_param` we know `bez1.len()` and `bez2.len()` are less than or equal to 256" + )] + let (n, m) = { ((bez1.len() - 1) as u8, (bez2.len() - 1) as u8) }; + let upsilon = r.min(n); + let theta = r - n.min(r); + let mut left: Vec2 = Vec2::ZERO; + for i in theta..upsilon + 1 { + let item = bez1[usize::from(i)]; + left += item * (choose(n, i) * choose(n, r - i)) as f64 / (choose(2 * n, r) as f64); + } + + let varsigma = k.min(m); + let sigma = k - m.min(k); + let mut right: Vec2 = Vec2::ZERO; + for j in sigma..varsigma + 1 { + let item = bez2[usize::from(j)]; + right += item * (choose(m, j) * choose(m, k - j)) as f64 / (choose(2 * m, k) as f64); + } + left.dot(right) +} + +// $ A_r=\sum _{i=\theta} ^\upsilon (P_i \cdot P_{r-i}) C_n^i C_n^{r-i} / C_{2n}^r $ +// ($ B_k $ is just the same as $ A_r $ but for the other curve.) + +#[allow(non_snake_case)] +fn A_r(r: u8, p: &[Vec2]) -> f64 { + #[expect( + clippy::cast_possible_truncation, + reason = "By the checks in `min_dist_param` we know `p.len()` is less than or equal to 256" + )] + let n = (p.len() - 1) as u8; + let upsilon = r.min(n); + let theta = r - n.min(r); + (theta..=upsilon) + .map(|i| { + let dot = p[usize::from(i)].dot(p[usize::from(r - i)]); // These are bounds checked by the sum limits + let factor = (choose(n, i) * choose(n, r - i)) as f64 / (choose(2 * n, r) as f64); + dot * factor + }) + .sum() +} + +#[allow(non_snake_case)] +fn D_rk(r: u8, k: u8, bez1: &[Vec2], bez2: &[Vec2]) -> f64 { + // In the paper, B_k is used for the second factor, but it's the same thing + A_r(r, bez1) + A_r(k, bez2) - 2.0 * C_rk(r, k, bez1, bez2) +} + +// Bézier basis function +fn basis_function(n: u8, i: u8, u: f64) -> f64 { + choose(n, i) as f64 * (1.0 - u).powi((n - i) as i32) * u.powi(i as i32) +} + +// Binomial co-efficient, but returning zeros for values outside of domain +fn choose(n: u8, k: u8) -> u32 { + let mut n = n as u32; + let k = k as u32; + if k > n { + return 0; + } + let mut p = 1; + for i in 1..=(n - k) { + p *= n; + p /= i; + n -= 1; + } + p +} + +#[cfg(test)] +mod tests { + use crate::mindist::A_r; + use crate::mindist::{D_rk, choose}; + use crate::param_curve::ParamCurve; + use crate::{CubicBez, Line, PathSeg, Vec2}; + + #[test] + fn test_choose() { + assert_eq!(choose(6, 0), 1); + assert_eq!(choose(6, 1), 6); + assert_eq!(choose(6, 2), 15); + } + + #[test] + fn test_d_rk() { + let bez1 = vec![ + Vec2::new(129.0, 139.0), + Vec2::new(190.0, 139.0), + Vec2::new(201.0, 364.0), + Vec2::new(90.0, 364.0), + ]; + let bez2 = vec![ + Vec2::new(309.0, 159.0), + Vec2::new(178.0, 159.0), + Vec2::new(215.0, 408.0), + Vec2::new(309.0, 408.0), + ]; + let b = A_r(1, &bez2); + assert!((b - 80283.0).abs() < 0.005, "B_1(Q)={b:?}"); + let d = D_rk(0, 1, &bez1, &bez2); + assert!((d - 9220.0).abs() < 0.005, "D={d:?}"); + } + + #[test] + fn test_mindist() { + let bez1 = PathSeg::Cubic(CubicBez::new( + (129.0, 139.0), + (190.0, 139.0), + (201.0, 364.0), + (90.0, 364.0), + )); + let bez2 = PathSeg::Cubic(CubicBez::new( + (309.0, 159.0), + (178.0, 159.0), + (215.0, 408.0), + (309.0, 408.0), + )); + let mindist = bez1.min_dist(bez2, 0.001); + assert!((mindist.distance - 50.9966).abs() < 0.5); + } + + #[test] + fn test_overflow() { + let bez1 = PathSeg::Cubic(CubicBez::new( + (232.0, 126.0), + (134.0, 126.0), + (139.0, 232.0), + (141.0, 301.0), + )); + let bez2 = PathSeg::Line(Line::new((359.0, 416.0), (367.0, 755.0))); + let mindist = bez1.min_dist(bez2, 0.001); + assert!((mindist.distance - 246.4731222669117).abs() < 0.5); + } + + #[test] + fn test_out_of_order() { + let bez1 = PathSeg::Cubic(CubicBez::new( + (287.0, 182.0), + (346.0, 277.0), + (356.0, 299.0), + (359.0, 416.0), + )); + let bez2 = PathSeg::Line(Line::new((141.0, 301.0), (152.0, 709.0))); + let mindist1 = bez1.min_dist(bez2, 0.5); + let mindist2 = bez2.min_dist(bez1, 0.5); + assert!((mindist1.distance - mindist2.distance).abs() < 0.5); + } + + #[test] + fn test_line_curve() { + let line = PathSeg::Line(Line::new((929.0, 335.0), (911.0, 340.0))); + + let line_as_bez = PathSeg::Cubic(CubicBez::new( + line.eval(0.0), + line.eval(1.0 / 3.0), + line.eval(2.0 / 3.0), + line.eval(1.0), + )); + + let bez2 = PathSeg::Cubic(CubicBez::new( + (1052.0, 401.0), + (1048.0, 305.0), + (1046.0, 216.0), + (1054.0, 146.0), + )); + let mindist_as_bez = line_as_bez.min_dist(bez2, 0.5); + let mindist_as_line = line.min_dist(bez2, 0.5); + assert!((mindist_as_line.distance - mindist_as_bez.distance).abs() < 0.5); + } +} diff --git a/vendor/kurbo/src/moments.rs b/vendor/kurbo/src/moments.rs new file mode 100644 index 0000000000..c54fe71a7b --- /dev/null +++ b/vendor/kurbo/src/moments.rs @@ -0,0 +1,594 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use crate::{PathEl, Point}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A collect of moment integrals for a path, used for computing +/// shape properties like area, centroid, and inertia. +/// +/// The moments are computed using Green's theorem, which relates the +/// integrals of a function over a closed curve to the integrals of its +/// partial derivatives over the region enclosed by the curve. +#[derive(Debug, Default, Copy, Clone)] +pub struct Moments { + /// The first moment of area about the x-axis. + pub moment_x: f64, + /// The first moment of area about the y-axis. + pub moment_y: f64, + /// The second moment of area about the x-axis (also known as the + /// area moment of inertia about the x-axis). + pub moment_xx: f64, + /// The second moment of area about the xy-axis (also known as the + /// product of inertia). + pub moment_xy: f64, + /// The second moment of area about the y-axis (also known as the + /// area moment of inertia about the y-axis). + pub moment_yy: f64, +} + +impl core::ops::Add for Moments { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + moment_x: self.moment_x + rhs.moment_x, + moment_y: self.moment_y + rhs.moment_y, + moment_xx: self.moment_xx + rhs.moment_xx, + moment_xy: self.moment_xy + rhs.moment_xy, + moment_yy: self.moment_yy + rhs.moment_yy, + } + } +} + +impl Moments { + // The code below is derived from fontTools's fontTools.pens.momentsPen, which is in turn generated + // by running sympy on the Green's theorem integral expressions. + fn handle_line(&mut self, p0: Point, p1: Point) { + let (x0, y0) = (p0.x, p0.y); + let (x1, y1) = (p1.x, p1.y); + let r0 = x1 * y0; + let r1 = x1 * y1; + let r2 = x1.powi(2); + let r3 = r2 * y1; + let r4 = y0 - y1; + let r5 = r4 * x0; + let r6 = x0.powi(2); + let r7 = 2.0 * y0; + let r8 = y0.powi(2); + let r9 = y1.powi(2); + let r10 = x1.powi(3); + let r11 = y0.powi(3); + let r12 = y1.powi(3); + self.moment_x += -r2 * y0 / 6.0 - r3 / 3.0 - r5 * x1 / 6.0 + r6 * (r7 + y1) / 6.0; + self.moment_y += + -r0 * y1 / 6.0 - r8 * x1 / 6.0 - r9 * x1 / 6.0 + x0 * (r8 + r9 + y0 * y1) / 6.0; + self.moment_xx += -r10 * y0 / 12.0 - r10 * y1 / 4.0 - r2 * r5 / 12.0 - r4 * r6 * x1 / 12.0 + + x0.powi(3) * (3.0 * y0 + y1) / 12.0; + self.moment_xy += -r2 * r8 / 24.0 - r2 * r9 / 8.0 - r3 * r7 / 24.0 + + r6 * (r7 * y1 + 3.0 * r8 + r9) / 24.0 + - x0 * x1 * (r8 - r9) / 12.0; + self.moment_yy += -r0 * r9 / 12.0 - r1 * r8 / 12.0 - r11 * x1 / 12.0 - r12 * x1 / 12.0 + + x0 * (r11 + r12 + r8 * y1 + r9 * y0) / 12.0; + } + + fn handle_quad(&mut self, p0: Point, p1: Point, p2: Point) { + let (x0, y0) = (p0.x, p0.y); + let x1 = p1.x; + let y1 = p1.y; + let x2 = p2.x; + let y2 = p2.y; + + let r0 = 2.0 * y1; + let r1 = r0 * x2; + let r2 = x2 * y2; + let r3 = 3.0 * r2; + let r4 = 2.0 * x1; + let r5 = 3.0 * y0; + let r6 = x1.powi(2); + let r7 = x2.powi(2); + let r8 = 4.0 * y1; + let r9 = 10.0 * y2; + let r10 = 2.0 * y2; + let r11 = r4 * x2; + let r12 = x0.powi(2); + let r13 = 10.0 * y0; + let r14 = r4 * y2; + let r15 = x2 * y0; + let r16 = 4.0 * x1; + let r17 = r0 * x1 + r2; + let r18 = r2 * r8; + let r19 = y1.powi(2); + let r20 = 2.0 * r19; + let r21 = y2.powi(2); + let r22 = r21 * x2; + let r23 = 5.0 * r22; + let r24 = y0.powi(2); + let r25 = y0 * y2; + let r26 = 5.0 * r24; + let r27 = x1.powi(3); + let r28 = x2.powi(3); + let r29 = 30.0 * y1; + let r30 = 6.0 * y1; + let r31 = 10.0 * r7 * x1; + let r32 = 5.0 * y2; + let r33 = 12.0 * r6; + let r34 = 30.0 * x1; + let r35 = x1 * y1; + let r36 = r3 + 20.0 * r35; + let r37 = 12.0 * x1; + let r38 = 20.0 * r6; + let r39 = 8.0 * r6 * y1; + let r40 = r32 * r7; + let r41 = 60.0 * y1; + let r42 = 20.0 * r19; + let r43 = 4.0 * r19; + let r44 = 15.0 * r21; + let r45 = 12.0 * x2; + let r46 = 12.0 * y2; + let r47 = 6.0 * x1; + let r48 = 8.0 * r19 * x1 + r23; + let r49 = 8.0 * y1.powi(3); + let r50 = y2.powi(3); + let r51 = y0.powi(3); + let r52 = 10.0 * y1; + let r53 = 12.0 * y1; + self.moment_x += -r11 * (-r10 + y1) / 30.0 + r12 * (r13 + r8 + y2) / 30.0 + r6 * y2 / 15.0 + - r7 * r8 / 30.0 + - r7 * r9 / 30.0 + + x0 * (r14 - r15 - r16 * y0 + r17) / 30.0 + - y0 * (r11 + 2.0 * r6 + r7) / 30.0; + self.moment_y += -r18 / 30.0 - r20 * x2 / 30.0 - r23 / 30.0 - r24 * (r16 + x2) / 30.0 + + x0 * (r0 * y2 + r20 + r21 + r25 + r26 + r8 * y0) / 30.0 + + x1 * y2 * (r10 + y1) / 15.0 + - y0 * (r1 + r17) / 30.0; + self.moment_xx += r12 * (r1 - 5.0 * r15 - r34 * y0 + r36 + r9 * x1) / 420.0 + + 2.0 * r27 * y2 / 105.0 + - r28 * r29 / 420.0 + - r28 * y2 / 4.0 + - r31 * (r0 - 3.0 * y2) / 420.0 + - r6 * x2 * (r0 - r32) / 105.0 + + x0.powi(3) * (r30 + 21.0 * y0 + y2) / 84.0 + - x0 * (r0 * r7 + r15 * r37 - r2 * r37 - r33 * y2 + r38 * y0 - r39 - r40 + r5 * r7) + / 420.0 + - y0 * (8.0 * r27 + 5.0 * r28 + r31 + r33 * x2) / 420.0; + self.moment_xy += r12 * (r13 * y2 + 3.0 * r21 + 105.0 * r24 + r41 * y0 + r42 + r46 * y1) + / 840.0 + - r16 * x2 * (r43 - r44) / 840.0 + - r21 * r7 / 8.0 + - r24 * (r38 + r45 * x1 + 3.0 * r7) / 840.0 + - r41 * r7 * y2 / 840.0 + - r42 * r7 / 840.0 + + r6 * y2 * (r32 + r8) / 210.0 + + x0 * (-r15 * r8 + r16 * r25 + r18 + r21 * r47 - r24 * r34 - r26 * x2 + + r35 * r46 + + r48) + / 420.0 + - y0 * (r16 * r2 + r30 * r7 + r35 * r45 + r39 + r40) / 420.0; + + self.moment_yy += -r2 * r42 / 420.0 + - r22 * r29 / 420.0 + - r24 * (r14 + r36 + r52 * x2) / 420.0 + - r49 * x2 / 420.0 + - r50 * x2 / 12.0 + - r51 * (r47 + x2) / 84.0 + + x0 * (r19 * r46 + + r21 * r5 + + r21 * r52 + + r24 * r29 + + r25 * r53 + + r26 * y2 + + r42 * y0 + + r49 + + 5.0 * r50 + + 35.0 * r51) + / 420.0 + + x1 * y2 * (r43 + r44 + r9 * y1) / 210.0 + - y0 * (r19 * r45 + r2 * r53 - r21 * r4 + r48) / 420.0; + } + + fn handle_cubic(&mut self, p0: Point, p1: Point, p2: Point, p3: Point) { + let x0 = p0.x; + let y0 = p0.y; + let x1 = p1.x; + let y1 = p1.y; + let x2 = p2.x; + let y2 = p2.y; + let x3 = p3.x; + let y3 = p3.y; + + let r0 = 6.0 * y2; + let r1 = r0 * x3; + let r2 = 10.0 * y3; + let r3 = r2 * x3; + let r4 = 3.0 * y1; + let r5 = 6.0 * x1; + let r6 = 3.0 * x2; + let r7 = 6.0 * y1; + let r8 = 3.0 * y2; + let r9 = x2.powi(2); + let r10 = 45.0 * r9; + let r11 = r10 * y3; + let r12 = x3.powi(2); + let r13 = r12 * y2; + let r14 = r12 * y3; + let r15 = 7.0 * y3; + let r16 = 15.0 * x3; + let r17 = r16 * x2; + let r18 = x1.powi(2); + let r19 = 9.0 * r18; + let r20 = x0.powi(2); + let r21 = 21.0 * y1; + let r22 = 9.0 * r9; + let r23 = r7 * x3; + let r24 = 9.0 * y2; + let r25 = r24 * x2 + r3; + let r26 = 9.0 * x2; + let r27 = x2 * y3; + let r28 = -r26 * y1 + 15.0 * r27; + let r29 = 3.0 * x1; + let r30 = 45.0 * x1; + let r31 = 12.0 * x3; + let r32 = 45.0 * r18; + let r33 = 5.0 * r12; + let r34 = r8 * x3; + let r35 = 105.0 * y0; + let r36 = 30.0 * y0; + let r37 = r36 * x2; + let r38 = 5.0 * x3; + let r39 = 15.0 * y3; + let r40 = 5.0 * y3; + let r41 = r40 * x3; + let r42 = x2 * y2; + let r43 = 18.0 * r42; + let r44 = 45.0 * y1; + let r45 = r41 + r43 + r44 * x1; + let r46 = y2 * y3; + let r47 = r46 * x3; + let r48 = y2.powi(2); + let r49 = 45.0 * r48; + let r50 = r49 * x3; + let r51 = y3.powi(2); + let r52 = r51 * x3; + let r53 = y1.powi(2); + let r54 = 9.0 * r53; + let r55 = y0.powi(2); + let r56 = 21.0 * x1; + let r57 = 6.0 * x2; + let r58 = r16 * y2; + let r59 = r39 * y2; + let r60 = 9.0 * r48; + let r61 = r6 * y3; + let r62 = 3.0 * y3; + let r63 = r36 * y2; + let r64 = y1 * y3; + let r65 = 45.0 * r53; + let r66 = 5.0 * r51; + let r67 = x2.powi(3); + let r68 = x3.powi(3); + let r69 = 630.0 * y2; + let r70 = 126.0 * x3; + let r71 = x1.powi(3); + let r72 = 126.0 * x2; + let r73 = 63.0 * r9; + let r74 = r73 * x3; + let r75 = r15 * x3 + 15.0 * r42; + let r76 = 630.0 * x1; + let r77 = 14.0 * x3; + let r78 = 21.0 * r27; + let r79 = 42.0 * x1; + let r80 = 42.0 * x2; + let r81 = x1 * y2; + let r82 = 63.0 * r42; + let r83 = x1 * y1; + let r84 = r41 + r82 + 378.0 * r83; + let r85 = x2 * x3; + let r86 = r85 * y1; + let r87 = r27 * x3; + let r88 = 27.0 * r9; + let r89 = r88 * y2; + let r90 = 42.0 * r14; + let r91 = 90.0 * x1; + let r92 = 189.0 * r18; + let r93 = 378.0 * r18; + let r94 = r12 * y1; + let r95 = 252.0 * x1 * x2; + let r96 = r79 * x3; + let r97 = 30.0 * r85; + let r98 = r83 * x3; + let r99 = 30.0 * x3; + let r100 = 42.0 * x3; + let r101 = r42 * x1; + let r102 = r10 * y2 + 14.0 * r14 + 126.0 * r18 * y1 + r81 * r99; + let r103 = 378.0 * r48; + let r104 = 18.0 * y1; + let r105 = r104 * y2; + let r106 = y0 * y1; + let r107 = 252.0 * y2; + let r108 = r107 * y0; + let r109 = y0 * y3; + let r110 = 42.0 * r64; + let r111 = 378.0 * r53; + let r112 = 63.0 * r48; + let r113 = 27.0 * x2; + let r114 = r27 * y2; + let r115 = r113 * r48 + 42.0 * r52; + let r116 = x3 * y3; + let r117 = 54.0 * r42; + let r118 = r51 * x1; + let r119 = r51 * x2; + let r120 = r48 * x1; + let r121 = 21.0 * x3; + let r122 = r64 * x1; + let r123 = r81 * y3; + let r124 = 30.0 * r27 * y1 + r49 * x2 + 14.0 * r52 + 126.0 * r53 * x1; + let r125 = y2.powi(3); + let r126 = y3.powi(3); + let r127 = y1.powi(3); + let r128 = y0.powi(3); + let r129 = r51 * y2; + let r130 = r112 * y3 + r21 * r51; + let r131 = 189.0 * r53; + let r132 = 90.0 * y2; + self.moment_x += r11 / 840.0 - r13 / 8.0 - r14 / 3.0 - r17 * (-r15 + r8) / 840.0 + + r19 * (r8 + 2.0 * y3) / 840.0 + + r20 * (r0 + r21 + 56.0 * y0 + y3) / 168.0 + + r29 * (-r23 + r25 + r28) / 840.0 + - r4 * (10.0 * r12 + r17 + r22) / 840.0 + + x0 * (12.0 * r27 + r30 * y2 + r34 - r35 * x1 - r37 - r38 * y0 + r39 * x1 - r4 * x3 + + r45) + / 840.0 + - y0 * (r17 + r30 * x2 + r31 * x1 + r32 + r33 + 18.0 * r9) / 840.0; + self.moment_y += -r4 * (r25 + r58) / 840.0 + - r47 / 8.0 + - r50 / 840.0 + - r52 / 6.0 + - r54 * (r6 + 2.0 * x3) / 840.0 + - r55 * (r56 + r57 + x3) / 168.0 + + x0 * (r35 * y1 + + r40 * y0 + + r44 * y2 + + 18.0 * r48 + + 140.0 * r55 + + r59 + + r63 + + 12.0 * r64 + + r65 + + r66) + / 840.0 + + x1 * (r24 * y1 + 10.0 * r51 + r59 + r60 + r7 * y3) / 280.0 + + x2 * y3 * (r15 + r8) / 56.0 + - y0 * (r16 * y1 + r31 * y2 + r44 * x2 + r45 + r61 - r62 * x1) / 840.0; + self.moment_xx += -r12 * r72 * (-r40 + r8) / 9240.0 + + 3.0 * r18 * (r28 + r34 - r38 * y1 + r75) / 3080.0 + + r20 + * (r24 * x3 - r72 * y0 - r76 * y0 - r77 * y0 + + r78 + + r79 * y3 + + r80 * y1 + + 210.0 * r81 + + r84) + / 9240.0 + - r29 + * (r12 * r21 + 14.0 * r13 + r44 * r9 - r73 * y3 + 54.0 * r86 + - 84.0 * r87 + - r89 + - r90) + / 9240.0 + - r4 * (70.0 * r12 * x2 + 27.0 * r67 + 42.0 * r68 + r74) / 9240.0 + + 3.0 * r67 * y3 / 220.0 + - r68 * r69 / 9240.0 + - r68 * y3 / 4.0 + - r70 * r9 * (-r62 + y2) / 9240.0 + + 3.0 * r71 * (r24 + r40) / 3080.0 + + x0.powi(3) * (r24 + r44 + 165.0 * y0 + y3) / 660.0 + + x0 * (r100 * r27 + 162.0 * r101 + r102 + r11 + 63.0 * r18 * y3 + r27 * r91 + - r33 * y0 + - r37 * x3 + + r43 * x3 + - r73 * y0 + - r88 * y1 + + r92 * y2 + - r93 * y0 + - 9.0 * r94 + - r95 * y0 + - r96 * y0 + - r97 * y1 + - 18.0 * r98 + + r99 * x1 * y3) + / 9240.0 + - y0 * (r12 * r56 + + r12 * r80 + + r32 * x3 + + 45.0 * r67 + + 14.0 * r68 + + 126.0 * r71 + + r74 + + r85 * r91 + + 135.0 * r9 * x1 + + r92 * x2) + / 9240.0; + self.moment_xy += -r103 * r12 / 18480.0 - r12 * r51 / 8.0 - 3.0 * r14 * y2 / 44.0 + + 3.0 * r18 * (r105 + r2 * y1 + 18.0 * r46 + 15.0 * r48 + 7.0 * r51) / 6160.0 + + r20 + * (1260.0 * r106 + + r107 * y1 + + r108 + + 28.0 * r109 + + r110 + + r111 + + r112 + + 30.0 * r46 + + 2310.0 * r55 + + r66) + / 18480.0 + - r54 * (7.0 * r12 + 18.0 * r85 + 15.0 * r9) / 18480.0 + - r55 * (r33 + r73 + r93 + r95 + r96 + r97) / 18480.0 + - r7 * (42.0 * r13 + r82 * x3 + 28.0 * r87 + r89 + r90) / 18480.0 + - 3.0 * r85 * (r48 - r66) / 220.0 + + 3.0 * r9 * y3 * (r62 + 2.0 * y2) / 440.0 + + x0 * (-r1 * y0 - 84.0 * r106 * x2 + + r109 * r56 + + 54.0 * r114 + + r117 * y1 + + 15.0 * r118 + + 21.0 * r119 + + 81.0 * r120 + + r121 * r46 + + 54.0 * r122 + + 60.0 * r123 + + r124 + - r21 * x3 * y0 + + r23 * y3 + - r54 * x3 + - r55 * r72 + - r55 * r76 + - r55 * r77 + + r57 * y0 * y3 + + r60 * x3 + + 84.0 * r81 * y0 + + 189.0 * r81 * y1) + / 9240.0 + + x1 * (r104 * r27 - r105 * x3 - r113 * r53 + 63.0 * r114 + r115 - r16 * r53 + + 28.0 * r47 + + r51 * r80) + / 3080.0 + - y0 * (54.0 * r101 + r102 + r116 * r5 + r117 * x3 + 21.0 * r13 - r19 * y3 + + r22 * y3 + + r78 * x3 + + 189.0 * r83 * x2 + + 60.0 * r86 + + 81.0 * r9 * y1 + + 15.0 * r94 + + 54.0 * r98) + / 9240.0; + self.moment_yy += -r103 * r116 / 9240.0 + - r125 * r70 / 9240.0 + - r126 * x3 / 12.0 + - 3.0 * r127 * (r26 + r38) / 3080.0 + - r128 * (r26 + r30 + x3) / 660.0 + - r4 * (r112 * x3 + r115 - 14.0 * r119 + 84.0 * r47) / 9240.0 + - r52 * r69 / 9240.0 + - r54 * (r58 + r61 + r75) / 9240.0 + - r55 * (r100 * y1 + r121 * y2 + r26 * y3 + r79 * y2 + r84 + 210.0 * x2 * y1) / 9240.0 + + x0 * (r108 * y1 + + r110 * y0 + + r111 * y0 + + r112 * y0 + + 45.0 * r125 + + 14.0 * r126 + + 126.0 * r127 + + 770.0 * r128 + + 42.0 * r129 + + r130 + + r131 * y2 + + r132 * r64 + + 135.0 * r48 * y1 + + 630.0 * r55 * y1 + + 126.0 * r55 * y2 + + 14.0 * r55 * y3 + + r63 * y3 + + r65 * y3 + + r66 * y0) + / 9240.0 + + x1 * (27.0 * r125 + + 42.0 * r126 + + 70.0 * r129 + + r130 + + r39 * r53 + + r44 * r48 + + 27.0 * r53 * y2 + + 54.0 * r64 * y2) + / 3080.0 + + 3.0 * x2 * y3 * (r48 + r66 + r8 * y3) / 220.0 + - y0 * (r100 * r46 + 18.0 * r114 + - 9.0 * r118 + - 27.0 * r120 + - 18.0 * r122 + - 30.0 * r123 + + r124 + + r131 * x2 + + r132 * x3 * y1 + + 162.0 * r42 * y1 + + r50 + + 63.0 * r53 * x3 + + r64 * r99) + / 9240.0; + } +} + +/// A trait for types that can provide moment integrals for a path using Green's theorem. +pub trait ParamCurveMoments<'a> { + /// Returns the moment integrals for the path using Green's theorem. + fn moments(&'a self) -> Moments; +} + +impl<'a, T: 'a> ParamCurveMoments<'a> for T +where + &'a T: IntoIterator, +{ + fn moments(&'a self) -> Moments { + let mut moments = Moments::default(); + let mut start_pt: Point = Point::ZERO; + let mut cur: Point = Point::ZERO; + for el in self { + match el { + PathEl::MoveTo(p) => { + start_pt = p; + cur = p; + } + PathEl::LineTo(p) => { + moments.handle_line(cur, p); + cur = p; + } + PathEl::QuadTo(p0, p1) => { + moments.handle_quad(cur, p0, p1); + cur = p1; + } + PathEl::CurveTo(p1, p2, p3) => { + moments.handle_cubic(cur, p1, p2, p3); + cur = p3; + } + PathEl::ClosePath => { + if cur != start_pt { + moments.handle_line(cur, start_pt); + cur = start_pt; + } + } + } + } + moments + } +} + +#[cfg(test)] +mod tests { + use crate::BezPath; + + use super::*; + + macro_rules! assert_approx_eq { + ($x: expr, $y: expr) => { + assert!(($x - $y).abs() < 1e-8, "{} != {}", $x, $y); + }; + } + + #[test] + fn test_moments() { + let path = BezPath::from_vec(vec![ + PathEl::MoveTo(Point::new(0.0, 0.0)), + PathEl::LineTo(Point::new(1.0, 0.0)), + PathEl::LineTo(Point::new(1.0, 1.0)), + PathEl::LineTo(Point::new(0.0, 1.0)), + PathEl::ClosePath, + ]); + let moments = path.moments(); + assert_approx_eq!(moments.moment_x, 0.5); + assert_approx_eq!(moments.moment_y, 0.5); + assert_approx_eq!(moments.moment_xx, 0.3333333333333333); + assert_approx_eq!(moments.moment_xy, 0.25); + assert_approx_eq!(moments.moment_yy, 0.3333333333333333); + } +} diff --git a/vendor/kurbo/src/offset.rs b/vendor/kurbo/src/offset.rs new file mode 100644 index 0000000000..48ecfad14e --- /dev/null +++ b/vendor/kurbo/src/offset.rs @@ -0,0 +1,668 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Computation of offset curves of cubic Béziers. +//! +//! The main algorithm in this module is a new technique designed for robustness +//! and speed. The details are involved; hopefully there will be a paper. + +use arrayvec::ArrayVec; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +use crate::{ + BezPath, CubicBez, ParamCurve, ParamCurveDeriv, PathSeg, Point, QuadBez, Vec2, + common::{solve_itp, solve_quadratic}, +}; + +/// State used for computing an offset curve of a single cubic. +struct CubicOffset { + /// The cubic being offset. This has been regularized. + c: CubicBez, + /// The derivative of `c`. + q: QuadBez, + /// The offset distance (same as the argument). + d: f64, + /// `c0 + c1 t + c2 t^2` is the cross product of second and first + /// derivatives of the underlying cubic, multiplied by the offset. + /// This is used for computing cusps on the offset curve. + /// + /// Note that given a curve `c(t)`, its signed curvature is + /// `c''(t) x c'(t) / ||c'(t)||^3`. See also [`Self::cusp_sign`]. + c0: f64, + c1: f64, + c2: f64, + /// The tolerance (same as the argument). + tolerance: f64, +} + +// We never let cusp values have an absolute value smaller than +// this. When a cusp is found, determine its sign and use this value. +const CUSP_EPSILON: f64 = 1e-12; + +/// Number of points for least-squares fit and error evaluation. +/// +/// This value is a tradeoff between accuracy and performance. The main risk in it +/// being to small is under-sampling the error and thus letting excessive error +/// slip through. That said, the "arc drawing" approach is designed to be robust +/// and not generate approximate results with narrow error peaks, even in near-cusp +/// "J" shape curves. +const N_LSE: usize = 8; + +/// The proportion of transverse error that is blended in the least-squares logic. +const BLEND: f64 = 1e-3; + +/// Maximum recursion depth. +/// +/// Recursion is bounded to this depth, so the total number of subdivisions will +/// not exceed two to this power. +/// +/// This is primarily a "belt and suspenders" robustness guard. In normal operation, +/// the recursion bound should never be reached, as accuracy improves very quickly +/// on subdivision. For unreasonably large coordinate values or small tolerances, it +/// is possible, and in those cases the result will be out of tolerance. +/// +/// Perhaps should be configurable. +const MAX_DEPTH: usize = 8; + +/// State local to a subdivision +struct OffsetRec { + t0: f64, + t1: f64, + // unit tangent at t0 + utan0: Vec2, + // unit tangent at t1 + utan1: Vec2, + cusp0: f64, + cusp1: f64, + /// Recursion depth + depth: usize, +} + +/// Result of error evaluation +struct ErrEval { + /// Maximum detected error + err_squared: f64, + /// Unit normals sampled uniformly across approximation + unorms: [Vec2; N_LSE], + /// Difference between point on source curve and normal from approximation. + err_vecs: [Vec2; N_LSE], +} + +/// Result of subdivision +struct SubdivisionPoint { + /// Source curve t value at subdivision point + t: f64, + /// Unit tangent at subdivision point + utan: Vec2, +} + +/// Compute an approximate offset curve. +/// +/// The parallel curve of `c` offset by `d` is written to the `result` path. +/// +/// There is a fair amount of attention to robustness, but this method is not suitable +/// for degenerate cubics with entirely co-linear control points. Those cases should be +/// handled before calling this function, by replacing them with linear segments. +pub fn offset_cubic(c: CubicBez, d: f64, tolerance: f64, result: &mut BezPath) { + result.truncate(0); + // A tuning parameter for regularization. A value too large may distort the curve, + // while a value too small may fail to generate smooth curves. This is a somewhat + // arbitrary value, and should be revisited. + const DIM_TUNE: f64 = 0.25; + // We use regularization to perturb the curve to avoid *interior* zero-derivative + // cusps. There is robustness logic in place to handle zero derivatives at the + // endpoints. + // + // As a performance note, it might be a good idea to move regularization and + // tangent determination to the caller, as those computations are the same for both + // signs of `d`. + let c_regularized = c.regularize_cusp(tolerance * DIM_TUNE); + let co = CubicOffset::new(c_regularized, d, tolerance); + let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + let utan0 = tan0.normalize(); + let utan1 = tan1.normalize(); + let cusp0 = co.endpoint_cusp(co.q.p0, co.c0); + let cusp1 = co.endpoint_cusp(co.q.p2, co.c0 + co.c1 + co.c2); + result.move_to(c.p0 + d * utan0.turn_90()); + let rec = OffsetRec::new(0., 1., utan0, utan1, cusp0, cusp1, 0); + co.offset_rec(&rec, result); +} + +impl CubicOffset { + /// Create a new curve from Bézier segment and offset. + fn new(c: CubicBez, d: f64, tolerance: f64) -> Self { + let q = c.deriv(); + let d2 = 2.0 * d; + let p1xp0 = q.p1.to_vec2().cross(q.p0.to_vec2()); + let p2xp0 = q.p2.to_vec2().cross(q.p0.to_vec2()); + let p2xp1 = q.p2.to_vec2().cross(q.p1.to_vec2()); + CubicOffset { + c, + q, + d, + c0: d2 * p1xp0, + c1: d2 * (p2xp0 - 2.0 * p1xp0), + c2: d2 * (p2xp1 - p2xp0 + p1xp0), + tolerance, + } + } + + /// Compute curvature of the source curve times offset plus 1. + /// + /// This quantity is called "cusp" because cusps appear in the offset curve + /// where this value crosses zero. This is based on the geometric property + /// that the offset curve has a cusp when the radius of curvature of the + /// source curve is equal to the offset curve's distance. + /// + /// Note: there is a potential division by zero when the derivative vanishes. + /// We avoid doing so for interior points by regularizing the cubic beforehand. + /// We avoid doing so for endpoints by calling `endpoint_cusp` instead. + fn cusp_sign(&self, t: f64) -> f64 { + let ds2 = self.q.eval(t).to_vec2().hypot2(); + ((self.c2 * t + self.c1) * t + self.c0) / (ds2 * ds2.sqrt()) + 1.0 + } + + /// Compute cusp value of endpoint. + /// + /// This is a special case of [`Self::cusp_sign`]. For the start point, `tan` should be + /// the start point tangent and `y` should be `c0`. For the end point, `tan` should be + /// the end point tangent and `y` should be `c0 + c1 + c2`. + /// + /// This is just evaluating the polynomial at t=0 and t=1. + /// + /// See [`Self::cusp_sign`] for a description of what "cusp value" means. + fn endpoint_cusp(&self, tan: Point, y: f64) -> f64 { + // Robustness to avoid divide-by-zero when derivatives vanish + const TAN_DIST_EPSILON: f64 = 1e-12; + let tan_dist = tan.to_vec2().hypot().max(TAN_DIST_EPSILON); + let rsqrt = 1.0 / tan_dist; + y * (rsqrt * rsqrt * rsqrt) + 1.0 + } + + /// Primary entry point for recursive subdivision. + /// + /// At a high level, this method determines whether subdivision is necessary. If + /// so, it determines a subdivision point and then recursively calls itself on + /// both subdivisions. If not, it computes a single cubic Bézier to approximate + /// the offset curve, and appends it to `result`. + fn offset_rec(&self, rec: &OffsetRec, result: &mut BezPath) { + // First, determine whether the offset curve contains a cusp. If the sign + // of the cusp value (curvature times offset plus 1) is different at the + // subdivision endpoints, then there is definitely a cusp inside. Find it and + // subdivide there. + // + // Note that there's a possibility the curve has two (or, potentially, any + // even number). We don't rigorously check for this case; if the measured + // error comes in under the tolerance, we simply accept it. Otherwise, in + // the common case we expect to detect a sign crossing from the new + // subdivision point. + if rec.cusp0 * rec.cusp1 < 0.0 { + let a = rec.t0; + let b = rec.t1; + let s = rec.cusp1.signum(); + let f = |t| s * self.cusp_sign(t); + let k1 = 0.2 / (b - a); + const ITP_EPS: f64 = 1e-12; + let t = solve_itp(f, a, b, ITP_EPS, 1, k1, s * rec.cusp0, s * rec.cusp1); + // TODO(robustness): If we're unlucky, there will be 3 cusps between t0 + // and t1, and the solver will land on the middle one. In that case, the + // derivative on cusp will be the opposite sign as expected. + // + // If we're even more unlucky, there is a second-order cusp, both zero + // cusp value and zero derivative. + let utan_t = self.q.eval(t).to_vec2().normalize(); + let cusp_t_minus = CUSP_EPSILON.copysign(rec.cusp0); + let cusp_t_plus = CUSP_EPSILON.copysign(rec.cusp1); + self.subdivide(rec, result, t, utan_t, cusp_t_minus, cusp_t_plus); + return; + } + // We determine the first approximation to the offset curve. + let (mut a, mut b) = self.draw_arc(rec); + let dt = (rec.t1 - rec.t0) * (1.0 / (N_LSE + 1) as f64); + // These represent t values on the source curve. + let mut ts = core::array::from_fn(|i| rec.t0 + (i + 1) as f64 * dt); + let mut c_approx = self.apply(rec, a, b); + let err_init = self.eval_err(rec, c_approx, &mut ts); + let mut err = err_init; + // Number of least-squares refinement steps. More gives a smaller + // error, but takes more time. + const N_REFINE: usize = 2; + for _ in 0..N_REFINE { + if err.err_squared <= self.tolerance * self.tolerance { + break; + } + let (a2, b2) = self.refine_least_squares(rec, a, b, &err); + let c_approx2 = self.apply(rec, a2, b2); + let err2 = self.eval_err(rec, c_approx2, &mut ts); + if err2.err_squared >= err.err_squared { + break; + } + err = err2; + (a, b) = (a2, b2); + c_approx = c_approx2; + } + if rec.depth < MAX_DEPTH && err.err_squared > self.tolerance * self.tolerance { + let SubdivisionPoint { t, utan } = self.find_subdivision_point(rec); + // TODO(robustness): if cusp is extremely near zero, then assign epsilon + // with alternate signs based on derivative of cusp. + let cusp = self.cusp_sign(t); + self.subdivide(rec, result, t, utan, cusp, cusp); + } else { + result.curve_to(c_approx.p1, c_approx.p2, c_approx.p3); + } + } + + /// Recursively subdivide. + /// + /// In the case of subdividing at a cusp, the cusp value at the subdivision point + /// is mathematically zero, but in those cases we treat it as a signed infinitesimal + /// value representing the values at t minus epsilon and t plus epsilon. + /// + /// Note that unit tangents are passed down explicitly. In the general case, they + /// are equal to the derivative (evaluated at that t value) normalized to unit + /// length, but in cases where the derivative is near-zero, they are computed more + /// robustly. + fn subdivide( + &self, + rec: &OffsetRec, + result: &mut BezPath, + t: f64, + utan_t: Vec2, + cusp_t_minus: f64, + cusp_t_plus: f64, + ) { + let rec0 = OffsetRec::new( + rec.t0, + t, + rec.utan0, + utan_t, + rec.cusp0, + cusp_t_minus, + rec.depth + 1, + ); + self.offset_rec(&rec0, result); + let rec1 = OffsetRec::new( + t, + rec.t1, + utan_t, + rec.utan1, + cusp_t_plus, + rec.cusp1, + rec.depth + 1, + ); + self.offset_rec(&rec1, result); + } + + /// Convert from (a, b) parameter space to the approximate cubic Bézier. + /// + /// The offset approximation can be considered `B(t) + d * D(t)`, where `D(t)` + /// is roughly a unit vector in the direction of the unit normal of the source + /// curve. (The word "roughly" is appropriate because transverse error may + /// cancel out normal error, resulting in a lower error than either alone). + /// The endpoints of `D(t)` must be the unit normals of the source curve, and + /// the endpoint tangents of `D(t)` must tangent to the endpoint tangents of + /// the source curve, to ensure G1 continuity. + /// + /// The (a, b) parameters refer to the magnitude of the vector from the endpoint + /// to the corresponding control point in `D(t)`, the direction being determined + /// by the unit tangent. + /// + /// When the candidate solution would lead to negative distance from the + /// endpoint to the control point, that distance is clamped to zero. Otherwise + /// such solutions should be considered invalid, and have the unpleasant + /// property of sometimes passing error tolerance checks. + fn apply(&self, rec: &OffsetRec, a: f64, b: f64) -> CubicBez { + // wondering if p0 and p3 should be in rec + // Scale factor from derivatives to displacements + let s = (1. / 3.) * (rec.t1 - rec.t0); + let p0 = self.c.eval(rec.t0) + self.d * rec.utan0.turn_90(); + let l0 = s * self.q.eval(rec.t0).to_vec2().length() + a * self.d; + let mut p1 = p0; + if l0 * rec.cusp0 > 0.0 { + p1 += l0 * rec.utan0; + } + let p3 = self.c.eval(rec.t1) + self.d * rec.utan1.turn_90(); + let mut p2 = p3; + let l1 = s * self.q.eval(rec.t1).to_vec2().length() - b * self.d; + if l1 * rec.cusp1 > 0.0 { + p2 -= l1 * rec.utan1; + } + CubicBez::new(p0, p1, p2, p3) + } + + /// Compute arc approximation. + /// + /// This is called "arc drawing" because if we just look at the delta + /// vector, it describes an arc from the initial unit normal to the final unit + /// normal, with "as smooth as possible" parametrization. This approximation + /// is not necessarily great, but is very robust, and in particular, accuracy + /// does not degrade for J shaped near-cusp source curves or when the offset + /// distance is large (with respect to the source curve arc length). + /// + /// It is a pretty good approximation overall and has very clean O(n^4) scaling. + /// Its worst performance is on curves with a large cubic component, where it + /// undershoots. The theory is that the least squares refinement improves those + /// cases. + fn draw_arc(&self, rec: &OffsetRec) -> (f64, f64) { + // possible optimization: this can probably be done with vectors + // rather than arctangent + let th = rec.utan1.cross(rec.utan0).atan2(rec.utan1.dot(rec.utan0)); + let a = (2. / 3.) / (1.0 + (0.5 * th).cos()) * 2.0 * (0.5 * th).sin(); + let b = -a; + (a, b) + } + + /// Evaluate error and also refine t values. + /// + /// Returns evaluation of error including error vectors and (squared) + /// maximum error. + /// + /// The vector of t values represents points on the source curve; the logic + /// here is a Newton step to bring those points closer to the normal ray of + /// the approximation. + fn eval_err(&self, rec: &OffsetRec, c_approx: CubicBez, ts: &mut [f64; N_LSE]) -> ErrEval { + let qa = c_approx.deriv(); + let mut err_squared = 0.0; + let mut unorms = [Vec2::ZERO; N_LSE]; + let mut err_vecs = [Vec2::ZERO; N_LSE]; + for i in 0..N_LSE { + let ta = (i + 1) as f64 * (1.0 / (N_LSE + 1) as f64); + let mut t = ts[i]; + let p = self.c.eval(t); + // Newton step to refine t value + let pa = c_approx.eval(ta); + let tana = qa.eval(ta).to_vec2(); + t += tana.dot(pa - p) / tana.dot(self.q.eval(t).to_vec2()); + t = t.max(rec.t0).min(rec.t1); + ts[i] = t; + let cusp = rec.cusp0.signum(); + let unorm = cusp * tana.normalize().turn_90(); + unorms[i] = unorm; + let p_new = self.c.eval(t) + self.d * unorm; + let err_vec = pa - p_new; + err_vecs[i] = err_vec; + let mut dist_err_squared = err_vec.length_squared(); + if !dist_err_squared.is_finite() { + // A hack to make sure we reject bad refinements + dist_err_squared = 1e12; + } + // Note: consider also incorporating angle error + err_squared = dist_err_squared.max(err_squared); + } + ErrEval { + err_squared, + unorms, + err_vecs, + } + } + + /// Refine an approximation, minimizing least squares error. + /// + /// Compute the approximation that minimizes least squares error, based on the given error + /// evaluation. + /// + /// The effectiveness of this refinement varies. Basically, if the curve has a large cubic + /// component, then the arc drawing will undershoot systematically and this refinement will + /// reduce error considerably. In other cases, it will eventually converge to a local + /// minimum, but convergence is slow. + /// + /// The `BLEND` parameter controls a tradeoff between robustness and speed of convergence. + /// In the happy case, convergence is fast and not very sensitive to this parameter. If the + /// parameter is too small, then in near-parabola cases the determinant will be small and + /// the result not numerically stable. + /// + /// A value of 1.0 for `BLEND` corresponds to essentially the Hoschek method, minimizing + /// Euclidean distance (which tends to over-anchor on the given t values). A value of 0 would + /// minimize the dot product of error wrt the normal vector, ignoring the cross product + /// component. + /// + /// A possible future direction would be to tune the parameter adaptively. + fn refine_least_squares(&self, rec: &OffsetRec, a: f64, b: f64, err: &ErrEval) -> (f64, f64) { + let mut aa = 0.0; + let mut ab = 0.0; + let mut ac = 0.0; + let mut bb = 0.0; + let mut bc = 0.0; + for i in 0..N_LSE { + let n = err.unorms[i]; + let err_vec = err.err_vecs[i]; + let c_n = err_vec.dot(n); + let c_t = err_vec.cross(n); + let a_n = A_WEIGHTS[i] * rec.utan0.dot(n); + let a_t = A_WEIGHTS[i] * rec.utan0.cross(n); + let b_n = B_WEIGHTS[i] * rec.utan1.dot(n); + let b_t = B_WEIGHTS[i] * rec.utan1.cross(n); + aa += a_n * a_n + BLEND * (a_t * a_t); + ab += a_n * b_n + BLEND * a_t * b_t; + ac += a_n * c_n + BLEND * a_t * c_t; + bb += b_n * b_n + BLEND * (b_t * b_t); + bc += b_n * c_n + BLEND * b_t * c_t; + } + let idet = 1.0 / (self.d * (aa * bb - ab * ab)); + let delta_a = idet * (ac * bb - ab * bc); + let delta_b = idet * (aa * bc - ac * ab); + (a - delta_a, b - delta_b) + } + + /// Decide where to subdivide when error is exceeded. + /// + /// For curves not containing an inflection point, subdivide at the tangent + /// bisecting the endpoint tangents. The logic is that for a near cusp in the + /// source curve, you want the subdivided sections to be approximately + /// circular arcs with progressively smaller angles. + /// + /// When there is an inflection point (or, more specifically, when the curve + /// crosses its chord), bisecting the angle can lead to very lopsided arc + /// lengths, so just subdivide by t in that case. + fn find_subdivision_point(&self, rec: &OffsetRec) -> SubdivisionPoint { + let t = 0.5 * (rec.t0 + rec.t1); + let q_t = self.q.eval(t).to_vec2(); + let x0 = rec.utan0.cross(q_t).abs(); + let x1 = rec.utan1.cross(q_t).abs(); + const SUBDIVIDE_THRESH: f64 = 0.1; + if x0 > SUBDIVIDE_THRESH * x1 && x1 > SUBDIVIDE_THRESH * x0 { + let utan = q_t.normalize(); + return SubdivisionPoint { t, utan }; + } + + // Note: do we want to track p0 & p3 in rec, to avoid repeated eval? + let chord = self.c.eval(rec.t1) - self.c.eval(rec.t0); + if chord.cross(rec.utan0) * chord.cross(rec.utan1) < 0.0 { + let tan = rec.utan0 + rec.utan1; + if let Some(subdivision) = + self.subdivide_for_tangent(rec.utan0, rec.t0, rec.t1, tan, false) + { + return subdivision; + } + } + // Curve definitely has an inflection point + // Try to subdivide based on integral of absolute curvature. + + // Tangents at recursion endpoints and inflection points. + let mut tangents: ArrayVec = ArrayVec::new(); + let mut ts: ArrayVec = ArrayVec::new(); + tangents.push(rec.utan0); + ts.push(rec.t0); + for t in self.c.inflections() { + if t > rec.t0 && t < rec.t1 { + tangents.push(self.q.eval(t).to_vec2()); + ts.push(t); + } + } + tangents.push(rec.utan1); + ts.push(rec.t1); + let mut arc_angles: ArrayVec = ArrayVec::new(); + let mut sum = 0.0; + for i in 0..tangents.len() - 1 { + let tan0 = tangents[i]; + let tan1 = tangents[i + 1]; + let th = tan0.cross(tan1).atan2(tan0.dot(tan1)); + sum += th.abs(); + arc_angles.push(th); + } + let mut target = sum * 0.5; + let mut i = 0; + while arc_angles[i].abs() < target { + target -= arc_angles[i].abs(); + i += 1; + } + let rotation = Vec2::from_angle(target.copysign(arc_angles[i])); + let base = tangents[i]; + let tan = base.rotate_scale(rotation); + let utan0 = if i == 0 { rec.utan0 } else { base.normalize() }; + self.subdivide_for_tangent(utan0, ts[i], ts[i + 1], tan, true) + .unwrap() + } + + /// Find a subdivision point, given a tangent vector. + /// + /// When subdividing by bisecting the angle (or, more generally, subdividing by + /// the L1 norm of curvature when there are inflection points), we find the + /// subdivision point by solving for the tangent matching, specifically the + /// cross-product of the tangent and the curve's derivative being zero. For + /// internal cusps, subdividing near the cusp is a good thing, but there is + /// still a robustness concern for vanishing derivative at the endpoints. + fn subdivide_for_tangent( + &self, + utan0: Vec2, + t0: f64, + t1: f64, + tan: Vec2, + force: bool, + ) -> Option { + let mut t = 0.0; + let mut n_soln = 0; + // set up quadratic equation for matching tangents + let z0 = tan.cross(self.q.p0.to_vec2()); + let z1 = tan.cross(self.q.p1.to_vec2()); + let z2 = tan.cross(self.q.p2.to_vec2()); + let c0 = z0; + let c1 = 2.0 * (z1 - z0); + let c2 = (z2 - z1) - (z1 - z0); + for root in solve_quadratic(c0, c1, c2) { + if root >= t0 && root <= t1 { + t = root; + n_soln += 1; + } + } + if n_soln != 1 { + if !force { + return None; + } + // Numerical failure, try to subdivide at cusp; we pick the + // smaller derivative. + if self.q.eval(t0).to_vec2().length_squared() + > self.q.eval(t1).to_vec2().length_squared() + { + t = t1; + } else { + t = t0; + } + } + let q = self.q.eval(t).to_vec2(); + const UTAN_EPSILON: f64 = 1e-12; + let utan = if n_soln == 1 && q.length_squared() >= UTAN_EPSILON { + q.normalize() + } else if tan.length_squared() >= UTAN_EPSILON { + // Curve has a zero-derivative cusp but angles well defined + tan.normalize() + } else { + // 180 degree U-turn, arbitrarily pick a direction. + // If we get to this point, there will probably be a failure. + utan0.turn_90() + }; + Some(SubdivisionPoint { t, utan }) + } +} + +impl OffsetRec { + #[allow(clippy::too_many_arguments)] + fn new( + t0: f64, + t1: f64, + utan0: Vec2, + utan1: Vec2, + cusp0: f64, + cusp1: f64, + depth: usize, + ) -> Self { + OffsetRec { + t0, + t1, + utan0, + utan1, + cusp0, + cusp1, + depth, + } + } +} + +/// Compute Bézier weights for evenly subdivided t values. +const fn mk_a_weights(rev: bool) -> [f64; N_LSE] { + let mut result = [0.0; N_LSE]; + let mut i = 0; + while i < N_LSE { + let t = (i + 1) as f64 / (N_LSE + 1) as f64; + let mt = 1. - t; + let ix = if rev { N_LSE - 1 - i } else { i }; + result[ix] = 3.0 * mt * t * mt; + i += 1; + } + result +} + +const A_WEIGHTS: [f64; N_LSE] = mk_a_weights(false); +const B_WEIGHTS: [f64; N_LSE] = mk_a_weights(true); + +#[cfg(test)] +mod tests { + use super::offset_cubic; + use crate::{BezPath, CubicBez, PathEl}; + + // This test tries combinations of parameters that have caused problems in the past. + #[test] + fn pathological_curves() { + let curve = CubicBez { + p0: (-1236.3746269978635, 152.17981429574826).into(), + p1: (-1175.18662093517, 108.04721798590596).into(), + p2: (-1152.142883879584, 105.76260301083356).into(), + p3: (-1151.842639804639, 105.73040758939104).into(), + }; + let offset = 3603.7267536453924; + let accuracy = 0.1; + + let mut result = BezPath::new(); + offset_cubic(curve, offset, accuracy, &mut result); + assert!(matches!(result.iter().next(), Some(PathEl::MoveTo(_)))); + + let mut result = BezPath::new(); + offset_cubic(curve, offset, accuracy, &mut result); + assert!(matches!(result.iter().next(), Some(PathEl::MoveTo(_)))); + } + + /// Cubic offset that used to trigger infinite recursion. + #[test] + fn infinite_recursion() { + const TOLERANCE: f64 = 0.1; + const OFFSET: f64 = -0.5; + let c = CubicBez::new( + (1096.2962962962963, 593.90243902439033), + (1043.6213991769548, 593.90243902439033), + (1030.4526748971193, 593.90243902439033), + (1056.7901234567901, 593.90243902439033), + ); + + let mut result = BezPath::new(); + offset_cubic(c, OFFSET, TOLERANCE, &mut result); + } + + #[test] + fn test_cubic_offset_simple_line() { + let cubic = CubicBez::new((0., 0.), (10., 0.), (20., 0.), (30., 0.)); + let mut result = BezPath::new(); + offset_cubic(cubic, 5., 1e-6, &mut result); + } +} diff --git a/vendor/kurbo/src/param_curve.rs b/vendor/kurbo/src/param_curve.rs new file mode 100644 index 0000000000..7fff046d89 --- /dev/null +++ b/vendor/kurbo/src/param_curve.rs @@ -0,0 +1,221 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A trait for curves parameterized by a scalar. + +use core::ops::Range; + +use arrayvec::ArrayVec; + +use crate::{Point, Rect, common}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A default value for methods that take an 'accuracy' argument. +/// +/// This value is intended to be suitable for general-purpose use, such as +/// 2d graphics. +pub const DEFAULT_ACCURACY: f64 = 1e-6; + +/// A curve parameterized by a scalar. +/// +/// If the result is interpreted as a point, this represents a curve. +/// But the result can be interpreted as a vector as well. +pub trait ParamCurve: Sized { + /// Evaluate the curve at parameter `t`. + /// + /// Generally `t` is in the range [0..1]. + fn eval(&self, t: f64) -> Point; + + /// Get a subsegment of the curve for the given parameter range. + fn subsegment(&self, range: Range) -> Self; + + /// Subdivide into (roughly) halves. + #[inline] + fn subdivide(&self) -> (Self, Self) { + (self.subsegment(0.0..0.5), self.subsegment(0.5..1.0)) + } + + /// The start point. + fn start(&self) -> Point { + self.eval(0.0) + } + + /// The end point. + fn end(&self) -> Point { + self.eval(1.0) + } +} + +// TODO: I might not want to have separate traits for all these. + +/// A differentiable parameterized curve. +pub trait ParamCurveDeriv { + /// The parametric curve obtained by taking the derivative of this one. + type DerivResult: ParamCurve; + + /// The derivative of the curve. + /// + /// Note that the type of the return value is somewhat inaccurate, as + /// the derivative of a curve (mapping of param to point) is a mapping + /// of param to vector. We choose to accept this rather than have a + /// more complex type scheme. + fn deriv(&self) -> Self::DerivResult; + + /// Estimate arclength using Gaussian quadrature. + /// + /// The coefficients are assumed to cover the range (-1..1), which is + /// traditional. + #[inline] + fn gauss_arclen(&self, coeffs: &[(f64, f64)]) -> f64 { + let d = self.deriv(); + coeffs + .iter() + .map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot()) + .sum::() + * 0.5 + } +} + +/// A parameterized curve that can have its arc length measured. +pub trait ParamCurveArclen: ParamCurve { + /// The arc length of the curve. + /// + /// The result is accurate to the given accuracy (subject to + /// roundoff errors for ridiculously low values). Compute time + /// may vary with accuracy, if the curve needs to be subdivided. + fn arclen(&self, accuracy: f64) -> f64; + + /// Solve for the parameter that has the given arc length from the start. + /// + /// This implementation uses the IPT method, as provided by + /// [`common::solve_itp`]. This is as robust as bisection but + /// typically converges faster. In addition, the method takes + /// care to compute arc lengths of increasingly smaller segments + /// of the curve, as that is likely faster than repeatedly + /// computing the arc length of the segment starting at t=0. + fn inv_arclen(&self, arclen: f64, accuracy: f64) -> f64 { + if arclen <= 0.0 { + return 0.0; + } + let total_arclen = self.arclen(accuracy); + if arclen >= total_arclen { + return 1.0; + } + let mut t_last = 0.0; + let mut arclen_last = 0.0; + let epsilon = accuracy / total_arclen; + let n = 1.0 - epsilon.log2().ceil().min(0.0); + let inner_accuracy = accuracy / n; + let f = |t: f64| { + let (range, dir) = if t > t_last { + (t_last..t, 1.0) + } else { + (t..t_last, -1.0) + }; + let arc = self.subsegment(range).arclen(inner_accuracy); + arclen_last += arc * dir; + t_last = t; + arclen_last - arclen + }; + common::solve_itp(f, 0.0, 1.0, epsilon, 1, 0.2, -arclen, total_arclen - arclen) + } +} + +/// A parameterized curve that can have its signed area measured. +pub trait ParamCurveArea { + /// Compute the signed area under the curve. + /// + /// For a closed path, the signed area of the path is the sum of signed + /// areas of the segments. This is a variant of the "shoelace formula." + /// See: + /// and + /// + /// + /// This can be computed exactly for Béziers thanks to Green's theorem, + /// and also for simple curves such as circular arcs. For more exotic + /// curves, it's probably best to subdivide to cubics. We leave that + /// to the caller, which is why we don't give an accuracy param here. + fn signed_area(&self) -> f64; +} + +/// The nearest position on a curve to some point. +/// +/// This is returned by [`ParamCurveNearest::nearest`] +#[derive(Debug, Clone, Copy)] +pub struct Nearest { + /// The square of the distance from the nearest position on the curve + /// to the given point. + pub distance_sq: f64, + /// The position on the curve of the nearest point, as a parameter. + /// + /// To resolve this to a [`Point`], use [`ParamCurve::eval`]. + pub t: f64, +} + +/// A parameterized curve that reports the nearest point. +pub trait ParamCurveNearest { + /// Find the position on the curve that is nearest to the given point. + /// + /// This returns a [`Nearest`] struct that contains information about + /// the position. + fn nearest(&self, p: Point, accuracy: f64) -> Nearest; +} + +/// A parameterized curve that reports its curvature. +pub trait ParamCurveCurvature: ParamCurveDeriv +where + Self::DerivResult: ParamCurveDeriv, +{ + /// Compute the signed curvature at parameter `t`. + #[inline] + fn curvature(&self, t: f64) -> f64 { + let deriv = self.deriv(); + let deriv2 = deriv.deriv(); + let d = deriv.eval(t).to_vec2(); + let d2 = deriv2.eval(t).to_vec2(); + // TODO: What's the convention for sign? I think it should match signed + // area - a positive area curve should have positive curvature. + d2.cross(d) * d.hypot2().powf(-1.5) + } +} + +/// The maximum number of extrema that can be reported in the `ParamCurveExtrema` trait. +/// +/// This is 4 to support cubic Béziers. If other curves are used, they should be +/// subdivided to limit the number of extrema. +pub const MAX_EXTREMA: usize = 4; + +/// A parameterized curve that reports its extrema. +pub trait ParamCurveExtrema: ParamCurve { + /// Compute the extrema of the curve. + /// + /// Only extrema within the interior of the curve count. + /// At most four extrema can be reported, which is sufficient for + /// cubic Béziers. + /// + /// The extrema should be reported in increasing parameter order. + fn extrema(&self) -> ArrayVec; + + /// Return parameter ranges, each of which is monotonic within the range. + fn extrema_ranges(&self) -> ArrayVec, { MAX_EXTREMA + 1 }> { + let mut result = ArrayVec::new(); + let mut t0 = 0.0; + for t in self.extrema() { + result.push(t0..t); + t0 = t; + } + result.push(t0..1.0); + result + } + + /// The smallest rectangle that encloses the curve in the range (0..1). + fn bounding_box(&self) -> Rect { + let mut bbox = Rect::from_points(self.start(), self.end()); + for t in self.extrema() { + bbox = bbox.union_pt(self.eval(t)); + } + bbox + } +} diff --git a/vendor/kurbo/src/point.rs b/vendor/kurbo/src/point.rs new file mode 100644 index 0000000000..fd3045d925 --- /dev/null +++ b/vendor/kurbo/src/point.rs @@ -0,0 +1,398 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A 2D point. + +use core::fmt; +use core::ops::{Add, AddAssign, Sub, SubAssign}; + +use crate::common::FloatExt; +use crate::{Axis, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D point. +/// +/// This type represents a point in 2D space. It has the same layout as [`Vec2`], but +/// its meaning is different: `Vec2` represents a change in location (for example velocity). +/// +/// In general, `kurbo` overloads math operators where it makes sense, for example implementing +/// `Affine * Point` as the point under the affine transformation. However `Point + Point` and +/// `f64 * Point` are not implemented, because the operations do not make geometric sense. If you +/// need to apply these operations, then 1) check what you're doing makes geometric sense, then 2) +/// use [`Point::to_vec2`] to convert the point to a `Vec2`. +#[derive(Clone, Copy, Default, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Point { + /// The x coordinate. + pub x: f64, + /// The y coordinate. + pub y: f64, +} + +impl Point { + /// The point (0, 0). + pub const ZERO: Point = Point::new(0., 0.); + + /// The point at the origin; (0, 0). + pub const ORIGIN: Point = Point::new(0., 0.); + + /// Create a new `Point` with the provided `x` and `y` coordinates. + #[inline(always)] + pub const fn new(x: f64, y: f64) -> Self { + Point { x, y } + } + + /// Convert this point into a `Vec2`. + #[inline(always)] + pub const fn to_vec2(self) -> Vec2 { + Vec2::new(self.x, self.y) + } + + /// Linearly interpolate between two points. + #[inline] + pub fn lerp(self, other: Point, t: f64) -> Point { + self.to_vec2().lerp(other.to_vec2(), t).to_point() + } + + /// Determine the midpoint of two points. + #[inline] + pub const fn midpoint(self, other: Point) -> Point { + Point::new(0.5 * (self.x + other.x), 0.5 * (self.y + other.y)) + } + + /// Euclidean distance. + /// + /// See [`Vec2::hypot`] for the same operation on [`Vec2`]. + #[inline] + pub fn distance(self, other: Point) -> f64 { + (self - other).hypot() + } + + /// Squared Euclidean distance. + /// + /// See [`Vec2::hypot2`] for the same operation on [`Vec2`]. + #[inline] + pub fn distance_squared(self, other: Point) -> f64 { + (self - other).hypot2() + } + + /// Returns a new `Point`, with `x` and `y` [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).round(); + /// let b = Point::new(3.0, -3.1).round(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Point { + Point::new(self.x.round(), self.y.round()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).ceil(); + /// let b = Point::new(3.0, -3.1).ceil(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Point { + Point::new(self.x.ceil(), self.y.ceil()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).floor(); + /// let b = Point::new(3.0, -3.1).floor(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Point { + Point::new(self.x.floor(), self.y.floor()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded away] from zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).expand(); + /// let b = Point::new(3.0, -3.1).expand(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded away]: FloatExt::expand + #[inline] + pub fn expand(self) -> Point { + Point::new(self.x.expand(), self.y.expand()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded towards] zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).trunc(); + /// let b = Point::new(3.0, -3.1).trunc(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded towards]: f64::trunc + #[inline] + pub fn trunc(self) -> Point { + Point::new(self.x.trunc(), self.y.trunc()) + } + + /// Is this point [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } + + /// Is this point [`NaN`]? + /// + /// [`NaN`]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.x.is_nan() || self.y.is_nan() + } + + /// Get the member matching the given axis. + #[inline] + pub const fn get_coord(self, axis: Axis) -> f64 { + match axis { + Axis::Horizontal => self.x, + Axis::Vertical => self.y, + } + } + + /// Get a mutable reference to the member matching the given axis. + #[inline] + pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 { + match axis { + Axis::Horizontal => &mut self.x, + Axis::Vertical => &mut self.y, + } + } + + /// Set the member matching the given axis to the given value. + #[inline] + pub const fn set_coord(&mut self, axis: Axis, value: f64) { + match axis { + Axis::Horizontal => self.x = value, + Axis::Vertical => self.y = value, + } + } +} + +impl From<(f32, f32)> for Point { + #[inline(always)] + fn from(v: (f32, f32)) -> Point { + Point { + x: v.0 as f64, + y: v.1 as f64, + } + } +} + +impl From<(f64, f64)> for Point { + #[inline(always)] + fn from(v: (f64, f64)) -> Point { + Point { x: v.0, y: v.1 } + } +} + +impl From for (f64, f64) { + #[inline(always)] + fn from(v: Point) -> (f64, f64) { + (v.x, v.y) + } +} + +impl Add for Point { + type Output = Point; + + #[inline] + fn add(self, other: Vec2) -> Self { + Point::new(self.x + other.x, self.y + other.y) + } +} + +impl AddAssign for Point { + #[inline] + fn add_assign(&mut self, other: Vec2) { + *self = Point::new(self.x + other.x, self.y + other.y); + } +} + +impl Sub for Point { + type Output = Point; + + #[inline] + fn sub(self, other: Vec2) -> Self { + Point::new(self.x - other.x, self.y - other.y) + } +} + +impl SubAssign for Point { + #[inline] + fn sub_assign(&mut self, other: Vec2) { + *self = Point::new(self.x - other.x, self.y - other.y); + } +} + +impl Add<(f64, f64)> for Point { + type Output = Point; + + #[inline] + fn add(self, (x, y): (f64, f64)) -> Self { + Point::new(self.x + x, self.y + y) + } +} + +impl AddAssign<(f64, f64)> for Point { + #[inline] + fn add_assign(&mut self, (x, y): (f64, f64)) { + *self = Point::new(self.x + x, self.y + y); + } +} + +impl Sub<(f64, f64)> for Point { + type Output = Point; + + #[inline] + fn sub(self, (x, y): (f64, f64)) -> Self { + Point::new(self.x - x, self.y - y) + } +} + +impl SubAssign<(f64, f64)> for Point { + #[inline] + fn sub_assign(&mut self, (x, y): (f64, f64)) { + *self = Point::new(self.x - x, self.y - y); + } +} + +impl Sub for Point { + type Output = Vec2; + + #[inline] + fn sub(self, other: Point) -> Vec2 { + Vec2::new(self.x - other.x, self.y - other.y) + } +} + +impl fmt::Debug for Point { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "({:?}, {:?})", self.x, self.y) + } +} + +impl fmt::Display for Point { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "(")?; + fmt::Display::fmt(&self.x, formatter)?; + write!(formatter, ", ")?; + fmt::Display::fmt(&self.y, formatter)?; + write!(formatter, ")") + } +} + +#[cfg(feature = "mint")] +impl From for mint::Point2 { + #[inline(always)] + fn from(p: Point) -> mint::Point2 { + mint::Point2 { x: p.x, y: p.y } + } +} + +#[cfg(feature = "mint")] +impl From> for Point { + #[inline(always)] + fn from(p: mint::Point2) -> Point { + Point { x: p.x, y: p.y } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn point_arithmetic() { + assert_eq!( + Point::new(0., 0.) - Vec2::new(10., 0.), + Point::new(-10., 0.) + ); + assert_eq!( + Point::new(0., 0.) - Point::new(-5., 101.), + Vec2::new(5., -101.) + ); + } + + #[test] + #[allow(clippy::float_cmp)] + fn distance() { + let p1 = Point::new(0., 10.); + let p2 = Point::new(0., 5.); + assert_eq!(p1.distance(p2), 5.); + + let p1 = Point::new(-11., 1.); + let p2 = Point::new(-7., -2.); + assert_eq!(p1.distance(p2), 5.); + } + + #[test] + fn display() { + let p = Point::new(0.12345, 9.87654); + assert_eq!(format!("{p}"), "(0.12345, 9.87654)"); + + let p = Point::new(0.12345, 9.87654); + assert_eq!(format!("{p:.2}"), "(0.12, 9.88)"); + } +} diff --git a/vendor/kurbo/src/quadbez.rs b/vendor/kurbo/src/quadbez.rs new file mode 100644 index 0000000000..5a68283a2e --- /dev/null +++ b/vendor/kurbo/src/quadbez.rs @@ -0,0 +1,594 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Quadratic Bézier segments. + +use core::ops::{Mul, Range}; + +use arrayvec::ArrayVec; + +use crate::MAX_EXTREMA; +use crate::common::{solve_cubic, solve_quadratic}; +use crate::{ + Affine, CubicBez, Line, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point, + Rect, Shape, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A single quadratic Bézier segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[allow(missing_docs)] +pub struct QuadBez { + pub p0: Point, + pub p1: Point, + pub p2: Point, +} + +impl QuadBez { + /// Create a new quadratic Bézier segment. + #[inline] + pub fn new>(p0: V, p1: V, p2: V) -> QuadBez { + QuadBez { + p0: p0.into(), + p1: p1.into(), + p2: p2.into(), + } + } + + /// Raise the order by 1. + /// + /// Returns a cubic Bézier segment that exactly represents this quadratic. + #[inline] + pub fn raise(&self) -> CubicBez { + CubicBez::new( + self.p0, + self.p0 + (2.0 / 3.0) * (self.p1 - self.p0), + self.p2 + (2.0 / 3.0) * (self.p1 - self.p2), + self.p2, + ) + } + + /// Estimate the number of subdivisions for flattening. + pub(crate) fn estimate_subdiv(&self, sqrt_tol: f64) -> FlattenParams { + // Determine transformation to $y = x^2$ parabola. + let d01 = self.p1 - self.p0; + let d12 = self.p2 - self.p1; + let dd = d01 - d12; + let cross = (self.p2 - self.p0).cross(dd); + let x0 = d01.dot(dd) * cross.recip(); + let x2 = d12.dot(dd) * cross.recip(); + let scale = (cross / (dd.hypot() * (x2 - x0))).abs(); + + // Compute number of subdivisions needed. + let a0 = approx_parabola_integral(x0); + let a2 = approx_parabola_integral(x2); + let val = if scale.is_finite() { + let da = (a2 - a0).abs(); + let sqrt_scale = scale.sqrt(); + if x0.signum() == x2.signum() { + da * sqrt_scale + } else { + // Handle cusp case (segment contains curvature maximum) + let xmin = sqrt_tol / sqrt_scale; + sqrt_tol * da / approx_parabola_integral(xmin) + } + } else { + 0.0 + }; + let u0 = approx_parabola_inv_integral(a0); + let u2 = approx_parabola_inv_integral(a2); + let uscale = (u2 - u0).recip(); + FlattenParams { + a0, + a2, + u0, + uscale, + val, + } + } + + // Maps a value from 0..1 to 0..1. + pub(crate) fn determine_subdiv_t(&self, params: &FlattenParams, x: f64) -> f64 { + let a = params.a0 + (params.a2 - params.a0) * x; + let u = approx_parabola_inv_integral(a); + (u - params.u0) * params.uscale + } + + /// Is this quadratic Bezier curve finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.p0.is_finite() && self.p1.is_finite() && self.p2.is_finite() + } + + /// Is this quadratic Bezier curve NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.p0.is_nan() || self.p1.is_nan() || self.p2.is_nan() + } + + /// Finds the value of `t` for which `self.eval(t)` is about `y`. + /// + /// Assumes that this segment is monotonic in `y` and that it crosses + /// the height `y`. (Under these assumptions, there is a unique answer.) + pub(crate) fn solve_monotonic_for_y(&self, y: f64) -> f64 { + let start = self.start(); + let end = self.end(); + + debug_assert!(start.y.min(end.y) <= y && y <= start.y.max(end.y)); + let a = end.y - 2.0 * self.p1.y + start.y; + let b = 2.0 * (self.p1.y - start.y); + let c = start.y - y; + + for t in solve_quadratic(c, b, a) { + if (0.0..=1.0).contains(&t) { + return t; + } + } + + // Even though we asserted that our y range contains `y`, it's possible + // that we failed to find a solution numerically. (For example, rounding + // of a, b, or c might have pushed the root outside of [0.0, 1.0].) + // If we failed to find a solution, the real solution should be close + // to one of the endpoints. So just find whichever endpoint was closer. + if (start.y - y).abs() <= (end.y - y).abs() { + 0.0 + } else { + 1.0 + } + } +} + +/// An iterator for quadratic beziers. +pub struct QuadBezIter { + quad: QuadBez, + ix: usize, +} + +impl Shape for QuadBez { + type PathElementsIter<'iter> = QuadBezIter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> QuadBezIter { + QuadBezIter { quad: *self, ix: 0 } + } + + fn area(&self) -> f64 { + 0.0 + } + + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.arclen(accuracy) + } + + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline] + fn bounding_box(&self) -> Rect { + ParamCurveExtrema::bounding_box(self) + } +} + +impl Iterator for QuadBezIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.quad.p0)), + 2 => Some(PathEl::QuadTo(self.quad.p1, self.quad.p2)), + _ => None, + } + } +} + +pub(crate) struct FlattenParams { + a0: f64, + a2: f64, + u0: f64, + uscale: f64, + /// The number of `subdivisions * 2 * sqrt_tol`. + pub(crate) val: f64, +} + +/// An approximation to $\int (1 + 4x^2) ^ -0.25 dx$ +/// +/// This is used for flattening curves. +fn approx_parabola_integral(x: f64) -> f64 { + const D: f64 = 0.67; + x / (1.0 - D + (D.powi(4) + 0.25 * x * x).sqrt().sqrt()) +} + +/// An approximation to the inverse parabola integral. +fn approx_parabola_inv_integral(x: f64) -> f64 { + const B: f64 = 0.39; + x * (1.0 - B + (B * B + 0.25 * x * x).sqrt()) +} + +impl ParamCurve for QuadBez { + #[inline] + fn eval(&self, t: f64) -> Point { + let mt = 1.0 - t; + (self.p0.to_vec2() * (mt * mt) + + (self.p1.to_vec2() * (mt * 2.0) + self.p2.to_vec2() * t) * t) + .to_point() + } + + fn subsegment(&self, range: Range) -> QuadBez { + let (t0, t1) = (range.start, range.end); + let p0 = self.eval(t0); + let p2 = self.eval(t1); + let p1 = p0 + (self.p1 - self.p0).lerp(self.p2 - self.p1, t0) * (t1 - t0); + QuadBez { p0, p1, p2 } + } + + /// Subdivide into halves, using de Casteljau. + #[inline] + fn subdivide(&self) -> (QuadBez, QuadBez) { + let pm = self.eval(0.5); + ( + QuadBez::new(self.p0, self.p0.midpoint(self.p1), pm), + QuadBez::new(pm, self.p1.midpoint(self.p2), self.p2), + ) + } + + #[inline] + fn start(&self) -> Point { + self.p0 + } + + #[inline] + fn end(&self) -> Point { + self.p2 + } +} + +impl ParamCurveDeriv for QuadBez { + type DerivResult = Line; + + #[inline] + fn deriv(&self) -> Line { + Line::new( + (2.0 * (self.p1.to_vec2() - self.p0.to_vec2())).to_point(), + (2.0 * (self.p2.to_vec2() - self.p1.to_vec2())).to_point(), + ) + } +} + +impl ParamCurveArclen for QuadBez { + /// Arclength of a quadratic Bézier segment. + /// + /// This computation is based on an analytical formula. Since that formula suffers + /// from numerical instability when the curve is very close to a straight line, we + /// detect that case and fall back to Legendre-Gauss quadrature. + /// + /// Accuracy should be better than 1e-13 over the entire range. + /// + /// Adapted from + /// with permission. + fn arclen(&self, _accuracy: f64) -> f64 { + let d2 = self.p0.to_vec2() - 2.0 * self.p1.to_vec2() + self.p2.to_vec2(); + let a = d2.hypot2(); + let d1 = self.p1 - self.p0; + let c = d1.hypot2(); + if a < 5e-4 * c { + // This case happens for nearly straight Béziers. + // + // Calculate arclength using Legendre-Gauss quadrature using formula from Behdad + // in https://github.com/Pomax/BezierInfo-2/issues/77 + let v0 = (-0.492943519233745 * self.p0.to_vec2() + + 0.430331482911935 * self.p1.to_vec2() + + 0.0626120363218102 * self.p2.to_vec2()) + .hypot(); + let v1 = ((self.p2 - self.p0) * 0.4444444444444444).hypot(); + let v2 = (-0.0626120363218102 * self.p0.to_vec2() + - 0.430331482911935 * self.p1.to_vec2() + + 0.492943519233745 * self.p2.to_vec2()) + .hypot(); + return v0 + v1 + v2; + } + let b = 2.0 * d2.dot(d1); + + let sabc = (a + b + c).sqrt(); + let a2 = a.powf(-0.5); + let a32 = a2.powi(3); + let c2 = 2.0 * c.sqrt(); + let ba_c2 = b * a2 + c2; + + let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc; + // TODO: justify and fine-tune this exact constant. + // The factor of a2 here is a little arbitrary: we really want + // to test whether ba_c2 is small, but it's also important for + // this comparison to be scale-invariant. We chose a2 (instead of, + // for example, c2 on the rhs) because it's unchanged under + // reversing the parametrization. + if ba_c2 * a2 < 1e-13 { + // This case happens for Béziers with a sharp kink. + v0 + } else { + v0 + 0.25 + * a32 + * (4.0 * c * a - b * b) + * (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln() + } + } +} + +impl ParamCurveArea for QuadBez { + #[inline] + fn signed_area(&self) -> f64 { + (self.p0.x * (2.0 * self.p1.y + self.p2.y) + 2.0 * self.p1.x * (self.p2.y - self.p0.y) + - self.p2.x * (self.p0.y + 2.0 * self.p1.y)) + * (1.0 / 6.0) + } +} + +impl ParamCurveNearest for QuadBez { + /// Find the nearest point, using analytical algorithm based on cubic root finding. + fn nearest(&self, p: Point, _accuracy: f64) -> Nearest { + fn eval_t(p: Point, t_best: &mut f64, r_best: &mut Option, t: f64, p0: Point) { + let r = (p0 - p).hypot2(); + if r_best.map(|r_best| r < r_best).unwrap_or(true) { + *r_best = Some(r); + *t_best = t; + } + } + fn try_t( + q: &QuadBez, + p: Point, + t_best: &mut f64, + r_best: &mut Option, + t: f64, + ) -> bool { + if !(0.0..=1.0).contains(&t) { + return true; + } + eval_t(p, t_best, r_best, t, q.eval(t)); + false + } + let d0 = self.p1 - self.p0; + let d1 = self.p0.to_vec2() + self.p2.to_vec2() - 2.0 * self.p1.to_vec2(); + let d = self.p0 - p; + let c0 = d.dot(d0); + let c1 = 2.0 * d0.hypot2() + d.dot(d1); + let c2 = 3.0 * d1.dot(d0); + let c3 = d1.hypot2(); + let roots = solve_cubic(c0, c1, c2, c3); + let mut r_best = None; + let mut t_best = 0.0; + let mut need_ends = false; + if roots.is_empty() { + need_ends = true; + } + for &t in &roots { + need_ends |= try_t(self, p, &mut t_best, &mut r_best, t); + } + if need_ends { + eval_t(p, &mut t_best, &mut r_best, 0.0, self.p0); + eval_t(p, &mut t_best, &mut r_best, 1.0, self.p2); + } + + Nearest { + t: t_best, + distance_sq: r_best.unwrap(), + } + } +} + +impl ParamCurveCurvature for QuadBez {} + +impl ParamCurveExtrema for QuadBez { + fn extrema(&self) -> ArrayVec { + let mut result = ArrayVec::new(); + let d0 = self.p1 - self.p0; + let d1 = self.p2 - self.p1; + let dd = d1 - d0; + if dd.x != 0.0 { + let t = -d0.x / dd.x; + if t > 0.0 && t < 1.0 { + result.push(t); + } + } + if dd.y != 0.0 { + let t = -d0.y / dd.y; + if t > 0.0 && t < 1.0 { + result.push(t); + if result.len() == 2 && result[0] > t { + result.swap(0, 1); + } + } + } + result + } +} + +impl Mul for Affine { + type Output = QuadBez; + + #[inline] + fn mul(self, other: QuadBez) -> QuadBez { + QuadBez { + p0: self * other.p0, + p1: self * other.p1, + p2: self * other.p2, + } + } +} + +#[cfg(test)] +mod tests { + use crate::{ + Affine, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, + ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, + }; + + fn assert_near(p0: Point, p1: Point, epsilon: f64) { + assert!((p1 - p0).hypot() < epsilon, "{p0:?} != {p1:?}"); + } + + #[test] + fn quadbez_deriv() { + let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0)); + let deriv = q.deriv(); + + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let delta = 1e-6; + let p = q.eval(t); + let p1 = q.eval(t + delta); + let d_approx = (p1 - p) * delta.recip(); + let d = deriv.eval(t).to_vec2(); + assert!((d - d_approx).hypot() < delta * 2.0); + } + } + + #[test] + fn quadbez_arclen() { + let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0)); + let true_arclen = 0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln(); + for i in 0..12 { + let accuracy = 0.1f64.powi(i); + let est = q.arclen(accuracy); + let error = est - true_arclen; + assert!(error.abs() < accuracy, "{est} != {true_arclen}"); + } + } + + #[test] + fn quadbez_arclen_pathological() { + let q = QuadBez::new((-1.0, 0.0), (1.03, 0.0), (1.0, 0.0)); + let true_arclen = 2.0008737864167325; // A rough empirical calculation + let accuracy = 1e-11; + let est = q.arclen(accuracy); + assert!( + (est - true_arclen).abs() < accuracy, + "{est} != {true_arclen}" + ); + } + + #[test] + fn quadbez_subsegment() { + let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8)); + let t0 = 0.1; + let t1 = 0.8; + let qs = q.subsegment(t0..t1); + let epsilon = 1e-12; + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let ts = t0 + t * (t1 - t0); + assert_near(q.eval(ts), qs.eval(t), epsilon); + } + } + + #[test] + fn quadbez_raise() { + let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8)); + let c = q.raise(); + let qd = q.deriv(); + let cd = c.deriv(); + let epsilon = 1e-12; + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + assert_near(q.eval(t), c.eval(t), epsilon); + assert_near(qd.eval(t), cd.eval(t), epsilon); + } + } + + #[test] + fn quadbez_signed_area() { + // y = 1 - x^2 + let q = QuadBez::new((1.0, 0.0), (0.5, 1.0), (0.0, 1.0)); + let epsilon = 1e-12; + assert!((q.signed_area() - 2.0 / 3.0).abs() < epsilon); + assert!(((Affine::rotate(0.5) * q).signed_area() - 2.0 / 3.0).abs() < epsilon); + assert!(((Affine::translate((0.0, 1.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon); + assert!(((Affine::translate((1.0, 0.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon); + } + + fn verify(result: Nearest, expected: f64) { + assert!( + (result.t - expected).abs() < 1e-6, + "got {result:?} expected {expected}" + ); + } + + #[test] + fn quadbez_nearest() { + // y = x^2 + let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0)); + verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5); + verify(q.nearest((0.0, 0.1).into(), 1e-3), 0.5); + verify(q.nearest((0.0, -0.1).into(), 1e-3), 0.5); + verify(q.nearest((0.5, 0.25).into(), 1e-3), 0.75); + verify(q.nearest((1.0, 1.0).into(), 1e-3), 1.0); + verify(q.nearest((1.1, 1.1).into(), 1e-3), 1.0); + verify(q.nearest((-1.1, 1.1).into(), 1e-3), 0.0); + let a = Affine::rotate(0.5); + verify((a * q).nearest(a * Point::new(0.5, 0.25), 1e-3), 0.75); + } + + // This test exposes a degenerate case in the solver used internally + // by the "nearest" calculation - the cubic term is zero. + #[test] + fn quadbez_nearest_low_order() { + let q = QuadBez::new((-1.0, 0.0), (0.0, 0.0), (1.0, 0.0)); + + verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5); + verify(q.nearest((0.0, 1.0).into(), 1e-3), 0.5); + } + + #[test] + fn quadbez_nearest_rounding_panic() { + let quad = QuadBez::new( + (-1.0394736842105263, 0.0), + (0.8210526315789474, -1.511111111111111), + (0.0, 1.9333333333333333), + ); + let test = Point::new(-1.7976931348623157e308, 0.8571428571428571); + // accuracy ignored + let _res = quad.nearest(test, 1e-6); + // if we got here then we didn't panic + } + + #[test] + fn quadbez_extrema() { + // y = x^2 + let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 1); + assert!((extrema[0] - 0.5).abs() < 1e-6); + + let q = QuadBez::new((0.0, 0.5), (1.0, 1.0), (0.5, 0.0)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 2); + assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6); + assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6); + + // Reverse direction + let q = QuadBez::new((0.5, 0.0), (1.0, 1.0), (0.0, 0.5)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 2); + assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6); + assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6); + } + + // A regression test for #477: the approximate-linearity test for + // using the analytic solution needs to be scale-invariant. + #[test] + fn perimeter_not_nan() { + let q = QuadBez::new((2685., -1251.), (2253., -1303.), (2253., -1303.)); + + let len = q.arclen(crate::DEFAULT_ACCURACY); + assert!(len.is_finite()); + } +} diff --git a/vendor/kurbo/src/quadspline.rs b/vendor/kurbo/src/quadspline.rs new file mode 100644 index 0000000000..51b823ef4d --- /dev/null +++ b/vendor/kurbo/src/quadspline.rs @@ -0,0 +1,130 @@ +// Copyright 2021 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Quadratic Bézier splines. +use crate::Point; + +use crate::QuadBez; +use alloc::vec::Vec; + +/// A quadratic Bézier spline in [B-spline](https://en.wikipedia.org/wiki/B-spline) format. +#[derive(Clone, Debug, PartialEq)] +pub struct QuadSpline(Vec); + +impl QuadSpline { + /// Construct a new `QuadSpline` from an array of [`Point`]s. + #[inline(always)] + pub fn new(points: Vec) -> Self { + Self(points) + } + + /// Return the spline's control [`Point`]s. + #[inline(always)] + pub fn points(&self) -> &[Point] { + &self.0 + } + + /// Return an iterator over the implied [`QuadBez`] sequence. + /// + /// The returned quads are guaranteed to be G1 continuous. + #[inline(always)] + pub fn to_quads(&self) -> impl Iterator + '_ { + ToQuadBez { + idx: 0, + points: &self.0, + } + } +} + +struct ToQuadBez<'a> { + idx: usize, + points: &'a Vec, +} + +impl Iterator for ToQuadBez<'_> { + type Item = QuadBez; + + fn next(&mut self) -> Option { + let [mut p0, p1, mut p2]: [Point; 3] = + self.points.get(self.idx..=self.idx + 2)?.try_into().ok()?; + + if self.idx != 0 { + p0 = p0.midpoint(p1); + } + if self.idx + 2 < self.points.len() - 1 { + p2 = p1.midpoint(p2); + } + + self.idx += 1; + + Some(QuadBez { p0, p1, p2 }) + } +} + +#[cfg(test)] +mod tests { + use crate::{Point, QuadBez, QuadSpline}; + + #[test] + fn no_points_no_quads() { + assert!(QuadSpline::new(Vec::new()).to_quads().next().is_none()); + } + + #[test] + fn one_point_no_quads() { + assert!( + QuadSpline::new(vec![Point::new(1.0, 1.0)]) + .to_quads() + .next() + .is_none() + ); + } + + #[test] + fn two_points_no_quads() { + assert!( + QuadSpline::new(vec![Point::new(1.0, 1.0), Point::new(1.0, 1.0)]) + .to_quads() + .next() + .is_none() + ); + } + + #[test] + fn three_points_same_quad() { + let p0 = Point::new(1.0, 1.0); + let p1 = Point::new(2.0, 2.0); + let p2 = Point::new(3.0, 3.0); + assert_eq!( + vec![QuadBez { p0, p1, p2 }], + QuadSpline::new(vec![p0, p1, p2]) + .to_quads() + .collect::>() + ); + } + + #[test] + fn four_points_implicit_on_curve() { + let p0 = Point::new(1.0, 1.0); + let p1 = Point::new(3.0, 3.0); + let p2 = Point::new(5.0, 5.0); + let p3 = Point::new(8.0, 8.0); + assert_eq!( + vec![ + QuadBez { + p0, + p1, + p2: p1.midpoint(p2) + }, + QuadBez { + p0: p1.midpoint(p2), + p1: p2, + p2: p3 + } + ], + QuadSpline::new(vec![p0, p1, p2, p3]) + .to_quads() + .collect::>() + ); + } +} diff --git a/vendor/kurbo/src/rect.rs b/vendor/kurbo/src/rect.rs new file mode 100644 index 0000000000..9a2b54a8ca --- /dev/null +++ b/vendor/kurbo/src/rect.rs @@ -0,0 +1,1053 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A rectangle. + +use core::fmt; +use core::ops::{Add, Sub}; + +use crate::{ + Axis, Ellipse, Insets, PathEl, Point, RoundedRect, RoundedRectRadii, Shape, Size, Vec2, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A rectangle. +#[derive(Clone, Copy, Default, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Rect { + /// The minimum x coordinate (left edge). + pub x0: f64, + /// The minimum y coordinate (top edge in y-down spaces). + pub y0: f64, + /// The maximum x coordinate (right edge). + pub x1: f64, + /// The maximum y coordinate (bottom edge in y-down spaces). + pub y1: f64, +} + +impl Rect { + /// The empty rectangle at the origin. + pub const ZERO: Rect = Rect::new(0., 0., 0., 0.); + + /// A new rectangle from minimum and maximum coordinates. + #[inline(always)] + pub const fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Rect { + Rect { x0, y0, x1, y1 } + } + + /// A new rectangle from two points. + /// + /// The result will have non-negative width and height. + #[inline] + pub fn from_points(p0: impl Into, p1: impl Into) -> Rect { + let p0 = p0.into(); + let p1 = p1.into(); + Rect::new(p0.x, p0.y, p1.x, p1.y).abs() + } + + /// A new rectangle from origin and size. + /// + /// The result will have non-negative width and height. + #[inline] + pub fn from_origin_size(origin: impl Into, size: impl Into) -> Rect { + let origin = origin.into(); + Rect::from_points(origin, origin + size.into().to_vec2()) + } + + /// A new rectangle from center and size. + #[inline] + pub fn from_center_size(center: impl Into, size: impl Into) -> Rect { + let center = center.into(); + let size = 0.5 * size.into(); + Rect::new( + center.x - size.width, + center.y - size.height, + center.x + size.width, + center.y + size.height, + ) + } + + /// Create a new `Rect` with the same size as `self` and a new origin. + #[inline] + pub fn with_origin(self, origin: impl Into) -> Rect { + Rect::from_origin_size(origin, self.size()) + } + + /// Create a new `Rect` with the same origin as `self` and a new size. + #[inline] + pub fn with_size(self, size: impl Into) -> Rect { + Rect::from_origin_size(self.origin(), size) + } + + /// Create a new `Rect` by applying the [`Insets`]. + /// + /// This will not preserve negative width and height. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let inset_rect = Rect::new(0., 0., 10., 10.,).inset(2.); + /// assert_eq!(inset_rect.width(), 14.0); + /// assert_eq!(inset_rect.x0, -2.0); + /// assert_eq!(inset_rect.x1, 12.0); + /// ``` + #[inline] + pub fn inset(self, insets: impl Into) -> Rect { + self + insets.into() + } + + /// The width of the rectangle. + /// + /// Note: nothing forbids negative width. + #[inline] + pub const fn width(&self) -> f64 { + self.x1 - self.x0 + } + + /// The height of the rectangle. + /// + /// Note: nothing forbids negative height. + #[inline] + pub const fn height(&self) -> f64 { + self.y1 - self.y0 + } + + /// Returns the minimum value for the x-coordinate of the rectangle. + #[inline] + pub const fn min_x(&self) -> f64 { + self.x0.min(self.x1) + } + + /// Returns the maximum value for the x-coordinate of the rectangle. + #[inline] + pub const fn max_x(&self) -> f64 { + self.x0.max(self.x1) + } + + /// Returns the minimum value for the y-coordinate of the rectangle. + #[inline] + pub const fn min_y(&self) -> f64 { + self.y0.min(self.y1) + } + + /// Returns the maximum value for the y-coordinate of the rectangle. + #[inline] + pub const fn max_y(&self) -> f64 { + self.y0.max(self.y1) + } + + /// The origin of the rectangle. + /// + /// This is the top left corner in a y-down space and with + /// non-negative width and height. + #[inline(always)] + pub const fn origin(&self) -> Point { + Point::new(self.x0, self.y0) + } + + /// The size of the rectangle. + #[inline] + pub const fn size(&self) -> Size { + Size::new(self.width(), self.height()) + } + + /// The area of the rectangle. + #[inline] + pub const fn area(&self) -> f64 { + self.width() * self.height() + } + + /// Whether this rectangle has zero area. + #[doc(alias = "is_empty")] + #[inline] + pub const fn is_zero_area(&self) -> bool { + self.area() == 0.0 + } + + /// The center point of the rectangle. + #[inline] + pub const fn center(&self) -> Point { + Point::new(0.5 * (self.x0 + self.x1), 0.5 * (self.y0 + self.y1)) + } + + /// Returns `true` if `point` lies within `self`. + #[inline] + pub fn contains(&self, point: impl Into) -> bool { + let point = point.into(); + point.x >= self.x0 && point.x < self.x1 && point.y >= self.y0 && point.y < self.y1 + } + + /// Take absolute value of width and height. + /// + /// The resulting rect has the same extents as the original, but is + /// guaranteed to have non-negative width and height. + #[inline] + pub const fn abs(&self) -> Rect { + let Rect { x0, y0, x1, y1 } = *self; + Rect::new(x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)) + } + + /// The smallest rectangle enclosing two rectangles. + /// + /// Results are valid only if width and height are non-negative. + #[inline] + pub const fn union(&self, other: Rect) -> Rect { + Rect::new( + self.x0.min(other.x0), + self.y0.min(other.y0), + self.x1.max(other.x1), + self.y1.max(other.y1), + ) + } + + /// Compute the union with one point. + /// + /// This method includes the perimeter of zero-area rectangles. + /// Thus, a succession of `union_pt` operations on a series of + /// points yields their enclosing rectangle. + /// + /// Results are valid only if width and height are non-negative. + pub fn union_pt(&self, pt: impl Into) -> Rect { + let pt = pt.into(); + Rect::new( + self.x0.min(pt.x), + self.y0.min(pt.y), + self.x1.max(pt.x), + self.y1.max(pt.y), + ) + } + + /// The intersection of two rectangles. + /// + /// The result is zero-area if either input has negative width or + /// height. The result always has non-negative width and height. + /// + /// If you want to determine whether two rectangles intersect, use the + /// [`overlaps`] method instead. + /// + /// [`overlaps`]: Rect::overlaps + #[inline] + pub const fn intersect(&self, other: Rect) -> Rect { + let x0 = self.x0.max(other.x0); + let y0 = self.y0.max(other.y0); + let x1 = self.x1.min(other.x1); + let y1 = self.y1.min(other.y1); + Rect::new(x0, y0, x1.max(x0), y1.max(y0)) + } + + /// Determines whether this rectangle overlaps with another in any way. + /// + /// Note that the edge of the rectangle is considered to be part of itself, meaning + /// that two rectangles that share an edge are considered to overlap. + /// + /// Returns `true` if the rectangles overlap, `false` otherwise. + /// + /// If you want to compute the *intersection* of two rectangles, use the + /// [`intersect`] method instead. + /// + /// [`intersect`]: Rect::intersect + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect1 = Rect::new(0.0, 0.0, 10.0, 10.0); + /// let rect2 = Rect::new(5.0, 5.0, 15.0, 15.0); + /// assert!(rect1.overlaps(rect2)); + /// + /// let rect1 = Rect::new(0.0, 0.0, 10.0, 10.0); + /// let rect2 = Rect::new(10.0, 0.0, 20.0, 10.0); + /// assert!(rect1.overlaps(rect2)); + /// ``` + #[inline] + pub const fn overlaps(&self, other: Rect) -> bool { + self.x0 <= other.x1 && self.x1 >= other.x0 && self.y0 <= other.y1 && self.y1 >= other.y0 + } + + /// Returns whether this rectangle contains another rectangle. + /// + /// A rectangle is considered to contain another rectangle if the other + /// rectangle is fully enclosed within the bounds of this rectangle. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect1 = Rect::new(0.0, 0.0, 10.0, 10.0); + /// let rect2 = Rect::new(2.0, 2.0, 4.0, 4.0); + /// assert!(rect1.contains_rect(rect2)); + /// ``` + /// + /// Two equal rectangles are considered to contain each other. + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect = Rect::new(0.0, 0.0, 10.0, 10.0); + /// assert!(rect.contains_rect(rect)); + /// ``` + #[inline] + pub const fn contains_rect(&self, other: Rect) -> bool { + self.x0 <= other.x0 && self.y0 <= other.y0 && self.x1 >= other.x1 && self.y1 >= other.y1 + } + + /// Expand a rectangle by a constant amount in both directions. + /// + /// The logic simply applies the amount in each direction. If rectangle + /// area or added dimensions are negative, this could give odd results. + pub const fn inflate(&self, width: f64, height: f64) -> Rect { + Rect::new( + self.x0 - width, + self.y0 - height, + self.x1 + width, + self.y1 + height, + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let rect = Rect::new(3.3, 3.6, 3.0, -3.1).round(); + /// assert_eq!(rect.x0, 3.0); + /// assert_eq!(rect.y0, 4.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -3.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Rect { + Rect::new( + self.x0.round(), + self.y0.round(), + self.x1.round(), + self.y1.round(), + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let rect = Rect::new(3.3, 3.6, 3.0, -3.1).ceil(); + /// assert_eq!(rect.x0, 4.0); + /// assert_eq!(rect.y0, 4.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Rect { + Rect::new( + self.x0.ceil(), + self.y0.ceil(), + self.x1.ceil(), + self.y1.ceil(), + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let rect = Rect::new(3.3, 3.6, 3.0, -3.1).floor(); + /// assert_eq!(rect.x0, 3.0); + /// assert_eq!(rect.y0, 3.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Rect { + Rect::new( + self.x0.floor(), + self.y0.floor(), + self.x1.floor(), + self.y1.floor(), + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value rounded away from the center of the `Rect` + /// to the nearest integer, unless they are already an integer. + /// That is to say this function will return the smallest possible `Rect` + /// with integer coordinates that is a superset of `self`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// // In positive space + /// let rect = Rect::new(3.3, 3.6, 5.6, 4.1).expand(); + /// assert_eq!(rect.x0, 3.0); + /// assert_eq!(rect.y0, 3.0); + /// assert_eq!(rect.x1, 6.0); + /// assert_eq!(rect.y1, 5.0); + /// + /// // In both positive and negative space + /// let rect = Rect::new(-3.3, -3.6, 5.6, 4.1).expand(); + /// assert_eq!(rect.x0, -4.0); + /// assert_eq!(rect.y0, -4.0); + /// assert_eq!(rect.x1, 6.0); + /// assert_eq!(rect.y1, 5.0); + /// + /// // In negative space + /// let rect = Rect::new(-5.6, -4.1, -3.3, -3.6).expand(); + /// assert_eq!(rect.x0, -6.0); + /// assert_eq!(rect.y0, -5.0); + /// assert_eq!(rect.x1, -3.0); + /// assert_eq!(rect.y1, -3.0); + /// + /// // Inverse orientation + /// let rect = Rect::new(5.6, -3.6, 3.3, -4.1).expand(); + /// assert_eq!(rect.x0, 6.0); + /// assert_eq!(rect.y0, -3.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -5.0); + /// ``` + #[inline] + pub fn expand(self) -> Rect { + // The compiler optimizer will remove the if branching. + let (x0, x1) = if self.x0 < self.x1 { + (self.x0.floor(), self.x1.ceil()) + } else { + (self.x0.ceil(), self.x1.floor()) + }; + let (y0, y1) = if self.y0 < self.y1 { + (self.y0.floor(), self.y1.ceil()) + } else { + (self.y0.ceil(), self.y1.floor()) + }; + Rect::new(x0, y0, x1, y1) + } + + /// Returns a new `Rect`, + /// with each coordinate value rounded towards the center of the `Rect` + /// to the nearest integer, unless they are already an integer. + /// That is to say this function will return the biggest possible `Rect` + /// with integer coordinates that is a subset of `self`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// // In positive space + /// let rect = Rect::new(3.3, 3.6, 5.6, 4.1).trunc(); + /// assert_eq!(rect.x0, 4.0); + /// assert_eq!(rect.y0, 4.0); + /// assert_eq!(rect.x1, 5.0); + /// assert_eq!(rect.y1, 4.0); + /// + /// // In both positive and negative space + /// let rect = Rect::new(-3.3, -3.6, 5.6, 4.1).trunc(); + /// assert_eq!(rect.x0, -3.0); + /// assert_eq!(rect.y0, -3.0); + /// assert_eq!(rect.x1, 5.0); + /// assert_eq!(rect.y1, 4.0); + /// + /// // In negative space + /// let rect = Rect::new(-5.6, -4.1, -3.3, -3.6).trunc(); + /// assert_eq!(rect.x0, -5.0); + /// assert_eq!(rect.y0, -4.0); + /// assert_eq!(rect.x1, -4.0); + /// assert_eq!(rect.y1, -4.0); + /// + /// // Inverse orientation + /// let rect = Rect::new(5.6, -3.6, 3.3, -4.1).trunc(); + /// assert_eq!(rect.x0, 5.0); + /// assert_eq!(rect.y0, -4.0); + /// assert_eq!(rect.x1, 4.0); + /// assert_eq!(rect.y1, -4.0); + /// ``` + #[inline] + pub fn trunc(self) -> Rect { + // The compiler optimizer will remove the if branching. + let (x0, x1) = if self.x0 < self.x1 { + (self.x0.ceil(), self.x1.floor()) + } else { + (self.x0.floor(), self.x1.ceil()) + }; + let (y0, y1) = if self.y0 < self.y1 { + (self.y0.ceil(), self.y1.floor()) + } else { + (self.y0.floor(), self.y1.ceil()) + }; + Rect::new(x0, y0, x1, y1) + } + + /// Scales the `Rect` by `factor` with respect to the origin (the point `(0, 0)`). + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect = Rect::new(2., 2., 4., 6.).scale_from_origin(2.); + /// assert_eq!(rect.x0, 4.); + /// assert_eq!(rect.x1, 8.); + /// ``` + #[inline] + pub const fn scale_from_origin(self, factor: f64) -> Rect { + Rect { + x0: self.x0 * factor, + y0: self.y0 * factor, + x1: self.x1 * factor, + y1: self.y1 * factor, + } + } + + /// Creates a new [`RoundedRect`] from this `Rect` and the provided + /// corner [radius](RoundedRectRadii). + #[inline] + pub fn to_rounded_rect(self, radii: impl Into) -> RoundedRect { + RoundedRect::from_rect(self, radii) + } + + /// Returns the [`Ellipse`] that is bounded by this `Rect`. + #[inline] + pub fn to_ellipse(self) -> Ellipse { + Ellipse::from_rect(self) + } + + /// The aspect ratio of this `Rect`. + /// + /// This is defined as the width divided by the height. It measures the + /// "squareness" of the rectangle (a value of `1` is square). + /// + /// If the height is `0`, the output will be `sign(self.width) * infinity`. + /// If the width and height are both `0`, then the output will be `NaN`. + #[inline] + pub const fn aspect_ratio_width(self) -> f64 { + self.size().aspect_ratio_width() + } + + /// **The inverse** of the aspect ratio of this `Rect`. + /// + /// Aspect ratios are usually defined as the ratio of the width to the height, but + /// this method incorrectly returns the ratio of height to width. + /// You should generally prefer [`aspect_ratio_width`](Self::aspect_ratio_width). + /// + /// If the width is `0` the output will be `sign(y1 - y0) * infinity`. + /// + /// If the width and height are both `0`, the result will be `NaN`. + #[deprecated( + note = "You should use `aspect_ratio_width` instead, as this method returns a potentially unexpected value.", + since = "0.12.0" + )] + #[inline] + pub fn aspect_ratio(&self) -> f64 { + #[expect(deprecated, reason = "This method is deprecated for the same reason.")] + self.size().aspect_ratio() + } + + /// Returns the largest possible `Rect` with the given `aspect_ratio` + /// that is fully contained in `self`. + /// + /// The aspect ratio is specified fractionally, as `width / height`. + /// + /// The resulting rectangle will be centered if it is smaller than this rectangle. + /// + /// # Examples + /// + /// ``` + /// # use kurbo::Rect; + /// let outer = Rect::new(0.0, 0.0, 10.0, 20.0); + /// let inner = outer.inscribed_rect_with_aspect_ratio(1.0); + /// // The new `Rect` is a square centered at the center of `outer`. + /// assert_eq!(inner, Rect::new(0.0, 5.0, 10.0, 15.0)); + /// ``` + pub const fn inscribed_rect_with_aspect_ratio(&self, aspect_ratio: f64) -> Rect { + let self_size @ Size { width, height } = self.size(); + let self_aspect = self_size.aspect_ratio_width(); + + // TODO the parameter `1e-9` was chosen quickly and may not be optimal. + // if self_aspect is `NaN`, that means we're the 0x0 rectangle (or have a `NaN`). + // We don't want NaNs in the output for the 0x0 rectangle + if self_aspect.is_nan() || (self_aspect - aspect_ratio).abs() < 1e-9 { + // short circuit + *self + } else if self_aspect.abs() < aspect_ratio.abs() { + // Our width/height is less than the requested width/height + // We use a smaller height to increase the ratio. + // shrink y to fit + let new_height = width * aspect_ratio.recip(); + let gap = (height - new_height) * 0.5; + let y0 = self.y0 + gap; + let y1 = self.y1 - gap; + Rect::new(self.x0, y0, self.x1, y1) + } else { + // shrink x to fit + let new_width = height * aspect_ratio; + let gap = (width - new_width) * 0.5; + let x0 = self.x0 + gap; + let x1 = self.x1 - gap; + Rect::new(x0, self.y0, x1, self.y1) + } + } + + /// Returns the largest possible `Rect` with the given **inverse**_aspect_ratio + /// that is fully contained in `self`. + /// + /// Aspect ratios are usually defined as the ratio of the width to the height, but + /// this method accepts an aspect ratio specified fractionally as `height / width`. + /// You should generally prefer + /// [`inscribed_rect_with_aspect_ratio`](Self::inscribed_rect_with_aspect_ratio), which + /// takes a "normal" aspect ratio. + /// + /// The resulting rectangle will be centered if it is smaller than this rectangle. + #[deprecated( + note = "You should use `inscribed_rect_with_aspect_ratio` instead, as this method expects an unusually defined parameter.", + since = "0.12.0" + )] + pub fn contained_rect_with_aspect_ratio(&self, inverse_aspect_ratio: f64) -> Rect { + self.inscribed_rect_with_aspect_ratio(1. / inverse_aspect_ratio) + } + + /// Is this rectangle [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.x0.is_finite() && self.x1.is_finite() && self.y0.is_finite() && self.y1.is_finite() + } + + /// Is this rectangle [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.x0.is_nan() || self.y0.is_nan() || self.x1.is_nan() || self.y1.is_nan() + } + + /// Get the members matching the given axis. + #[inline] + pub const fn get_coords(self, axis: Axis) -> (f64, f64) { + match axis { + Axis::Horizontal => (self.x0, self.x1), + Axis::Vertical => (self.y0, self.y1), + } + } + + /// Get a mutable reference to the members matching the given axis. + #[inline] + pub const fn get_coords_mut(&mut self, axis: Axis) -> (&mut f64, &mut f64) { + match axis { + Axis::Horizontal => (&mut self.x0, &mut self.x1), + Axis::Vertical => (&mut self.y0, &mut self.y1), + } + } + + /// Set the members matching the given axis to the given values. + #[inline] + pub const fn set_coords(&mut self, axis: Axis, v0: f64, v1: f64) { + match axis { + Axis::Horizontal => (self.x0, self.x1) = (v0, v1), + Axis::Vertical => (self.y0, self.y1) = (v0, v1), + } + } +} + +impl From<(Point, Point)> for Rect { + #[inline(always)] + fn from(points: (Point, Point)) -> Rect { + Rect::from_points(points.0, points.1) + } +} + +impl From<(Point, Size)> for Rect { + fn from(params: (Point, Size)) -> Rect { + Rect::from_origin_size(params.0, params.1) + } +} + +impl Add for Rect { + type Output = Rect; + + #[inline] + fn add(self, v: Vec2) -> Rect { + Rect::new(self.x0 + v.x, self.y0 + v.y, self.x1 + v.x, self.y1 + v.y) + } +} + +impl Sub for Rect { + type Output = Rect; + + #[inline] + fn sub(self, v: Vec2) -> Rect { + Rect::new(self.x0 - v.x, self.y0 - v.y, self.x1 - v.x, self.y1 - v.y) + } +} + +impl Sub for Rect { + type Output = Insets; + + #[inline] + fn sub(self, other: Rect) -> Insets { + let x0 = other.x0 - self.x0; + let y0 = other.y0 - self.y0; + let x1 = self.x1 - other.x1; + let y1 = self.y1 - other.y1; + Insets { x0, y0, x1, y1 } + } +} + +#[doc(hidden)] +pub struct RectPathIter { + rect: Rect, + ix: usize, +} + +impl Shape for Rect { + type PathElementsIter<'iter> = RectPathIter; + + fn path_elements(&self, _tolerance: f64) -> RectPathIter { + RectPathIter { rect: *self, ix: 0 } + } + + // It's a bit of duplication having both this and the impl method, but + // removing that would require using the trait. We'll leave it for now. + #[inline] + fn area(&self) -> f64 { + Rect::area(self) + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + 2.0 * (self.width().abs() + self.height().abs()) + } + + /// Note: this function is carefully designed so that if the plane is + /// tiled with rectangles, the winding number will be nonzero for exactly + /// one of them. + #[inline] + fn winding(&self, pt: Point) -> i32 { + let xmin = self.x0.min(self.x1); + let xmax = self.x0.max(self.x1); + let ymin = self.y0.min(self.y1); + let ymax = self.y0.max(self.y1); + if pt.x >= xmin && pt.x < xmax && pt.y >= ymin && pt.y < ymax { + if (self.x1 > self.x0) ^ (self.y1 > self.y0) { + -1 + } else { + 1 + } + } else { + 0 + } + } + + #[inline] + fn bounding_box(&self) -> Rect { + self.abs() + } + + #[inline(always)] + fn as_rect(&self) -> Option { + Some(*self) + } + + #[inline] + fn contains(&self, pt: Point) -> bool { + self.contains(pt) + } +} + +// This is clockwise in a y-down coordinate system for positive area. +impl Iterator for RectPathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(Point::new(self.rect.x0, self.rect.y0))), + 2 => Some(PathEl::LineTo(Point::new(self.rect.x1, self.rect.y0))), + 3 => Some(PathEl::LineTo(Point::new(self.rect.x1, self.rect.y1))), + 4 => Some(PathEl::LineTo(Point::new(self.rect.x0, self.rect.y1))), + 5 => Some(PathEl::ClosePath), + _ => None, + } + } +} + +impl fmt::Debug for Rect { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if f.alternate() { + write!( + f, + "Rect {{ origin: {:?}, size: {:?} }}", + self.origin(), + self.size() + ) + } else { + write!( + f, + "Rect {{ x0: {:?}, y0: {:?}, x1: {:?}, y1: {:?} }}", + self.x0, self.y0, self.x1, self.y1 + ) + } + } +} + +impl fmt::Display for Rect { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Rect {{ ")?; + fmt::Display::fmt(&self.origin(), f)?; + write!(f, " ")?; + fmt::Display::fmt(&self.size(), f)?; + write!(f, " }}") + } +} + +#[cfg(test)] +mod tests { + use crate::{Point, Rect, Shape}; + + fn assert_approx_eq(x: f64, y: f64) { + assert!((x - y).abs() < 1e-7); + } + + #[test] + fn area_sign() { + let r = Rect::new(0.0, 0.0, 10.0, 10.0); + let center = r.center(); + assert_approx_eq(r.area(), 100.0); + + assert_eq!(r.winding(center), 1); + + let p = r.to_path(1e-9); + assert_approx_eq(r.area(), p.area()); + assert_eq!(r.winding(center), p.winding(center)); + + let r_flip = Rect::new(0.0, 10.0, 10.0, 0.0); + assert_approx_eq(r_flip.area(), -100.0); + + assert_eq!(r_flip.winding(Point::new(5.0, 5.0)), -1); + let p_flip = r_flip.to_path(1e-9); + assert_approx_eq(r_flip.area(), p_flip.area()); + assert_eq!(r_flip.winding(center), p_flip.winding(center)); + } + + #[test] + fn display() { + let r = Rect::from_origin_size((10., 12.23214), (22.222222222, 23.1)); + assert_eq!( + format!("{r}"), + "Rect { (10, 12.23214) (22.222222222×23.1) }" + ); + assert_eq!(format!("{r:.2}"), "Rect { (10.00, 12.23) (22.22×23.10) }"); + } + + /* TODO uncomment when a (possibly approximate) equality test has been decided on + #[test] + fn rect_from_center_size() { + assert_eq!( + Rect::from_center_size(Point::new(3.0, 2.0), Size::new(2.0, 4.0)), + Rect::new(2.0, 0.0, 4.0, 4.0) + ); + } + */ + + #[test] + #[expect( + deprecated, + reason = "Testing behaviour of deprecated function is still as expected." + )] + fn contained_rect_with_aspect_ratio() { + #[track_caller] + fn case(outer: [f64; 4], aspect_ratio: f64, expected: [f64; 4]) { + let outer = Rect::new(outer[0], outer[1], outer[2], outer[3]); + let expected = Rect::new(expected[0], expected[1], expected[2], expected[3]); + assert_eq!( + outer.contained_rect_with_aspect_ratio(aspect_ratio), + expected + ); + assert!( + expected.size().width.abs() <= outer.size().width.abs() + && expected.size().width.abs() <= outer.size().height.abs(), + "Sanity check {expected} should be smaller than {outer}." + ); + } + // squares (different point orderings) + case([0.0, 0.0, 10.0, 20.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([0.0, 20.0, 10.0, 0.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([10.0, 0.0, 0.0, 20.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + case([10.0, 20.0, 0.0, 0.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + // non-square + case([0.0, 0.0, 10.0, 20.0], 0.5, [0.0, 7.5, 10.0, 12.5]); + // same aspect ratio + case([0.0, 0.0, 10.0, 20.0], 2.0, [0.0, 0.0, 10.0, 20.0]); + // negative aspect ratio + case([0.0, 0.0, 10.0, 20.0], -1.0, [0.0, 15.0, 10.0, 5.0]); + // infinite aspect ratio + case([0.0, 0.0, 10.0, 20.0], f64::INFINITY, [5.0, 0.0, 5.0, 20.0]); + // zero aspect ratio + case([0.0, 0.0, 10.0, 20.0], 0.0, [0.0, 10.0, 10.0, 10.0]); + // zero width rect + case([0.0, 0.0, 0.0, 20.0], 1.0, [0.0, 10.0, 0.0, 10.0]); + // many zeros + case([0.0, 0.0, 0.0, 20.0], 0.0, [0.0, 10.0, 0.0, 10.0]); + // everything zero + case([0.0, 0.0, 0.0, 0.0], 0.0, [0.0, 0.0, 0.0, 0.0]); + } + + #[test] + fn inscribed_rect_with_aspect_ratio() { + #[track_caller] + fn case(outer: [f64; 4], aspect_ratio: f64, expected: [f64; 4]) { + let outer = Rect::new(outer[0], outer[1], outer[2], outer[3]); + let expected = Rect::new(expected[0], expected[1], expected[2], expected[3]); + assert_eq!( + outer.inscribed_rect_with_aspect_ratio(aspect_ratio), + expected + ); + assert!( + expected.size().width.abs() <= outer.size().width.abs() + && expected.size().width.abs() <= outer.size().height.abs(), + "Sanity check {expected} should be smaller than {outer}." + ); + } + // squares (different point orderings) + case([0.0, 0.0, 10.0, 20.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([0.0, 20.0, 10.0, 0.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([10.0, 0.0, 0.0, 20.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + case([10.0, 20.0, 0.0, 0.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + // same aspect ratio + case([0.0, 0.0, 10.0, 20.0], 0.5, [0.0, 0.0, 10.0, 20.0]); + // non-square + case([0.0, 0.0, 10.0, 20.0], 2.0, [0.0, 7.5, 10.0, 12.5]); + // negative aspect ratio + case([0.0, 0.0, 10.0, 20.0], -1.0, [0.0, 15.0, 10.0, 5.0]); + // infinite aspect ratio, horizontal line through the center + case( + [0.0, 0.0, 10.0, 20.0], + f64::INFINITY, + [0.0, 10.0, 10.0, 10.0], + ); + // zero aspect ratio, vertical line through the center + case([0.0, 0.0, 10.0, 20.0], 0.0, [5.0, 0.0, 5.0, 20.0]); + // zero width rect + case([0.0, 0.0, 0.0, 20.0], 1.0, [0.0, 10.0, 0.0, 10.0]); + // many zeros, vertical line + case([0.0, 0.0, 0.0, 20.0], 0.0, [0.0, 0.0, 0.0, 20.0]); + // many zeros + case([0.0, 0.0, 20.0, 0.0], 0.0, [10.0, 0.0, 10.0, 0.0]); + // everything zero + case([0.0, 0.0, 0.0, 0.0], 0.0, [0.0, 0.0, 0.0, 0.0]); + } + + #[test] + #[expect(deprecated, reason = "Testing deprecated function.")] + fn aspect_ratio() { + let test = Rect::new(0.0, 0.0, 1.0, 1.0); + assert!((test.aspect_ratio() - 1.0).abs() < 1e-6); + } + + #[test] + fn aspect_ratio_width() { + let test = Rect::new(0.0, 0.0, 1.0, 1.0); + assert!((test.aspect_ratio_width() - 1.0).abs() < 1e-6); + // 16:10 + let test = Rect::new(0.0, 0.0, 16.0, 10.0); + assert!((test.aspect_ratio_width() - 1.6).abs() < 1e-6); + // 16:9 screen resolutions + let test = Rect::new(0.0, 0.0, 1920.0, 1080.0); + assert!((test.aspect_ratio_width() - (16. / 9.)).abs() < 1e-6); + } + + #[test] + fn contained_rect_overlaps() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(2.0, 2.0, 4.0, 4.0); + assert!(outer.overlaps(inner)); + } + + #[test] + fn overlapping_rect_overlaps() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(5.0, 5.0, 15.0, 15.0); + assert!(a.overlaps(b)); + } + + #[test] + fn disjoint_rect_overlaps() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(11.0, 11.0, 15.0, 15.0); + assert!(!a.overlaps(b)); + } + + #[test] + fn sharing_edge_overlaps() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(10.0, 0.0, 20.0, 10.0); + assert!(a.overlaps(b)); + } + + // Test the two other directions in case there is a bug that only appears in one direction. + #[test] + fn disjoint_rect_overlaps_negative() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(-10.0, -10.0, -5.0, -5.0); + assert!(!a.overlaps(b)); + } + + #[test] + fn contained_rectangle_contains() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(2.0, 2.0, 4.0, 4.0); + assert!(outer.contains_rect(inner)); + } + + #[test] + fn overlapping_rectangle_contains() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(5.0, 5.0, 15.0, 15.0); + assert!(!outer.contains_rect(inner)); + } + + #[test] + fn disjoint_rectangle_contains() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(11.0, 11.0, 15.0, 15.0); + assert!(!outer.contains_rect(inner)); + } + + #[test] + fn rect_intersect_zero() { + // These rectangles don't overlap vertically. + let a = Rect::new(25., 101., 200., 130.); + let b = Rect::new(0., 0., 100., 100.); + + for intersection in [a.intersect(b), b.intersect(a)] { + assert_eq!(intersection.x0, 25.); + assert_eq!(intersection.x1, 100.); + assert_eq!(intersection.area(), 0.); + assert_eq!(intersection.y0, intersection.y1); + + // We don't guarantee this in the documentation, but the intersection's `y` values should + // be a sensible value taken from the input. + assert!([0., 100., 101., 130.].contains(&intersection.y0)); + } + } +} diff --git a/vendor/kurbo/src/rounded_rect.rs b/vendor/kurbo/src/rounded_rect.rs new file mode 100644 index 0000000000..26625f79bc --- /dev/null +++ b/vendor/kurbo/src/rounded_rect.rs @@ -0,0 +1,489 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A rectangle with rounded corners. + +use core::f64::consts::{FRAC_PI_2, FRAC_PI_4}; +use core::ops::{Add, Sub}; + +use crate::{Arc, PathEl, Point, Rect, RoundedRectRadii, Shape, Size, Vec2, arc::ArcAppendIter}; + +#[allow(unused_imports)] // This is unused in later versions of Rust because of additions to core::f32 +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A rectangle with rounded corners. +/// +/// By construction the rounded rectangle will have +/// non-negative dimensions and radii clamped to half size of the rect. +/// The rounded rectangle can have different radii for each corner. +/// +/// The easiest way to create a `RoundedRect` is often to create a [`Rect`], +/// and then call [`to_rounded_rect`]. +/// +/// ``` +/// use kurbo::{RoundedRect, RoundedRectRadii}; +/// +/// // Create a rounded rectangle with a single radius for all corners: +/// RoundedRect::new(0.0, 0.0, 10.0, 10.0, 5.0); +/// +/// // Or, specify different radii for each corner, clockwise from the top-left: +/// RoundedRect::new(0.0, 0.0, 10.0, 10.0, (1.0, 2.0, 3.0, 4.0)); +/// ``` +/// +/// [`to_rounded_rect`]: Rect::to_rounded_rect +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RoundedRect { + /// Coordinates of the rectangle. + rect: Rect, + /// Radius of all four corners. + radii: RoundedRectRadii, +} + +impl RoundedRect { + /// A new rectangle from minimum and maximum coordinates. + /// + /// The result will have non-negative width, height and radii. + #[inline] + pub fn new( + x0: f64, + y0: f64, + x1: f64, + y1: f64, + radii: impl Into, + ) -> RoundedRect { + RoundedRect::from_rect(Rect::new(x0, y0, x1, y1), radii) + } + + /// A new rounded rectangle from a rectangle and corner radii. + /// + /// The result will have non-negative width, height and radii. + /// + /// See also [`Rect::to_rounded_rect`], which offers the same utility. + #[inline] + pub fn from_rect(rect: Rect, radii: impl Into) -> RoundedRect { + let rect = rect.abs(); + let shortest_side_length = (rect.width()).min(rect.height()); + let radii = radii.into().abs().clamp(shortest_side_length / 2.0); + + RoundedRect { rect, radii } + } + + /// A new rectangle from two [`Point`]s. + /// + /// The result will have non-negative width, height and radius. + #[inline] + pub fn from_points( + p0: impl Into, + p1: impl Into, + radii: impl Into, + ) -> RoundedRect { + Rect::from_points(p0, p1).to_rounded_rect(radii) + } + + /// A new rectangle from origin and size. + /// + /// The result will have non-negative width, height and radius. + #[inline] + pub fn from_origin_size( + origin: impl Into, + size: impl Into, + radii: impl Into, + ) -> RoundedRect { + Rect::from_origin_size(origin, size).to_rounded_rect(radii) + } + + /// The width of the rectangle. + #[inline] + pub const fn width(&self) -> f64 { + self.rect.width() + } + + /// The height of the rectangle. + #[inline] + pub const fn height(&self) -> f64 { + self.rect.height() + } + + /// Radii of the rounded corners. + #[inline(always)] + pub const fn radii(&self) -> RoundedRectRadii { + self.radii + } + + /// The (non-rounded) rectangle. + #[inline(always)] + pub const fn rect(&self) -> Rect { + self.rect + } + + /// The origin of the rectangle. + /// + /// This is the top left corner in a y-down space. + #[inline(always)] + pub const fn origin(&self) -> Point { + self.rect.origin() + } + + /// The center point of the rectangle. + #[inline] + pub const fn center(&self) -> Point { + self.rect.center() + } + + /// Is this rounded rectangle finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.rect.is_finite() && self.radii.is_finite() + } + + /// Is this rounded rectangle NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.rect.is_nan() || self.radii.is_nan() + } +} + +#[doc(hidden)] +pub struct RoundedRectPathIter { + idx: usize, + rect: RectPathIter, + arcs: [ArcAppendIter; 4], +} + +impl Shape for RoundedRect { + type PathElementsIter<'iter> = RoundedRectPathIter; + + fn path_elements(&self, tolerance: f64) -> RoundedRectPathIter { + let radii = self.radii(); + + let build_arc_iter = |i, center, ellipse_radii| { + let arc = Arc { + center, + radii: ellipse_radii, + start_angle: FRAC_PI_2 * i as f64, + sweep_angle: FRAC_PI_2, + x_rotation: 0.0, + }; + arc.append_iter(tolerance) + }; + + // Note: order follows the rectangle path iterator. + let arcs = [ + build_arc_iter( + 2, + Point { + x: self.rect.x0 + radii.top_left, + y: self.rect.y0 + radii.top_left, + }, + Vec2 { + x: radii.top_left, + y: radii.top_left, + }, + ), + build_arc_iter( + 3, + Point { + x: self.rect.x1 - radii.top_right, + y: self.rect.y0 + radii.top_right, + }, + Vec2 { + x: radii.top_right, + y: radii.top_right, + }, + ), + build_arc_iter( + 0, + Point { + x: self.rect.x1 - radii.bottom_right, + y: self.rect.y1 - radii.bottom_right, + }, + Vec2 { + x: radii.bottom_right, + y: radii.bottom_right, + }, + ), + build_arc_iter( + 1, + Point { + x: self.rect.x0 + radii.bottom_left, + y: self.rect.y1 - radii.bottom_left, + }, + Vec2 { + x: radii.bottom_left, + y: radii.bottom_left, + }, + ), + ]; + + let rect = RectPathIter { + rect: self.rect, + ix: 0, + radii, + }; + + RoundedRectPathIter { idx: 0, rect, arcs } + } + + #[inline] + fn area(&self) -> f64 { + // A corner is a quarter-circle, i.e. + // .............# + // . ###### + // . ######### + // . ########### + // . ############ + // .############# + // ############## + // |-----r------| + // For each corner, we need to subtract the square that bounds this + // quarter-circle, and add back in the area of quarter circle. + + let radii = self.radii(); + + // Start with the area of the bounding rectangle. For each corner, + // subtract the area of the corner under the quarter-circle, and add + // back the area of the quarter-circle. + self.rect.area() + + [ + radii.top_left, + radii.top_right, + radii.bottom_right, + radii.bottom_left, + ] + .iter() + .map(|radius| (FRAC_PI_4 - 1.0) * radius * radius) + .sum::() + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + // A corner is a quarter-circle, i.e. + // .............# + // . # + // . # + // . # + // . # + // .# + // # + // |-----r------| + // If we start with the bounding rectangle, then subtract 2r (the + // straight edge outside the circle) and add 1/4 * pi * (2r) (the + // perimeter of the quarter-circle) for each corner with radius r, we + // get the perimeter of the shape. + + let radii = self.radii(); + + // Start with the full perimeter. For each corner, subtract the + // border surrounding the rounded corner and add the quarter-circle + // perimeter. + self.rect.perimeter(1.0) + + ([ + radii.top_left, + radii.top_right, + radii.bottom_right, + radii.bottom_left, + ]) + .iter() + .map(|radius| (-2.0 + FRAC_PI_2) * radius) + .sum::() + } + + #[inline] + fn winding(&self, mut pt: Point) -> i32 { + let center = self.center(); + + // 1. Translate the point relative to the center of the rectangle. + pt.x -= center.x; + pt.y -= center.y; + + // 2. Pick a radius value to use based on which quadrant the point is + // in. + let radius = { + /// Calculates `if !cond { a } else { b }`. + /// + /// This function is theoretically pretty nonsensical to have, as the compiler should + /// pretty trivially be able to compile both this function and the explicit + /// `if`-statement equivalent to the same thing. However, for some reason, writing + /// these bit operations explicitly causes the compiler to be better about prefetching + /// the rounded rect data. + /// + /// See for more. + #[inline(always)] + fn select(a: f64, b: f64, cond: bool) -> f64 { + let mask = (cond as u64).wrapping_neg(); // 0 or !0 + f64::from_bits((a.to_bits() & !mask) | (b.to_bits() & mask)) + } + + let radii = self.radii(); + let radius_top = select(radii.top_left, radii.top_right, pt.x >= 0.); + let radius_bottom = select(radii.bottom_left, radii.bottom_right, pt.x >= 0.); + select(radius_top, radius_bottom, pt.y >= 0.) + }; + + // 3. This is the width and height of a rectangle with one corner at + // the center of the rounded rectangle, and another corner at the + // center of the relevant corner circle. + let inside_half_width = (self.width() / 2.0 - radius).max(0.0); + let inside_half_height = (self.height() / 2.0 - radius).max(0.0); + + // 4. Three things are happening here. + // + // First, the x- and y-values are being reflected into the positive + // (bottom-right quadrant). The radius has already been determined, + // so it doesn't matter what quadrant is used. + // + // After reflecting, the points are clamped so that their x- and y- + // values can't be lower than the x- and y- values of the center of + // the corner circle, and the coordinate system is transformed + // again, putting (0, 0) at the center of the corner circle. + let px = (pt.x.abs() - inside_half_width).max(0.0); + let py = (pt.y.abs() - inside_half_height).max(0.0); + + // 5. The transforms above clamp all input points such that they will + // be inside the rounded rectangle if the corresponding output point + // (px, py) is inside a circle centered around the origin with the + // given radius. + let inside = px * px + py * py <= radius * radius; + if inside { 1 } else { 0 } + } + + #[inline] + fn bounding_box(&self) -> Rect { + self.rect.bounding_box() + } + + #[inline(always)] + fn as_rounded_rect(&self) -> Option { + Some(*self) + } +} + +struct RectPathIter { + rect: Rect, + radii: RoundedRectRadii, + ix: usize, +} + +// This is clockwise in a y-down coordinate system for positive area. +impl Iterator for RectPathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(Point::new( + self.rect.x0, + self.rect.y0 + self.radii.top_left, + ))), + 2 => Some(PathEl::LineTo(Point::new( + self.rect.x1 - self.radii.top_right, + self.rect.y0, + ))), + 3 => Some(PathEl::LineTo(Point::new( + self.rect.x1, + self.rect.y1 - self.radii.bottom_right, + ))), + 4 => Some(PathEl::LineTo(Point::new( + self.rect.x0 + self.radii.bottom_left, + self.rect.y1, + ))), + 5 => Some(PathEl::ClosePath), + _ => None, + } + } +} + +// This is clockwise in a y-down coordinate system for positive area. +impl Iterator for RoundedRectPathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + if self.idx > 4 { + return None; + } + + // Iterate between rectangle and arc iterators. + // Rect iterator will start and end the path. + + // Initial point set by the rect iterator + if self.idx == 0 { + self.idx += 1; + return self.rect.next(); + } + + // Generate the arc curve elements. + // If we reached the end of the arc, add a line towards next arc (rect iterator). + match self.arcs[self.idx - 1].next() { + Some(elem) => Some(elem), + None => { + self.idx += 1; + self.rect.next() + } + } + } +} + +impl Add for RoundedRect { + type Output = RoundedRect; + + #[inline] + fn add(self, v: Vec2) -> RoundedRect { + RoundedRect::from_rect(self.rect + v, self.radii) + } +} + +impl Sub for RoundedRect { + type Output = RoundedRect; + + #[inline] + fn sub(self, v: Vec2) -> RoundedRect { + RoundedRect::from_rect(self.rect - v, self.radii) + } +} + +#[cfg(test)] +mod tests { + use crate::{Circle, Point, Rect, RoundedRect, Shape}; + + #[test] + fn area() { + let epsilon = 1e-9; + + // Extremum: 0.0 radius corner -> rectangle + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let rounded_rect = RoundedRect::new(0.0, 0.0, 100.0, 100.0, 0.0); + assert!((rect.area() - rounded_rect.area()).abs() < epsilon); + + // Extremum: half-size radius corner -> circle + let circle = Circle::new((0.0, 0.0), 50.0); + let rounded_rect = RoundedRect::new(0.0, 0.0, 100.0, 100.0, 50.0); + assert!((circle.area() - rounded_rect.area()).abs() < epsilon); + } + + #[test] + fn winding() { + let rect = RoundedRect::new(-5.0, -5.0, 10.0, 20.0, (5.0, 5.0, 5.0, 0.0)); + assert_eq!(rect.winding(Point::new(0.0, 0.0)), 1); + assert_eq!(rect.winding(Point::new(-5.0, 0.0)), 1); // left edge + assert_eq!(rect.winding(Point::new(0.0, 20.0)), 1); // bottom edge + assert_eq!(rect.winding(Point::new(10.0, 20.0)), 0); // bottom-right corner + assert_eq!(rect.winding(Point::new(-5.0, 20.0)), 1); // bottom-left corner (has a radius of 0) + assert_eq!(rect.winding(Point::new(-10.0, 0.0)), 0); + + let rect = RoundedRect::new(-10.0, -20.0, 10.0, 20.0, 0.0); // rectangle + assert_eq!(rect.winding(Point::new(10.0, 20.0)), 1); // bottom-right corner + } + + #[test] + fn bez_conversion() { + let rect = RoundedRect::new(-5.0, -5.0, 10.0, 20.0, 5.0); + let p = rect.to_path(1e-9); + // Note: could be more systematic about tolerance tightness. + let epsilon = 1e-7; + assert!((rect.area() - p.area()).abs() < epsilon); + assert_eq!(p.winding(Point::new(0.0, 0.0)), 1); + } +} diff --git a/vendor/kurbo/src/rounded_rect_radii.rs b/vendor/kurbo/src/rounded_rect_radii.rs new file mode 100644 index 0000000000..3a1632a2b1 --- /dev/null +++ b/vendor/kurbo/src/rounded_rect_radii.rs @@ -0,0 +1,124 @@ +// Copyright 2021 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A description of the radii for each corner of a rounded rectangle. + +use core::convert::From; + +#[allow(unused_imports)] // This is unused in later versions of Rust because of additions to core::f32 +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// Radii for each corner of a rounded rectangle. +/// +/// The use of `top` as in `top_left` assumes a y-down coordinate space. Piet +/// (and Druid by extension) uses a y-down coordinate space, but Kurbo also +/// supports a y-up coordinate space, in which case `top_left` would actually +/// refer to the bottom-left corner, and vice versa. Top may not always +/// actually be the top, but `top` corners will always have a smaller y-value +/// than `bottom` corners. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RoundedRectRadii { + /// The radius of the top-left corner. + pub top_left: f64, + /// The radius of the top-right corner. + pub top_right: f64, + /// The radius of the bottom-right corner. + pub bottom_right: f64, + /// The radius of the bottom-left corner. + pub bottom_left: f64, +} + +impl RoundedRectRadii { + /// Create a new `RoundedRectRadii`. This function takes radius values for + /// the four corners. The argument order is `top_left`, `top_right`, + /// `bottom_right`, `bottom_left`, or clockwise starting from `top_left`. + #[inline(always)] + pub const fn new(top_left: f64, top_right: f64, bottom_right: f64, bottom_left: f64) -> Self { + RoundedRectRadii { + top_left, + top_right, + bottom_right, + bottom_left, + } + } + + /// Create a new `RoundedRectRadii` from a single radius. The `radius` + /// argument will be set as the radius for all four corners. + #[inline(always)] + pub const fn from_single_radius(radius: f64) -> Self { + RoundedRectRadii { + top_left: radius, + top_right: radius, + bottom_right: radius, + bottom_left: radius, + } + } + + /// Takes the absolute value of all corner radii. + pub const fn abs(&self) -> Self { + RoundedRectRadii::new( + self.top_left.abs(), + self.top_right.abs(), + self.bottom_right.abs(), + self.bottom_left.abs(), + ) + } + + /// For each corner, takes the min of that corner's radius and `max`. + pub const fn clamp(&self, max: f64) -> Self { + RoundedRectRadii::new( + self.top_left.min(max), + self.top_right.min(max), + self.bottom_right.min(max), + self.bottom_left.min(max), + ) + } + + /// Returns `true` if all radius values are finite. + pub const fn is_finite(&self) -> bool { + self.top_left.is_finite() + && self.top_right.is_finite() + && self.bottom_right.is_finite() + && self.bottom_left.is_finite() + } + + /// Returns `true` if any corner radius value is NaN. + pub const fn is_nan(&self) -> bool { + self.top_left.is_nan() + || self.top_right.is_nan() + || self.bottom_right.is_nan() + || self.bottom_left.is_nan() + } + + /// If all radii are equal, returns the value of the radii. Otherwise, + /// returns `None`. + pub const fn as_single_radius(&self) -> Option { + let epsilon = 1e-9; + + if (self.top_left - self.top_right).abs() < epsilon + && (self.top_right - self.bottom_right).abs() < epsilon + && (self.bottom_right - self.bottom_left).abs() < epsilon + { + Some(self.top_left) + } else { + None + } + } +} + +impl From for RoundedRectRadii { + #[inline(always)] + fn from(radius: f64) -> Self { + RoundedRectRadii::from_single_radius(radius) + } +} + +impl From<(f64, f64, f64, f64)> for RoundedRectRadii { + #[inline(always)] + fn from(radii: (f64, f64, f64, f64)) -> Self { + RoundedRectRadii::new(radii.0, radii.1, radii.2, radii.3) + } +} diff --git a/vendor/kurbo/src/shape.rs b/vendor/kurbo/src/shape.rs new file mode 100644 index 0000000000..fb28450890 --- /dev/null +++ b/vendor/kurbo/src/shape.rs @@ -0,0 +1,229 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A generic trait for shapes. + +use crate::{BezPath, Circle, Line, PathEl, Point, Rect, RoundedRect, Segments, segments}; + +/// A generic trait for open and closed shapes. +/// +/// This trait provides conversion from shapes to [`BezPath`]s, as well as +/// general geometry functionality like computing [`area`], [`bounding_box`]es, +/// and [`winding`] number. +/// +/// [`area`]: Shape::area +/// [`bounding_box`]: Shape::bounding_box +/// [`winding`]: Shape::winding +pub trait Shape { + /// The iterator returned by the [`path_elements`] method. + /// + /// [`path_elements`]: Shape::path_elements + type PathElementsIter<'iter>: Iterator + 'iter + where + Self: 'iter; + + /// Returns an iterator over this shape expressed as [`PathEl`]s; + /// that is, as Bézier path _elements_. + /// + /// All shapes can be represented as Béziers, but in many situations + /// (such as when interfacing with a platform drawing API) there are more + /// efficient native types for specific concrete shapes. In this case, + /// the user should exhaust the `as_` methods ([`as_rect`], [`as_line`], etc) + /// before converting to a [`BezPath`], as those are likely to be more + /// efficient. + /// + /// In many cases, shapes are able to iterate their elements without + /// allocating; however creating a [`BezPath`] object always allocates. + /// If you need an owned [`BezPath`] you can use [`to_path`] instead. + /// + /// # Tolerance + /// + /// The `tolerance` parameter controls the accuracy of + /// conversion of geometric primitives to Bézier curves, as + /// curves such as circles cannot be represented exactly but + /// only approximated. For drawing as in UI elements, a value + /// of 0.1 is appropriate, as it is unlikely to be visible to + /// the eye. For scientific applications, a smaller value + /// might be appropriate. Note that in general the number of + /// cubic Bézier segments scales as `tolerance ^ (-1/6)`. + /// + /// [`as_rect`]: Shape::as_rect + /// [`as_line`]: Shape::as_line + /// [`to_path`]: Shape::to_path + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_>; + + /// Convert to a Bézier path. + /// + /// This always allocates. It is appropriate when both the source + /// shape and the resulting path are to be retained. + /// + /// If you only need to iterate the elements (such as to convert them to + /// drawing commands for a given 2D graphics API) you should prefer + /// [`path_elements`], which can avoid allocating where possible. + /// + /// The `tolerance` parameter is the same as for [`path_elements`]. + /// + /// [`path_elements`]: Shape::path_elements + fn to_path(&self, tolerance: f64) -> BezPath { + self.path_elements(tolerance).collect() + } + + /// Convert into a Bézier path. + /// + /// This allocates in the general case, but is zero-cost if the + /// shape is already a [`BezPath`]. + /// + /// The `tolerance` parameter is the same as for [`path_elements()`]. + /// + /// [`path_elements()`]: Shape::path_elements + fn into_path(self, tolerance: f64) -> BezPath + where + Self: Sized, + { + self.to_path(tolerance) + } + + /// Returns an iterator over this shape expressed as Bézier path + /// _segments_ ([`PathSeg`]s). + /// + /// The allocation behaviour and `tolerance` parameter are the + /// same as for [`path_elements()`] + /// + /// [`PathSeg`]: crate::PathSeg + /// [`path_elements()`]: Shape::path_elements + fn path_segments(&self, tolerance: f64) -> Segments> { + segments(self.path_elements(tolerance)) + } + + /// Signed area. + /// + /// This method only produces meaningful results with closed shapes. + /// + /// The convention for positive area is that y increases when x is + /// positive. Thus, it is clockwise when down is increasing y (the + /// usual convention for graphics), and anticlockwise when + /// up is increasing y (the usual convention for math). + fn area(&self) -> f64; + + /// Total length of perimeter. + //FIXME: document the accuracy param + fn perimeter(&self, accuracy: f64) -> f64; + + /// The [winding number] of a point. + /// + /// This method only produces meaningful results with closed shapes. + /// + /// The sign of the winding number is consistent with that of [`area`], + /// meaning it is +1 when the point is inside a positive area shape + /// and -1 when it is inside a negative area shape. Of course, greater + /// magnitude values are also possible when the shape is more complex. + /// + /// [`area`]: Shape::area + /// [winding number]: https://mathworld.wolfram.com/ContourWindingNumber.html + fn winding(&self, pt: Point) -> i32; + + /// Returns `true` if the [`Point`] is inside this shape. + /// + /// This is only meaningful for closed shapes. Some shapes may have specialized + /// implementations of this function or of [`winding`] determination. + /// + /// The default implementation uses the non-zero winding rule. + /// + /// To determine containment using the even-odd winding rule, check the + /// [`winding`] directly. + /// + /// [`winding`]: Self::winding + fn contains(&self, pt: Point) -> bool { + self.winding(pt) != 0 + } + + /// The smallest rectangle that encloses the shape. + fn bounding_box(&self) -> Rect; + + /// If the shape is a line, make it available. + fn as_line(&self) -> Option { + None + } + + /// If the shape is a rectangle, make it available. + fn as_rect(&self) -> Option { + None + } + + /// If the shape is a rounded rectangle, make it available. + fn as_rounded_rect(&self) -> Option { + None + } + + /// If the shape is a circle, make it available. + fn as_circle(&self) -> Option { + None + } + + /// If the shape is stored as a slice of path elements, make + /// that available. + /// + /// Note: when GAT's land, a method like `path_elements` would be + /// able to iterate through the slice with no extra allocation, + /// without making any assumption that storage is contiguous. + fn as_path_slice(&self) -> Option<&[PathEl]> { + None + } +} + +/// Blanket implementation so `impl Shape` will accept owned or reference. +impl<'a, T: Shape> Shape for &'a T { + type PathElementsIter<'iter> + = T::PathElementsIter<'iter> + where + T: 'iter, + 'a: 'iter; + + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> { + (*self).path_elements(tolerance) + } + + fn to_path(&self, tolerance: f64) -> BezPath { + (*self).to_path(tolerance) + } + + fn path_segments(&self, tolerance: f64) -> Segments> { + (*self).path_segments(tolerance) + } + + fn area(&self) -> f64 { + (*self).area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + (*self).perimeter(accuracy) + } + + fn winding(&self, pt: Point) -> i32 { + (*self).winding(pt) + } + + fn bounding_box(&self) -> Rect { + (*self).bounding_box() + } + + fn as_line(&self) -> Option { + (*self).as_line() + } + + fn as_rect(&self) -> Option { + (*self).as_rect() + } + + fn as_rounded_rect(&self) -> Option { + (*self).as_rounded_rect() + } + + fn as_circle(&self) -> Option { + (*self).as_circle() + } + + fn as_path_slice(&self) -> Option<&[PathEl]> { + (*self).as_path_slice() + } +} diff --git a/vendor/kurbo/src/simplify.rs b/vendor/kurbo/src/simplify.rs new file mode 100644 index 0000000000..411571e38b --- /dev/null +++ b/vendor/kurbo/src/simplify.rs @@ -0,0 +1,396 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Simplification of a Bézier path. +//! +//! This module is currently experimental. +//! +//! The methods in this module create a `SimplifyBezPath` object, which can then +//! be fed to [`fit_to_bezpath`] or [`fit_to_bezpath_opt`] depending on the degree +//! of optimization desired. +//! +//! The implementation uses a number of techniques to achieve high performance and +//! accuracy. The parameter (generally written `t`) evenly divides the curve segments +//! in the original, so sampling can be done in constant time. The derivatives are +//! computed analytically, as that is straightforward with Béziers. +//! +//! The areas and moments are computed analytically (using Green's theorem), and +//! the prefix sum is stored. Thus, it is possible to analytically compute the area +//! and moment of any subdivision of the curve, also in constant time, by taking +//! the difference of two stored prefix sum values, then fixing up the subsegments. +//! +//! A current limitation (hoped to be addressed in the future) is that non-regular +//! cubic segments may have tangents computed incorrectly. This can easily happen, +//! for example when setting a control point equal to an endpoint. +//! +//! In addition, this method does not report corners (adjoining segments where the +//! tangents are not continuous). It is not clear whether it's best to handle such +//! cases here, or in client code. +//! +//! [`fit_to_bezpath`]: crate::fit_to_bezpath +//! [`fit_to_bezpath_opt`]: crate::fit_to_bezpath_opt + +use alloc::vec::Vec; + +use core::ops::Range; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +use crate::{ + BezPath, CubicBez, CurveFitSample, Line, ParamCurve, ParamCurveDeriv, ParamCurveFit, PathEl, + PathSeg, Point, QuadBez, Vec2, fit_to_bezpath, fit_to_bezpath_opt, +}; + +/// A Bézier path which has been prepared for simplification. +/// +/// See the [module-level documentation] for a bit more discussion of the approach, +/// and how this struct is to be used. +/// +/// [module-level documentation]: crate::simplify +pub struct SimplifyBezPath(Vec); + +struct SimplifyCubic { + c: CubicBez, + // The inclusive prefix sum of the moment integrals + moments: (f64, f64, f64), +} + +/// Options for simplifying paths. +pub struct SimplifyOptions { + /// The tangent of the minimum angle below which the path is considered smooth. + angle_thresh: f64, + opt_level: SimplifyOptLevel, +} + +/// Optimization level for simplification. +pub enum SimplifyOptLevel { + /// Subdivide; faster but not as optimized results. + Subdivide, + /// Optimize subdivision points. + Optimize, +} + +impl Default for SimplifyOptions { + fn default() -> Self { + let opt_level = SimplifyOptLevel::Subdivide; + SimplifyOptions { + angle_thresh: 1e-3, + opt_level, + } + } +} + +#[doc(hidden)] +/// Compute moment integrals. +/// +/// This is exposed for testing purposes but is an internal detail. We can +/// add to the public, documented interface if there is a use case. +pub fn moment_integrals(c: CubicBez) -> (f64, f64, f64) { + let (x0, y0) = (c.p0.x, c.p0.y); + let (x1, y1) = (c.p1.x - x0, c.p1.y - y0); + let (x2, y2) = (c.p2.x - x0, c.p2.y - y0); + let (x3, y3) = (c.p3.x - x0, c.p3.y - y0); + + let r0 = 3. * x1; + let r1 = 3. * y1; + let r2 = x2 * y3; + let r3 = x3 * y2; + let r4 = x3 * y3; + let r5 = 27. * y1; + let r6 = x1 * x2; + let r7 = 27. * y2; + let r8 = 45. * r2; + let r9 = 18. * x3; + let r10 = x1 * y1; + let r11 = 30. * x1; + let r12 = 45. * x3; + let r13 = x2 * y1; + let r14 = 45. * r3; + let r15 = x1.powi(2); + let r16 = 18. * y3; + let r17 = x2.powi(2); + let r18 = 45. * y3; + let r19 = x3.powi(2); + let r20 = 30. * y1; + let r21 = y2.powi(2); + let r22 = y3.powi(2); + let r23 = y1.powi(2); + let a = -r0 * y2 - r0 * y3 + r1 * x2 + r1 * x3 - 6. * r2 + 6. * r3 + 10. * r4; + + // Scale and add chord + let lift = x3 * y0; + let area = a * 0.05 + lift; + let x = r10 * r9 - r11 * r4 + r12 * r13 + r14 * x2 - r15 * r16 - r15 * r7 - r17 * r18 + + r17 * r5 + + r19 * r20 + + 105. * r19 * y2 + + 280. * r19 * y3 + - 105. * r2 * x3 + + r5 * r6 + - r6 * r7 + - r8 * x1; + let y = -r10 * r16 - r10 * r7 - r11 * r22 + r12 * r21 + r13 * r7 + r14 * y1 - r18 * x1 * y2 + + r20 * r4 + - 27. * r21 * x1 + - 105. * r22 * x2 + + 140. * r22 * x3 + + r23 * r9 + + 27. * r23 * x2 + + 105. * r3 * y3 + - r8 * y2; + + let mx = x * (1. / 840.) + x0 * area + 0.5 * x3 * lift; + let my = y * (1. / 420.) + y0 * a * 0.1 + y0 * lift; + + (area, mx, my) +} + +impl SimplifyBezPath { + /// Set up a new Bézier path for simplification. + /// + /// Currently this is not dealing with discontinuities at all, but it + /// could be extended to do so. + pub fn new(path: impl IntoIterator) -> Self { + let (mut a, mut x, mut y) = (0.0, 0.0, 0.0); + let els = crate::segments(path) + .map(|seg| { + let c = seg.to_cubic(); + let (ai, xi, yi) = moment_integrals(c); + a += ai; + x += xi; + y += yi; + SimplifyCubic { + c, + moments: (a, x, y), + } + }) + .collect(); + SimplifyBezPath(els) + } + + /// Resolve a `t` value to a cubic. + /// + /// Also return the resulting `t` value for the selected cubic. + fn scale(&self, t: f64) -> (usize, f64) { + let t_scale = t * self.0.len() as f64; + let t_floor = t_scale.floor(); + (t_floor as usize, t_scale - t_floor) + } + + fn moment_integrals(&self, i: usize, range: Range) -> (f64, f64, f64) { + if range.end == range.start { + (0.0, 0.0, 0.0) + } else { + moment_integrals(self.0[i].c.subsegment(range)) + } + } +} + +impl ParamCurveFit for SimplifyBezPath { + fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2) { + let (mut i, mut t0) = self.scale(t); + let n = self.0.len(); + if i == n { + i -= 1; + t0 = 1.0; + } + let c = self.0[i].c; + (c.eval(t0), c.deriv().eval(t0).to_vec2() * n as f64) + } + + fn sample_pt_tangent(&self, t: f64, _: f64) -> CurveFitSample { + let (mut i, mut t0) = self.scale(t); + if i == self.0.len() { + i -= 1; + t0 = 1.0; + } + let c = self.0[i].c; + let p = c.eval(t0); + let tangent = c.deriv().eval(t0).to_vec2(); + CurveFitSample { p, tangent } + } + + // We could use the default implementation, but provide our own, mostly + // because it is possible to efficiently provide an analytically accurate + // answer. + fn moment_integrals(&self, range: Range) -> (f64, f64, f64) { + let (i0, t0) = self.scale(range.start); + let (i1, t1) = self.scale(range.end); + if i0 == i1 { + self.moment_integrals(i0, t0..t1) + } else { + let (a0, x0, y0) = self.moment_integrals(i0, t0..1.0); + let (a1, x1, y1) = self.moment_integrals(i1, 0.0..t1); + let (mut a, mut x, mut y) = (a0 + a1, x0 + x1, y0 + y1); + if i1 > i0 + 1 { + let (a2, x2, y2) = self.0[i0].moments; + let (a3, x3, y3) = self.0[i1 - 1].moments; + a += a3 - a2; + x += x3 - x2; + y += y3 - y2; + } + (a, x, y) + } + } + + fn break_cusp(&self, _: Range) -> Option { + None + } +} + +#[derive(Default)] +struct SimplifyState { + queue: BezPath, + result: BezPath, + needs_moveto: bool, +} + +impl SimplifyState { + fn add_seg(&mut self, seg: PathSeg) { + if self.queue.is_empty() { + self.queue.move_to(seg.start()); + } + match seg { + PathSeg::Line(l) => self.queue.line_to(l.p1), + PathSeg::Quad(q) => self.queue.quad_to(q.p1, q.p2), + PathSeg::Cubic(c) => self.queue.curve_to(c.p1, c.p2, c.p3), + } + } + + fn flush(&mut self, accuracy: f64, options: &SimplifyOptions) { + if self.queue.is_empty() { + return; + } + if self.queue.elements().len() == 2 { + // Queue is just one segment (count is moveto + primitive) + // Just output the segment, no simplification is possible. + self.result + .extend(self.queue.iter().skip(!self.needs_moveto as usize)); + } else { + let s = SimplifyBezPath::new(&self.queue); + let b = match options.opt_level { + SimplifyOptLevel::Subdivide => fit_to_bezpath(&s, accuracy), + SimplifyOptLevel::Optimize => fit_to_bezpath_opt(&s, accuracy), + }; + self.result + .extend(b.iter().skip(!self.needs_moveto as usize)); + } + self.needs_moveto = false; + self.queue.truncate(0); + } +} + +/// Simplify a Bézier path. +/// +/// This function simplifies an arbitrary Bézier path; it is designed to handle +/// multiple subpaths and also corners. +/// +/// The underlying curve-fitting approach works best if the source path is very +/// smooth. If it contains higher frequency noise, then results may be poor, as +/// the resulting curve matches the original with G1 continuity at each subdivision +/// point, and also preserves the area. For such inputs, consider some form of +/// smoothing or low-pass filtering before simplification. In particular, if the +/// input is derived from a sequence of points, consider fitting a smooth spline. +/// +/// We may add such capabilities in the future, possibly as opt-in smoothing +/// specified through the options. +pub fn simplify_bezpath( + path: impl IntoIterator, + accuracy: f64, + options: &SimplifyOptions, +) -> BezPath { + let mut last_pt = None; + let mut last_seg: Option = None; + let mut state = SimplifyState::default(); + for el in path { + let mut this_seg = None; + match el { + PathEl::MoveTo(p) => { + state.flush(accuracy, options); + state.needs_moveto = true; + last_pt = Some(p); + } + PathEl::LineTo(p) => { + let last = last_pt.unwrap(); + if last == p { + continue; + } + this_seg = Some(PathSeg::Line(Line::new(last, p))); + } + PathEl::QuadTo(p1, p2) => { + let last = last_pt.unwrap(); + if last == p1 && last == p2 { + continue; + } + this_seg = Some(PathSeg::Quad(QuadBez::new(last, p1, p2))); + } + PathEl::CurveTo(p1, p2, p3) => { + let last = last_pt.unwrap(); + if last == p1 && last == p2 && last == p3 { + continue; + } + this_seg = Some(PathSeg::Cubic(CubicBez::new(last, p1, p2, p3))); + } + PathEl::ClosePath => { + state.flush(accuracy, options); + state.result.close_path(); + state.needs_moveto = true; + last_seg = None; + continue; + } + } + if let Some(seg) = this_seg { + if let Some(last) = last_seg { + let last_tan = last.tangents().1; + let this_tan = seg.tangents().0; + if last_tan.cross(this_tan).abs() + > last_tan.dot(this_tan).abs() * options.angle_thresh + { + state.flush(accuracy, options); + } + } + last_pt = Some(seg.end()); + state.add_seg(seg); + } + last_seg = this_seg; + } + state.flush(accuracy, options); + state.result +} + +impl SimplifyOptions { + /// Set optimization level. + pub fn opt_level(mut self, level: SimplifyOptLevel) -> Self { + self.opt_level = level; + self + } + + /// Set angle threshold. + /// + /// The tangent of the angle below which joins are considered smooth and + /// not corners. The default is approximately 1 milliradian. + pub fn angle_thresh(mut self, thresh: f64) -> Self { + self.angle_thresh = thresh; + self + } +} + +#[cfg(test)] +mod tests { + use crate::BezPath; + + use super::{SimplifyOptions, simplify_bezpath}; + + #[test] + fn simplify_lines_corner() { + // Make sure lines are passed through unchanged if there is a corner. + let mut path = BezPath::new(); + path.move_to((1., 2.)); + path.line_to((3., 4.)); + path.line_to((10., 5.)); + let options = SimplifyOptions::default(); + let simplified = simplify_bezpath(path.clone(), 1.0, &options); + assert_eq!(path, simplified); + } +} diff --git a/vendor/kurbo/src/size.rs b/vendor/kurbo/src/size.rs new file mode 100644 index 0000000000..ad1f6c6579 --- /dev/null +++ b/vendor/kurbo/src/size.rs @@ -0,0 +1,492 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A 2D size. + +use core::fmt; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; + +use crate::common::FloatExt; +use crate::{Axis, Rect, RoundedRect, RoundedRectRadii, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D size. +#[derive(Clone, Copy, Default, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Size { + /// The width. + pub width: f64, + /// The height. + pub height: f64, +} + +impl Size { + /// A size with zero width or height. + pub const ZERO: Size = Size::new(0., 0.); + + /// A size with width and height set to `f64::INFINITY`. + pub const INFINITY: Size = Size::new(f64::INFINITY, f64::INFINITY); + + /// Create a new `Size` with the provided `width` and `height`. + #[inline(always)] + pub const fn new(width: f64, height: f64) -> Self { + Size { width, height } + } + + /// Returns the max of `width` and `height`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size = Size::new(-10.5, 42.0); + /// assert_eq!(size.max_side(), 42.0); + /// ``` + pub const fn max_side(self) -> f64 { + self.width.max(self.height) + } + + /// Returns the min of `width` and `height`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size = Size::new(-10.5, 42.0); + /// assert_eq!(size.min_side(), -10.5); + /// ``` + pub const fn min_side(self) -> f64 { + self.width.min(self.height) + } + + /// The area covered by this size. + #[inline] + pub const fn area(self) -> f64 { + self.width * self.height + } + + /// Whether this size has zero area. + #[doc(alias = "is_empty")] + #[inline] + pub const fn is_zero_area(self) -> bool { + self.area() == 0.0 + } + + /// Returns the component-wise minimum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// + /// let this = Size::new(0., 100.); + /// let other = Size::new(10., 10.); + /// + /// assert_eq!(this.min(other), Size::new(0., 10.)); + /// ``` + pub const fn min(self, other: Size) -> Self { + Size { + width: self.width.min(other.width), + height: self.height.min(other.height), + } + } + + /// Returns the component-wise maximum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// + /// let this = Size::new(0., 100.); + /// let other = Size::new(10., 10.); + /// + /// assert_eq!(this.max(other), Size::new(10., 100.)); + /// ``` + pub const fn max(self, other: Size) -> Self { + Size { + width: self.width.max(other.width), + height: self.height.max(other.height), + } + } + + /// Returns a new size bounded by `min` and `max.` + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// + /// let this = Size::new(0., 100.); + /// let min = Size::new(10., 10.,); + /// let max = Size::new(50., 50.); + /// assert_eq!(this.clamp(min, max), Size::new(10., 50.)) + /// ``` + pub const fn clamp(self, min: Size, max: Size) -> Self { + self.max(min).min(max) + } + + /// Convert this size into a [`Vec2`], with `width` mapped to `x` and `height` + /// mapped to `y`. + #[inline(always)] + pub const fn to_vec2(self) -> Vec2 { + Vec2::new(self.width, self.height) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).round(); + /// assert_eq!(size_pos.width, 3.0); + /// assert_eq!(size_pos.height, 4.0); + /// let size_neg = Size::new(-3.3, -3.6).round(); + /// assert_eq!(size_neg.width, -3.0); + /// assert_eq!(size_neg.height, -4.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Size { + Size::new(self.width.round(), self.height.round()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).ceil(); + /// assert_eq!(size_pos.width, 4.0); + /// assert_eq!(size_pos.height, 4.0); + /// let size_neg = Size::new(-3.3, -3.6).ceil(); + /// assert_eq!(size_neg.width, -3.0); + /// assert_eq!(size_neg.height, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Size { + Size::new(self.width.ceil(), self.height.ceil()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).floor(); + /// assert_eq!(size_pos.width, 3.0); + /// assert_eq!(size_pos.height, 3.0); + /// let size_neg = Size::new(-3.3, -3.6).floor(); + /// assert_eq!(size_neg.width, -4.0); + /// assert_eq!(size_neg.height, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Size { + Size::new(self.width.floor(), self.height.floor()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded away] from zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).expand(); + /// assert_eq!(size_pos.width, 4.0); + /// assert_eq!(size_pos.height, 4.0); + /// let size_neg = Size::new(-3.3, -3.6).expand(); + /// assert_eq!(size_neg.width, -4.0); + /// assert_eq!(size_neg.height, -4.0); + /// ``` + /// + /// [rounded away]: FloatExt::expand + #[inline] + pub fn expand(self) -> Size { + Size::new(self.width.expand(), self.height.expand()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded towards] zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).trunc(); + /// assert_eq!(size_pos.width, 3.0); + /// assert_eq!(size_pos.height, 3.0); + /// let size_neg = Size::new(-3.3, -3.6).trunc(); + /// assert_eq!(size_neg.width, -3.0); + /// assert_eq!(size_neg.height, -3.0); + /// ``` + /// + /// [rounded towards]: f64::trunc + #[inline] + pub fn trunc(self) -> Size { + Size::new(self.width.trunc(), self.height.trunc()) + } + + /// Returns the aspect ratio of a rectangle with this size. + /// + /// The aspect ratio is the ratio of the width to the height. + /// + /// If the height is `0`, the output will be `sign(self.width) * infinity`. If the width and + /// height are both `0`, then the output will be `NaN`. + #[inline] + pub const fn aspect_ratio_width(self) -> f64 { + // ratio is determined by width / height + // https://en.wikipedia.org/wiki/Aspect_ratio_(image) + // https://en.wikipedia.org/wiki/Ratio + self.width / self.height + } + + /// Returns **the inverse** of the aspect ratio of a rectangle with this size. + /// + /// Aspect ratios are usually defined as the ratio of the width to the height, but + /// this method incorrectly returns the ratio of height to width. + /// You should generally prefer [`aspect_ratio_width`](Self::aspect_ratio_width). + /// + /// If the width is `0`, the output will be `sign(self.height) * infinity`. If the width and + /// height are both `0`, then the output will be `NaN`. + #[deprecated( + note = "You should use `aspect_ratio_width` instead, as this method returns a potentially unexpected value.", + since = "0.12.0" + )] + #[inline] + // TODO: When we remove this, we should also work out what to do with aspect_ratio_width + // The tentatitive plan is to rename `aspect_ratio_width` back to this name + pub const fn aspect_ratio(self) -> f64 { + self.height / self.width + } + + /// Convert this `Size` into a [`Rect`] with origin `(0.0, 0.0)`. + #[inline(always)] + pub const fn to_rect(self) -> Rect { + Rect::new(0., 0., self.width, self.height) + } + + /// Convert this `Size` into a [`RoundedRect`] with origin `(0.0, 0.0)` and + /// the provided corner radius. + #[inline] + pub fn to_rounded_rect(self, radii: impl Into) -> RoundedRect { + self.to_rect().to_rounded_rect(radii) + } + + /// Is this size [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.width.is_finite() && self.height.is_finite() + } + + /// Is this size [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.width.is_nan() || self.height.is_nan() + } + + /// Get the member matching the given axis. + #[inline] + pub const fn get_coord(self, axis: Axis) -> f64 { + match axis { + Axis::Horizontal => self.width, + Axis::Vertical => self.height, + } + } + + /// Get a mutable reference to the member matching the given axis. + #[inline] + pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 { + match axis { + Axis::Horizontal => &mut self.width, + Axis::Vertical => &mut self.height, + } + } + + /// Set the member matching the given axis to the given value. + #[inline] + pub const fn set_coord(&mut self, axis: Axis, value: f64) { + match axis { + Axis::Horizontal => self.width = value, + Axis::Vertical => self.height = value, + } + } +} + +impl fmt::Debug for Size { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}W×{:?}H", self.width, self.height) + } +} + +impl fmt::Display for Size { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "(")?; + fmt::Display::fmt(&self.width, formatter)?; + write!(formatter, "×")?; + fmt::Display::fmt(&self.height, formatter)?; + write!(formatter, ")") + } +} + +impl MulAssign for Size { + #[inline] + fn mul_assign(&mut self, other: f64) { + *self = Size { + width: self.width * other, + height: self.height * other, + }; + } +} + +impl Mul for f64 { + type Output = Size; + + #[inline] + fn mul(self, other: Size) -> Size { + other * self + } +} + +impl Mul for Size { + type Output = Size; + + #[inline] + fn mul(self, other: f64) -> Size { + Size { + width: self.width * other, + height: self.height * other, + } + } +} + +impl DivAssign for Size { + #[inline] + fn div_assign(&mut self, other: f64) { + *self = Size { + width: self.width / other, + height: self.height / other, + }; + } +} + +impl Div for Size { + type Output = Size; + + #[inline] + fn div(self, other: f64) -> Size { + Size { + width: self.width / other, + height: self.height / other, + } + } +} + +impl Add for Size { + type Output = Size; + #[inline] + fn add(self, other: Size) -> Size { + Size { + width: self.width + other.width, + height: self.height + other.height, + } + } +} + +impl AddAssign for Size { + #[inline] + fn add_assign(&mut self, other: Size) { + *self = *self + other; + } +} + +impl Sub for Size { + type Output = Size; + #[inline] + fn sub(self, other: Size) -> Size { + Size { + width: self.width - other.width, + height: self.height - other.height, + } + } +} + +impl SubAssign for Size { + #[inline] + fn sub_assign(&mut self, other: Size) { + *self = *self - other; + } +} + +impl From<(f64, f64)> for Size { + #[inline(always)] + fn from(v: (f64, f64)) -> Size { + Size { + width: v.0, + height: v.1, + } + } +} + +impl From for (f64, f64) { + #[inline(always)] + fn from(v: Size) -> (f64, f64) { + (v.width, v.height) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display() { + let s = Size::new(-0.12345, 9.87654); + assert_eq!(format!("{s}"), "(-0.12345×9.87654)"); + + let s = Size::new(-0.12345, 9.87654); + assert_eq!(format!("{s:+6.2}"), "( -0.12× +9.88)"); + } + + #[test] + #[expect(deprecated, reason = "Testing deprecated function.")] + fn aspect_ratio() { + let s = Size::new(1.0, 1.0); + assert!((s.aspect_ratio() - 1.0).abs() < 1e-6); + } + + #[test] + fn aspect_ratio_width() { + let s = Size::new(1.0, 1.0); + assert!((s.aspect_ratio_width() - 1.0).abs() < 1e-6); + + // 3:2 film (mm) + let s = Size::new(36.0, 24.0); + assert!((s.aspect_ratio_width() - 1.5).abs() < 1e-6); + // 4k screen + let s = Size::new(3840.0, 2160.0); + assert!((s.aspect_ratio_width() - (16. / 9.)).abs() < 1e-6); + } +} diff --git a/vendor/kurbo/src/stroke.rs b/vendor/kurbo/src/stroke.rs new file mode 100644 index 0000000000..2cdeb87d5a --- /dev/null +++ b/vendor/kurbo/src/stroke.rs @@ -0,0 +1,1267 @@ +// Copyright 2023 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use core::{borrow::Borrow, f64::consts::PI}; + +use alloc::vec::Vec; + +use smallvec::SmallVec; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +use crate::{ + Affine, Arc, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Point, + QuadBez, Vec2, common::solve_quadratic, +}; + +/// Defines the connection between two segments of a stroke. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Join { + /// A straight line connecting the segments. + Bevel, + /// The segments are extended to their natural intersection point. + Miter, + /// An arc between the segments. + Round, +} + +/// Defines the shape to be drawn at the ends of a stroke. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Cap { + /// Flat cap. + Butt, + /// Square cap with dimensions equal to half the stroke width. + Square, + /// Rounded cap with radius equal to half the stroke width. + Round, +} + +/// The visual style of a stroke. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Stroke { + /// Width of the stroke. + pub width: f64, + /// Style for connecting segments of the stroke. + pub join: Join, + /// Limit for miter joins. + pub miter_limit: f64, + /// Style for capping the beginning of an open subpath. + pub start_cap: Cap, + /// Style for capping the end of an open subpath. + pub end_cap: Cap, + /// Lengths of dashes in alternating on/off order. + pub dash_pattern: Dashes, + /// Offset of the first dash. + pub dash_offset: f64, +} + +/// Options for path stroking. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StrokeOpts { + opt_level: StrokeOptLevel, + /// When `true`, dashes are emitted in the order they appear along the path. The default `false` delays a subpath's first dash so it can be merged with a dash that wraps through `ClosePath`; this option disables both the reorder and the wraparound merge, so a dash spanning the seam is truncated there. + stable_dash_order: bool, +} + +/// Optimization level for computing stroke outlines. +/// +/// Note that in the current implementation, this setting has no effect. +/// However, having a tradeoff between optimization of number of segments +/// and speed makes sense and may be added in the future, so applications +/// should set it appropriately. For real time rendering, the appropriate +/// value is `Subdivide`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum StrokeOptLevel { + /// Adaptively subdivide segments in half. + Subdivide, + /// Compute optimized subdivision points to minimize error. + Optimized, +} + +impl Default for StrokeOpts { + fn default() -> Self { + let opt_level = StrokeOptLevel::Subdivide; + StrokeOpts { + opt_level, + stable_dash_order: false, + } + } +} + +impl Default for Stroke { + fn default() -> Self { + Self::new(1.0) + } +} + +impl Stroke { + /// Creates a new stroke with the specified width. + pub const fn new(width: f64) -> Self { + Self { + width, + join: Join::Round, + miter_limit: 4.0, + start_cap: Cap::Round, + end_cap: Cap::Round, + dash_pattern: SmallVec::new_const(), + dash_offset: 0.0, + } + } + + /// Builder method for setting the join style. + pub const fn with_join(mut self, join: Join) -> Self { + self.join = join; + self + } + + /// Builder method for setting the limit for miter joins. + pub const fn with_miter_limit(mut self, limit: f64) -> Self { + self.miter_limit = limit; + self + } + + /// Builder method for setting the cap style for the start of the stroke. + pub const fn with_start_cap(mut self, cap: Cap) -> Self { + self.start_cap = cap; + self + } + + /// Builder method for setting the cap style for the end of the stroke. + pub const fn with_end_cap(mut self, cap: Cap) -> Self { + self.end_cap = cap; + self + } + + /// Builder method for setting the cap style. + pub const fn with_caps(mut self, cap: Cap) -> Self { + self.start_cap = cap; + self.end_cap = cap; + self + } + + /// Builder method for setting the dashing parameters. + pub fn with_dashes

(mut self, offset: f64, pattern: P) -> Self + where + P: IntoIterator, + P::Item: Borrow, + { + self.dash_offset = offset; + self.dash_pattern.clear(); + self.dash_pattern + .extend(pattern.into_iter().map(|dash| *dash.borrow())); + self + } + + /// Returns `true` if all floating-point stroke parameters are [finite]. + /// + /// [finite]: f64::is_finite + pub fn is_finite(&self) -> bool { + self.width.is_finite() + && self.miter_limit.is_finite() + && self.dash_offset.is_finite() + && self.dash_pattern.iter().all(|dash| dash.is_finite()) + } + + /// Returns `true` if any floating-point stroke parameter is [`NaN`]. + /// + /// [`NaN`]: f64::is_nan + pub fn is_nan(&self) -> bool { + self.width.is_nan() + || self.miter_limit.is_nan() + || self.dash_offset.is_nan() + || self.dash_pattern.iter().any(|dash| dash.is_nan()) + } +} + +impl StrokeOpts { + /// Set optimization level for computing stroke outlines. + pub fn opt_level(mut self, opt_level: StrokeOptLevel) -> Self { + self.opt_level = opt_level; + self + } + + /// When `true`, dashes are emitted in the order they appear along the path. + pub fn stable_dash_order(mut self, stable: bool) -> Self { + self.stable_dash_order = stable; + self + } +} + +/// Collection of values representing lengths in a dash pattern. +pub type Dashes = SmallVec<[f64; 4]>; + +/// A structure that is used for creating strokes. +/// +/// See also [`stroke_with`]. +#[derive(Default, Debug)] +pub struct StrokeCtx { + // As a possible future optimization, we might not need separate storage + // for forward and backward paths, we can add forward to the output in-place. + // However, this structure is clearer and the cost fairly modest. + output: BezPath, + forward_path: BezPath, + backward_path: BezPath, + result_path: BezPath, + start_pt: Point, + start_norm: Vec2, + start_tan: Vec2, + last_pt: Point, + last_tan: Vec2, + // Precomputation of the join threshold, to optimize per-join logic. + // If hypot < (hypot + dot) * join_thresh, omit join altogether. + join_thresh: f64, +} + +impl StrokeCtx { + /// Return the path that defines the expanded stroke. + pub fn output(&self) -> &BezPath { + &self.output + } +} + +impl StrokeCtx { + fn reset(&mut self) { + self.output.truncate(0); + self.forward_path.truncate(0); + self.backward_path.truncate(0); + self.start_pt = Point::default(); + self.start_norm = Vec2::default(); + self.start_tan = Vec2::default(); + self.last_pt = Point::default(); + self.last_tan = Vec2::default(); + self.join_thresh = 0.0; + } +} + +/// Expand a stroke into a fill. +/// +/// The `tolerance` parameter controls the accuracy of the result. In general, +/// the number of subdivisions in the output scales at least to the -1/4 power +/// of the parameter, for example making it 1/16 as big generates twice as many +/// segments. Currently the algorithm is not tuned for extremely fine tolerances. +/// The theoretically optimum scaling exponent is -1/6, but achieving this may +/// require slow numerical techniques (currently a subject of research). The +/// appropriate value depends on the application; if the result of the stroke +/// will be scaled up, a smaller value is needed. +/// +/// This method attempts a fairly high degree of correctness, but ultimately +/// is based on computing parallel curves and adding joins and caps, rather than +/// computing the rigorously correct parallel sweep (which requires evolutes in +/// the general case). See [Nehab 2020] for more discussion. +/// +/// [Nehab 2020]: https://dl.acm.org/doi/10.1145/3386569.3392392 +pub fn stroke( + path: impl IntoIterator, + style: &Stroke, + opts: &StrokeOpts, + tolerance: f64, +) -> BezPath { + let mut ctx = StrokeCtx::default(); + stroke_with(path, style, opts, tolerance, &mut ctx); + + ctx.output +} + +/// Expand a stroke into a fill. +/// +/// This is the same as [`stroke`], except for the fact that you can explicitly pass a +/// `StrokeCtx`. By doing so, you can reuse the same context over multiple calls and ensure +/// that the number of reallocations is minimized. +/// +/// Unlike [`stroke`], this method doesn't return an owned version of the expanded stroke as a +/// [`BezPath`]. Instead, you can get a reference to the resulting path by calling +/// [`StrokeCtx::output`]. +pub fn stroke_with( + path: impl IntoIterator, + style: &Stroke, + opts: &StrokeOpts, + tolerance: f64, + ctx: &mut StrokeCtx, +) { + if style.dash_pattern.is_empty() { + stroke_undashed(path, style, tolerance, ctx); + } else { + let dashed = dash_iter( + path.into_iter(), + style.dash_offset, + &style.dash_pattern, + opts.stable_dash_order, + ); + stroke_undashed(dashed, style, tolerance, ctx); + } +} + +/// Version of stroke expansion for styles with no dashes. +fn stroke_undashed( + path: impl IntoIterator, + style: &Stroke, + tolerance: f64, + ctx: &mut StrokeCtx, +) { + ctx.reset(); + ctx.join_thresh = 2.0 * tolerance / style.width; + + for el in path { + let p0 = ctx.last_pt; + match el { + PathEl::MoveTo(p) => { + ctx.finish(style); + ctx.start_pt = p; + ctx.last_pt = p; + } + PathEl::LineTo(p1) => { + if p1 != p0 { + let tangent = p1 - p0; + ctx.do_join(style, tangent); + ctx.last_tan = tangent; + ctx.do_line(style, tangent, p1); + } + } + PathEl::QuadTo(p1, p2) => { + if p1 != p0 || p2 != p0 { + let q = QuadBez::new(p0, p1, p2); + let (tan0, tan1) = PathSeg::Quad(q).tangents(); + // Craft patch (zero tangent): `tangents` falls back to the + // chord when the control arms are shorter than its + // threshold, and the chord of a loop that ends where it + // starts is zero. Such a loop is skipped like a zero-length + // line. + if tan0 == Vec2::ZERO || tan1 == Vec2::ZERO { + continue; + } + ctx.do_join(style, tan0); + // Craft patch (zero tangent): the raised cubic's control + // arms are 2/3 as long and can fall under the threshold + // of `tangents`, so the quadratic's tangents are passed on. + ctx.do_cubic(style, q.raise(), (tan0, tan1), tolerance); + ctx.last_tan = tan1; + } + } + PathEl::CurveTo(p1, p2, p3) => { + if p1 != p0 || p2 != p0 || p3 != p0 { + let c = CubicBez::new(p0, p1, p2, p3); + let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + // Craft patch (zero tangent): as for a quadratic above. + if tan0 == Vec2::ZERO || tan1 == Vec2::ZERO { + continue; + } + ctx.do_join(style, tan0); + ctx.do_cubic(style, c, (tan0, tan1), tolerance); + ctx.last_tan = tan1; + } + } + PathEl::ClosePath => { + if p0 != ctx.start_pt { + let tangent = ctx.start_pt - p0; + ctx.do_join(style, tangent); + ctx.last_tan = tangent; + ctx.do_line(style, tangent, ctx.start_pt); + } + ctx.finish_closed(style); + } + } + } + ctx.finish(style); +} + +fn round_cap(out: &mut BezPath, tolerance: f64, center: Point, norm: Vec2) { + round_join(out, tolerance, center, norm, PI); +} + +fn round_join(out: &mut BezPath, tolerance: f64, center: Point, norm: Vec2, angle: f64) { + let a = Affine::new([norm.x, norm.y, -norm.y, norm.x, center.x, center.y]); + let arc = Arc::new(Point::ORIGIN, (1.0, 1.0), PI - angle, angle, 0.0); + arc.to_cubic_beziers(tolerance, |p1, p2, p3| out.curve_to(a * p1, a * p2, a * p3)); +} + +fn round_join_rev(out: &mut BezPath, tolerance: f64, center: Point, norm: Vec2, angle: f64) { + let a = Affine::new([norm.x, norm.y, norm.y, -norm.x, center.x, center.y]); + let arc = Arc::new(Point::ORIGIN, (1.0, 1.0), PI - angle, angle, 0.0); + arc.to_cubic_beziers(tolerance, |p1, p2, p3| out.curve_to(a * p1, a * p2, a * p3)); +} + +fn square_cap(out: &mut BezPath, close: bool, center: Point, norm: Vec2) { + let a = Affine::new([norm.x, norm.y, -norm.y, norm.x, center.x, center.y]); + out.line_to(a * Point::new(1.0, 1.0)); + out.line_to(a * Point::new(-1.0, 1.0)); + if close { + out.close_path(); + } else { + out.line_to(a * Point::new(-1.0, 0.0)); + } +} + +fn extend_reversed(out: &mut BezPath, elements: &[PathEl]) { + for i in (1..elements.len()).rev() { + let end = elements[i - 1].end_point().unwrap(); + match elements[i] { + PathEl::LineTo(_) => out.line_to(end), + PathEl::QuadTo(p1, _) => out.quad_to(p1, end), + PathEl::CurveTo(p1, p2, _) => out.curve_to(p2, p1, end), + _ => unreachable!(), + } + } +} + +impl StrokeCtx { + /// Append forward and backward paths to output. + fn finish(&mut self, style: &Stroke) { + // TODO: scale + let tolerance = 1e-3; + if self.forward_path.is_empty() { + return; + } + self.output.extend(&self.forward_path); + let back_els = self.backward_path.elements(); + let return_p = back_els[back_els.len() - 1].end_point().unwrap(); + let d = self.last_pt - return_p; + match style.end_cap { + Cap::Butt => self.output.line_to(return_p), + Cap::Round => round_cap(&mut self.output, tolerance, self.last_pt, d), + Cap::Square => square_cap(&mut self.output, false, self.last_pt, d), + } + extend_reversed(&mut self.output, back_els); + match style.start_cap { + Cap::Butt => self.output.close_path(), + Cap::Round => round_cap(&mut self.output, tolerance, self.start_pt, self.start_norm), + Cap::Square => square_cap(&mut self.output, true, self.start_pt, self.start_norm), + } + + self.forward_path.truncate(0); + self.backward_path.truncate(0); + } + + /// Finish a closed path + fn finish_closed(&mut self, style: &Stroke) { + if self.forward_path.is_empty() { + return; + } + self.do_join(style, self.start_tan); + self.output.extend(&self.forward_path); + self.output.close_path(); + let back_els = self.backward_path.elements(); + let last_pt = back_els[back_els.len() - 1].end_point().unwrap(); + self.output.move_to(last_pt); + extend_reversed(&mut self.output, back_els); + self.output.close_path(); + self.forward_path.truncate(0); + self.backward_path.truncate(0); + } + + fn do_join(&mut self, style: &Stroke, tan0: Vec2) { + // TODO: scale + let tolerance = 1e-3; + let scale = 0.5 * style.width / tan0.hypot(); + let norm = scale * Vec2::new(-tan0.y, tan0.x); + let p0 = self.last_pt; + if self.forward_path.elements().is_empty() { + self.forward_path.move_to(p0 - norm); + self.backward_path.move_to(p0 + norm); + self.start_tan = tan0; + self.start_norm = norm; + } else { + let ab = self.last_tan; + let cd = tan0; + let cross = ab.cross(cd); + let dot = ab.dot(cd); + let hypot = cross.hypot(dot); + // possible TODO: a minor speedup could be squaring both sides + if dot <= 0.0 || cross.abs() >= hypot * self.join_thresh { + match style.join { + Join::Bevel => { + self.forward_path.line_to(p0 - norm); + self.backward_path.line_to(p0 + norm); + } + Join::Miter => { + if 2.0 * hypot < (hypot + dot) * style.miter_limit.powi(2) { + // TODO: maybe better to store last_norm or derive from path? + let last_scale = 0.5 * style.width / ab.hypot(); + let last_norm = last_scale * Vec2::new(-ab.y, ab.x); + if cross > 0.0 { + let fp_last = p0 - last_norm; + let fp_this = p0 - norm; + let h = ab.cross(fp_this - fp_last) / cross; + let miter_pt = fp_this - cd * h; + self.forward_path.line_to(miter_pt); + self.backward_path.line_to(p0); + } else if cross < 0.0 { + let fp_last = p0 + last_norm; + let fp_this = p0 + norm; + let h = ab.cross(fp_this - fp_last) / cross; + let miter_pt = fp_this - cd * h; + self.backward_path.line_to(miter_pt); + self.forward_path.line_to(p0); + } + } + self.forward_path.line_to(p0 - norm); + self.backward_path.line_to(p0 + norm); + } + Join::Round => { + let angle = cross.atan2(dot); + if angle > 0.0 { + self.backward_path.line_to(p0 + norm); + round_join(&mut self.forward_path, tolerance, p0, norm, angle); + } else { + self.forward_path.line_to(p0 - norm); + round_join_rev(&mut self.backward_path, tolerance, p0, -norm, -angle); + } + } + } + } + } + } + + fn do_line(&mut self, style: &Stroke, tangent: Vec2, p1: Point) { + let scale = 0.5 * style.width / tangent.hypot(); + let norm = scale * Vec2::new(-tangent.y, tangent.x); + self.forward_path.line_to(p1 - norm); + self.backward_path.line_to(p1 + norm); + self.last_pt = p1; + } + + fn do_cubic(&mut self, style: &Stroke, c: CubicBez, tangents: (Vec2, Vec2), tolerance: f64) { + // First, detect degenerate linear case + + // Ordinarily, this is the direction of the chord, but if the chord is very + // short, we take the longer control arm. + let chord = c.p3 - c.p0; + let mut chord_ref = chord; + let mut chord_ref_hypot2 = chord_ref.hypot2(); + let d01 = c.p1 - c.p0; + if d01.hypot2() > chord_ref_hypot2 { + chord_ref = d01; + chord_ref_hypot2 = chord_ref.hypot2(); + } + let d23 = c.p3 - c.p2; + if d23.hypot2() > chord_ref_hypot2 { + chord_ref = d23; + chord_ref_hypot2 = chord_ref.hypot2(); + } + // Project Bézier onto chord + let p0 = c.p0.to_vec2().dot(chord_ref); + let p1 = c.p1.to_vec2().dot(chord_ref); + let p2 = c.p2.to_vec2().dot(chord_ref); + let p3 = c.p3.to_vec2().dot(chord_ref); + const ENDPOINT_D: f64 = 0.01; + if p3 <= p0 + || p1 > p2 + || p1 < p0 + ENDPOINT_D * (p3 - p0) + || p2 > p3 - ENDPOINT_D * (p3 - p0) + { + // potentially a cusp inside + let x01 = d01.cross(chord_ref); + let x23 = d23.cross(chord_ref); + let x03 = chord.cross(chord_ref); + let thresh = tolerance.powi(2) * chord_ref_hypot2; + if x01 * x01 < thresh && x23 * x23 < thresh && x03 * x03 < thresh { + // control points are nearly co-linear + let midpoint = c.p0.midpoint(c.p3); + // Mapping back from projection of reference chord + let ref_vec = chord_ref / chord_ref_hypot2; + let ref_pt = midpoint - 0.5 * (p0 + p3) * ref_vec; + self.do_linear(style, c, tangents, [p0, p1, p2, p3], ref_pt, ref_vec); + return; + } + } + + crate::offset::offset_cubic(c, -0.5 * style.width, tolerance, &mut self.result_path); + self.forward_path.extend(self.result_path.iter().skip(1)); + crate::offset::offset_cubic(c, 0.5 * style.width, tolerance, &mut self.result_path); + self.backward_path.extend(self.result_path.iter().skip(1)); + self.last_pt = c.p3; + } + + /// Do a cubic which is actually linear. + /// + /// The `p` argument is the control points projected to the reference chord. + /// The ref arguments are the inverse map of a projection back to the client + /// coordinate space. + fn do_linear( + &mut self, + style: &Stroke, + c: CubicBez, + (tan0, tan1): (Vec2, Vec2), + p: [f64; 4], + ref_pt: Point, + ref_vec: Vec2, + ) { + // Always do round join, to model cusp as limit of finite curvature (see Nehab). + let style = Stroke::new(style.width).with_join(Join::Round); + // Tangents of endpoints (for connecting to joins) are those of the + // segment, which the caller has checked are nonzero. + self.last_tan = tan0; + // find cusps + let c0 = p[1] - p[0]; + let c1 = 2.0 * p[2] - 4.0 * p[1] + 2.0 * p[0]; + let c2 = p[3] - 3.0 * p[2] + 3.0 * p[1] - p[0]; + let roots = solve_quadratic(c0, c1, c2); + // discard cusps right at endpoints + const EPSILON: f64 = 1e-6; + for t in roots { + if t > EPSILON && t < 1.0 - EPSILON { + let mt = 1.0 - t; + let z = mt * (mt * mt * p[0] + 3.0 * t * (mt * p[1] + t * p[2])) + t * t * t * p[3]; + let p = ref_pt + z * ref_vec; + let tan = p - self.last_pt; + // Craft patch (zero tangent): after rounding, a cusp can land + // on the previous point, and a zero tangent has no normal. + if tan != Vec2::ZERO { + self.do_join(&style, tan); + self.do_line(&style, tan, p); + self.last_tan = tan; + } + } + } + let tan = c.p3 - self.last_pt; + if tan != Vec2::ZERO { + self.do_join(&style, tan); + self.do_line(&style, tan, c.p3); + self.last_tan = tan; + } + self.do_join(&style, tan1); + } +} + +/// An implementation of dashing as an iterator-to-iterator transformation. +struct DashIterator<'a, T> { + inner: T, + input_done: bool, + closepath_pending: bool, + dashes: &'a [f64], + dash_ix: usize, + init_dash_ix: usize, + init_dash_remaining: f64, + init_is_active: bool, + is_active: bool, + state: DashState, + current_seg: PathSeg, + t: f64, + dash_remaining: f64, + seg_remaining: f64, + start_pt: Point, + last_pt: Point, + stash: Vec, + stash_ix: usize, + stable_dash_order: bool, + needs_moveto: bool, +} + +#[derive(PartialEq, Eq)] +enum DashState { + NeedInput, + ToStash, + Working, + FromStash, +} + +impl> Iterator for DashIterator<'_, T> { + type Item = PathEl; + + fn next(&mut self) -> Option { + loop { + match self.state { + DashState::NeedInput => { + if self.input_done { + return None; + } + self.get_input(); + if self.input_done { + return None; + } + self.state = DashState::ToStash; + } + DashState::ToStash => { + if let Some(el) = self.step() { + if self.stable_dash_order { + return Some(el); + } + self.stash.push(el); + } + } + DashState::Working => { + if let Some(el) = self.step() { + return Some(el); + } + } + DashState::FromStash => { + if let Some(el) = self.stash.get(self.stash_ix) { + self.stash_ix += 1; + return Some(*el); + } else { + self.stash.clear(); + self.stash_ix = 0; + if self.input_done { + return None; + } + if self.closepath_pending { + self.closepath_pending = false; + self.state = DashState::NeedInput; + } else { + self.state = DashState::ToStash; + } + } + } + } + } + } +} + +fn seg_to_el(el: &PathSeg) -> PathEl { + match el { + PathSeg::Line(l) => PathEl::LineTo(l.p1), + PathSeg::Quad(q) => PathEl::QuadTo(q.p1, q.p2), + PathSeg::Cubic(c) => PathEl::CurveTo(c.p1, c.p2, c.p3), + } +} + +const DASH_ACCURACY: f64 = 1e-6; + +/// Create a new dashing iterator. +/// +/// Handling of dashes is fairly orthogonal to stroke expansion. This iterator +/// is an internal detail of the stroke expansion logic, but is also available +/// separately, and is expected to be useful when doing stroke expansion on +/// GPU. +/// +/// It is implemented as an iterator-to-iterator transform. Because it consumes +/// the input sequentially and produces consistent output with correct joins, +/// it requires internal state and may allocate. +/// +/// Accuracy is currently hard-coded to 1e-6. This is better than generally +/// expected, and care is taken to get cusps correct, among other things. +pub fn dash<'a>( + inner: impl Iterator + 'a, + dash_offset: f64, + dashes: &'a [f64], +) -> impl Iterator + 'a { + dash_iter(inner, dash_offset, dashes, false) +} + +fn dash_iter<'a>( + inner: impl Iterator + 'a, + dash_offset: f64, + dashes: &'a [f64], + stable_dash_order: bool, +) -> DashIterator<'a, impl Iterator + 'a> { + // Ensure that offset is positive and minimal by normalization using period + let period = dashes.iter().sum(); + // The SVG spec requires odd-length dash arrays to be doubled to become even-length: + // + // This prevents gaps and dashes from swapping with one another as the offset increases. + let period = if dashes.len() % 2 == 1 { + 2.0 * period + } else { + period + }; + let dash_offset = dash_offset.rem_euclid(period); + + let mut dash_ix = 0; + let mut dash_remaining = dashes[dash_ix] - dash_offset; + let mut is_active = true; + // Find place in dashes array for initial offset. + while dash_remaining < 0.0 { + dash_ix = (dash_ix + 1) % dashes.len(); + dash_remaining += dashes[dash_ix]; + is_active = !is_active; + } + DashIterator { + inner, + input_done: false, + closepath_pending: false, + dashes, + dash_ix, + init_dash_ix: dash_ix, + init_dash_remaining: dash_remaining, + init_is_active: is_active, + is_active, + state: DashState::NeedInput, + current_seg: PathSeg::Line(Line::new(Point::ORIGIN, Point::ORIGIN)), + t: 0.0, + dash_remaining, + seg_remaining: 0.0, + start_pt: Point::ORIGIN, + last_pt: Point::ORIGIN, + stash: Vec::new(), + stash_ix: 0, + stable_dash_order, + needs_moveto: true, + } +} + +impl<'a, T: Iterator> DashIterator<'a, T> { + fn get_input(&mut self) { + loop { + if self.closepath_pending { + self.handle_closepath(); + break; + } + let Some(next_el) = self.inner.next() else { + self.input_done = true; + self.state = DashState::FromStash; + return; + }; + let p0 = self.last_pt; + match next_el { + PathEl::MoveTo(p) => { + if !self.stash.is_empty() { + self.state = DashState::FromStash; + } + self.start_pt = p; + self.last_pt = p; + self.reset_phase(); + continue; + } + PathEl::LineTo(p1) => { + let l = Line::new(p0, p1); + self.seg_remaining = l.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Line(l); + self.last_pt = p1; + } + PathEl::QuadTo(p1, p2) => { + let q = QuadBez::new(p0, p1, p2); + self.seg_remaining = q.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Quad(q); + self.last_pt = p2; + } + PathEl::CurveTo(p1, p2, p3) => { + let c = CubicBez::new(p0, p1, p2, p3); + self.seg_remaining = c.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Cubic(c); + self.last_pt = p3; + } + PathEl::ClosePath => { + self.closepath_pending = true; + if p0 != self.start_pt { + let l = Line::new(p0, self.start_pt); + self.seg_remaining = l.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Line(l); + self.last_pt = self.start_pt; + } else { + self.handle_closepath(); + } + } + } + break; + } + self.t = 0.0; + } + + /// Move arc length forward to next event. + fn step(&mut self) -> Option { + let mut result = None; + if self.state == DashState::ToStash && self.needs_moveto { + self.needs_moveto = false; + if self.is_active { + result = Some(PathEl::MoveTo(self.current_seg.start())); + } else { + self.state = DashState::Working; + } + } else if self.dash_remaining < self.seg_remaining { + // next transition is a dash transition + let seg = self.current_seg.subsegment(self.t..1.0); + let t1 = seg.inv_arclen(self.dash_remaining, DASH_ACCURACY); + if self.is_active { + let subseg = seg.subsegment(0.0..t1); + result = Some(seg_to_el(&subseg)); + self.state = DashState::Working; + } else { + let p = seg.eval(t1); + result = Some(PathEl::MoveTo(p)); + } + self.is_active = !self.is_active; + self.t += t1 * (1.0 - self.t); + self.seg_remaining -= self.dash_remaining; + self.dash_ix += 1; + if self.dash_ix == self.dashes.len() { + self.dash_ix = 0; + } + self.dash_remaining = self.dashes[self.dash_ix]; + } else { + if self.is_active { + let seg = self.current_seg.subsegment(self.t..1.0); + result = Some(seg_to_el(&seg)); + } + self.dash_remaining -= self.seg_remaining; + self.get_input(); + } + result + } + + fn handle_closepath(&mut self) { + if self.state == DashState::ToStash { + // Have looped back without breaking a dash, just play it back + self.stash.push(PathEl::ClosePath); + } else if self.is_active && !self.stable_dash_order { + // connect with path in stash, skip MoveTo. + self.stash_ix = 1; + } + self.state = DashState::FromStash; + self.reset_phase(); + } + + fn reset_phase(&mut self) { + self.dash_ix = self.init_dash_ix; + self.dash_remaining = self.init_dash_remaining; + self.is_active = self.init_is_active; + self.needs_moveto = true; + } +} + +#[cfg(test)] +mod tests { + use super::dash_iter; + use crate::{ + BezPath, Cap::Butt, CubicBez, Join::Miter, Line, PathEl, PathSeg, Shape, Stroke, + StrokeOpts, dash, segments, stroke, + }; + + // A degenerate stroke with a cusp at the endpoint. + #[test] + fn pathological_stroke() { + let curve = CubicBez::new( + (602.469, 286.585), + (641.975, 286.585), + (562.963, 286.585), + (562.963, 286.585), + ); + let path = curve.into_path(0.1); + let stroke_style = Stroke::new(1.); + let stroked = stroke(path, &stroke_style, &StrokeOpts::default(), 0.001); + assert!(stroked.is_finite()); + } + + #[test] + /// + fn dash_miter_join() { + let path = BezPath::from_vec(vec![ + PathEl::MoveTo((70.0, 80.0).into()), + PathEl::LineTo((0.0, 80.0).into()), + PathEl::LineTo((0.0, 77.0).into()), + ]); + let expected_stroke = BezPath::from_vec(vec![ + PathEl::MoveTo((70.0, 90.0).into()), + PathEl::LineTo((0.0, 90.0).into()), + // Miter join point on forward path + PathEl::LineTo((-10.0, 90.0).into()), + PathEl::LineTo((-10.0, 80.0).into()), + PathEl::LineTo((-10.0, 77.0).into()), + PathEl::LineTo((10.0, 77.0).into()), + PathEl::LineTo((10.0, 80.0).into()), + // Miter join point on backward path + PathEl::LineTo((0.0, 80.0).into()), + PathEl::LineTo((0.0, 70.0).into()), + PathEl::LineTo((70.0, 70.0).into()), + PathEl::ClosePath, + ]); + let stroke_style = Stroke::new(20.0) + .with_join(Miter) + .with_caps(Butt) + .with_dashes(0.0, [73.0, 12.0]); + let stroke = stroke(path, &stroke_style, &StrokeOpts::default(), 0.25); + assert_eq!(stroke, expected_stroke); + } + + // Test cases adapted from https://github.com/linebender/vello/pull/388 + #[test] + fn broken_strokes() { + let broken_cubics = [ + [ + (465.24423, 107.11105), + (475.50754, 107.11105), + (475.50754, 107.11105), + (475.50754, 107.11105), + ], + [(0., -0.01), (128., 128.001), (128., -0.01), (0., 128.001)], // Near-cusp + [(0., 0.), (0., -10.), (0., -10.), (0., 10.)], // Flat line with 180 + [(10., 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(39., -39.), (40., -40.), (40., -40.), (0., 0.)], // Flat diagonal with 180 + [(40., 40.), (0., 0.), (200., 200.), (0., 0.)], // Diag w/ an internal 180 + [(0., 0.), (1e-2, 0.), (-1e-2, 0.), (0., 0.)], // Circle + // Flat line with no turns: + [ + (400.75, 100.05), + (400.75, 100.05), + (100.05, 300.95), + (100.05, 300.95), + ], + [(0.5, 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(10., 0.), (0., 0.), (10., 0.), (10., 0.)], // Flat line with a 180 + ]; + let stroke_style = Stroke::new(30.).with_caps(Butt).with_join(Miter); + for cubic in &broken_cubics { + let path = CubicBez::new(cubic[0], cubic[1], cubic[2], cubic[3]).into_path(0.1); + let stroked = stroke(path, &stroke_style, &StrokeOpts::default(), 0.001); + assert!(stroked.is_finite()); + } + } + + #[test] + fn dash_sequence() { + let shape = Line::new((0.0, 0.0), (21.0, 0.0)); + let dashes = [1., 5., 2., 5.]; + let expansion = [ + PathSeg::Line(Line::new((6., 0.), (8., 0.))), + PathSeg::Line(Line::new((13., 0.), (14., 0.))), + PathSeg::Line(Line::new((19., 0.), (21., 0.))), + PathSeg::Line(Line::new((0., 0.), (1., 0.))), + ]; + let iter = segments(dash(shape.path_elements(0.), 0., &dashes)); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_closed_path() { + let shape = crate::Rect::from_points((0.0, 0.0), (4.0, 4.0)); + let dashes = [5., 1.]; + let expansion = [ + PathEl::MoveTo((4.0, 2.0).into()), + PathEl::LineTo((4.0, 4.0).into()), + PathEl::LineTo((1.0, 4.0).into()), + PathEl::MoveTo((0.0, 4.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + PathEl::LineTo((4.0, 0.0).into()), + PathEl::LineTo((4.0, 1.0).into()), + ]; + let iter = dash(shape.path_elements(0.), 0., &dashes); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_stable_order() { + let shape = Line::new((0.0, 0.0), (21.0, 0.0)); + let dashes = [1., 5., 2., 5.]; + let expansion = [ + PathSeg::Line(Line::new((0., 0.), (1., 0.))), + PathSeg::Line(Line::new((6., 0.), (8., 0.))), + PathSeg::Line(Line::new((13., 0.), (14., 0.))), + PathSeg::Line(Line::new((19., 0.), (21., 0.))), + ]; + let iter = segments(dash_iter(shape.path_elements(0.), 0., &dashes, true)); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_closed_path_stable_order() { + let shape = crate::Rect::from_points((0.0, 0.0), (4.0, 4.0)); + let dashes = [5., 1.]; + let expansion = [ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((4.0, 0.0).into()), + PathEl::LineTo((4.0, 1.0).into()), + PathEl::MoveTo((4.0, 2.0).into()), + PathEl::LineTo((4.0, 4.0).into()), + PathEl::LineTo((1.0, 4.0).into()), + PathEl::MoveTo((0.0, 4.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + ]; + let iter = dash_iter(shape.path_elements(0.), 0., &dashes, true); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_offset() { + // Same as dash_sequence, but with a dash offset + // of 3, which skips the first dash and cuts into + // the first gap. + let shape = Line::new((0.0, 0.0), (21.0, 0.0)); + let dashes = [1., 5., 2., 5.]; + let expansion = [ + PathSeg::Line(Line::new((3., 0.), (5., 0.))), + PathSeg::Line(Line::new((10., 0.), (11., 0.))), + PathSeg::Line(Line::new((16., 0.), (18., 0.))), + ]; + let iter = segments(dash(shape.path_elements(0.), 3., &dashes)); + assert_eq!(iter.collect::>(), expansion); + } + + // Differently-sized subpaths verify stable mode restarts the dash pattern per subpath without leaking state. + #[test] + fn dash_stable_order_multi_subpath() { + let mut path = BezPath::new(); + path.move_to((0., 0.)); + path.line_to((2., 0.)); + path.line_to((2., 2.)); + path.line_to((0., 2.)); + path.close_path(); + path.move_to((10., 10.)); + path.line_to((15., 10.)); + path.line_to((15., 14.)); + path.line_to((10., 14.)); + path.close_path(); + let dashes = [3., 1.]; + let expansion = [ + PathEl::MoveTo((0., 0.).into()), + PathEl::LineTo((2., 0.).into()), + PathEl::LineTo((2., 1.).into()), + PathEl::MoveTo((2., 2.).into()), + PathEl::LineTo((0., 2.).into()), + PathEl::LineTo((0., 1.).into()), + PathEl::MoveTo((10., 10.).into()), + PathEl::LineTo((13., 10.).into()), + PathEl::MoveTo((14., 10.).into()), + PathEl::LineTo((15., 10.).into()), + PathEl::LineTo((15., 12.).into()), + PathEl::MoveTo((15., 13.).into()), + PathEl::LineTo((15., 14.).into()), + PathEl::LineTo((13., 14.).into()), + PathEl::MoveTo((12., 14.).into()), + PathEl::LineTo((10., 14.).into()), + PathEl::LineTo((10., 13.).into()), + PathEl::MoveTo((10., 12.).into()), + PathEl::LineTo((10., 10.).into()), + ]; + let iter = dash_iter(path.into_iter(), 0., &dashes, true); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_negative_offset() { + let shape = Line::new((0.0, 0.0), (28.0, 0.0)); + let dashes = [4., 2.]; + let pos = segments(dash(shape.path_elements(0.), 60., &dashes)).collect::>(); + let neg = segments(dash(shape.path_elements(0.), -60., &dashes)).collect::>(); + assert_eq!(neg, pos); + } + + #[test] + fn dash_odd_length_matches_doubled() { + let shape = Line::new((0.0, 0.0), (50.0, 0.0)); + let odd = [10.]; + let doubled = [10., 10.]; + for offset in [0., 5., 9., 10., 11., 15., 20., 25., 100., -7.] { + let from_odd = + segments(dash(shape.path_elements(0.), offset, &odd)).collect::>(); + let from_doubled = + segments(dash(shape.path_elements(0.), offset, &doubled)).collect::>(); + assert_eq!(from_odd, from_doubled, "mismatch at offset {offset}"); + } + } + + #[test] + fn dash_three_element_matches_doubled() { + let shape = Line::new((0.0, 0.0), (200.0, 0.0)); + let three = [20., 10., 3.]; + let doubled = [20., 10., 3., 20., 10., 3.]; + for offset in [0., 15., 32., 33., 34., 50., 66., 99.] { + let from_three = + segments(dash(shape.path_elements(0.), offset, &three)).collect::>(); + let from_doubled = + segments(dash(shape.path_elements(0.), offset, &doubled)).collect::>(); + assert_eq!(from_three, from_doubled, "mismatch at offset {offset}"); + } + } + + #[test] + fn stroke_is_finite_fields() { + let finite = Stroke::new(2.0) + .with_miter_limit(4.0) + .with_dashes(0.0, [1.0, 2.0]); + assert!(finite.is_finite()); + + let non_finite_width = Stroke::new(f64::INFINITY); + assert!(!non_finite_width.is_finite()); + + let non_finite_miter = Stroke::new(2.0).with_miter_limit(f64::NAN); + assert!(!non_finite_miter.is_finite()); + + let non_finite_dash_offset = Stroke::new(2.0).with_dashes(f64::NEG_INFINITY, [1.0, 2.0]); + assert!(!non_finite_dash_offset.is_finite()); + + let non_finite_dash_pattern = Stroke::new(2.0).with_dashes(0.0, [1.0, f64::NAN]); + assert!(!non_finite_dash_pattern.is_finite()); + } + + #[test] + fn stroke_is_nan_fields() { + let finite = Stroke::new(2.0) + .with_miter_limit(4.0) + .with_dashes(0.0, [1.0, 2.0]); + assert!(!finite.is_nan()); + + let nan_width = Stroke::new(f64::NAN); + assert!(nan_width.is_nan()); + + let nan_miter = Stroke::new(2.0).with_miter_limit(f64::NAN); + assert!(nan_miter.is_nan()); + + let nan_dash_offset = Stroke::new(2.0).with_dashes(f64::NAN, [1.0, 2.0]); + assert!(nan_dash_offset.is_nan()); + + let nan_dash_pattern = Stroke::new(2.0).with_dashes(0.0, [1.0, f64::NAN]); + assert!(nan_dash_pattern.is_nan()); + + let infinite_width = Stroke::new(f64::INFINITY); + assert!(!infinite_width.is_nan()); + } + + // A curve that ends where it starts, with control arms shorter than the + // threshold of `PathSeg::tangents`, has a zero tangent at both ends. A + // quadratic with arms of 1.25e-6 passes that threshold, but the cubic it + // is raised to has arms of 2/3 that length, which do not. + #[test] + fn tiny_closed_loops() { + for arm in [1e-7, 1.25e-6, 1e-5] { + for lead_in in [false, true] { + let mut cubic = BezPath::new(); + let mut quad = BezPath::new(); + for path in [&mut cubic, &mut quad] { + path.move_to((0.0, 10.0)); + if lead_in { + path.line_to((10.0, 10.0)); + } else { + path.move_to((10.0, 10.0)); + } + } + cubic.curve_to((10.0 + arm, 10.0), (10.0 + arm, 10.0 + arm), (10.0, 10.0)); + quad.quad_to((10.0 + arm, 10.0), (10.0, 10.0)); + for path in [&mut cubic, &mut quad] { + path.line_to((10.0, 20.0)); + } + for (name, path) in [("cubic", &cubic), ("quad", &quad)] { + let outline = stroke(path, &Stroke::new(2.0), &StrokeOpts::default(), 0.25); + assert!(outline.is_finite(), "{name} {arm} {lead_in}"); + let bounds = outline.bounding_box(); + assert!( + bounds.y0 < 10.0 && bounds.y1 > 20.0, + "{name} {arm} {lead_in} {bounds:?}" + ); + } + } + } + } + + // A collinear cubic that runs back and forth has cusps. After rounding, a + // cusp can map to the point before it or to the end point, giving a zero + // tangent. In the first path, a double cusp root gives two cusps at the + // same point; in the second, the cusp rounds to the end point. + #[test] + fn linear_cubic_with_coincident_cusps() { + use crate::Join; + for svg in [ + "M342.22660294061905,5 C342.22654190545893,5 342.22660294061905,5 342.22654190545893,5", + "M697.7493196978551,5 C697.7493115238381,5 697.7492364261329,5 697.7492364262838,5", + ] { + let path = BezPath::from_svg(svg).unwrap(); + for join in [Join::Bevel, Miter, Join::Round] { + for width in [0.3, 3.0] { + for tolerance in [0.25, 0.01] { + let style = Stroke::new(width).with_join(join); + let outline = stroke(&path, &style, &StrokeOpts::default(), tolerance); + assert!( + !outline.elements().is_empty(), + "{svg} {join:?} {width} {tolerance}" + ); + assert!(outline.is_finite(), "{svg} {join:?} {width} {tolerance}"); + } + } + } + } + } +} diff --git a/vendor/kurbo/src/svg.rs b/vendor/kurbo/src/svg.rs new file mode 100644 index 0000000000..0935381d61 --- /dev/null +++ b/vendor/kurbo/src/svg.rs @@ -0,0 +1,692 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! SVG path representation. + +use alloc::vec::Vec; +use core::error::Error; +use core::f64::consts::PI; +use core::fmt::{self, Display, Formatter}; +#[cfg(feature = "std")] +use std::io::{self, Write}; + +use crate::{Arc, BezPath, ParamCurve, PathEl, PathSeg, Point, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +// Note: the SVG arc logic is heavily adapted from https://github.com/nical/lyon + +/// A single SVG arc segment. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct SvgArc { + /// The arc's start point. + pub from: Point, + /// The arc's end point. + pub to: Point, + /// The arc's radii, where the vector's x-component is the radius in the + /// positive x direction after applying `x_rotation`. + pub radii: Vec2, + /// How much the arc is rotated, in radians. + pub x_rotation: f64, + /// Does this arc sweep through more than π radians? + pub large_arc: bool, + /// Determines if the arc should begin moving at positive angles. + pub sweep: bool, +} + +impl BezPath { + /// Create a `BezPath` with segments corresponding to the sequence of + /// `PathSeg`s + pub fn from_path_segments(segments: impl Iterator) -> BezPath { + let mut path_elements = Vec::new(); + let mut current_pos = None; + + for segment in segments { + let start = segment.start(); + if Some(start) != current_pos { + path_elements.push(PathEl::MoveTo(start)); + } + path_elements.push(match segment { + PathSeg::Line(l) => PathEl::LineTo(l.p1), + PathSeg::Quad(q) => PathEl::QuadTo(q.p1, q.p2), + PathSeg::Cubic(c) => PathEl::CurveTo(c.p1, c.p2, c.p3), + }); + + current_pos = Some(segment.end()); + } + + BezPath::from_vec(path_elements) + } + + /// Convert the path to an SVG path string representation. + /// + /// The current implementation doesn't take any special care to produce a + /// short string (reducing precision, using relative movement). + #[cfg(feature = "std")] + pub fn to_svg(&self) -> String { + let mut buffer = Vec::new(); + self.write_to(&mut buffer).unwrap(); + String::from_utf8(buffer).unwrap() + } + + /// Write the SVG representation of this path to the provided buffer. + #[cfg(feature = "std")] + pub fn write_to(&self, mut writer: W) -> io::Result<()> { + for (i, el) in self.elements().iter().enumerate() { + if i > 0 { + write!(writer, " ")?; + } + match *el { + PathEl::MoveTo(p) => write!(writer, "M{},{}", p.x, p.y)?, + PathEl::LineTo(p) => write!(writer, "L{},{}", p.x, p.y)?, + PathEl::QuadTo(p1, p2) => write!(writer, "Q{},{} {},{}", p1.x, p1.y, p2.x, p2.y)?, + PathEl::CurveTo(p1, p2, p3) => write!( + writer, + "C{},{} {},{} {},{}", + p1.x, p1.y, p2.x, p2.y, p3.x, p3.y + )?, + PathEl::ClosePath => write!(writer, "Z")?, + } + } + + Ok(()) + } + + /// Try to parse a bezier path from an SVG path element. + /// + /// This is implemented on a best-effort basis, intended for cases where the + /// user controls the source of paths, and is not intended as a replacement + /// for a general, robust SVG parser. + pub fn from_svg(data: &str) -> Result { + let mut lexer = SvgLexer::new(data); + let mut path = BezPath::new(); + let mut last_cmd = 0; + let mut last_ctrl = None; + let mut first_pt = Point::ORIGIN; + let mut implicit_moveto = None; + while let Some(c) = lexer.get_cmd(last_cmd) { + if c != b'm' && c != b'M' { + if path.elements().is_empty() { + return Err(SvgParseError::UninitializedPath); + } + + if let Some(pt) = implicit_moveto.take() { + path.move_to(pt); + } + } + match c { + b'm' | b'M' => { + implicit_moveto = None; + let pt = lexer.get_maybe_relative(c)?; + path.move_to(pt); + lexer.last_pt = pt; + first_pt = pt; + last_ctrl = Some(pt); + last_cmd = c - (b'M' - b'L'); + } + b'l' | b'L' => { + let pt = lexer.get_maybe_relative(c)?; + path.line_to(pt); + lexer.last_pt = pt; + last_ctrl = Some(pt); + last_cmd = c; + } + b'h' | b'H' => { + let mut x = lexer.get_number()?; + lexer.opt_comma(); + if c == b'h' { + x += lexer.last_pt.x; + } + let pt = Point::new(x, lexer.last_pt.y); + path.line_to(pt); + lexer.last_pt = pt; + last_ctrl = Some(pt); + last_cmd = c; + } + b'v' | b'V' => { + let mut y = lexer.get_number()?; + lexer.opt_comma(); + if c == b'v' { + y += lexer.last_pt.y; + } + let pt = Point::new(lexer.last_pt.x, y); + path.line_to(pt); + lexer.last_pt = pt; + last_ctrl = Some(pt); + last_cmd = c; + } + b'q' | b'Q' => { + let p1 = lexer.get_maybe_relative(c)?; + let p2 = lexer.get_maybe_relative(c)?; + path.quad_to(p1, p2); + last_ctrl = Some(p1); + lexer.last_pt = p2; + last_cmd = c; + } + b't' | b'T' => { + let p1 = match last_ctrl { + Some(ctrl) => (2.0 * lexer.last_pt.to_vec2() - ctrl.to_vec2()).to_point(), + None => lexer.last_pt, + }; + let p2 = lexer.get_maybe_relative(c)?; + path.quad_to(p1, p2); + last_ctrl = Some(p1); + lexer.last_pt = p2; + last_cmd = c; + } + b'c' | b'C' => { + let p1 = lexer.get_maybe_relative(c)?; + let p2 = lexer.get_maybe_relative(c)?; + let p3 = lexer.get_maybe_relative(c)?; + path.curve_to(p1, p2, p3); + last_ctrl = Some(p2); + lexer.last_pt = p3; + last_cmd = c; + } + b's' | b'S' => { + let p1 = match last_ctrl { + Some(ctrl) => (2.0 * lexer.last_pt.to_vec2() - ctrl.to_vec2()).to_point(), + None => lexer.last_pt, + }; + let p2 = lexer.get_maybe_relative(c)?; + let p3 = lexer.get_maybe_relative(c)?; + path.curve_to(p1, p2, p3); + last_ctrl = Some(p2); + lexer.last_pt = p3; + last_cmd = c; + } + b'a' | b'A' => { + let radii = lexer.get_number_pair()?; + let x_rotation = lexer.get_number()?.to_radians(); + lexer.opt_comma(); + let large_arc = lexer.get_flag()?; + lexer.opt_comma(); + let sweep = lexer.get_flag()?; + lexer.opt_comma(); + let p = lexer.get_maybe_relative(c)?; + let svg_arc = SvgArc { + from: lexer.last_pt, + to: p, + radii: radii.to_vec2(), + x_rotation, + large_arc, + sweep, + }; + + match Arc::from_svg_arc(&svg_arc) { + Some(arc) => { + // TODO: consider making tolerance configurable + arc.to_cubic_beziers(0.1, |p1, p2, p3| { + path.curve_to(p1, p2, p3); + }); + } + None => { + path.line_to(p); + } + } + + last_ctrl = Some(p); + lexer.last_pt = p; + last_cmd = c; + } + b'z' | b'Z' => { + path.close_path(); + lexer.last_pt = first_pt; + implicit_moveto = Some(first_pt); + } + _ => return Err(SvgParseError::UnknownCommand(c as char)), + } + } + Ok(path) + } +} + +/// An error which can be returned when parsing an SVG. +#[derive(Debug)] +#[non_exhaustive] +pub enum SvgParseError { + /// A number was expected. + Wrong, + /// The input string ended while still expecting input. + UnexpectedEof, + /// Encountered an unknown command letter. + UnknownCommand(char), + /// Encountered a command that precedes expected 'moveto' command. + UninitializedPath, +} + +impl Display for SvgParseError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + match self { + SvgParseError::Wrong => write!(f, "Unable to parse a number"), + SvgParseError::UnexpectedEof => write!(f, "Unexpected EOF"), + SvgParseError::UnknownCommand(letter) => write!(f, "Unknown command, \"{letter}\""), + SvgParseError::UninitializedPath => { + write!(f, "Uninitialized path (missing moveto command)") + } + } + } +} + +impl Error for SvgParseError {} + +struct SvgLexer<'a> { + data: &'a str, + ix: usize, + pub last_pt: Point, +} + +impl SvgLexer<'_> { + fn new(data: &str) -> SvgLexer<'_> { + SvgLexer { + data, + ix: 0, + last_pt: Point::ORIGIN, + } + } + + fn skip_ws(&mut self) { + while let Some(&c) = self.data.as_bytes().get(self.ix) { + if !(c == b' ' || c == 9 || c == 10 || c == 12 || c == 13) { + break; + } + self.ix += 1; + } + } + + fn get_cmd(&mut self, last_cmd: u8) -> Option { + self.skip_ws(); + if let Some(c) = self.get_byte() { + if c.is_ascii_lowercase() || c.is_ascii_uppercase() { + return Some(c); + } else if last_cmd != 0 && (c == b'-' || c == b'.' || c.is_ascii_digit()) { + // Plausible number start + self.unget(); + return Some(last_cmd); + } else { + self.unget(); + } + } + None + } + + fn get_byte(&mut self) -> Option { + self.data.as_bytes().get(self.ix).map(|&c| { + self.ix += 1; + c + }) + } + + fn unget(&mut self) { + self.ix -= 1; + } + + fn get_number(&mut self) -> Result { + self.skip_ws(); + let start = self.ix; + let c = self.get_byte().ok_or(SvgParseError::UnexpectedEof)?; + if !(c == b'-' || c == b'+') { + self.unget(); + } + let mut digit_count = 0; + let mut seen_period = false; + while let Some(c) = self.get_byte() { + if c.is_ascii_digit() { + digit_count += 1; + } else if c == b'.' && !seen_period { + seen_period = true; + } else { + self.unget(); + break; + } + } + if let Some(c) = self.get_byte() { + if c == b'e' || c == b'E' { + let mut c = self.get_byte().ok_or(SvgParseError::Wrong)?; + if c == b'-' || c == b'+' { + c = self.get_byte().ok_or(SvgParseError::Wrong)?; + } + if !c.is_ascii_digit() { + return Err(SvgParseError::Wrong); + } + while let Some(c) = self.get_byte() { + if !c.is_ascii_digit() { + self.unget(); + break; + } + } + } else { + self.unget(); + } + } + if digit_count > 0 { + self.data[start..self.ix] + .parse() + .map_err(|_| SvgParseError::Wrong) + } else { + Err(SvgParseError::Wrong) + } + } + + fn get_flag(&mut self) -> Result { + self.skip_ws(); + match self.get_byte().ok_or(SvgParseError::UnexpectedEof)? { + b'0' => Ok(false), + b'1' => Ok(true), + _ => Err(SvgParseError::Wrong), + } + } + + fn get_number_pair(&mut self) -> Result { + let x = self.get_number()?; + self.opt_comma(); + let y = self.get_number()?; + self.opt_comma(); + Ok(Point::new(x, y)) + } + + fn get_maybe_relative(&mut self, cmd: u8) -> Result { + let pt = self.get_number_pair()?; + if cmd.is_ascii_lowercase() { + Ok(self.last_pt + pt.to_vec2()) + } else { + Ok(pt) + } + } + + fn opt_comma(&mut self) { + self.skip_ws(); + if let Some(c) = self.get_byte() { + if c != b',' { + self.unget(); + } + } + } +} + +impl SvgArc { + /// Checks that arc is actually a straight line. + /// + /// In this case, it can be replaced with a `LineTo`. + pub fn is_straight_line(&self) -> bool { + self.radii.x.abs() <= 1e-5 || self.radii.y.abs() <= 1e-5 || self.from == self.to + } +} + +impl Arc { + /// Creates an `Arc` from a `SvgArc`. + /// + /// Returns `None` if `arc` is actually a straight line. + pub fn from_svg_arc(arc: &SvgArc) -> Option { + // Have to check this first, otherwise `sum_of_sq` will be 0. + if arc.is_straight_line() { + return None; + } + + let mut rx = arc.radii.x.abs(); + let mut ry = arc.radii.y.abs(); + + let xr = arc.x_rotation % (2.0 * PI); + let (sin_phi, cos_phi) = xr.sin_cos(); + let hd_x = (arc.from.x - arc.to.x) * 0.5; + let hd_y = (arc.from.y - arc.to.y) * 0.5; + let hs_x = (arc.from.x + arc.to.x) * 0.5; + let hs_y = (arc.from.y + arc.to.y) * 0.5; + + // F6.5.1 + let p = Vec2::new( + cos_phi * hd_x + sin_phi * hd_y, + -sin_phi * hd_x + cos_phi * hd_y, + ); + + // Sanitize the radii. + // If rf > 1 it means the radii are too small for the arc to + // possibly connect the end points. In this situation we scale + // them up according to the formula provided by the SVG spec. + + // F6.6.2 + let rf = p.x * p.x / (rx * rx) + p.y * p.y / (ry * ry); + if rf > 1.0 { + let scale = rf.sqrt(); + rx *= scale; + ry *= scale; + } + + let rxry = rx * ry; + let rxpy = rx * p.y; + let rypx = ry * p.x; + let sum_of_sq = rxpy * rxpy + rypx * rypx; + + debug_assert!(sum_of_sq != 0.0); + + // F6.5.2 + let sign_coe = if arc.large_arc == arc.sweep { + -1.0 + } else { + 1.0 + }; + let coe = sign_coe * ((rxry * rxry - sum_of_sq) / sum_of_sq).abs().sqrt(); + let transformed_cx = coe * rxpy / ry; + let transformed_cy = -coe * rypx / rx; + + // F6.5.3 + let center = Point::new( + cos_phi * transformed_cx - sin_phi * transformed_cy + hs_x, + sin_phi * transformed_cx + cos_phi * transformed_cy + hs_y, + ); + + let start_v = Vec2::new((p.x - transformed_cx) / rx, (p.y - transformed_cy) / ry); + let end_v = Vec2::new((-p.x - transformed_cx) / rx, (-p.y - transformed_cy) / ry); + + let start_angle = start_v.atan2(); + + let mut sweep_angle = (end_v.atan2() - start_angle) % (2.0 * PI); + + if arc.sweep && sweep_angle < 0.0 { + sweep_angle += 2.0 * PI; + } else if !arc.sweep && sweep_angle > 0.0 { + sweep_angle -= 2.0 * PI; + } + + Some(Arc { + center, + radii: Vec2::new(rx, ry), + start_angle, + sweep_angle, + x_rotation: arc.x_rotation, + }) + } +} + +#[cfg(test)] +mod tests { + use crate::{BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez, Shape}; + + #[test] + fn test_parse_svg() { + let path = BezPath::from_svg("m10 10 100 0 0 100 -100 0z").unwrap(); + assert_eq!(path.segments().count(), 4); + } + + #[test] + fn test_parse_svg2() { + let path = + BezPath::from_svg("M3.5 8a.5.5 0 01.5-.5h8a.5.5 0 010 1H4a.5.5 0 01-.5-.5z").unwrap(); + assert_eq!(path.segments().count(), 6); + } + + #[test] + fn test_parse_svg_arc() { + let path = BezPath::from_svg("M 100 100 A 25 25 0 1 0 -25 25 z").unwrap(); + assert_eq!(path.segments().count(), 3); + } + + // Regression test for #51 + #[test] + #[allow(clippy::float_cmp)] + fn test_parse_svg_arc_pie() { + let path = BezPath::from_svg("M 100 100 h 25 a 25 25 0 1 0 -25 25 z").unwrap(); + // Approximate figures, but useful for regression testing + assert_eq!(path.area().round(), -1473.0); + assert_eq!(path.perimeter(1e-6).round(), 168.0); + } + + #[test] + fn test_parse_svg_uninitialized() { + let path = BezPath::from_svg("L10 10 100 0 0 100"); + assert!(path.is_err()); + } + + #[test] + #[allow(clippy::float_cmp)] + fn test_parse_scientific_notation() { + let path = BezPath::from_svg("M 0 0 L 1e-123 -4E+5").unwrap(); + assert_eq!( + path.elements(), + &[ + PathEl::MoveTo(Point { x: 0.0, y: 0.0 }), + PathEl::LineTo(Point { + x: 1e-123, + y: -4E+5 + }) + ] + ); + } + + #[test] + fn test_write_svg_single() { + let segments = [CubicBez::new( + Point::new(10., 10.), + Point::new(20., 20.), + Point::new(30., 30.), + Point::new(40., 40.), + ) + .into()]; + let path = BezPath::from_path_segments(segments.iter().cloned()); + + assert_eq!(path.to_svg(), "M10,10 C20,20 30,30 40,40"); + } + + #[test] + fn test_write_svg_two_nomove() { + let segments = [ + CubicBez::new( + Point::new(10., 10.), + Point::new(20., 20.), + Point::new(30., 30.), + Point::new(40., 40.), + ) + .into(), + CubicBez::new( + Point::new(40., 40.), + Point::new(30., 30.), + Point::new(20., 20.), + Point::new(10., 10.), + ) + .into(), + ]; + let path = BezPath::from_path_segments(segments.iter().cloned()); + + assert_eq!( + path.to_svg(), + "M10,10 C20,20 30,30 40,40 C30,30 20,20 10,10" + ); + } + + #[test] + fn test_write_svg_two_move() { + let segments = [ + CubicBez::new( + Point::new(10., 10.), + Point::new(20., 20.), + Point::new(30., 30.), + Point::new(40., 40.), + ) + .into(), + CubicBez::new( + Point::new(50., 50.), + Point::new(30., 30.), + Point::new(20., 20.), + Point::new(10., 10.), + ) + .into(), + ]; + let path = BezPath::from_path_segments(segments.iter().cloned()); + + assert_eq!( + path.to_svg(), + "M10,10 C20,20 30,30 40,40 M50,50 C30,30 20,20 10,10" + ); + } + + use rand::prelude::*; + // Suppress the unused_crate_dependencies lint for getrandom. + #[cfg(all( + target_arch = "wasm32", + target_vendor = "unknown", + target_os = "unknown" + ))] + use getrandom as _; + + fn gen_random_path_sequence(rng: &mut impl Rng) -> Vec { + const MAX_LENGTH: u32 = 10; + + let mut elements = vec![]; + let mut position = None; + + let length = rng.random_range(0..MAX_LENGTH); + for _ in 0..length { + let should_follow: bool = rand::random_bool(0.5); + let kind = rng.random_range(0..3); + + let first = position + .filter(|_| should_follow) + .unwrap_or_else(|| Point::new(rng.random(), rng.random())); + + let element: PathSeg = match kind { + 0 => Line::new(first, Point::new(rng.random(), rng.random())).into(), + + 1 => QuadBez::new( + first, + Point::new(rng.random(), rng.random()), + Point::new(rng.random(), rng.random()), + ) + .into(), + + 2 => CubicBez::new( + first, + Point::new(rng.random(), rng.random()), + Point::new(rng.random(), rng.random()), + Point::new(rng.random(), rng.random()), + ) + .into(), + + _ => unreachable!(), + }; + + position = Some(element.end()); + elements.push(element); + } + + elements + } + + #[test] + fn test_serialize_deserialize() { + const N_TESTS: u32 = 100; + let mut rng = rand::rng(); + + for _ in 0..N_TESTS { + let vec = gen_random_path_sequence(&mut rng); + let ser = BezPath::from_path_segments(vec.iter().cloned()).to_svg(); + let deser = BezPath::from_svg(&ser).expect("failed deserialization"); + + let deser_vec = deser.segments().collect::>(); + + assert_eq!(vec, deser_vec); + } + } +} diff --git a/vendor/kurbo/src/translate_scale.rs b/vendor/kurbo/src/translate_scale.rs new file mode 100644 index 0000000000..d9db142639 --- /dev/null +++ b/vendor/kurbo/src/translate_scale.rs @@ -0,0 +1,345 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A transformation that includes both scale and translation. + +use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}; + +use crate::{ + Affine, Circle, CubicBez, Line, Point, QuadBez, Rect, RoundedRect, RoundedRectRadii, Vec2, +}; + +/// A transformation consisting of a uniform scaling followed by a translation. +/// +/// If the translation is `(x, y)` and the scale is `s`, then this +/// transformation represents this augmented matrix: +/// +/// ```text +/// | s 0 x | +/// | 0 s y | +/// | 0 0 1 | +/// ``` +/// +/// See [`Affine`] for more details about the +/// equivalence with augmented matrices. +/// +/// Various multiplication ops are defined, and these are all defined +/// to be consistent with matrix multiplication. Therefore, +/// `TranslateScale * Point` is defined but not the other way around. +/// +/// Also note that multiplication is not commutative. Thus, +/// `TranslateScale::scale(2.0) * TranslateScale::translate(Vec2::new(1.0, 0.0))` +/// has a translation of (2, 0), while +/// `TranslateScale::translate(Vec2::new(1.0, 0.0)) * TranslateScale::scale(2.0)` +/// has a translation of (1, 0). (Both have a scale of 2; also note that +/// the first case can be written +/// `2.0 * TranslateScale::translate(Vec2::new(1.0, 0.0))` as this case +/// has an implicit conversion). +/// +/// This transformation is less powerful than [`Affine`], but can be applied +/// to more primitives, especially including [`Rect`]. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct TranslateScale { + /// The translation component of this transformation + pub translation: Vec2, + /// The scale component of this transformation + pub scale: f64, +} + +impl TranslateScale { + /// Create a new transformation from translation and scale. + #[inline(always)] + pub const fn new(translation: Vec2, scale: f64) -> TranslateScale { + TranslateScale { translation, scale } + } + + /// Create a new transformation with scale only. + #[inline(always)] + pub const fn scale(s: f64) -> TranslateScale { + TranslateScale::new(Vec2::ZERO, s) + } + + /// Create a new transformation with translation only. + #[inline(always)] + pub fn translate(translation: impl Into) -> TranslateScale { + TranslateScale::new(translation.into(), 1.0) + } + + /// Create a transform that scales about a point other than the origin. + /// + /// # Examples + /// + /// ``` + /// # use kurbo::{Point, TranslateScale}; + /// # fn assert_near(p0: Point, p1: Point) { + /// # assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + /// # } + /// let center = Point::new(1., 1.); + /// let ts = TranslateScale::from_scale_about(2., center); + /// // Should keep the point (1., 1.) stationary + /// assert_near(ts * center, center); + /// // (2., 2.) -> (3., 3.) + /// assert_near(ts * Point::new(2., 2.), Point::new(3., 3.)); + /// ``` + #[inline] + pub fn from_scale_about(scale: f64, focus: impl Into) -> Self { + // We need to create a transform that is equivalent to translating `focus` + // to the origin, followed by a normal scale, followed by reversing the translation. + // We need to find the (translation ∘ scale) that matches this. + let focus = focus.into().to_vec2(); + let translation = focus - focus * scale; + Self::new(translation, scale) + } + + /// Compute the inverse transform. + /// + /// Multiplying a transform with its inverse (either on the + /// left or right) results in the identity transform + /// (modulo floating point rounding errors). + /// + /// Produces NaN values when scale is zero. + #[inline] + pub fn inverse(self) -> TranslateScale { + let scale_recip = self.scale.recip(); + TranslateScale { + translation: self.translation * -scale_recip, + scale: scale_recip, + } + } + + /// Is this translate/scale [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub fn is_finite(&self) -> bool { + self.translation.is_finite() && self.scale.is_finite() + } + + /// Is this translate/scale [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub fn is_nan(&self) -> bool { + self.translation.is_nan() || self.scale.is_nan() + } +} + +impl Default for TranslateScale { + #[inline(always)] + fn default() -> TranslateScale { + TranslateScale::new(Vec2::ZERO, 1.0) + } +} + +impl From for Affine { + #[inline(always)] + fn from(ts: TranslateScale) -> Affine { + let TranslateScale { translation, scale } = ts; + Affine::new([scale, 0.0, 0.0, scale, translation.x, translation.y]) + } +} + +impl Mul for TranslateScale { + type Output = Point; + + #[inline] + fn mul(self, other: Point) -> Point { + (self.scale * other.to_vec2()).to_point() + self.translation + } +} + +impl Mul for TranslateScale { + type Output = TranslateScale; + + #[inline] + fn mul(self, other: TranslateScale) -> TranslateScale { + TranslateScale { + translation: self.translation + self.scale * other.translation, + scale: self.scale * other.scale, + } + } +} + +impl MulAssign for TranslateScale { + #[inline] + fn mul_assign(&mut self, other: TranslateScale) { + *self = self.mul(other); + } +} + +impl Mul for f64 { + type Output = TranslateScale; + + #[inline] + fn mul(self, other: TranslateScale) -> TranslateScale { + TranslateScale { + translation: other.translation * self, + scale: other.scale * self, + } + } +} + +impl Add for TranslateScale { + type Output = TranslateScale; + + #[inline] + fn add(self, other: Vec2) -> TranslateScale { + TranslateScale { + translation: self.translation + other, + scale: self.scale, + } + } +} + +impl Add for Vec2 { + type Output = TranslateScale; + + #[inline] + fn add(self, other: TranslateScale) -> TranslateScale { + other + self + } +} + +impl AddAssign for TranslateScale { + #[inline] + fn add_assign(&mut self, other: Vec2) { + *self = self.add(other); + } +} + +impl Sub for TranslateScale { + type Output = TranslateScale; + + #[inline] + fn sub(self, other: Vec2) -> TranslateScale { + TranslateScale { + translation: self.translation - other, + scale: self.scale, + } + } +} + +impl SubAssign for TranslateScale { + #[inline] + fn sub_assign(&mut self, other: Vec2) { + *self = self.sub(other); + } +} + +impl Mul for TranslateScale { + type Output = Circle; + + #[inline] + fn mul(self, other: Circle) -> Circle { + Circle::new(self * other.center, self.scale * other.radius) + } +} + +impl Mul for TranslateScale { + type Output = Line; + + #[inline] + fn mul(self, other: Line) -> Line { + Line::new(self * other.p0, self * other.p1) + } +} + +impl Mul for TranslateScale { + type Output = Rect; + + #[inline] + fn mul(self, other: Rect) -> Rect { + let pt0 = self * Point::new(other.x0, other.y0); + let pt1 = self * Point::new(other.x1, other.y1); + (pt0, pt1).into() + } +} + +impl Mul for TranslateScale { + type Output = RoundedRect; + + #[inline] + fn mul(self, other: RoundedRect) -> RoundedRect { + RoundedRect::from_rect(self * other.rect(), self * other.radii()) + } +} + +impl Mul for TranslateScale { + type Output = RoundedRectRadii; + + #[inline] + fn mul(self, other: RoundedRectRadii) -> RoundedRectRadii { + RoundedRectRadii::new( + self.scale * other.top_left, + self.scale * other.top_right, + self.scale * other.bottom_right, + self.scale * other.bottom_left, + ) + } +} + +impl Mul for TranslateScale { + type Output = QuadBez; + + #[inline] + fn mul(self, other: QuadBez) -> QuadBez { + QuadBez::new(self * other.p0, self * other.p1, self * other.p2) + } +} + +impl Mul for TranslateScale { + type Output = CubicBez; + + #[inline] + fn mul(self, other: CubicBez) -> CubicBez { + CubicBez::new( + self * other.p0, + self * other.p1, + self * other.p2, + self * other.p3, + ) + } +} + +#[cfg(test)] +mod tests { + use crate::{Affine, Point, TranslateScale, Vec2}; + + fn assert_near(p0: Point, p1: Point) { + assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + } + + #[test] + fn translate_scale() { + let p = Point::new(3.0, 4.0); + let ts = TranslateScale::new(Vec2::new(5.0, 6.0), 2.0); + + assert_near(ts * p, Point::new(11.0, 14.0)); + } + + #[test] + fn conversions() { + let p = Point::new(3.0, 4.0); + let s = 2.0; + let t = Vec2::new(5.0, 6.0); + let ts = TranslateScale::new(t, s); + + // Test that conversion to affine is consistent. + let a: Affine = ts.into(); + assert_near(ts * p, a * p); + + assert_near((s * p.to_vec2()).to_point(), TranslateScale::scale(s) * p); + assert_near(p + t, TranslateScale::translate(t) * p); + } + + #[test] + fn inverse() { + let p = Point::new(3.0, 4.0); + let ts = TranslateScale::new(Vec2::new(5.0, 6.0), 2.0); + + assert_near(p, (ts * ts.inverse()) * p); + assert_near(p, (ts.inverse() * ts) * p); + } +} diff --git a/vendor/kurbo/src/triangle.rs b/vendor/kurbo/src/triangle.rs new file mode 100644 index 0000000000..7c3a6990a1 --- /dev/null +++ b/vendor/kurbo/src/triangle.rs @@ -0,0 +1,373 @@ +// Copyright 2024 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Triangle shape +use crate::{Circle, PathEl, Point, Rect, Shape, Vec2}; + +use core::cmp::*; +use core::f64::consts::FRAC_PI_4; +use core::ops::{Add, Sub}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// Triangle +// A +// * +// / \ +// / \ +// *-----* +// B C +#[derive(Clone, Copy, PartialEq, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Triangle { + /// vertex a. + pub a: Point, + /// vertex b. + pub b: Point, + /// vertex c. + pub c: Point, +} + +impl Triangle { + /// The empty [`Triangle`] at the origin. + pub const ZERO: Self = Self::from_coords((0., 0.), (0., 0.), (0., 0.)); + + /// Equilateral [`Triangle`] with the x-axis unit vector as its base. + pub const EQUILATERAL: Self = Self::from_coords( + ( + 1.0 / 2.0, + 1.732050807568877293527446341505872367_f64 / 2.0, /* (sqrt 3)/2 */ + ), + (0.0, 0.0), + (1.0, 0.0), + ); + + /// A new [`Triangle`] from three vertices ([`Point`]s). + #[inline(always)] + pub fn new(a: impl Into, b: impl Into, c: impl Into) -> Self { + Self { + a: a.into(), + b: b.into(), + c: c.into(), + } + } + + /// A new [`Triangle`] from three float vertex coordinates. + /// + /// Works as a constant [`Triangle::new`]. + #[inline(always)] + pub const fn from_coords(a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> Self { + Self { + a: Point::new(a.0, a.1), + b: Point::new(b.0, b.1), + c: Point::new(c.0, c.1), + } + } + + /// The centroid of the [`Triangle`]. + #[inline] + pub fn centroid(&self) -> Point { + (1.0 / 3.0 * (self.a.to_vec2() + self.b.to_vec2() + self.c.to_vec2())).to_point() + } + + /// The offset of each vertex from the centroid. + #[inline] + pub fn offsets(&self) -> [Vec2; 3] { + let centroid = self.centroid().to_vec2(); + + [ + (self.a.to_vec2() - centroid), + (self.b.to_vec2() - centroid), + (self.c.to_vec2() - centroid), + ] + } + + /// The area of the [`Triangle`]. + #[inline] + pub fn area(&self) -> f64 { + 0.5 * (self.b - self.a).cross(self.c - self.a) + } + + /// Whether this [`Triangle`] has zero area. + #[doc(alias = "is_empty")] + #[inline] + pub fn is_zero_area(&self) -> bool { + self.area() == 0.0 + } + + /// The inscribed circle of [`Triangle`]. + /// + /// This is defined as the greatest [`Circle`] that lies within the [`Triangle`]. + #[doc(alias = "incircle")] + #[inline] + pub fn inscribed_circle(&self) -> Circle { + let ab = self.a.distance(self.b); + let bc = self.b.distance(self.c); + let ac = self.a.distance(self.c); + + // [`Vec2::div`] also multiplies by the reciprocal of the argument, but as this reciprocal + // is reused below to calculate the radius, there's explicitly only one division needed. + let perimeter_recip = 1. / (ab + bc + ac); + let incenter = (self.a.to_vec2() * bc + self.b.to_vec2() * ac + self.c.to_vec2() * ab) + * perimeter_recip; + + Circle::new(incenter.to_point(), 2.0 * self.area() * perimeter_recip) + } + + /// The circumscribed circle of [`Triangle`]. + /// + /// This is defined as the smallest [`Circle`] which intercepts each vertex of the [`Triangle`]. + #[doc(alias = "circumcircle")] + #[inline] + pub fn circumscribed_circle(&self) -> Circle { + let b = self.b - self.a; + let c = self.c - self.a; + let b_len2 = b.hypot2(); + let c_len2 = c.hypot2(); + let d_recip = 0.5 / b.cross(c); + + let x = (c.y * b_len2 - b.y * c_len2) * d_recip; + let y = (b.x * c_len2 - c.x * b_len2) * d_recip; + let r = (b_len2 * c_len2).sqrt() * (c - b).hypot() * d_recip; + + Circle::new(self.a + Vec2::new(x, y), r) + } + + /// Expand the triangle by a constant amount (`scalar`) in all directions. + #[doc(alias = "offset")] + pub fn inflate(&self, scalar: f64) -> Self { + let centroid = self.centroid(); + + Self::new( + centroid + (0.0, scalar), + centroid + scalar * Vec2::from_angle(5.0 * FRAC_PI_4), + centroid + scalar * Vec2::from_angle(7.0 * FRAC_PI_4), + ) + } + + /// Is this [`Triangle`] [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.a.is_finite() && self.b.is_finite() && self.c.is_finite() + } + + /// Is this [`Triangle`] [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.a.is_nan() || self.b.is_nan() || self.c.is_nan() + } +} + +impl From<(Point, Point, Point)> for Triangle { + fn from(points: (Point, Point, Point)) -> Triangle { + Triangle::new(points.0, points.1, points.2) + } +} + +impl Add for Triangle { + type Output = Triangle; + + #[inline] + fn add(self, v: Vec2) -> Triangle { + Triangle::new(self.a + v, self.b + v, self.c + v) + } +} + +impl Sub for Triangle { + type Output = Triangle; + + #[inline] + fn sub(self, v: Vec2) -> Triangle { + Triangle::new(self.a - v, self.b - v, self.c - v) + } +} + +#[doc(hidden)] +pub struct TrianglePathIter { + triangle: Triangle, + ix: usize, +} + +impl Shape for Triangle { + type PathElementsIter<'iter> = TrianglePathIter; + + fn path_elements(&self, _tolerance: f64) -> TrianglePathIter { + TrianglePathIter { + triangle: *self, + ix: 0, + } + } + + #[inline] + fn area(&self) -> f64 { + Triangle::area(self) + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + self.a.distance(self.b) + self.b.distance(self.c) + self.c.distance(self.a) + } + + #[inline] + fn winding(&self, pt: Point) -> i32 { + let s0 = (self.b - self.a).cross(pt - self.a).signum(); + let s1 = (self.c - self.b).cross(pt - self.b).signum(); + let s2 = (self.a - self.c).cross(pt - self.c).signum(); + + if s0 == s1 && s1 == s2 { s0 as i32 } else { 0 } + } + + #[inline] + fn bounding_box(&self) -> Rect { + Rect::new( + self.a.x.min(self.b.x.min(self.c.x)), + self.a.y.min(self.b.y.min(self.c.y)), + self.a.x.max(self.b.x.max(self.c.x)), + self.a.y.max(self.b.y.max(self.c.y)), + ) + } +} + +// Note: vertices a, b and c are not guaranteed to be in order as described in the struct comments +// (i.e. as "vertex a is topmost, vertex b is leftmost, and vertex c is rightmost") +impl Iterator for TrianglePathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.triangle.a)), + 2 => Some(PathEl::LineTo(self.triangle.b)), + 3 => Some(PathEl::LineTo(self.triangle.c)), + 4 => Some(PathEl::ClosePath), + _ => None, + } + } +} + +// TODO: better and more tests +#[cfg(test)] +mod tests { + use crate::{Point, Triangle, Vec2}; + + fn assert_approx_eq(x: f64, y: f64, max_relative_error: f64) { + assert!( + (x - y).abs() <= f64::max(x.abs(), y.abs()) * max_relative_error, + "{x} != {y}" + ); + } + + fn assert_approx_eq_point(x: Point, y: Point, max_relative_error: f64) { + assert_approx_eq(x.x, y.x, max_relative_error); + assert_approx_eq(x.y, y.y, max_relative_error); + } + + #[test] + fn centroid() { + let test = Triangle::from_coords((-90.02, 3.5), (7.2, -9.3), (8.0, 9.1)).centroid(); + let expected = Point::new(-24.94, 1.1); + + assert_approx_eq_point(test, expected, f64::EPSILON * 100.); + } + + #[test] + fn offsets() { + let test = Triangle::from_coords((-20.0, 180.2), (1.2, 0.0), (290.0, 100.0)).offsets(); + let expected = [ + Vec2::new(-110.4, 86.8), + Vec2::new(-89.2, -93.4), + Vec2::new(199.6, 6.6), + ]; + + test.iter().zip(expected.iter()).for_each(|(t, e)| { + assert_approx_eq_point(t.to_point(), e.to_point(), f64::EPSILON * 100.); + }); + } + + #[test] + fn area() { + let test = Triangle::new( + (12123.423, 2382.7834), + (7892.729, 238.459), + (7820.2, 712.23), + ); + let expected = 1079952.9157407999; + + // initial + assert_approx_eq(test.area(), -expected, f64::EPSILON * 100.); + // permutate vertex + let test = Triangle::new(test.b, test.a, test.c); + assert_approx_eq(test.area(), expected, f64::EPSILON * 100.); + } + + #[test] + fn circumcenter() { + let test = Triangle::EQUILATERAL.circumscribed_circle().center; + let expected = Point::new(0.5, 0.28867513459481288); + + assert_approx_eq_point(test, expected, f64::EPSILON * 100.); + } + + #[test] + fn inradius() { + let test = Triangle::EQUILATERAL.inscribed_circle().radius; + let expected = 0.28867513459481287; + + assert_approx_eq(test, expected, f64::EPSILON * 100.); + } + + #[test] + fn circumradius() { + let test = Triangle::EQUILATERAL; + let expected = 0.57735026918962576; + + assert_approx_eq( + test.circumscribed_circle().radius, + expected, + f64::EPSILON * 100., + ); + // permute vertex + let test = Triangle::new(test.b, test.a, test.c); + assert_approx_eq( + test.circumscribed_circle().radius, + -expected, + f64::EPSILON * 100., + ); + } + + #[test] + fn inscribed_circle() { + let test = Triangle::new((-4., 1.), (-4., -1.), (10., 3.)); + + let inscribed = test.inscribed_circle(); + assert_approx_eq_point( + inscribed.center, + (-3.0880178529263671, 0.20904207741504303).into(), + f64::EPSILON * 100., + ); + assert_approx_eq(inscribed.radius, 0.91198214707363295, f64::EPSILON * 100.); + } + + #[test] + fn circumscribed_circle() { + let test = Triangle::new((-4., 1.), (-4., -1.), (10., 3.)); + + let circumscribed = test.circumscribed_circle(); + assert_approx_eq_point( + circumscribed.center, + (3.2857142857142857, 0.).into(), + f64::EPSILON * 100., + ); + assert_approx_eq( + circumscribed.radius, + 7.3540215292764288, + f64::EPSILON * 100., + ); + } +} diff --git a/vendor/kurbo/src/vec2.rs b/vendor/kurbo/src/vec2.rs new file mode 100644 index 0000000000..38aa2c2775 --- /dev/null +++ b/vendor/kurbo/src/vec2.rs @@ -0,0 +1,568 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A simple 2D vector. + +use core::fmt; +use core::iter::Sum; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; + +use crate::common::FloatExt; +use crate::{Axis, Point, Size}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D vector. +/// +/// This is intended primarily for a vector in the mathematical sense, +/// but it can be interpreted as a translation, and converted to and +/// from a [`Point`] (vector relative to the origin) and [`Size`]. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Vec2 { + /// The x-coordinate. + pub x: f64, + /// The y-coordinate. + pub y: f64, +} + +impl Vec2 { + /// The vector (0, 0). + pub const ZERO: Vec2 = Vec2::new(0., 0.); + + /// Create a new vector. + #[inline(always)] + pub const fn new(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } + } + + /// Convert this vector into a [`Point`]. + #[inline(always)] + pub const fn to_point(self) -> Point { + Point::new(self.x, self.y) + } + + /// Convert this vector into a [`Size`]. + #[inline(always)] + pub const fn to_size(self) -> Size { + Size::new(self.x, self.y) + } + + /// Create a vector with the same value for `x` and `y`. + #[inline(always)] + pub const fn splat(v: f64) -> Self { + Vec2 { x: v, y: v } + } + + /// Dot product of two vectors. + #[inline] + pub const fn dot(self, other: Vec2) -> f64 { + self.x * other.x + self.y * other.y + } + + /// Cross product of two vectors. + /// + /// This is signed so that `(1, 0) × (0, 1) = 1`. + /// + /// The following relations hold: + /// + /// `u.cross(v) = -v.cross(u)` + /// + /// `v.cross(v) = 0.0` + #[inline] + pub const fn cross(self, other: Vec2) -> f64 { + self.x * other.y - self.y * other.x + } + + /// Magnitude of vector. + /// + /// See [`Point::distance`] for the same operation on [`Point`]. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let v = Vec2::new(3.0, 4.0); + /// assert_eq!(v.hypot(), 5.0); + /// ``` + #[inline] + pub fn hypot(self) -> f64 { + // Avoid f64::hypot as it calls a slow library function. + self.hypot2().sqrt() + } + + /// Magnitude of vector. + /// + /// This is an alias for [`Vec2::hypot`]. + #[inline] + pub fn length(self) -> f64 { + self.hypot() + } + + /// Magnitude squared of vector. + /// + /// See [`Point::distance_squared`] for the same operation on [`Point`]. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let v = Vec2::new(3.0, 4.0); + /// assert_eq!(v.hypot2(), 25.0); + /// ``` + #[inline] + pub const fn hypot2(self) -> f64 { + self.dot(self) + } + + /// Magnitude squared of vector. + /// + /// This is an alias for [`Vec2::hypot2`]. + #[inline] + pub const fn length_squared(self) -> f64 { + self.hypot2() + } + + /// Find the angle in radians between this vector and the vector `Vec2 { x: 1.0, y: 0.0 }` + /// in the positive `y` direction. + /// + /// If the vector is interpreted as a complex number, this is the argument. + /// The angle is expressed in radians. + #[inline] + pub fn atan2(self) -> f64 { + self.y.atan2(self.x) + } + + /// Find the angle in radians between this vector and the vector `Vec2 { x: 1.0, y: 0.0 }` + /// in the positive `y` direction. + /// + /// This is an alias for [`Vec2::atan2`]. + #[inline] + pub fn angle(self) -> f64 { + self.atan2() + } + + /// A unit vector of the given angle. + /// + /// With `th` at zero, the result is the positive X unit vector, and + /// at π/2, it is the positive Y unit vector. The angle is expressed + /// in radians. + /// + /// Thus, in a Y-down coordinate system (as is common for graphics), + /// it is a clockwise rotation, and in Y-up (traditional for math), it + /// is anti-clockwise. This convention is consistent with + /// [`Affine::rotate`]. + /// + /// [`Affine::rotate`]: crate::Affine::rotate + #[inline] + pub fn from_angle(th: f64) -> Vec2 { + let (th_sin, th_cos) = th.sin_cos(); + Vec2 { + x: th_cos, + y: th_sin, + } + } + + /// Linearly interpolate between two vectors. + #[inline] + pub fn lerp(self, other: Vec2, t: f64) -> Vec2 { + self + t * (other - self) + } + + /// Returns a vector of [magnitude] 1.0 with the same angle as `self`; i.e. + /// a unit/direction vector. + /// + /// This produces `NaN` values when the magnitude is `0`. + /// + /// [magnitude]: Self::hypot + #[inline] + pub fn normalize(self) -> Vec2 { + self / self.hypot() + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).round(); + /// let b = Vec2::new(3.0, -3.1).round(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Vec2 { + Vec2::new(self.x.round(), self.y.round()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).ceil(); + /// let b = Vec2::new(3.0, -3.1).ceil(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Vec2 { + Vec2::new(self.x.ceil(), self.y.ceil()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).floor(); + /// let b = Vec2::new(3.0, -3.1).floor(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Vec2 { + Vec2::new(self.x.floor(), self.y.floor()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded away] from zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).expand(); + /// let b = Vec2::new(3.0, -3.1).expand(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded away]: FloatExt::expand + #[inline] + pub fn expand(self) -> Vec2 { + Vec2::new(self.x.expand(), self.y.expand()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded towards] zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).trunc(); + /// let b = Vec2::new(3.0, -3.1).trunc(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded towards]: f64::trunc + #[inline] + pub fn trunc(self) -> Vec2 { + Vec2::new(self.x.trunc(), self.y.trunc()) + } + + /// Is this `Vec2` [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } + + /// Is this `Vec2` [`NaN`]? + /// + /// [`NaN`]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.x.is_nan() || self.y.is_nan() + } + + /// Divides this `Vec2` by a scalar. + /// + /// Unlike the division by scalar operator, which multiplies by the + /// reciprocal for performance, this performs the division + /// per-component for consistent rounding behavior. + pub(crate) fn div_exact(self, divisor: f64) -> Vec2 { + Vec2 { + x: self.x / divisor, + y: self.y / divisor, + } + } + + /// Turn by 90 degrees. + /// + /// The rotation is clockwise in a Y-down coordinate system. The following relations hold: + /// + /// `u.dot(v) = u.cross(v.turn_90())` + /// + /// `u.cross(v) = u.turn_90().dot(v)` + #[inline] + pub const fn turn_90(self) -> Vec2 { + Vec2::new(-self.y, self.x) + } + + /// Combine two vectors interpreted as rotation and scaling. + /// + /// Interpret both vectors as a rotation and a scale, and combine + /// their effects. by adding the angles and multiplying the magnitudes. + /// This operation is equivalent to multiplication when the vectors + /// are interpreted as complex numbers. It is commutative. + #[inline] + pub const fn rotate_scale(self, rhs: Vec2) -> Vec2 { + Vec2::new( + self.x * rhs.x - self.y * rhs.y, + self.x * rhs.y + self.y * rhs.x, + ) + } + + /// Get the member matching the given axis. + #[inline] + pub const fn get_coord(self, axis: Axis) -> f64 { + match axis { + Axis::Horizontal => self.x, + Axis::Vertical => self.y, + } + } + + /// Get a mutable reference to the member matching the given axis. + #[inline] + pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 { + match axis { + Axis::Horizontal => &mut self.x, + Axis::Vertical => &mut self.y, + } + } + + /// Set the member matching the given axis to the given value. + #[inline] + pub const fn set_coord(&mut self, axis: Axis, value: f64) { + match axis { + Axis::Horizontal => self.x = value, + Axis::Vertical => self.y = value, + } + } +} + +impl From<(f64, f64)> for Vec2 { + #[inline(always)] + fn from(v: (f64, f64)) -> Vec2 { + Vec2 { x: v.0, y: v.1 } + } +} + +impl From for (f64, f64) { + #[inline(always)] + fn from(v: Vec2) -> (f64, f64) { + (v.x, v.y) + } +} + +impl Add for Vec2 { + type Output = Vec2; + + #[inline] + fn add(self, other: Vec2) -> Vec2 { + Vec2 { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +impl AddAssign for Vec2 { + #[inline] + fn add_assign(&mut self, other: Vec2) { + *self = Vec2 { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +impl Sum for Vec2 { + fn sum>(iter: I) -> Self { + iter.fold(Vec2::ZERO, |sum, v| sum + v) + } +} + +impl Sub for Vec2 { + type Output = Vec2; + + #[inline] + fn sub(self, other: Vec2) -> Vec2 { + Vec2 { + x: self.x - other.x, + y: self.y - other.y, + } + } +} + +impl SubAssign for Vec2 { + #[inline] + fn sub_assign(&mut self, other: Vec2) { + *self = Vec2 { + x: self.x - other.x, + y: self.y - other.y, + } + } +} + +impl Mul for Vec2 { + type Output = Vec2; + + #[inline] + fn mul(self, other: f64) -> Vec2 { + Vec2 { + x: self.x * other, + y: self.y * other, + } + } +} + +impl MulAssign for Vec2 { + #[inline] + fn mul_assign(&mut self, other: f64) { + *self = Vec2 { + x: self.x * other, + y: self.y * other, + }; + } +} + +impl Mul for f64 { + type Output = Vec2; + + #[inline] + fn mul(self, other: Vec2) -> Vec2 { + other * self + } +} + +impl Div for Vec2 { + type Output = Vec2; + + /// Note: division by a scalar is implemented by multiplying by the reciprocal. + /// + /// This is more efficient but has different roundoff behavior than division. + #[inline] + #[allow(clippy::suspicious_arithmetic_impl)] + fn div(self, other: f64) -> Vec2 { + self * other.recip() + } +} + +impl DivAssign for Vec2 { + #[inline] + fn div_assign(&mut self, other: f64) { + self.mul_assign(other.recip()); + } +} + +impl Neg for Vec2 { + type Output = Vec2; + + #[inline] + fn neg(self) -> Vec2 { + Vec2 { + x: -self.x, + y: -self.y, + } + } +} + +impl fmt::Display for Vec2 { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "𝐯=(")?; + fmt::Display::fmt(&self.x, formatter)?; + write!(formatter, ", ")?; + fmt::Display::fmt(&self.y, formatter)?; + write!(formatter, ")") + } +} + +// Conversions to and from mint +#[cfg(feature = "mint")] +impl From for mint::Vector2 { + #[inline(always)] + fn from(p: Vec2) -> mint::Vector2 { + mint::Vector2 { x: p.x, y: p.y } + } +} + +#[cfg(feature = "mint")] +impl From> for Vec2 { + #[inline(always)] + fn from(p: mint::Vector2) -> Vec2 { + Vec2 { x: p.x, y: p.y } + } +} + +#[cfg(test)] +mod tests { + use core::f64::consts::FRAC_PI_2; + + use super::*; + #[test] + fn display() { + let v = Vec2::new(1.2332421, 532.10721213123); + let s = format!("{v:.2}"); + assert_eq!(s.as_str(), "𝐯=(1.23, 532.11)"); + } + + #[test] + fn cross_sign() { + let v = Vec2::new(1., 0.).cross(Vec2::new(0., 1.)); + assert_eq!(v, 1.); + } + + #[test] + fn turn_90() { + let u = Vec2::new(0.1, 0.2); + let turned = u.turn_90(); + // This should be exactly equal by IEEE rules, might fail + // in fastmath conditions. + assert_eq!(u.length(), turned.length()); + const EPSILON: f64 = 1e-12; + assert!((u.angle() + FRAC_PI_2 - turned.angle()).abs() < EPSILON); + } + + #[test] + fn rotate_scale() { + let u = Vec2::new(0.1, 0.2); + let v = Vec2::new(0.3, -0.4); + let uv = u.rotate_scale(v); + const EPSILON: f64 = 1e-12; + assert!((u.length() * v.length() - uv.length()).abs() < EPSILON); + assert!((u.angle() + v.angle() - uv.angle()).abs() < EPSILON); + } +} diff --git a/vendor/linesweeper/Cargo.toml b/vendor/linesweeper/Cargo.toml index 841a0e500a..3c476fdfd3 100644 --- a/vendor/linesweeper/Cargo.toml +++ b/vendor/linesweeper/Cargo.toml @@ -29,6 +29,7 @@ repository = "https://github.com/jneem/linesweeper" arbitrary = ["dep:arbitrary"] debug-svg = ["dep:svg"] generators = [] +metrics = [] slow-asserts = [] [lib] @@ -36,11 +37,6 @@ name = "linesweeper" path = "src/lib.rs" bench = false -[[example]] -name = "boolean_op" -path = "examples/boolean_op.rs" -required-features = ["generators"] - [[example]] name = "bus" path = "examples/bus.rs" @@ -48,20 +44,12 @@ path = "examples/bus.rs" [[example]] name = "curve_metrics" path = "examples/curve_metrics.rs" +required-features = ["metrics"] [[example]] name = "visualize_op" path = "examples/visualize_op.rs" -[[example]] -name = "winding-numbers" -path = "examples/winding-numbers.rs" - -[[test]] -name = "fonts" -path = "tests/fonts.rs" -harness = false - [[test]] name = "paperjs" path = "tests/paperjs.rs" @@ -72,16 +60,6 @@ name = "regression" path = "tests/regression.rs" harness = false -[[test]] -name = "snapshots" -path = "tests/snapshots.rs" -harness = false - -[[bench]] -name = "linebender_logo" -path = "benches/linebender_logo.rs" -harness = false - [[bench]] name = "painted_dreams" path = "benches/painted_dreams.rs" diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index cd0c999939..5d0915160c 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,41 +1,118 @@ # Local linesweeper 0.5.0 copy This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the -local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from, +changes listed under Local changes. `.cargo_vcs_info.json` names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest names, which is archived; its README says development moved off GitHub. -The patched files are `src/sweep/sweep_line.rs`, `src/topology.rs`, `src/segments.rs`, -`src/curve/transverse.rs`, -`src/curve/mod.rs`, `src/curve/line.rs` and `docs/sweep.typ`. - -Every file here except this one, `SOURCE.json` and the patched files below is byte for byte the file -in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download +Every file here except this one, `SOURCE.json` and the files under Local changes is byte for byte the +file in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name holds `upstream_revision`. `local_patches` describes each local change. ## Local changes -`src/sweep/sweep_line.rs` also differs from the archive, in one doc comment. - | File | Change | |---|---| -| `src/sweep/sweep_line.rs` | The touch branch of `Sweeper::handle_intersection` runs its scan right from a segment, or left from a segment, at most once per sweep line until the sweep-line order changes. Exact copies of a shape queue a touch event for every pair of coincident segments, and each event used to scan the whole bundle in both directions, so sweeping `n` copies took time growing faster than `n^3`. The skipped scans would only push events already queued, so the output does not change. The `coincident_copies_scan_once_per_order` test counts the scans for 60 copies of two shapes, and `coincident_copies_keep_the_fill` compares the output fill with the input's nonzero fill for 200 inputs with exact, reversed and split copies. | -| `src/sweep/sweep_line.rs` | The doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out. Code comments label the change `Craft patch (exited slots)`. | -| `src/segments.rs` | Adding paths one at a time no longer sorts every entrance and exit in the arena on each call: the new entries are sorted and merged into the sorted ones, in the same order as before. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add many paths and merge once; on an open subpath, `add_bez_paths` keeps the paths before it and adds nothing of that path or later ones. The tests `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort` and `segments::tests::paths_added_in_height_order_are_not_sorted_again` cover it. Code comments label the change `Craft patch (batch paths)`. | -| `src/curve/transverse.rs` | `transversal_after` returns `false` when either dy/dt bound it divides by is zero, negative or nan. It compared the two slope bounds by cross-multiplying, which reverses the comparison when a bound is negative. Two curves that leave a shared start point in opposite directions, with their first control points one ulp below the start, were reported as keeping their left-to-right order although they cross. `transversal_before` reflects its curves and calls `transversal_after`, so it returned the same wrong answer. The `crossing_with_negative_start_dy` test checks both functions. | -| `src/sweep/sweep_line.rs` | `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions the two segments hold. A pair queued again at the same `y` and positions is queued at the pair's next order change instead, when that comes before both segments end. Nearly coincident segments whose comparisons are not transitive used to queue the same pairs at one `y` forever while memory grew. The `repeated_intersections_at_one_y` test sweeps five circles 7e-7 apart; test builds panic after `n^4` intersection events on one sweep line. | +| `src/arbitrary.rs`, `src/geom.rs`, `src/position.rs`, `src/curve/mod.rs`, `src/curve/line.rs` | Numeric helpers reject invalid float bounds and retain extreme quadratic roots, conservative slope bounds, small affine offsets, exact mapped endpoints, and finite midpoint heights. Disjoint height ranges have an empty curve order. | +| `src/order.rs`, `src/sweep/output_event.rs`, `src/topology.rs` | Mutable reversed comparisons retain edits until eviction or an arena change. Output events use total floating-point ordering, including NaNs and signed zero. Bounded output checks merged winding storage and rejects size overflow. | +| `src/segments.rs`, `src/sweep/sweep_line.rs`, `src/treevec.rs`, `docs/sweep.typ` | An iterator panic rolls back a batch's unentered suffix. Sweep work counts actual tree-search predicates. Ordinary touches do not hash intervening spans. Reverse iterators use the shared inline stack. The crossing-height proof requires finite denominator additions. | +| `src/lib.rs`, `src/topology.rs`, `src/segments.rs` | `binary_op_accuracy` returns the checked automatic accuracy, including for open paths. `binary_op` and `Topology::from_paths_with_automatic_limits` compute accuracy from monotonic pieces before preparing sweep metadata, then sort accepted input once. The accuracy uses the retained segments' coordinate scale, including their curve control points. `automatic_accuracy_checks_control_point_scale` checks both argument orders and a wider-feature control. `automatic_accuracy_ignores_discarded_horizontal_handles` checks that a retraced horizontal curve does not raise the floor. `automatic_boolean_reuses_the_prepared_segment_events` uses the shared test comparison counter to check one input sort for ordinary and bounded operations. `automatic_accuracy_does_not_sort_events`, `automatic_feature_rejection_does_not_sort_events`, and `automatic_accuracy_does_not_prepare_sweep_metadata` check that accuracy queries and rejected features do not sort events or prepare sweep metadata. `automatic_accuracy_accepts_open_paths` checks an open accuracy query and the topology constructor's closure check. | +| `src/curve/line.rs` | Vertical lines keep their exact endpoint x coordinate. `coincident_vertical_lines_keep_their_exact_x` compares coincident lines at x = 0.1 with tolerance 1e-18. | +| `src/sweep/sweep_line.rs` | Sweep-order checks accept an `Ish` interval at its boundary, including a zero-height touch. The `invalid_order` test checks a reversed crossing before, at and after that boundary. `work_limit_counts_position_searches_by_their_probes` uses 100 and 200 rectangles with `slow-asserts`, and 2,000 and 4,000 otherwise. Both configurations check the same work-count growth and work-limit behavior. | +| `src/sweep/sweep_line.rs` | `SegmentOrder::position` finds a segment by binary search over a key on each sweep-line entry. Code comments label it `Craft patch (sweep position)`. Tests: `position_after_edits`, `position_after_repeated_insertion`, `position_after_insertion_next_to_the_extreme_keys`, `position_after_moving_a_contour_continuation`, `position_on_a_wide_sweep_line`. | +| `src/order.rs`, `src/curve/mod.rs` | `ComparisonCache` skips the curve comparison for segments whose horizontal bounds are far apart. Code comments label it `Craft patch (far-apart comparison)`. Tests: `far_apart_order`, `far_apart_curves_compare_like_the_full_comparison`, `far_apart_steep_curves_never_reverse`, `far_apart_steep_curves_skip_the_full_comparison`. | +| `src/curve/mod.rs` | `Metrics::entries` holds two entries inline, as a `SmallVec`. Code comments label it `Craft patch (inline metrics)`. Tests: `cargo check --locked --example curve_metrics --features metrics`. | +| `src/perturbation.rs` | `F64Perturbation::Ulp` on a subnormal value gives the value on the other side of zero when the step toward zero is larger than the value. Code comments label it `Craft patch (ulp across zero)`. Tests: `subnormal_ulp_step_crosses_zero`. | +| `examples/boolean_op.rs`, `examples/visualize_op.rs`, `examples/winding-numbers.rs` | The SVG stroke width is the larger of the bounding box's width and height divided by 512. Code comments label it `Craft patch (example stroke width)`. Tests: `stroke_width_follows_the_larger_side` in `examples/visualize_op.rs`. | +| `src/order.rs`, `src/sweep/sweep_line.rs`, `src/position.rs`, `src/topology.rs` | `ComparisonCache::compare_segments` returns `Option<&mut CurveOrder>`, and returns `None` when either segment is horizontal, in every build profile; its doc comment states it. The sweep line, `position` and `topology` hold only segments that are not horizontal and call the crate-private `compare_non_horizontal_segments`, which checks that with a `debug_assert`. Code comments label it `Craft patch (horizontal comparison)`. Tests: `horizontal_and_cubic`, `horizontal_and_line`. | +| `src/position.rs` | `compute_positions` starts each output segment's `last_y` at the segment's start height instead of 0, so a segment that starts at `y < 0` is not skipped at its first queue entry and close segments there are put in order. Code comments label it `Craft patch (start height)`. Tests: `position::tests::correct_positions_at_negative_y`. | +| `src/geom.rs` | `Segment::lower` and `Segment::upper` bound a horizontal line by both of its endpoints. Code comments label it `Craft patch (horizontal line bounds)`. Tests: `horizontal_line_bounds_cover_both_endpoints`. | +| `examples/visualize_op.rs` | The `visualize_op` example draws its two input paths with `fill-rule="evenodd"`, the fill rule its operation uses. Code comments label it `Craft patch (example fill rule)`. Tests: `inputs_are_drawn_with_the_operation_fill_rule`, `svg_fill_rule_names`. | +| `docs/sweep.typ` | The floating-point ratio lemma assumes `fl(y_1 - y_0)` is finite and `y_0 < y_1`, and its proof bounds `fl(y_1 - y_0)` instead of `fl(y + y_0)`; the x-coordinate accuracy lemma takes `M` as a floating-point number and shows both assumptions hold. Code comments label it `Craft patch (ratio lemma)`. The change is in documentation only and has no test. | +| `src/segments.rs` | `Segments::add_points` skips a point equal to the one before it, as the closed-polyline path does, so it adds no zero-length segment. Code comments label it `Craft patch (repeated points)`. Tests: `segments::tests::add_points_skips_repeated_points`. | +| `src/curve/mod.rs` | The `Ish` entry that `CurveOrder::push` inserts between opposite `Left` and `Right` intervals ends where the earlier interval ends, so it has zero height. Code comments label it `Craft patch (zero-height Ish)`. Tests: `opposite_orders_get_a_zero_height_ish`. | +| `src/curve/mod.rs` | When `b * b` or `a * c` would underflow or overflow, `quadratic_signs` multiplies the coefficients by one power of two before it computes the discriminant, so a cubic with very small or very large y coordinates is split where its y direction turns. Code comments label it `Craft patch (quadratic scale)`. Tests: `curve::test::quadratic_signs_at_extreme_scales`. | +| `src/arbitrary.rs` | `float_in_range` interpolates as `start * (1 - t) + end * t`, so a range such as `-1e308..1e308` gives a value in the range instead of NaN. Code comments label it `Craft patch (wide float range)`. Tests: `float_in_range_handles_a_range_wider_than_f64_max`. | +| `src/sweep/output_event.rs`, `src/sweep/sweep_line.rs` | `OutputEvent`'s `Ord` breaks ties between events with the same horizontal range by segment and then by the other fields, so two events compare equal only when they are equal; the sweep line still sorts its events by horizontal range alone. Code comments label it `Craft patch (output event order)`. Tests: `events_on_different_segments_with_the_same_range_are_not_equal`, `events_differing_only_in_flags_are_not_equal`. | +| `src/treevec.rs` | `TreeVec::range` and `range_mut` panic with a message when a bound is past `usize::MAX` or the start is after the end, instead of overflowing, and their doc comments list these panics. Code comments label it `Craft patch (range bounds)`. Tests: `treevec::tests::range_reversed`, `range_mut_reversed`, `range_start_past_max`, `range_end_past_max`. | +| `tests/paperjs.rs` | The `paperjs` test's image comparison counts a difference in alpha. Code comments label it `Craft patch (image distance alpha)`. Tests: `pixmap_distance_counts_coverage`. | +| `src/curve/mod.rs` | `AlmostHorizontalDecomposition::from_monotone_cubic` keeps each piece's handles on the right side of its end points instead of clamping them into the piece's y-range, so the pieces the sweep compares follow the input curve. Code comments label it `Craft patch (monotone handles)`. Tests: `curve::test::decomposition_keeps_handles_outside_the_y_range`. | +| `src/segments.rs`, `src/lib.rs` | `Topology::from_path`, the other `Topology` constructors that take Bézier paths, `Segments::add_bez_path` and `binary_op` skip a `ClosePath` that comes before the first point of a path instead of panicking with "Can't start a segment on a ClosePath". Code comments label it `Craft patch (leading ClosePath)`. Tests: `tests::leading_close_path`. | +| `src/curve/mod.rs` | `AlmostHorizontalDecomposition` stores up to two pieces inline in a `SmallVec` instead of six in an `ArrayVec`, which takes it from 824 to 288 bytes; `Segments` keeps one for every segment. Code comments label it `Craft patch (inline pieces)`. Tests: `curve::test::horizontal_decomposition_stores_two_pieces_inline`, `curve::test::horizontal_decomposition_keeps_every_piece`. | +| `src/topology.rs` | `Topology` allocates one output segment for each run of coincident horizontal pieces between two points instead of one per piece, and none for a run whose winding numbers cancel. n overlapping rectangles that share their top and bottom edges give 6n - 2 output segments instead of 2n² + 2n. The contours do not change. `has_normal_contours` and `is_disjoint_tags` read the winding numbers on either side of a run, not the ones between its pieces. Code comments label it `Craft patch (coincident horizontals)`. Tests: `topology::tests::coincident_horizontals_get_one_output_segment_per_run`. | +| `src/curve/mod.rs` | `intersect_cubics_with_precomputed_decomp` compares the precomputed approximations of two pieces with `ish_tolerance` before it cuts either cubic to their shared y-range, and when that gives one `Left` or `Right` interval it records that order without cutting them. Code comments label it `Craft patch (approximation first)`. Tests: `curve::test::approximation_first_keeps_the_curve_order`. | +| `src/curve/mod.rs` | `order_from_precomputed_approx` leaves a piece whose approximation is almost horizontal to `intersect_cubics_rec`, because such an approximation carries the end x values of its whole piece. Code comments label it `Craft patch (approximation first)`. Tests: `order::tests::far_apart_steep_curves_never_reverse`. | +| `src/curve/mod.rs` | `intersect_cubics_rec` gives the precomputed approximations the end x values of the cut curves instead of those of the whole pieces, so an almost-horizontal piece compared over part of its height is not reported as close to a curve that is far from it. Code comments label it `Craft patch (cut end bounds)`. Tests: `curve::test::almost_horizontal_piece_cut_to_the_overlap`. | +| `src/curve/mod.rs`, `Cargo.toml` | `CurveOrder` records `Metrics` entries only with the new `metrics` feature, which is off by default; without it `metrics.entries` stays empty. The `curve_metrics` example requires the feature. Code comments label it `Craft patch (metrics opt-in)`. Tests: `curve::test::crossing_cubics_metrics_follow_the_feature`, `curve::test::crossing_cubics_order_does_not_depend_on_metrics`, `curve::test::crossing_cubics_metrics_record_the_recursion_depth`, `curve::test::curve_order_no_overlap`. | +| `src/segments.rs`, `src/lib.rs` | `Segments::add_bez_path` leaves the arena unchanged when a subpath is not closed, instead of keeping the segments it pushed before the open subpath, the last of them linked to an index past the end of the arena. Code comments label it `Craft patch (add_bez_path error)`. Tests: `tests::add_bez_path_error_leaves_segments_unchanged`. | +| `src/generators.rs`, `scripts/test-pdf-backends.sh` | `checkerboard(0)` and `slanted_checkerboard(0)` return empty collections; the inner count was `n - 1`, which overflowed. Code comments label it `Craft patch (empty checkerboard)`. Tests: `checkerboards_of_size_zero_and_one`. | +| `src/arbitrary.rs` | `another_monotonic_bezier` returns `arbitrary::Error::IncorrectFormat` when no piece of the generated cubic increases in y; it returned that cubic, which can be horizontal. Code comments label it `Craft patch (flat cubic)`. Tests: `another_monotonic_bezier_increases_in_y_or_fails`. | +| `src/perturbation.rs` | A ulp step past `f64::MAX` in the test-only `F64Perturbation::apply` gives infinity; `Ulp(2)` of `f64::MAX` gave NaN. Code comments label it `Craft patch (ulp overflow)`. Tests: `ulp_step_past_f64_max_is_infinite`. | +| `src/order.rs`, `src/segments.rs` | `ComparisonCache` holds the comparisons of one `Segments` arena; given another arena, a clone included, it drops them and compares again. Code comments label it `Craft patch (comparison cache arena)`. Tests: `other_arena_is_compared_again`, `diverged_clone_is_compared_again`, `appending_keeps_cached_comparisons`. | +| `src/lib.rs` | `binary_op` returns the new `Error::FeatureBelowTolerance { eps }` when its automatic `eps` is above `MIN_AUTO_EPS` (1e-6) and an input subpath at least `4 * MIN_AUTO_EPS` wide and high is narrower than `FEATURE_EPS_RATIO * eps` (4 * eps) in x or y, measured on the subpath's exact bounding box. Before, one far point raised `eps` for every segment and `binary_op` returned `Ok` without the small subpaths: with a triangle at 3e13 (eps 0.43) a 0.3 x 10 sliver was lost, and at 1e15 (eps 14.2) most of a 10 x 10 square was. The docs of `binary_op` and `binary_op_with_eps` state that `eps` is one absolute tolerance and what the check does not cover. Code comments label it `Craft patch (far-point eps)`. Tests: `tests::far_point_eps`. | +| `src/segments.rs` | Adding paths one at a time no longer sorts every entrance and exit in the arena on each call: the new entries are sorted and merged into the sorted ones, in the same order as before. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add many paths and merge once; on an open subpath, `add_bez_paths` keeps the paths before it and adds nothing of that path or later ones. Code comments label it `Craft patch (batch paths)`. Tests: `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort`, `segments::tests::paths_added_in_height_order_are_not_sorted_again`. | +| `src/curve/mod.rs` | In `intersect_cubics_rec`, the exact check that both curves are on the interval's side at each re-centered interval end runs only with the `slow-asserts` feature. Without the change, debug builds panicked on finite curves near 1e8, where the rounded end puts the curves on the wrong side by up to 69 times `ish_tolerance`; release builds already skipped the check. Code comments label it `Craft patch (end order check)`. Tests: `curve::test::crossing_at_large_coordinates`. | +| `src/sweep/sweep_line.rs`, `src/topology.rs` | Clippy 1.100.0 with `-D warnings` and every feature passes on every registered target: the `slow-asserts` invariant check in `sweep_line.rs` passes `self.line` to `assert!` without a `&` (`useless_borrows_in_formatting`), and `Contours::grouped` iterates over the contours with `enumerate` instead of indexing them (`needless_range_loop`). The behavior does not change. Code comments label it `Craft patch (clippy lints)`. Tests: `cargo clippy --locked --all-targets --all-features -- -D warnings`. | +| `src/curve/line.rs` | `line_at_ys` divides each `y` offset by the line's height instead of multiplying it by the height's reciprocal. For a height below about 5.6e-309 the reciprocal is infinite, and `intersect_lines` returned NaN positions and failed its `z0 >= z1` debug assertion. The `subnormal_span` test covers two vertical lines 1e-310 tall. | +| `src/sweep/sweep_line.rs` | `choose_cross_height` takes the midpoint of a crossing's height range with `f64::midpoint` instead of `(y0 + y1) / 2.0`. For heights above about 9e307 the sum overflowed, so a range from 1e308 to 1.5e308 gave an infinite crossing height instead of 1.25e308. The `cross_height_near_f64_max` test covers that range. | +| `tests/paperjs.rs` | A test file in `boolean-test/data/` that cannot be loaded becomes a failing `/load` trial. The package does not include `boolean-test/data/`, and the packaged file skipped files it could not load, so the `paperjs` target passed with zero trials. The `load_errors_are_reported` trial covers a missing file; run it with `cargo test --locked --test paperjs load_errors_are_reported`. The full `paperjs` target fails here because the data files are not included. | +| `src/sweep/sweep_line.rs` | `Sweeper::next_line` handles a pair of segments at most once per sweep line for each arrangement of the sweep line from one segment of the pair to the other: the positions of both segments and a 64-bit hash of the segments between them, in order. A pair queued again at the same `y` with the same arrangement is queued at the pair's next order change instead, when that comes before both segments end. When the segments between the pair change, `handle_intersection` runs again and checks them. The position searches and the segments hashed count toward the sweep's work limit. Nearly coincident segments whose comparisons are not transitive used to queue the same pairs at one `y` forever while memory grew. The `repeated_intersections_at_one_y` test sweeps five circles 7e-7 apart; test builds panic after `n^4` intersection events on one sweep line. The `repeat_key_includes_segments_between_the_pair` test checks that the same pair at the same positions with different segments between them gets a different key. | +| `src/topology.rs` | `contours_for_positions` returns `Error::InconsistentWindingNumbers` when the contour walk finds no boundary segment leaving a point, or re-enters a segment it already walked. Its `debug_assert!` checks of the windings along the walk and its panic for a western boundary segment with no contour return the same error. The new `Topology::try_contours` returns that error, and `Topology::contours` returns no contours in that case. Before, a path whose winding numbers came out inconsistent around a point made `contours` loop forever in a build without debug assertions, and in one case allocate a new contour on every lap. The `contours_finish_*` tests cover both loops. They run only without the `slow-asserts` feature, because with it `Topology::from_path` checks the windings and panics on their paths. | +| `src/lib.rs` | `Error` has the `InconsistentWindingNumbers` variant, and `binary_op_with_eps` returns it from `Topology::try_contours`. The `inconsistent_winding_numbers_are_an_error` test covers it, and runs only without the `slow-asserts` feature for the same reason as the `contours_finish_*` tests. | | `src/sweep/sweep_line.rs` | `Sweeper::handle_intersection` queues a delayed intersection only when its `y` is before the ends of both segments, as the intersection scans do. A delayed intersection at a segment's end used to panic in `CurveOrder::entry_at`. The `delayed_intersection_at_a_segment_end` test sweeps three wide, flat contours whose sweep delayed an intersection to a segment's end. | +| `src/lib.rs`, `src/topology.rs` | `Topology::from_paths`, `from_paths_with_correctness`, `from_paths_with_work_limit`, `from_path` and `from_paths_binary` return `Error` instead of `NonClosedPath`, and return `Error::NaN`, `Error::Infinity` or the new `Error::TooLarge` when a path has a coordinate that is not finite or has a magnitude above `MAX_COORDINATE` (`f64::MAX / 16`). `binary_op` returns `Error::TooLarge` through `from_paths_binary`. Before, both panicked on a cubic with a coordinate above about `f64::MAX / 3`. A release build panicked in `f64::clamp` with "min > max, or either was NaN", and a debug build failed the `y.is_finite()` assertion in `Point::new`. The `coordinates_above_max_coordinate` test covers 6e307, 7e307 and 1.7e308. | +| `src/topology.rs` | `Contours::grouped` walks each containment tree with an explicit stack instead of one recursive call per nesting level, and returns the contours in the same order. Before, contours nested about 10,000 deep overflowed a 1 MiB stack, which aborts the process. The `grouped_*` tests cover the order and a 30,000-deep nesting on a 256 KiB stack. | +| `src/topology.rs` | `Topology::merge_coincident` compares a segment with its nearest west neighbor that an earlier merge did not delete. Before, it used the west neighbor recorded when the segment was created, so a run of three or more coincident segments merged only in pairs: four copies of one square, two in each direction, left 4 segments and 2 zero-area contours instead of none. The `merge_coincident_runs_longer_than_two` test covers that input and three copies, which leave the square once. The search for that neighbor follows a copy of `scan_west` and points each link it follows past the deleted segments, so a later search does not pass them again; `scan_west` itself is unchanged. `merge_coincident_many_copies` checks 64 copies of one square, and `nearest_live_west_shortens_the_links_it_follows` checks the shortened links. | +| `src/topology.rs` | `contours_for_positions` sorts the pieces it splits off a contour walk at a repeated point by the way they wind. A piece that winds like the walked contour becomes its sibling, and a piece that winds the other way becomes a child of the piece that contains it. Before, every piece split off became a child of the walk with the opposite `outer` flag, so of two holes touching at a point, the second came out with `outer = true` and the first hole as its parent, although it winds counter-clockwise. When only one piece winds like the walked contour, as when holes touch their outer contour, each other piece becomes its child without a winding test; otherwise a piece's winding test runs only for the pieces whose bounding box holds its probe point, starting with the pieces that share a point with it. A full winding test of the outer contour for every touching hole took time growing like `n^2` for `n` holes. The `holes_touching_at_a_point_are_siblings` test covers it, and `holes_touching_their_outer_contour_need_no_winding_test` checks that 200 holes touching one square run no winding test, and `touching_child_attaches_to_the_sibling_that_contains_it` covers holes and islands that touch one of two touching contours. | +| `src/sweep/sweep_line.rs` | The touch branch of `Sweeper::handle_intersection` runs its scan right from a segment, or left from a segment, at most once per sweep line until the sweep-line order changes. Exact copies of a shape queue a touch event for every pair of coincident segments, and each event used to scan the whole bundle in both directions, so sweeping `n` copies took time growing faster than `n^3`. The skipped scans would only push events already queued, so the output does not change. The `coincident_copies_scan_once_per_order` test counts the scans for 60 copies of two shapes, and `coincident_copies_keep_the_fill` compares the output fill with the input's nonzero fill for 200 inputs with exact, reversed and split copies. | +| `src/sweep/sweep_line.rs`, `src/treevec.rs` | `intersection_scan_right` and `intersection_scan_left` step over each run of sweep-line segments that end at the current height with one pass of a `TreeVec` iterator, instead of one indexed tree lookup per segment. `TreeVec::range_rev_to` iterates the elements before an index from back to front for the left scan. The scans compare the same segments and push the same events, so the output does not change; a polygon with 40,000 segments ending and 40,000 starting at one height sweeps in about 60% of the time. The `scans_step_over_segments_that_end` test checks that a segment ending at the current height does not stop the scan, `runs_of_ending_segments_keep_the_output` checks the area of such a polygon, and the `treevec` test `range_rev_to` checks the iterator. | +| `src/topology.rs` | `is_disjoint_tags` no longer calls `dbg!`, which printed two lines to stderr for every output segment on every call, in release builds too. It loops over `segment_indices()` instead of every winding entry, so it skips the segments that merging coincident segments deleted. The `disjoint_skips_merged_segments` test covers the second change. | +| `src/treevec.rs` | The iterators that `iter`, `iter_mut`, `range` and `range_mut` return on a tree with more than one level keep their stack of child iterators in a `Stack`, which holds 8 levels in place and puts any deeper level in a `Vec`. Before, the stack was a `Vec` and each of these calls allocated once. The sweep line calls `range_mut` on a `TreeVec<_, 128>`, which needs at least `2 * 64^9` elements to have more than 8 levels. The iterators visit the same elements in the same order. The `treevec` test `iterators_on_short_and_tall_trees` compares the four iterators with a `Vec` on a tree of at most 8 levels and on one with more. | +| `src/curve/mod.rs` | `intersect_cubics` compares a curve whose `p3.y` is below its `p0.y` as the same curve reversed, instead of panicking in `clamp`. `intersect_cubics_with_precomputed_decomp` returns close (`Ish`) over the common range when `sure_tolerance` is not positive, is larger than `ish_tolerance`, or `ish_tolerance` is not finite, instead of panicking, overflowing the stack or returning a wrong order; when the curves' vertical ranges do not overlap, it returns an empty order without a debug assertion failure, and `CurveOrder::with_y_slop`, `CurveOrder::order_after` and `CurveOrder::check_invariants` accept that empty order instead of panicking on an `unwrap`. The docs of these functions, `from_monotone_cubic`, `solve_t_for_y` and `y_subsegment` state their input rules. The `curves_decreasing_in_y`, `curved_crossing_decreasing_in_y`, `invalid_tolerances` and `disjoint_vertical_ranges` tests cover the changes; `curved_crossing_decreasing_in_y` compares a curve that runs down in y and crosses a line, while its chord does not, with the same curve reversed. | +| `src/topology.rs` | `Topology::bounding_box` returns `Rect::ZERO` for a topology with no segments, as kurbo does for an empty path, instead of a rectangle from infinity to negative infinity. The `empty_bounding_box` test covers it, and the `nonempty_bounding_box` test checks the bounds of a square away from the origin. | +| `src/curve/mod.rs` | `solve_t_for_y` divides every height by 32 before it builds the cubic's coefficients when the largest height or the target has a magnitude above `f64::MAX / 32`. Before, a segment with heights above about `f64::MAX / 3` gave an infinite coefficient, and polycool's critical point search recursed until the process aborted with a stack overflow. Two overlapping rectangles near y = 1e308 reached it; `Topology::from_path` now returns `Error::TooLarge` for them. The `solve_for_t_near_the_float_limit` test solves straight segments with heights from 5.5e307 up to `f64::MAX` at their midpoints, and three curved segments with heights from -1.5e308 to 1.5e308 at heights whose parameter is 0.25 or 0.75. `intersect_cubics_rec` and `AlmostHorizontalDecomposition::from_monotone_cubic` take the midpoint of two heights with `f64::midpoint` instead of `(a + b) / 2.0`. Before, two heights above about 9e307 summed to infinity, the comparison of two overlapping segments had no entries, and a release build panicked on the empty list. The `compare_near_the_float_limit` test compares two lines that start at heights up to 1.7e308, and the `overlapping_rectangles_near_the_float_limit` test checks that `Topology::from_path` returns `Error::TooLarge` for the two rectangles near y = 1e308. | +| `src/lib.rs`, `src/order.rs`, `src/sweep/range.rs`, `src/sweep/sweep_line.rs`, `src/topology.rs` | `ComparisonCache` counts its calls, so `Sweeper` counts its segment comparisons, and `Sweeper` also counts the segment positions it checks against horizontal segments and contour endpoints while finding a sweep line's changed intervals, n log2 n units for sorting a sweep line's n horizontal segments, one unit for every 16 segments that linear searches of the sweep line step over or that binary searches for a segment's position probe, and the active horizontal segments that each step of a `SweepLineRange` visits. `SweepLineRange::work_limit_exceeded` reports the limit to the code that processes a range, and the topology stops there. `Sweeper::set_work_limit` sets the most work it may do; past it, `Sweeper::next_line` returns `None`, also between the enter, exit and intersection events of one sweep line and between the comparisons and position checks that find its changed intervals, never returns a sweep line past the limit, and keeps returning `None` if the limit is raised; `Sweeper::work_limit_exceeded` returns `true`. `Topology::from_paths_with_work_limit` returns the new `Error::WorkLimitExceeded` when its sweep passes the limit. `Topology::from_paths_with_limits` also returns it before the topology's output passes its `output_limit`, counting one unit per output segment plus the new `WindingNumber::storage_units` of its two winding numbers (1 by default), which bounds the memory the topology uses. The sweep had no limit: the union of 400 identical circles made 1.36 billion comparisons in 19 sweep lines and took 66 to 83 s and 1.3 GB in a release build. `Topology::from_paths` and the other constructors set no limit. The `work_limit` and `work_limit_stops_within_a_sweep_line` tests sweep 20 stacked circles with a limit of 1,000 comparisons, and `work_limit_returns_no_line_past_the_limit` sweeps 3 stacked circles with every limit below the sweep's total. `work_limit_counts_the_horizontal_scans` sweeps 150 bars crossed by the top and bottom edges of 30 wide rectangles, where the sweep makes 1,462 comparisons but checks at least 18,000 positions, and stops it at half its total work. `work_limit_counts_position_searches_by_their_probes` sweeps 2,000 and 4,000 disjoint rectangles sharing their top and bottom heights, where each exit finds its segment by binary search, stops each sweep at half its total work, and checks that the larger sweep counts less than 2.5 times the work of the smaller one. `work_limit_counts_sorting_the_horizontals` sweeps 4,096 horizontal segments at one height with an empty sweep line, and stops it before the sort at half its total work. `work_limit_counts_the_horizontal_splits` builds the topology of 300 closed paths made only of overlapping horizontal segments at one height, which take little sweep work while the range steps visit about n^2 horizontal segments, and returns `Error::WorkLimitExceeded` at a limit of 100,000. `output_limit` builds 1,200 separate squares with an output limit of 10,000 units, of one unit less than three per output segment, and of exactly three per output segment. `unlimited_constructors_ignore_storage_units` builds a square with a winding number whose `storage_units` is `usize::MAX` through `Topology::from_paths` and `Topology::from_paths_with_work_limit`, which count no output units. A sweep that a `SweepLineRange` step stopped stays stopped when `Sweeper::set_work_limit` raises the limit afterwards; `work_limit_stays_exceeded_after_a_range_passes_it` checks it with 300 overlapping horizontal segments. With an output limit, the topology preallocates its output vectors for at most that many segments instead of one per input segment. | +| `src/topology.rs` | `Topology::can_merge` merges two output segments only when the neighbor at the shared point is the adjacent piece of the same input segment. Before, after coincident segments were deleted, a piece of one input curve could be merged with a piece of another, and the output rebuilt a sub-curve from the wrong curve's parameters: two arches whose right legs agree to within about 1e-6 (area about 0.00096) gave a contour of area 900 at eps 1e-6, and a path followed by its own reverse panicked in `segs_to_path`. `segs_to_path` also starts at the first segment instead of panicking when every segment looks mergeable. The `merge_only_pieces_of_one_input_curve` and `path_followed_by_its_reverse` tests cover both inputs. | +| `src/topology.rs` | With `Correctness::GoodEnough`, `Topology::contours` builds paths only for the output segments on the boundary of the result instead of for every output segment, which it then did not read. The contours it returns are unchanged. The `contour_positions_cover_only_boundary_segments` and `contours_match_contours_from_all_positions` tests cover the change. | +| `src/topology.rs` | `contours_for_positions` finds the nearest boundary segment west of each new contour through `Topology::west_boundary`, which remembers the answer for every segment it passes, so each link of a scan-west chain is followed once per call. A segment's boundary test runs the first time the walk asks for it, and its result is kept. Before, every contour walked its whole chain again, and `n` bars of one set west of `m` squares of the other with the test "first set and not second" called `inside` about `4nm` times: 1,024,240,000 calls for `n = m = 16,000`. The contours do not change. The `contour_starts_follow_each_west_chain_once` test counts the scan-west links that `west_boundary` follows for 200 bars and 200 squares, and `contour_starts_find_the_boundary_past_non_boundary_segments` checks the parents of squares whose chains pass non-boundary segments. `contours_of_one_polygon_test_the_boundary_only_where_needed` counts the calls to `inside` for one polygon with 1,000 edges. | +| `src/curve/mod.rs` | `solve_t_for_y` asks the root finder for `t` to the precision of f64 (`x_error` 0) instead of to within 1e-12. The x error of a `t` that is off by 1e-12 grows with the coordinates: on a curve 1e9 tall it reached 166 times `64 * f64::EPSILON * 1e9`, and pieces that `y_subsegment` cut from curves near 3e7 tall moved by tens of tolerances. Comparing two near-parallel curves of that size recursed down to y intervals shorter than the tolerance: 950,130 entries and 9 s for a pair 3e7 tall, minutes for a pair 1e8 tall. The `solve_x_for_y_on_tall_curve` test checks x on a curve 1e9 tall against a bisection, and the `near_parallel_tall_curves` test compares two curves 2e7 tall, 1.2 tolerances apart, and allows at most 64 entries. | +| `src/curve/mod.rs` | `CurveOrder::next_touch_after(y)` walks the order once and compares each touch with `y`. Before, when `y` was inside a touch followed by a Left interval and another touch, it called itself with the end of the Left interval, which is where the next touch starts, so it skipped that touch too and returned `None`. Two curves that start at one point and touch again later gave no later touch at the start height. The `next_touch_after_a_touch_that_contains_y`, `next_touch_after_a_crossing_after_a_touch_that_contains_y` and `next_touch_after_on_two_curves_that_start_together` tests cover built orders and two curves from `intersect_cubics`. | +| `src/curve/mod.rs` | `fit_quadratic` multiplies the heights by the power of two that brings the largest of them to between 2 and 4 when one of them has a magnitude above 2^500, does the same to the x coordinates when one of them has a magnitude above 2^500, and scales the quadratic's coefficients back at the end. `QuadraticApprox::from_cubic` multiplies by the quadratic's `y^2` coefficient before the second y coefficient when the product of two y coefficients is not finite. Before, a curve taller than about 1.3e154 gave a product of two heights that overflowed to infinity, and `inf * 0` gave a NaN coefficient, or an error bound that left out the curve's extremes. The curve comparison then reported a definite order that could be wrong, and `binary_op` returned a wrong result without an error. The quadratic sign checks used by curve comparisons now report the order as unknown (or close) over the whole interval when a coefficient is NaN or infinite, instead of a definite order. The `far_apart_with_huge_coordinates` test compares two curves with heights up to 1e155, 1e200 and 1e300, `tall_lines_at_any_height` compares two lines from 1 to 1e300 tall at three heights, `quadratic_approx_error_bounds_on_tall_curves` checks the coefficients and error bounds of an S-shaped curve up to 1e300 tall and 1e300 wide, `non_finite_quadratics_have_no_definite_order` checks the sign checks, and `fit_quadratic_with_huge_x` fits vertical curves at x = 1e307, -1e307 and 5e307 that are 1, 2^501 and 1e300 tall. | +| `src/curve/line.rs` | `intersect_lines` compares the x coordinates and the tolerance times 1/16 when one of them has a magnitude above 2^1019 and the overlap arithmetic is not finite, and works with half of each height for a line or height range more than `f64::MAX` tall. Before, two vertical lines at x = -1e308 and x = 1e308 came back `Right`, because the difference of their x values overflowed, and lines from y = -1e308 to 1e308 gave NaN positions. The `unchanging_with_huge_coordinates` test covers 1e300, 1e308 and `f64::MAX`, and `huge_coordinates_on_one_axis` covers lines near x = 1e308 that are 1e-307 tall, lines from y = -1e308 to 1e308 that stay apart or cross, and a line 1e-308 tall beside one of them. `subnormal_height` covers two vertical lines 1e-310 tall. `overlap_preserves_a_subnormal_gap_beside_a_distant_endpoint` checks both operand orders when an endpoint outside the overlap is near 1e308 and the overlap has a subnormal gap. | +| `src/geom.rs` | For a straight segment more than `f64::MAX` long on an axis, `Segment::at_y` works with half of each height and takes a weighted sum of the x coordinates, and `Segment::to_kurbo_cubic` takes weighted sums of the end points on that axis. Before, both returned NaN or infinite coordinates for such a segment. The `line_wider_and_taller_than_f64_max` test covers a segment from (-1e308, -1e308) to (1e308, 1e308), `line_wider_than_f64_max_and_very_short` covers a segment from (-1e308, 0) to (1e308, 3 times the smallest positive `f64`), and `line_wider_than_f64_max_with_uneven_ends` covers a segment from (-2^1023, 0) to (`f64::MAX`, 1). | +| `src/lib.rs` | The `union_with_huge_coordinates` test checks the union of a circle and a rectangle at sizes 1e155, 1e200 and 1e300. | +| `src/lib.rs` | `binary_op_with_eps` returns the new `Error::InvalidEps` when `eps` is NaN, infinite, zero or negative, instead of returning a wrong region (NaN or negative `eps`) or hanging (`-inf`). The `binary_op_with_eps_rejects_invalid_eps`, `topology_raises_unusable_eps` and `binary_op_with_eps_raises_eps_below_coordinate_resolution` tests cover the changes in this file, `src/segments.rs`, `src/sweep/sweep_line.rs` and `src/topology.rs`. | +| `src/segments.rs`, `src/sweep/sweep_line.rs`, `src/topology.rs` | The `Topology` constructors and `Sweeper::new_with_correctness` replace an `eps` that is NaN, infinite, not positive, or below `64 * f64::EPSILON` times the largest coordinate magnitude (and at least 64 times the spacing of subnormal floats) with that value, the scale `binary_op` uses. Before, an infinite `eps` made a lens of two arcs vanish, and an `eps` below one ulp of the coordinates (0 included, or 1e-10 at 1.5e8) overflowed the stack and aborted the process. These entry points return no error for an invalid `eps`, while `binary_op_with_eps` returns `Error::InvalidEps` for it. A caller that wants an invalid `eps` reported calls `binary_op_with_eps`; a caller that wants it replaced calls a `Topology` constructor or the `Sweeper`. | +| `src/curve/mod.rs` | `intersect_cubics` and `intersect_cubics_with_precomputed_decomp` raise a positive `ish_tolerance` below `4 * f64::EPSILON` times the two curves' largest x coordinate magnitude (two to four ulps of it, and at least four times the spacing of subnormal floats) to that value, and a positive `sure_tolerance` below half of it to half of it. Below that, rounding made the comparison report the wrong order. `intersect_cubics_rec` returns close (`Ish`) for an interval whose midpoint rounds to one of its ends instead of splitting it again, which repeated the same call until the stack overflowed. The `ish_tolerance_below_float_spacing` test covers both. `raised_tolerance_keeps_far_curves_apart`, `raised_tolerance_ignores_large_y` and `raised_tolerance_keeps_subnormal_curves_apart` check that lines 1.0 apart at x = 1e15, lines 1.0 apart at y = 2e15, and lines at x = 1e-310 and 2e-310 stay ordered. | +| `src/position.rs` | `approximate` stops halving an interval whose midpoint rounds to one of its ends. Before, it could return the interval's start, and the loop in `compute_positions_correct` then made no progress. The `approx_stops_at_one_float` test covers it. | +| `src/curve/mod.rs` | `intersect_cubics_rec` calls the new `order_from_control_points` after cutting both cubics to their shared y-range. It bounds the x gap between the two pieces by the smallest and largest control point x gap, widened by the largest control point y gap times a bound on `\|dx/dy\|` from the control polygon (`max_slope`). When that range stays more than `ish_tolerance` on one side of zero, the whole range gets `Left` or `Right` and the comparison does not recurse. Pieces of the almost-horizontal decomposition skip this step, because their comparison also widens each curve by the tolerance in y. Before, two nearly parallel cubics split their shared y-range into about `(height / ish_tolerance)^(1/3)` pieces even when they stayed more than `ish_tolerance` apart: a tall S-shaped cubic and a copy moved 10 * `ish_tolerance` sideways took 4,096 recursion leaves at height 1e6 and 16,384 at height 1e8; now each takes one. The `near_parallel_cubics_are_ordered_without_recursing` test counts the entries for that pair, `control_point_order_is_sound` checks every order the control points give against sampled gaps, `control_point_order_keeps_band_contours` checks that the contours of a tall wavy band and a moved copy do not change, and `control_point_order_skips_almost_horizontal_pieces` checks that an almost-horizontal cubic and a copy moved 16 sideways, with `ish_tolerance` 2, are still reported as close. | +| `src/order.rs`, `src/sweep/sweep_line.rs`, `src/position.rs`, `src/curve/mod.rs` | `ComparisonCache` stores one `CurveOrder` per pair of segments instead of one for each direction, and flips it when the pair is looked up in the other order. `CurveOrder::flip_into` writes each flip into the buffers of the previous one, so a lookup in the other order does not allocate while the order's entries fit in the buffers that earlier flips allocated. `ComparisonCache::evict_ended` drops the pairs in which a segment ends above a given height, once the cache has doubled since its last scan. `Sweeper` calls it on both of its caches each time the sweep line moves down, and `compute_positions` calls it each time it takes the next height from its queue. Both caches used to keep every pair the sweep compared until the sweep ended, so a sweep of a 2,001-point star polygon held 4,001,998 cached orders (1,463 MiB). Code comments label the changes `Craft patch (comparison cache size)`. The `one_order_per_pair` and `reversed_lookup_flips_the_stored_order` tests check the stored and flipped orders, `reversed_lookups_reuse_the_flipped_buffers` checks that a second lookup in the other order keeps the same buffer and that `flip_into` gives the result of `flip`, `ended_pairs_leave_the_comparison_cache` checks that a sweep of a tall band keeps fewer than a tenth of the pairs, and `evicting_comparisons_keeps_the_sweep_lines` and `evicting_comparisons_keeps_the_correct_positions` check that the sweep lines, output events and positions do not change. | +| `src/position.rs` | `PositionedOutputSeg::from_cubic` and `from_quad`, and the copied pieces of the strict layout (`next_subsegment`), cut the input curve at the points nearest the output piece's end points, found by Newton steps from the parameters `solve_t_for_y` gives (restarted from the nearest point of the whole curve at a point where a step cannot leave, such as a repeated handle; the start's search may pass the parameter of the end's height), and move the piece onto its end points: each end moves sideways with its handle (a quadratic's control point by the mean of its ends' moves), and the heights are mapped linearly, so the piece stays monotonic in `y`. `from_cubic` and `from_quad` used to move the inner control points sideways by their height's share of the gap at each end, and `next_subsegment` moved only the end points. Where a curve is almost flat at an end, a tiny error in that end's height is a large gap: the union of `M0,0 C0,1000 300,1000 1000,1000 L1000,2000 L-1000,2000 Z` with the rectangle `M998.37,500 L1500,500 L1500,1500 L998.37,1500 Z` at eps 1e-6 gave an outline 1.05 from both inputs and 815 too small in area, and with the rectangle at x = 990.37 the strict layout gave an outline 9.9e-4 from both inputs. Code comments label the changes `Craft patch (flat-end shear)`. `repeated_end_handle_stays_near_the_end` places cubics with a repeated handle at the flat end between end points moved along it, the `flat_end_shift_stays_near_the_end` test places steep-to-flat and flat-to-steep cubics and quadratics between end points moved along their flat ends, `flat_end_pieces_stay_monotonic` places a quadratic and a cubic between end points off the curve and checks that their heights do not decrease or pass the end point, `flat_start_piece_past_the_end_height_does_not_turn_back` places a cubic and a quadratic between end points both moved along their flat start and checks that `x` does not decrease, `flat_end_union_stays_on_the_inputs` checks the union of that shape with a copy moved by (-3.26e-6, -4.66e-8), and `flat_end_crossing_stays_on_the_inputs` checks the unions with the two rectangles in both layouts. | +| `src/sweep/sweep_line.rs` | `Sweeper::scan_for_removal` starts its intersection scans from the nearest segment left of the removed slot that does not end at the current `y`. Segments that end at `y` stay in the sweep line until `advance`, and a scan from one of them returns at once, so the live segments on both sides of the gap were never compared and their crossing was missed. The `removal_scan_skips_segments_that_end` test sweeps two integer polygons whose crossing at (0.75, 1.5) used to be missed; their Intersection came out with area 1.5 instead of 1.125. Both removal paths call this function: a segment's exit and the removals in `handle_intersection`. During the exits at one height, `EndedRuns` keeps each walk to such a segment and the segments the scans already started from, so many segments ending at one height do not each repeat the walk or the scans. `removal_scans_share_the_run_of_ended_segments` counts the positions visited, and `removal_scans_run_once_from_each_live_segment` counts the scans when two groups of such segments, with interleaved exits, each sit beside a taller rectangle. | +| `src/order.rs`, `src/sweep/sweep_line.rs` | Segments that start at one point all compare "ish" there, so each intersection scan and insertion search run at that point passes every other segment that starts there. Those comparisons are no longer stored: `ComparisonCache::with_order` uses a stored comparison if there is one and otherwise computes it the same way and drops it. `n` segments that start at one point and do not cross later now store `O(n)` comparisons instead of `O(n^2)` (comparisons made at a later crossing are stored as before); 1,000 triangles that share their apex peak at 8 MiB instead of 2,431 MiB and sweep in 0.56 s instead of 7.7 s. The comparisons are the same, so the output does not change. The `segments_starting_at_one_point_are_not_stored` and `curves_starting_at_one_point_are_not_stored` tests count the stored comparisons, `segments_starting_at_one_point_sweep_as_with_stored_comparisons` checks that every sweep line is the same as with all comparisons stored, and the `order` test `unstored_order_matches_stored_order` checks `with_order` against `compare_segments`. Each call to `with_order` counts toward the sweep's work limit, as a call to `compare_segments` does. At the shared apex of 200 triangles, the first sweep line counted 998 comparisons before and more than 100,000 now. The `work_limit_counts_comparisons_of_segments_that_start_together` test covers it. | +| `src/curve/transverse.rs` | `transversal_after` returns `false` when either dy/dt bound it divides by is zero, negative or nan. It compared the two slope bounds by cross-multiplying, which reverses the comparison when a bound is negative. Two curves that leave a shared start point in opposite directions, with their first control points one ulp below the start, were reported as keeping their left-to-right order although they cross. `transversal_before` reflects its curves and calls `transversal_after`, so it returned the same wrong answer. The `crossing_with_negative_start_dy` test checks both functions. | +| `src/curve/mod.rs` | `CurveOrder::with_y_slop` keeps the comparison's `metrics` when it changes the entries, instead of returning empty metrics. Code comments label the change `Craft patch (y-slop metrics)`. The `y_slop_keeps_metrics` test applies slop to an order with one metrics entry. | +| `src/sweep/sweep_line.rs` | The doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out. Code comments label the change `Craft patch (exited slots)`. | +| `tests/regression.rs` | The test escapes `CARGO_MANIFEST_DIR` with `glob::Pattern::escape` and fails when it finds no inputs. A checkout path containing `[` used to match no files, so the test ran zero cases and passed. Code comments label the change `Craft patch (regression glob)`. | +| `src/sweep/range.rs` | `SweepLineRange::events` starts a horizontal fragment at the later of the previous position and the fragment's own start. Called after `increase_x` at the first position it panicked on an unset position, and a fragment that `increase_x` added was reported from the earlier position. The tests `events_after_increase_x_at_the_first_position` and `events_after_increase_x_start_a_new_fragment_at_its_own_start` check both cases. | +| `src/topology.rs`, `src/snapshots/linesweeper__topology__tests__*.snap` | Building a `Topology` and walking its contours no longer make small allocations per segment. The open output segments of each input segment are kept in an inline queue of three (`OpenSegs`) instead of a `VecDeque`, and that state now lives only for the sweep instead of in the `Topology`, so the nine topology snapshots no longer list `open_segs`. The segment buffers are kept for the whole sweep instead of being allocated for each sweep-line range, the winding number is cloned for horizontals only when a horizontal starts at the point, `can_merge` returns early at a point that is not simple before solving for `t`, and `segs_to_path` reverses first halves into one reused buffer instead of calling `reverse_subpaths` for each one. On a stroked serpentine of 501,993 segments, building allocates 4,324,964 times instead of 6,044,487 and holds 731.2 MB instead of 764.0 MB, and `contours` allocates 632,030 times instead of 834,041; the contours are the same. The `reverse_path_into_matches_reverse_subpaths` test checks the reversal against `reverse_subpaths`, `open_segs_pop_like_a_deque` checks the queue against a `VecDeque`, and `contours_keep_their_elements_and_direction` compares two contours with the elements the unpatched code writes. | | `src/curve/mod.rs` | When the chord that `fit_quadratic` takes for a very short curve gives a constant term that is not finite, `fit_quadratic` takes the line through the curve's start point with the chord's slope instead. Before, a curve near x = 1e305 with heights near 1e4 and less than about 3e-12 tall gave a product of an x coordinate and a height above `f64::MAX`, and the chord's constant term was NaN. The `short_curve_chord_with_huge_x` test fits vertical curves one ulp tall at y = 1e4 and x = 1e305, -1e305 and 5e307. Code comments label the change `Craft patch (huge chord)`. | | `src/curve/line.rs` | `line_at_ys` multiplies the x coordinates by 2^600 before the weighted sum and the sum by 2^-600 after it when both x coordinates have a magnitude below 2^-500. Before, a vertical line at x = 5e-324 gave x = 0 halfway along its height. The `subnormal_x` test checks that line and a line from x = -1.5e-323 to 1.5e-323. Code comments label the change `Craft patch (subnormal x)`. | | `docs/sweep.typ` | The intersection scan to the left compares each segment with `alpha^(i+1)` instead of `alpha^i`. With `alpha^i`, its first pass compared `alpha^i` with itself, and the lemma after it is stated for `alpha^(i+1)`. | | `docs/sweep.typ` | The crossing-height lemma (`lem-intersection-height-error`) and its proof divide the starting gap `beta(y_0) - alpha(y_0)` by the sum of both gaps. With the ending gap `alpha(y_1) - beta(y_1)` as the numerator, gaps of 1 and 3 gave `t = 0.75`, while the segments cross at `t = 0.25`. The proof's inverse-slope difference is `d/(y_1 - y_0)`; the package has `d/(y_1 - y_1)`, whose denominator is zero. The lemma's bound and the later bound on the crossing height use the absolute values of `1/m_alpha` and `1/m_beta`, because the slopes can be negative. | | `docs/sweep.typ` | Two typos are corrected. "condi0.2tions" reads "conditions", and `q(i+i)` reads `q(i+1)`, the first index for which `q` is false. | | `docs/sweep.typ` | The lemma for the intersection scan to the left asks for the ordering invariant on `(alpha^1, ..., alpha^(i+1))` and the crossing invariant on `(alpha^1, ..., alpha^i)`, which is how the bidirectional lemma uses it. The argument for the order invariant cites the crossing invariant instead of a "third invariant"; the document defines two. | -| `src/sweep/sweep_line.rs`, `src/topology.rs` | Clippy 1.100.0 with `-D warnings` and every feature passes on the library, its unit tests and the `regression` test: the `slow-asserts` invariant check in `sweep_line.rs` passes `self.line` to `assert!` without a `&` (`useless_borrows_in_formatting`), and `Contours::grouped` iterates over the contours with `enumerate` instead of indexing them (`needless_range_loop`). The behavior does not change. Code comments label the change `Craft patch (clippy lints)`. | +| `docs/sweep.typ` | The crossing-height lemma (`lem-intersection-height-error`) and its proof divide the starting gap `beta(y_0) - alpha(y_0)` by the sum of both gaps. With the ending gap `alpha(y_1) - beta(y_1)` as the numerator, gaps of 1 and 3 gave `t = 0.75`, while the segments cross at `t = 0.25`. The proof's inverse-slope difference is `d/(y_1 - y_0)`; the package has `d/(y_1 - y_1)`, whose denominator is zero. The lemma's bound and the later bound on the crossing height use the absolute values of `1/m_alpha` and `1/m_beta`, because the slopes can be negative. | +| `src/curve/mod.rs` | The `QuadraticApprox` doc says the quadratic gives `x` as a function of `y`, as `from_cubic`, `dmin` and `dmax` use it; the package's doc says `y` as a function of `x`. The test `curve::test::quad_approximation_gives_x_of_y` checks it on the curve `x = y^2`. | +| `examples/curve_metrics.rs` | The SVG's `viewBox` starts at x = -1.5 instead of 0, so the left half of each curve, which spans x = -1 to 1, is drawn. A test checks that every curve fits in the `viewBox`. | +| `examples/bus.rs` | The SVG's `viewBox` is the size of the one composite the example draws, with its padding, instead of 3 composites wide and 2 tall. | +| `Cargo.toml` | `Cargo.toml` does not register the `boolean_op` and `winding-numbers` examples, the `fonts` and `snapshots` tests or the `linebender_logo` bench, which need dev-dependencies or files the package leaves out. Their source files are retained; the two examples also have the separately recorded stroke-width changes. | -Every change here updates this table and `SOURCE.json` in the same commit. +Every change here updates this table and `SOURCE.json` in the same commit. To take a new linesweeper +release, unpack the crates.io package, carry these changes over, regenerate `SOURCE.json`, and run the +tests below. `omitted_files` lists the 43 files of the package left out here, with their hashes: @@ -46,8 +123,8 @@ Every change here updates this table and `SOURCE.json` in the same commit. - `.config/`, `.helix/`, `.typos.toml`, `.gitmodules`, `flake.nix`, `flake.lock` and `nix/`: the package's repository tooling. -Only the targets listed under Tests read the font, the logos and the snapshot files, and those targets -do not compile from the published package. +Only the targets listed under Tests read the font, the logos and the snapshot files. Those targets do +not compile from the published package, and `Cargo.toml` here does not register them. ## Using it @@ -62,20 +139,33 @@ linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "" } ## Tests -`scripts/test-pdf-backends.sh` runs the package's unit, regression and doc tests. The `craft-prepress` -tests with the `flatten` feature run against this copy. `pdf.yml`'s path filter lists this directory, -so a pull request that changes files here starts `pdf.yml`. No workflow runs clippy on this copy. Run -the tests and clippy from this directory: +`scripts/test-pdf-backends.sh` runs the package's unit, regression and doc tests, the unit and +regression tests again with the `slow-asserts` feature, the `generators` tests, the two `paperjs` trials that need no data files, and the tests in the `visualize_op` and +`curve_metrics` examples, and checks that every registered target compiles with all features. The +`craft-prepress` tests with the `flatten` feature run against this copy. `pdf.yml`'s path filter +lists this directory, so a pull request that changes files here starts `pdf.yml`, which runs the +script. No workflow runs clippy on this copy. Run the tests and clippy from this directory: ```sh cargo test --locked --lib --test regression +cargo test --locked --lib --test regression --features slow-asserts +cargo test --locked --lib --features generators generators:: +cargo test --locked --test paperjs pixmap_distance_counts_coverage +cargo test --locked --test paperjs load_errors_are_reported cargo test --locked --doc -cargo clippy --locked --all-features --lib --test regression -- -D warnings -cargo clippy --locked --all-features --lib --profile test -- -D warnings +cargo test --locked --example visualize_op +cargo test --locked --example curve_metrics --features metrics +cargo check --locked --all-targets --all-features +cargo clippy --locked --all-targets --all-features -- -D warnings ``` `Cargo.toml` leaves out the `kompari`, `linesweeper_util` and `path-bool` dev-dependencies, which `Cargo.toml.orig` gives as git or path dependencies. The `fonts` and `snapshots` tests, the -`winding-numbers` and `boolean_op` examples and the `linebender_logo` bench do not compile here. +`winding-numbers` and `boolean_op` examples and the `linebender_logo` bench need them, or the +omitted `examples/linebender.svg`, and do not compile here. The package's `Cargo.toml` registers +these five targets; the copy's `Cargo.toml` does not. Their source files are retained, and the two +examples have the stroke-width changes listed above. The +package does not include the `boolean-test/data/` files that the `paperjs` test reads, so the full +`paperjs` target fails here with one failing `load` trial per missing file. Cargo writes to `target/` in this directory, which the root `.gitignore` excludes. diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 45f29d2ae6..2115a279e4 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,25 +8,95 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ - "In `src/sweep/sweep_line.rs`, the touch branch of `Sweeper::handle_intersection` runs each scan from a segment in a direction at most once per sweep line until the sweep-line order changes, so exact copies of a shape no longer rescan the whole coincident bundle for every touch event.", - "In `src/sweep/sweep_line.rs`, the doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out.", - "In `src/segments.rs`, `update_enter_exit` sorts only the new entrances and exits and merges them into the sorted ones, in the order a stable sort of the whole list gives, instead of sorting the whole list on every call. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add a collection of paths and merge once, as `add_closed_polylines` and `Topology::from_paths` already do, and `add_bez_paths` removes the segments of a path with an open subpath before it returns the error. Without it, adding 2,000 triangles one at a time from the top row down takes 6,006,993 entrance comparisons, and adding n paths one at a time takes time quadratic in n. The tests `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort` and `segments::tests::paths_added_in_height_order_are_not_sorted_again` cover it.", - "In `src/curve/transverse.rs`, `transversal_after` (and `transversal_before`, which calls it) returns `false` when either dy/dt bound is not positive, instead of cross-multiplying the slope bounds, which reverses the comparison for a negative bound.", - "In `src/sweep/sweep_line.rs`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions they hold and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y.", - "In `src/sweep/sweep_line.rs`, `Sweeper::handle_intersection` queues a delayed intersection only when its y is before the ends of both segments, so a delayed intersection at a segment's end no longer panics in `CurveOrder::entry_at`.", - "In `src/curve/mod.rs`, when the chord that `fit_quadratic` takes for a very short curve gives a constant term that is not finite, `fit_quadratic` takes the line through the curve's start point with the chord's slope, so a curve near x = 1e305 with heights near 1e4 no longer gives a NaN coefficient. In `src/curve/line.rs`, `line_at_ys` scales the x coordinates by 2^600 before the weighted sum and back after it when both have a magnitude below 2^-500, so a subnormal x coordinate no longer rounds to 0. Both files add tests for it.", + "Numeric helpers reject invalid float bounds and retain extreme quadratic roots, conservative slope bounds, small affine offsets, and exact mapped endpoints. Curve comparisons return an empty order for disjoint height ranges. Mutable reversed cache entries retain edits until eviction or an arena change. Output events have total floating-point ordering, including NaNs and signed zero. Bounded topology output accounts for merged winding storage and rejects size overflow. Batch insertion rolls back its unentered suffix if its iterator panics. Sweep work counts actual tree-search predicates; ordinary touches do not hash the intervening span. Reverse iterators use the shared inline stack. The crossing-height proof explicitly assumes finite denominator additions.", + "`binary_op_accuracy` in `src/lib.rs` returns the checked automatic accuracy, including for open paths. `binary_op` and `Topology::from_paths_with_automatic_limits` in `src/topology.rs` compute accuracy from monotonic pieces before preparing sweep metadata, then sort accepted input once. The accuracy uses the retained segments' coordinate scale, including their curve control points. `automatic_accuracy_checks_control_point_scale` checks both argument orders and a wider-feature control; `automatic_accuracy_ignores_discarded_horizontal_handles` checks that a retraced horizontal curve does not raise the floor. `automatic_boolean_reuses_the_prepared_segment_events` uses the shared test comparison counter from `src/segments.rs` to check one input sort for ordinary and bounded operations. `automatic_accuracy_does_not_sort_events`, `automatic_feature_rejection_does_not_sort_events`, and `automatic_accuracy_does_not_prepare_sweep_metadata` check that accuracy queries and rejected features do not sort events or prepare sweep metadata. `automatic_accuracy_accepts_open_paths` checks an open accuracy query and the topology constructor's closure check.", + "Sweep-order checks in `src/sweep/sweep_line.rs` accept closed `Ish` intervals, including zero-height touches. The position-search work test uses 100 and 200 rectangles with `slow-asserts` and keeps 2,000 and 4,000 without that feature; both configurations retain the same work-count and work-limit assertions.", + "`SegmentOrder::position` finds a segment by binary search over a key on each sweep-line entry instead of scanning the line. The order of the line and the index returned do not change.", + "`ComparisonCache` skips the curve comparison for two segments whose horizontal bounds are more than four times the larger of the tolerance and the accuracy apart, and records one order for all the heights they share. The full comparison can report part of such a pair as `Ish`, and this result does not. This result's `metrics` holds one entry at depth zero.", + "`Metrics::entries` is a `SmallVec<[MetricsEntry; 2]>` instead of a `Vec`.", "In `docs/sweep.typ`, the intersection scan to the left compares each segment with `alpha^(i+1)`, the segment the lemma after it is stated for, instead of `alpha^i`.", "In `docs/sweep.typ`, the typo \"condi0.2tions\" reads \"conditions\", and `q(i+i)` reads `q(i+1)`, the first index for which `q` is false.", "In `docs/sweep.typ`, the lemma for the intersection scan to the left asks for the ordering invariant on `(alpha^1, ..., alpha^(i+1))` and the crossing invariant on `(alpha^1, ..., alpha^i)`, as the bidirectional lemma uses it, and the argument for the order invariant cites the crossing invariant instead of a \"third invariant\".", + "In `src/curve/line.rs`, `line_at_ys` divides each y offset by the line's height instead of multiplying it by the height's reciprocal, so a line less than about 5.6e-309 tall no longer gives NaN positions in `intersect_lines`. Vertical lines keep their exact endpoint x coordinate; `coincident_vertical_lines_keep_their_exact_x` checks coincident lines at x = 0.1 with tolerance 1e-18.", + "`F64Perturbation::Ulp` on a subnormal value gives the value on the other side of zero when a step toward zero is larger than the value, instead of keeping the value's sign. The module is compiled only for tests.", + "src/curve/mod.rs: the `QuadraticApprox` doc says the quadratic gives `x` as a function of `y`, as `from_cubic`, `dmin` and `dmax` use it, and the test `curve::test::quad_approximation_gives_x_of_y` checks it on the curve `x = y^2`.", + "In `examples/boolean_op.rs`, `examples/visualize_op.rs` and `examples/winding-numbers.rs`, the SVG stroke width is the larger of the bounding box's width and height divided by 512. The package computed `(max_y - min_y).max(max_x - max_y) / 512.0`, which uses `max_x - max_y` for the width: a box from (0, 1000) to (512, 1001) got a stroke width of 1/512 instead of 1. `examples/visualize_op.rs` computes it in a `stroke_width` function with the test `stroke_width_follows_the_larger_side`; the other two examples do not compile in this copy.", + "Remove the `boolean_op` and `winding-numbers` examples, the `fonts` and `snapshots` tests and the `linebender_logo` bench from `Cargo.toml`, since they need dev-dependencies or files the package leaves out. Their source files are retained; the two examples also have the separately recorded stroke-width changes.", + "`ComparisonCache::compare_segments` in `src/order.rs` returns `Option<&mut CurveOrder>`, and returns `None` when either segment is horizontal, in every build profile; its doc comment states it. The crate's own callers in `src/sweep/sweep_line.rs`, `src/position.rs` and `src/topology.rs` hold only segments that are not horizontal and call the crate-private `compare_non_horizontal_segments`, which checks that with a `debug_assert`; `ComparisonCache::with_order` is crate-private for the same reason. Before, a horizontal line and a cubic stopped at a `debug_assert` in `Segments::horiz_decomp` in a debug build, and a release build skipped that check.", + "In `src/position.rs`, `compute_positions` sets each output segment's `last_y` to the segment's start height before queuing it. It started at 0, so a segment starting at `y < 0` was skipped at its first queue entry and close segments there were not put in order: with `Correctness::ReallyCorrect`, two lenses 0.001 apart at `dy = 100` gave 48 corrected quadratics, and the same lenses at `dy = -100` gave 20 uncorrected cubics. `position::tests::correct_positions_at_negative_y` checks both heights.", + "`Segment::lower` and `Segment::upper` bound a horizontal line by both of its endpoints. In the package, `local_bbox` takes both x values from `at_y`, which returns the right end of a horizontal line, and `lower` returns the right end minus `eps`.", + "The `visualize_op` example draws its two input paths with `fill-rule=\"evenodd\"`. Its `binary_op` call uses `FillRule::EvenOdd`, and the SVG default fill rule is nonzero.", + "In `docs/sweep.typ`, the floating-point ratio lemma assumes `y_0 < y_1` and a finite `fl(y_1 - y_0)`, and its proof bounds `fl(y_1 - y_0)` where it wrote `fl(y + y_0)`. The ordering alone does not rule out overflow: with `y_0 = -1e308`, `y = 0` and `y_1 = 1e308` the computed ratio is 0. The x-coordinate accuracy lemma that uses it takes `M` as a floating-point number, and its proof shows both assumptions hold for a segment that is not horizontal.", + "In `src/segments.rs`, `Segments::add_points` skips a point equal to the one before it, as `add_closed_polyline` already does. Without it, `add_points([(0, 0), (0, 0), (1, 1)])` adds a zero-length segment, and `check_invariants` fails on it. The test `segments::tests::add_points_skips_repeated_points` covers it.", + "Start the `viewBox` in `examples/curve_metrics.rs` at x = -1.5 instead of 0, so the left half of each curve is drawn, and add a test that every curve fits in it.", + "End the `Ish` entry that `CurveOrder::push` inserts between opposite `Left` and `Right` intervals at the earlier interval's end, so it has zero height and the new order covers its own interval.", + "In `src/curve/mod.rs`, `quadratic_signs` calls the new `balance_quadratic`, which multiplies the coefficients by one power of two when `b * b` or `a * c` would underflow or overflow, keeping every coefficient below `2^1021`. Without it, the discriminant underflows to zero or overflows for very small or very large coefficients: for the cubic with y coordinates `[0, -s, -2s, s]`, `monotonic_cubic_pieces` splits at t = 0.5 when s = 1 but returns one piece that is not monotonic when s = 1e-200 or s = 1e160. `curve::test::quadratic_signs_at_extreme_scales` covers it.", + "`float_in_range` interpolates as `start * (1 - t) + end * t` instead of `start + t * (end - start)`, so a range wider than `f64::MAX`, such as `-1e308..1e308`, gives a value in the range instead of NaN.", + "`OutputEvent`'s `Ord` breaks ties between events with the same horizontal range by segment and then by the other fields, so `cmp` returns `Equal` only for equal events. In the package, `cmp` compares the horizontal ranges only, so two events on different segments compare equal while `==` is false, and a `BTreeSet` keeps one of them. The sweep line still sorts its events by horizontal range alone.", + "In `src/sweep/sweep_line.rs`, `choose_cross_height` takes the midpoint of a crossing's height range with `f64::midpoint` instead of `(y0 + y1) / 2.0`, so heights above about 9e307 no longer give an infinite crossing height.", + "In `src/treevec.rs`, `TreeVec::range` and `range_mut` panic with a message when a bound is past `usize::MAX` or the start is after the end, and their doc comments list these panics. Without it, `range((Excluded(usize::MAX), Unbounded))` overflows in `normalize_bounds`, and `range(10..5)` on a tree with internal nodes overflows in a subtraction; in a release build both wrap instead. The tests `treevec::tests::range_reversed`, `range_mut_reversed`, `range_start_past_max` and `range_end_past_max` cover it.", + "The `paperjs` test's `pixmap_distance` counts the alpha difference as well as the color differences. Both images are filled black, so in the package a covered pixel and an empty one have the same color and the image comparison passes on any result.", "In `docs/sweep.typ`, the crossing-height lemma and its proof use the starting gap `beta(y_0) - alpha(y_0)` as the numerator of `t`, instead of the ending gap `alpha(y_1) - beta(y_1)`, so that `y_0 + t(y_1 - y_0)` is the height where the segments cross, and the proof's inverse-slope difference is `d/(y_1 - y_0)` instead of `d/(y_1 - y_1)`. The lemma's bound and the later bound on the crossing height use the absolute values of the inverse slopes, because the slopes can be negative.", - "In `src/sweep/sweep_line.rs` and `src/topology.rs`, two changes make clippy 1.100.0 with `-D warnings` and every feature pass on the library, its unit tests and the `regression` test: the `slow-asserts` invariant check passes `self.line` to `assert!` without a `&`, and `Contours::grouped` iterates over the contours with `enumerate` instead of indexing them. The behavior does not change." + "In `tests/paperjs.rs`, a test file in `boolean-test/data/` that cannot be loaded becomes a failing `/load` trial instead of being skipped, so the `paperjs` target no longer passes with zero trials when the data files are missing.", + "In `src/sweep/sweep_line.rs`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each arrangement of the positions they hold and the segments between them, and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y.", + "In `src/topology.rs`, `contours_for_positions` returns `Error::InconsistentWindingNumbers` when the contour walk finds no boundary segment leaving a point or re-enters a segment it already walked, so `contours` no longer loops forever on a path whose winding numbers come out inconsistent around a point. Its `debug_assert!` checks of the windings along the walk and its panic for a western boundary segment with no contour return the same error. The new `Topology::try_contours` returns that error, and `Topology::contours` returns no contours in that case.", + "In `src/lib.rs`, `Error` has the `InconsistentWindingNumbers` variant, and `binary_op_with_eps` returns it from `Topology::try_contours`.", + "In `src/sweep/sweep_line.rs`, `Sweeper::handle_intersection` queues a delayed intersection only when its y is before the ends of both segments, so a delayed intersection at a segment's end no longer panics in `CurveOrder::entry_at`.", + "In `src/lib.rs` and `src/topology.rs`, the `Topology` constructors that take Bézier paths return `Error` instead of `NonClosedPath`, and return `Error::NaN`, `Error::Infinity` or the new `Error::TooLarge` for a coordinate that is not finite or has a magnitude above `MAX_COORDINATE` (`f64::MAX / 16`), so `Topology::from_path` and `binary_op` no longer panic on cubics with coordinates above about `f64::MAX / 3`.", + "In `src/topology.rs`, `Contours::grouped` walks each containment tree with an explicit stack instead of one recursive call per nesting level, so deeply nested contours no longer overflow the stack. The order of the returned contours is unchanged.", + "In `src/curve/mod.rs`, `AlmostHorizontalDecomposition::from_monotone_cubic` keeps `p1.y` at least `p0.y` and `p2.y` at most `p3.y` for each piece, instead of clamping both into the piece's y-range. A y-monotone cubic can have handles outside that range, and the clamp moved the curve the sweep compares: for `M0,5 C5,0 2,0 1,1 C0,2 4,0 5,5 Z` at eps 1e-6, `Topology::from_path(..).contours(|w| *w != 0)` gave an outline of area 11.0108 instead of 10.9122, with a horizontal cut at y = 1.97218 that lies 0.2588 from the input. `curve::test::decomposition_keeps_handles_outside_the_y_range` covers the shape and its mirror image in y.", + "In `src/segments.rs` and `src/lib.rs`, a `ClosePath` that comes before the first point of a path is skipped. Without it, a `BezPath` deserialized from `[ClosePath]` or `[ClosePath, MoveTo, LineTo, LineTo, ClosePath]` makes `Topology::from_path` and `binary_op` panic in kurbo with \"Can't start a segment on a ClosePath\". With it, `[ClosePath]` gives no contours and the second path gives the same contours as the path without its leading `ClosePath`. The test `tests::leading_close_path` covers it.", + "In `src/topology.rs`, `Topology::merge_coincident` compares a segment with its nearest west neighbor that an earlier merge did not delete, so a run of three or more coincident segments merges fully instead of in pairs.", + "In `src/topology.rs`, `contours_for_positions` makes a piece split off a contour walk at a repeated point a sibling of the walked contour when it winds the same way and a child of the piece that contains it otherwise, so a hole touching another hole at a point is no longer marked outer with that hole as its parent. When only one piece winds like the walked contour, each other piece becomes its child without a winding test, and otherwise the winding test runs only for the pieces whose bounding box holds the probe point, so `n` holes touching their outer contour no longer take time growing like `n^2`.", + "In `src/sweep/sweep_line.rs`, the touch branch of `Sweeper::handle_intersection` runs each scan from a segment in a direction at most once per sweep line until the sweep-line order changes, so exact copies of a shape no longer rescan the whole coincident bundle for every touch event.", + "In `src/curve/mod.rs`, `AlmostHorizontalDecomposition` stores its pieces in a `SmallVec<[CubicParams; 2]>` instead of an `ArrayVec`, so a decomposition takes 288 bytes instead of 824 and one with more than two pieces goes on the heap. `Segments` keeps one decomposition for every segment, horizontal ones included. For a closed polygon of 200,000 lines, the peak heap of `Topology::from_path` plus `contours` went from 500.9 MB to 360.4 MB with the same contours. `curve::test::horizontal_decomposition_stores_two_pieces_inline` covers the size and `curve::test::horizontal_decomposition_keeps_every_piece` covers decompositions of one, two and five pieces.", + "In `src/topology.rs`, `Topology` allocates one output segment for each run of coincident horizontal pieces between two points instead of one per piece, and none for a run whose winding numbers cancel. Without it, n overlapping rectangles `rect(i, 0, i + n, 10)` give 2n² + 2n output segments (80,400 for n = 200), and `merge_coincident` deletes all but 6n - 2 of them. With it, they give 6n - 2 (1,198), with the same contours. `has_normal_contours` and `is_disjoint_tags` read the winding numbers on either side of a run, not the ones between its pieces, and the `slow-asserts` continuity check includes the pieces without an output segment. The test `topology::tests::coincident_horizontals_get_one_output_segment_per_run` covers it.", + "In `src/sweep/sweep_line.rs`, `intersection_scan_right` and `intersection_scan_left` step over each run of segments that end at the current height with one pass of a `TreeVec` iterator instead of one indexed lookup per segment; `src/treevec.rs` adds `TreeVec::range_rev_to` for the left scan. The output does not change.", + "In `src/curve/mod.rs`, `intersect_cubics_with_precomputed_decomp` calls the new `order_from_precomputed_approx` for each pair of pieces before `intersect_cubics_rec`. It compares the pieces' precomputed quadratic approximations over their shared y-range, with `ish_tolerance` as both tolerances, and when the result is a single `Left` or `Right` interval it records that order and skips `intersect_cubics_rec`, which would first cut both cubics with `y_subsegment`. Intervals shorter than `ish_tolerance` are left to `intersect_cubics_rec`. For `binary_op` on the stroke outline of 20,000 zigzag cubics (200,034 elements), 804,727 of 1,165,896 piece comparisons are decided this way, calls that cut cubics fall from 1,427,218 to 622,491, the median time falls from 2225.9 ms to 2109.1 ms, and the output is bit-identical. `curve::test::approximation_first_keeps_the_curve_order` compares the `CurveOrder` with and without the change for hand-built and generated pairs.", + "In `src/curve/mod.rs`, `intersect_cubics_rec` replaces the end x values in the precomputed approximations' `almost_horiz` with the end x values of the curves cut to the compared y-range, as `QuadraticApprox::from_cubic` sets them. The precomputed values belong to the whole almost-horizontal piece, so over a shorter y-range they bounded the wrong ends: for `c0 = (311.848,248.7972) (313.515,248.9023) (315.181,248.9698) (316.848,248.9988)` and `c1 = (316.909,243.813) (316.818,245.48) (316.698,247.146) (316.549,248.813)`, `intersect_cubics(c0, c1, 5e-7, 1e-6)` returned Left up to y = 248.8129995 and Ish up to 248.813, although the curves are 4.4457 apart there, and the sweep split `c0` at y = 248.813. `curve::test::almost_horizontal_piece_cut_to_the_overlap` covers the pair.", + "In `src/curve/mod.rs`, `CurveOrder::push` adds a `MetricsEntry` only when the new `metrics` feature is on. Before, it added one for every interval of every curve comparison, and `CurveOrder::flip` cloned them all, while only `examples/curve_metrics.rs` reads them. `Cargo.toml` adds the `metrics` feature, off by default, and gives the `curve_metrics` example `required-features = [\"metrics\"]`. The public `Metrics` types stay; without the feature `metrics.entries` is empty. For 150 horizontal and 150 vertical wavy cubics, each stroked 1.5 pt, `Topology::from_path` plus `contours` went from 877.1 ms to 806.8 ms (median of 7), from 1,946,341 to 1,378,442 allocations and from 163.0 MB to 117.9 MB peak heap, with the same contours. `curve::test::crossing_cubics_metrics_follow_the_feature` covers the recording and `curve::test::crossing_cubics_order_does_not_depend_on_metrics` covers the order, with and without the feature. With the feature, `curve::test::crossing_cubics_metrics_record_the_recursion_depth` checks the depth each interval records, and `curve::test::curve_order_no_overlap` checks the single entry of a comparison at one y.", + "In `src/topology.rs`, `is_disjoint_tags` no longer prints its per-segment `dbg!` output to stderr, and it visits only the output segments that `segment_indices()` lists, skipping those deleted when coincident segments were merged.", + "In `src/treevec.rs`, the tree iterators keep their stack of child iterators in a `Stack` that holds 8 levels in place and any deeper level in a `Vec`, so `iter`, `iter_mut`, `range` and `range_mut` no longer allocate on trees of up to 8 levels. The iterators visit the same elements in the same order.", + "In `src/curve/mod.rs`, `intersect_cubics` reverses a curve whose `p3.y` is below its `p0.y` before comparing it, and `intersect_cubics_with_precomputed_decomp` returns `Ish` over the common range when `sure_tolerance` is not positive or is larger than `ish_tolerance`, or `ish_tolerance` is not finite, and an empty order for curves whose vertical ranges do not overlap, which `CurveOrder::with_y_slop`, `CurveOrder::order_after` and `CurveOrder::check_invariants` accept; the docs of these functions, `from_monotone_cubic`, `solve_t_for_y` and `y_subsegment` state their input rules. In `src/topology.rs`, `Topology::bounding_box` returns `Rect::ZERO` when there are no segments.", + "In `src/curve/mod.rs`, `solve_t_for_y` divides every height by 32 before it builds the cubic's coefficients when a height or the target has a magnitude above `f64::MAX / 32`, so a segment with heights above about `f64::MAX / 3` no longer gives an infinite coefficient that makes polycool recurse until the stack overflows. `intersect_cubics_rec` and `AlmostHorizontalDecomposition::from_monotone_cubic` take the midpoint of two heights with `f64::midpoint`, so heights above about 9e307 no longer sum to infinity and leave a curve comparison with no entries.", + "In `src/sweep/sweep_line.rs`, `src/sweep/range.rs`, `src/order.rs`, `src/topology.rs` and `src/lib.rs`, `Sweeper` counts its segment comparisons and the segment positions it checks against horizontal segments and contour endpoints, n log2 n units for sorting a sweep line's n horizontal segments, one unit per 16 segments that linear searches of the sweep line step over or that binary searches for a segment's position probe, and the active horizontal segments that each step of a `SweepLineRange` visits, and `Sweeper::set_work_limit` stops the sweep, between the events of one sweep line and between the comparisons and position checks that find its changed intervals too, once it passes the limit, so no sweep line comes back past the limit; the topology also stops between the steps of a range once `SweepLineRange::work_limit_exceeded` returns `true`, and `Topology::from_paths_with_work_limit` then returns the new `Error::WorkLimitExceeded`, which `Topology::from_paths_with_limits` also returns before the topology's output passes its `output_limit`, counted as one unit per output segment plus the new `WindingNumber::storage_units` of its two winding numbers, so stacked or nearly coincident shapes no longer sweep for minutes with no way to stop them. A sweep that a range step stopped stays stopped when the limit is raised, and with an output limit the topology preallocates its output vectors for at most that many segments.", + "In `src/topology.rs`, `Topology::can_merge` merges two output segments only when the neighbor at the shared point is the adjacent piece of the same input segment, so pieces of different input curves are no longer merged, and `segs_to_path` starts at the first segment instead of panicking when every segment looks mergeable.", + "In `src/topology.rs`, `Topology::contours` with `Correctness::GoodEnough` builds paths only for the output segments on the boundary of the result, not for every output segment.", + "In `src/segments.rs`, `Segments::add_bez_path` removes the segments it pushed when a subpath is not closed. Without it, adding `M0,0 L10,0 L5,10 Z M20,0 L30,5 L25,10` returns `NonClosedPath` but keeps five segments with no entrances, the last linked to index 5 of a 5-segment arena: `check_invariants` panics with an index out of bounds, and after a closed square is added the open piece is linked into the square and the sweep visits only the square's 4 of 9 segments. With it, the arena is unchanged after the error and the square's 4 segments are all entered. The test `tests::add_bez_path_error_leaves_segments_unchanged` in `src/lib.rs` covers it.", + "In `src/topology.rs`, `contours_for_positions` finds the nearest boundary segment west of each new contour through `Topology::west_boundary`, which remembers the answer for every segment it passes, so each link of a scan-west chain is followed once per call instead of once per contour. Each segment's boundary test runs at most once, when the walk first asks for it.", + "In `src/curve/mod.rs`, `solve_t_for_y` asks for `t` to the precision of f64 instead of to within 1e-12, so comparing near-parallel curves with coordinates near 3e7 or larger no longer recurses into millions of entries.", + "In `src/curve/mod.rs`, `CurveOrder::next_touch_after(y)` walks the order once and compares each touch with `y`, so a touch that follows a touch containing `y` and a Left interval is no longer skipped, which made it return `None`.", + "`checkerboard` and `slanted_checkerboard` count the inner squares as `n.saturating_sub(1)` instead of `n - 1`, so `n = 0` gives empty collections instead of an overflow.", + "`another_monotonic_bezier` returns `arbitrary::Error::IncorrectFormat` when no piece of the generated cubic increases in y, instead of returning that cubic, which can be horizontal.", + "`F64Perturbation::apply` clamps a ulp step on a normal value to infinity when the bits reach the infinity encoding, instead of testing the sign bit, so `Ulp(2)` of `f64::MAX` gives infinity instead of NaN.", + "`ComparisonCache` in `src/order.rs` holds the comparisons of one `Segments` arena. `compare_segments` reads the arena's number, which `src/segments.rs` gives each arena and each clone, and drops the cached comparisons when the number differs from the one they were made with. Before, a cache given a second arena returned the first arena's order for the same pair of indices.", + "In `src/curve/mod.rs`, `fit_quadratic` multiplies the heights by the power of two that brings the largest to between 2 and 4 when one of them has a magnitude above 2^500, does the same to the x coordinates when one of them has a magnitude above 2^500, and scales the coefficients back, and `QuadraticApprox::from_cubic` multiplies by the `y^2` coefficient first when a product of two y coefficients is not finite, so curves taller than about 1.3e154 no longer give NaN coefficients or error bounds that make curve comparisons, and `binary_op`, return a wrong order without an error. The quadratic sign checks of curve comparisons report an unknown (or close) order for a quadratic with a NaN or infinite coefficient. In `src/curve/line.rs`, `intersect_lines` scales the x coordinates and the tolerance by 1/16 when one of them is above 2^1019 and the overlap arithmetic is not finite, and works with half of each height for lines more than `f64::MAX` tall, so coordinates near `f64::MAX` no longer give a wrong order. Finite overlap arithmetic uses the unscaled values, including a subnormal gap beside a distant endpoint. In `src/geom.rs`, `Segment::at_y` and `Segment::to_kurbo_cubic` give finite results for a straight segment more than `f64::MAX` long on either axis. `src/curve/mod.rs`, `src/curve/line.rs`, `src/geom.rs` and `src/lib.rs` add tests for it.", + "In `src/lib.rs`, `src/segments.rs`, `src/sweep/sweep_line.rs` and `src/topology.rs`, `binary_op_with_eps` returns the new `Error::InvalidEps` for an `eps` that is NaN, infinite, zero or negative, and the `Topology` constructors and `Sweeper::new_with_correctness` replace an `eps` that is NaN, infinite, not positive, or below `64 * f64::EPSILON` times the largest coordinate magnitude (and at least 64 times the spacing of subnormal floats) with that value, so a bad `eps` no longer gives a wrong region, a hang or a stack overflow. In `src/curve/mod.rs`, `intersect_cubics` and `intersect_cubics_with_precomputed_decomp` raise a positive `ish_tolerance` below `4 * f64::EPSILON` times the curves' largest x coordinate magnitude (and at least four times the spacing of subnormal floats) to that value and a positive `sure_tolerance` below half of it to half of it, and `intersect_cubics_rec` returns `Ish` for an interval whose midpoint rounds to one of its ends instead of recursing on it again. In `src/position.rs`, `approximate` stops halving such an interval, so `compute_positions_correct` always advances.", + "In `src/curve/mod.rs`, `intersect_cubics_rec` calls the new `order_from_control_points` after cutting both cubics to the shared y-range and before building quadratic approximations. It takes the smallest and largest gap between matching control point x coordinates and widens that range by the largest control point y gap times a bound on `|dx/dy|` from the control polygon (`max_slope`); when the widened range stays more than `ish_tolerance` on one side of zero it records `Left` or `Right` for the whole range and does not recurse. Before the change, a tall S-shaped cubic and a copy moved 10 * `ish_tolerance` sideways took 4,096 recursion leaves at height 1e6 and 16,384 at height 1e8; now each takes one. `curve::test::near_parallel_cubics_are_ordered_without_recursing`, `curve::test::control_point_order_is_sound` and `curve::test::control_point_order_keeps_band_contours` cover it.", + "In `src/order.rs`, `ComparisonCache` stores one `CurveOrder` per pair of segments and flips it for a lookup in the other order, and `ComparisonCache::evict_ended` drops the pairs in which a segment ends above a given height once the cache has doubled since its last scan; `Sweeper::advance` in `src/sweep/sweep_line.rs` and `compute_positions` in `src/position.rs` call it, so the comparison caches no longer keep every compared pair until the sweep ends.", + "In `src/position.rs`, `PositionedOutputSeg::from_cubic` and `from_quad`, and `next_subsegment` for the copied pieces of the strict layout, cut the input curve at the points nearest the output piece's end points, found by Newton steps from the parameters `solve_t_for_y` gives (restarted from the nearest point of the whole curve at a point where a step cannot leave, such as a repeated handle), and move the piece onto its end points: each end moves sideways with its handle (a quadratic's control point by the mean of its ends' moves), and the heights are mapped linearly, so the piece stays monotonic in `y`. `from_cubic` and `from_quad` used to move the inner control points sideways by their height's share of the gap at each end, and `next_subsegment` moved only the end points. Where a curve is almost flat at an end, a tiny error in that end's height is a large gap: the union of `M0,0 C0,1000 300,1000 1000,1000 L1000,2000 L-1000,2000 Z` with a copy moved by (-3.26e-6, -4.66e-8) at eps 1e-6 gave an outline 0.487 from both inputs and 377.8 too large in area, and its union with the rectangle `M998.37,500 L1500,500 L1500,1500 L998.37,1500 Z` gave one 1.05 from both inputs. `src/position.rs` adds the `repeated_end_handle_stays_near_the_end`, `flat_end_shift_stays_near_the_end`, `flat_end_pieces_stay_monotonic`, `flat_end_union_stays_on_the_inputs` and `flat_end_crossing_stays_on_the_inputs` tests for it.", + "In `src/sweep/sweep_line.rs`, `Sweeper::scan_for_removal` starts its intersection scans from the nearest segment left of the removed slot that does not end at the current y, so a crossing between the live segments on both sides of the gap is no longer missed when the slot's left neighbor ends at that y.", + "In `src/lib.rs`, `binary_op` returns the new `Error::FeatureBelowTolerance { eps }` when its automatic `eps` (64 * `f64::EPSILON` times the largest coordinate magnitude) is above `MIN_AUTO_EPS` (1e-6) and an input subpath at least `4 * MIN_AUTO_EPS` wide and high is narrower than `FEATURE_EPS_RATIO * eps` (4 * eps) in x or y, measured on the subpath's exact bounding box. Without it, one far point raises `eps` for every segment and `binary_op` returns `Ok` without the small subpaths: with a triangle at 3e13 (eps 0.43) a 0.3 x 10 sliver near the origin is lost, and at 1e15 (eps 14.2) most of a 10 x 10 square is. The docs of `binary_op` and `binary_op_with_eps` state that `eps` is one absolute tolerance for every segment and that the check does not see a thin part of a larger subpath or a narrow gap between subpaths. The test `tests::far_point_eps` covers it.", + "In `src/sweep/sweep_line.rs`, intersection scans and insertion searches run at the point where two segments start compare them without storing the comparison; `src/order.rs` adds `ComparisonCache::with_order`, which uses a stored comparison or computes one without storing it, and counts each call toward the sweep's work limit as `compare_segments` does. `n` segments that start at one point and do not cross later store `O(n)` comparisons instead of `O(n^2)`; comparisons made at a later crossing are stored as before. The output does not change.", + "In `src/segments.rs`, `update_enter_exit` sorts only the new entrances and exits and merges them into the sorted ones, in the order a stable sort of the whole list gives, instead of sorting the whole list on every call. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add a collection of paths and merge once, as `add_closed_polylines` and `Topology::from_paths` already do, and `add_bez_paths` removes the segments of a path with an open subpath before it returns the error. Without it, adding 2,000 triangles one at a time from the top row down takes 6,006,993 entrance comparisons, and adding n paths one at a time takes time quadratic in n. The tests `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort` and `segments::tests::paths_added_in_height_order_are_not_sorted_again` cover it.", + "In `src/curve/mod.rs`, `intersect_cubics_rec` checks that both curves are on the interval's side at each interval end after re-centering only when the `slow-asserts` feature is on, as the crate's other expensive self-checks are. Re-centering rounds each end, and with finite curves near 1e8 the curves at a rounded end were on the wrong side by up to 69 times `ish_tolerance`, so debug builds panicked with `assertion failed: solve_x_for_y(cubic0.c, y0) > solve_x_for_y(cubic1.c, y0)` or one of its three companions. Release builds already skipped the check, and the change gives debug builds the release result. The test `curve::test::crossing_at_large_coordinates` covers it.", + "In `src/curve/transverse.rs`, `transversal_after` (and `transversal_before`, which calls it) returns `false` when either dy/dt bound is not positive, instead of cross-multiplying the slope bounds, which reverses the comparison for a negative bound.", + "In `src/curve/mod.rs`, `CurveOrder::with_y_slop` keeps the comparison's `metrics` when it changes the entries, instead of returning empty metrics. `y_slop_keeps_metrics` tests it.", + "In `src/sweep/sweep_line.rs`, the doc comment of `SweepLine::line_segment` says it can return a segment that has exited, which `segment_range` leaves out.", + "In `tests/regression.rs`, the test escapes `CARGO_MANIFEST_DIR` with `glob::Pattern::escape` and fails when it finds no inputs, so a checkout path containing `[` no longer gives a passing run of zero cases.", + "In `examples/bus.rs`, the SVG's `viewBox` is the size of the one composite the example draws, with its padding, instead of 3 composites wide and 2 tall.", + "In `src/sweep/range.rs`, `SweepLineRange::events` starts a horizontal fragment at the later of the previous position and the fragment's own start, instead of unwrapping the previous position, which panicked after `increase_x` at the first position and reported a fragment that `increase_x` added from the earlier position. Two tests cover both cases, and the doc comment on `increase_x` says which events it skips.", + "In `src/topology.rs`, building a `Topology` keeps each input segment's open output segments in an inline queue of three that lives only for the sweep, keeps the segment buffers for the whole sweep instead of allocating them per sweep-line range, clones the winding number for horizontals only when one starts at the point, and `can_merge` returns early at a point that is not simple; `segs_to_path` reverses first halves into one reused buffer instead of calling `reverse_subpaths` for each. The nine topology snapshots in `src/snapshots/` no longer list `open_segs`. The contours do not change.", + "`order_from_precomputed_approx` returns no order for a piece whose approximation is almost horizontal, because such an approximation carries the end x values of its whole piece.", + "In `src/sweep/sweep_line.rs` and `src/topology.rs`, two changes make clippy 1.100.0 with `-D warnings` and every feature pass on every registered target: the `slow-asserts` invariant check passes `self.line` to `assert!` without a `&`, and `Contours::grouped` iterates over the contours with `enumerate` instead of indexing them. The behavior does not change.", + "In `src/curve/mod.rs`, when the chord that `fit_quadratic` takes for a very short curve gives a constant term that is not finite, `fit_quadratic` takes the line through the curve's start point with the chord's slope, so a curve near x = 1e305 with heights near 1e4 no longer gives a NaN coefficient. In `src/curve/line.rs`, `line_at_ys` scales the x coordinates by 2^600 before the weighted sum and back after it when both have a magnitude below 2^-500, so a subnormal x coordinate no longer rounds to 0. Both files add tests for it." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, { "path": "CHANGELOG.md", "source_sha256": "70df2144c3ab6858e3857e159590116f7859f3b077ac60fd4a2f510707894dc7", "source_git_blob": null, "sha256": "70df2144c3ab6858e3857e159590116f7859f3b077ac60fd4a2f510707894dc7" }, { "path": "Cargo.lock", "source_sha256": "42d3aea0c577080ff5a23e3213a05a9ca9f0437584ac3f75aeb6d29941417f0c", "source_git_blob": null, "sha256": "42d3aea0c577080ff5a23e3213a05a9ca9f0437584ac3f75aeb6d29941417f0c" }, - { "path": "Cargo.toml", "source_sha256": "2f925d646204059bb3b4e980704b04e9accc5184d9dd24e3ef9ed1751ac6095b", "source_git_blob": null, "sha256": "2f925d646204059bb3b4e980704b04e9accc5184d9dd24e3ef9ed1751ac6095b" }, + { "path": "Cargo.toml", "source_sha256": "2f925d646204059bb3b4e980704b04e9accc5184d9dd24e3ef9ed1751ac6095b", "source_git_blob": null, "sha256": "fa9d9c9e4213354b0d0b3a2c226f0377d2adbc11e7e15d792c8703c009b3340c" }, { "path": "Cargo.toml.orig", "source_sha256": "9ce4a22c92543eb8a2caa9e59ec1e8933c8975f12bad6fef731a0c0fe9c34ced", "source_git_blob": null, "sha256": "9ce4a22c92543eb8a2caa9e59ec1e8933c8975f12bad6fef731a0c0fe9c34ced" }, { "path": "LICENSE-APACHE", "source_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", "source_git_blob": null, "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" }, { "path": "LICENSE-MIT", "source_sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e", "source_git_blob": null, "sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e" }, @@ -34,54 +104,54 @@ { "path": "benches/linebender_logo.rs", "source_sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3", "source_git_blob": null, "sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3" }, { "path": "benches/painted_dreams.rs", "source_sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf", "source_git_blob": null, "sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf" }, { "path": "benches/synthetic.rs", "source_sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810", "source_git_blob": null, "sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810" }, - { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "392f538b00cc4823d4fcec533de062c3315413498c4892cb6140ed6d476a4f47" }, - { "path": "examples/boolean_op.rs", "source_sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f", "source_git_blob": null, "sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f" }, - { "path": "examples/bus.rs", "source_sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33", "source_git_blob": null, "sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33" }, - { "path": "examples/curve_metrics.rs", "source_sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2", "source_git_blob": null, "sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2" }, - { "path": "examples/visualize_op.rs", "source_sha256": "a5210ed389ceb1e9c43b952b992e29e65065d129d2b2f4be62fffc747376bf79", "source_git_blob": null, "sha256": "a5210ed389ceb1e9c43b952b992e29e65065d129d2b2f4be62fffc747376bf79" }, - { "path": "examples/winding-numbers.rs", "source_sha256": "4a756c908564703b165257001e73d2f7235476cd536580091f3a7a70d2eab242", "source_git_blob": null, "sha256": "4a756c908564703b165257001e73d2f7235476cd536580091f3a7a70d2eab242" }, + { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "679ddf9c11eec7883661bde12c14fd0dce3eed634d690a1945fb4386dfad70f4" }, + { "path": "examples/boolean_op.rs", "source_sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f", "source_git_blob": null, "sha256": "7b4f4fc94d3b1fd9b9ee06622b2e8c38bd6c85697d21505b09765139283df576" }, + { "path": "examples/bus.rs", "source_sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33", "source_git_blob": null, "sha256": "cadc2829c1f4dde6948e0246286a07e0c1cf6bb71960859a3f2b77020cd84691" }, + { "path": "examples/curve_metrics.rs", "source_sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2", "source_git_blob": null, "sha256": "18bf2447d7338113b578964b359ee5c4f706be570721abec049ea01d13705ea1" }, + { "path": "examples/visualize_op.rs", "source_sha256": "a5210ed389ceb1e9c43b952b992e29e65065d129d2b2f4be62fffc747376bf79", "source_git_blob": null, "sha256": "e7d3e3f24c346dcabb1072039822c79d40200b313de91c14696c31e1d78c8fc2" }, + { "path": "examples/winding-numbers.rs", "source_sha256": "4a756c908564703b165257001e73d2f7235476cd536580091f3a7a70d2eab242", "source_git_blob": null, "sha256": "7ed7689995b44c5c59ee5bf77eb0a5aeb00ff45de1b7e0fa8f74b88dc8d0ea95" }, { "path": "proptest-regressions/sweep/sweep_line.txt", "source_sha256": "f5311edf1c0c4d1574bb7b24ed1d1c66106d9949214014d0a8479f685938dc98", "source_git_blob": null, "sha256": "f5311edf1c0c4d1574bb7b24ed1d1c66106d9949214014d0a8479f685938dc98" }, { "path": "proptest-regressions/sweep/weak_ordering.txt", "source_sha256": "b5b183ab470399c15246457d8a1a35cafb49fee120d6777dfdd563bfdbadda52", "source_git_blob": null, "sha256": "b5b183ab470399c15246457d8a1a35cafb49fee120d6777dfdd563bfdbadda52" }, { "path": "proptest-regressions/topology.txt", "source_sha256": "49ff0b5b370f082984276d5312f03b1fc96ef0dd218f9efd7b084b11abbb9d19", "source_git_blob": null, "sha256": "49ff0b5b370f082984276d5312f03b1fc96ef0dd218f9efd7b084b11abbb9d19" }, - { "path": "src/arbitrary.rs", "source_sha256": "9c3753a40cfea2528a546295d39e0513537db5a3411a931fccea063873d95750", "source_git_blob": null, "sha256": "9c3753a40cfea2528a546295d39e0513537db5a3411a931fccea063873d95750" }, - { "path": "src/curve/line.rs", "source_sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e", "source_git_blob": null, "sha256": "4cdcb0493a5772eaf64af3ee50b48ddf01e655e3ea0776c5c801cca146671a42" }, - { "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "33b506d2d1d869ac384787825e19779fe40603effb33b40970e4ea6785ae2f84" }, + { "path": "src/arbitrary.rs", "source_sha256": "9c3753a40cfea2528a546295d39e0513537db5a3411a931fccea063873d95750", "source_git_blob": null, "sha256": "188cca0f6b4d40539e0d5ae9b38d72a109ac297aeaac69dd43bbbafa038da17a" }, + { "path": "src/curve/line.rs", "source_sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e", "source_git_blob": null, "sha256": "d7f9c100f483eb4307f55ae5e3841cc6bb14544bbb0326f6c03c2f297e3b5e39" }, + { "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "20c73c9f08ec9967408d7acadb97e2092a13459fe1adcc68e08868d72c2f24c7" }, { "path": "src/curve/split_quad.rs", "source_sha256": "b8aae4ce7c16fa623724f667e1058130a9c7eed693b5b01e8b9e16632b8ec45f", "source_git_blob": null, "sha256": "b8aae4ce7c16fa623724f667e1058130a9c7eed693b5b01e8b9e16632b8ec45f" }, { "path": "src/curve/transverse.rs", "source_sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e", "source_git_blob": null, "sha256": "e1b8658f2b6e0e502bc81d16c393a16a426b6cc1572477ca809ca861fc005de9" }, - { "path": "src/generators.rs", "source_sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef", "source_git_blob": null, "sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef" }, - { "path": "src/geom.rs", "source_sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08", "source_git_blob": null, "sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08" }, - { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6" }, + { "path": "src/generators.rs", "source_sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef", "source_git_blob": null, "sha256": "24b25da4c07a9361b72b324564e2aaa4c2dd9f7d9a6e27dfb1cb1b3d08104edf" }, + { "path": "src/geom.rs", "source_sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08", "source_git_blob": null, "sha256": "b80ff5363060e2e1d1603566df7c517e1881c1904201fc037ab674b59d99da8e" }, + { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "c6cc6ac747eb4865378da59e79790baa1df867d7ae00ab339d39fa706a347aad" }, { "path": "src/num.rs", "source_sha256": "39ff85da50c500ce91cf6dea81aedc0dcca1db5e7d0506696dde2da118e93a2a", "source_git_blob": null, "sha256": "39ff85da50c500ce91cf6dea81aedc0dcca1db5e7d0506696dde2da118e93a2a" }, - { "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596" }, - { "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5" }, - { "path": "src/position.rs", "source_sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0", "source_git_blob": null, "sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0" }, - { "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "717ef16f77623ae020307dff376032c9948aff2f7008bd797507b9f67095d6d0" }, + { "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "316b6cc99a15fa82063ec27ef14e3cbad8c7f380c82d750cebc89953c848ac67" }, + { "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "5030efede9c94b5837f70f2eb3e5447dec772ea1aac3800d162d2fb26da0b929" }, + { "path": "src/position.rs", "source_sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0", "source_git_blob": null, "sha256": "86106cea0fe52d6421b5a53720f267271eb04027686c76955b8c77fa14fa1f43" }, + { "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "047adf1bfa7ba73eae668d327ef49395c4b7251923799778fcb79afb0ad7a824" }, { "path": "src/snapshots/linesweeper__tests__empty_horizontals.snap", "source_sha256": "e319881853e889badf6524f19af4cd6f112e8dd71bdc516826f4463134a82244", "source_git_blob": null, "sha256": "e319881853e889badf6524f19af4cd6f112e8dd71bdc516826f4463134a82244" }, { "path": "src/snapshots/linesweeper__tests__two_squares.snap", "source_sha256": "01961e0311a5af3b8f13eb52a2a7112560c47cf86771c04e40475dc6f15a0846", "source_git_blob": null, "sha256": "01961e0311a5af3b8f13eb52a2a7112560c47cf86771c04e40475dc6f15a0846" }, - { "path": "src/snapshots/linesweeper__topology__tests__diamond.snap", "source_sha256": "cfaefd620a0a3d1376861bca09cd7c658ef00a32635b88f1b259a9b39cd15502", "source_git_blob": null, "sha256": "cfaefd620a0a3d1376861bca09cd7c658ef00a32635b88f1b259a9b39cd15502" }, - { "path": "src/snapshots/linesweeper__topology__tests__inner_loop.snap", "source_sha256": "d6259594f87cc91bf015e9086df94f000c265164d6d361beda4ef0e422947d91", "source_git_blob": null, "sha256": "d6259594f87cc91bf015e9086df94f000c265164d6d361beda4ef0e422947d91" }, - { "path": "src/snapshots/linesweeper__topology__tests__merge_monotonic_segs.snap", "source_sha256": "871db61c9bf44a5d50cd63f3682c72ac19b1ae5d4752d911ac75a2e94c9f8cf5", "source_git_blob": null, "sha256": "871db61c9bf44a5d50cd63f3682c72ac19b1ae5d4752d911ac75a2e94c9f8cf5" }, - { "path": "src/snapshots/linesweeper__topology__tests__merge_monotonic_segs_with_cut.snap", "source_sha256": "0c67eb18012af31d9d5a46ce16e49f3033a4a7bd986bdc41d14cb3d4ce7adf39", "source_git_blob": null, "sha256": "0c67eb18012af31d9d5a46ce16e49f3033a4a7bd986bdc41d14cb3d4ce7adf39" }, - { "path": "src/snapshots/linesweeper__topology__tests__nested_squares.snap", "source_sha256": "212e53e762e633ae8316ce1ba16d94c4f6608573dac6ec3325bf7a9e592c6f8e", "source_git_blob": null, "sha256": "212e53e762e633ae8316ce1ba16d94c4f6608573dac6ec3325bf7a9e592c6f8e" }, - { "path": "src/snapshots/linesweeper__topology__tests__square.snap", "source_sha256": "c0835f86603b9f3aabcb0da22c1dcf597c6575ce9ca72d5ae95bf125f40020e8", "source_git_blob": null, "sha256": "c0835f86603b9f3aabcb0da22c1dcf597c6575ce9ca72d5ae95bf125f40020e8" }, - { "path": "src/snapshots/linesweeper__topology__tests__square_and_diamond.snap", "source_sha256": "6dffc3dc182e133222481d562de20b5e9e39d0ee343088c42f29868d97d1b304", "source_git_blob": null, "sha256": "6dffc3dc182e133222481d562de20b5e9e39d0ee343088c42f29868d97d1b304" }, - { "path": "src/snapshots/linesweeper__topology__tests__square_with_double_back.snap", "source_sha256": "b6709e07eb96d1148269caa9ea39663bb432524e892fffe10f784fa44edb29e0", "source_git_blob": null, "sha256": "b6709e07eb96d1148269caa9ea39663bb432524e892fffe10f784fa44edb29e0" }, - { "path": "src/snapshots/linesweeper__topology__tests__squares_with_gaps.snap", "source_sha256": "52a5e09ecd081f7ace976692a5d5e3549210441f78ad1dc25cd98a4d9d5dceb6", "source_git_blob": null, "sha256": "52a5e09ecd081f7ace976692a5d5e3549210441f78ad1dc25cd98a4d9d5dceb6" }, + { "path": "src/snapshots/linesweeper__topology__tests__diamond.snap", "source_sha256": "cfaefd620a0a3d1376861bca09cd7c658ef00a32635b88f1b259a9b39cd15502", "source_git_blob": null, "sha256": "ee40ad81bbb17f73ac710806aac9c8060e47a3843219dac82c0c0cc9ce18a412" }, + { "path": "src/snapshots/linesweeper__topology__tests__inner_loop.snap", "source_sha256": "d6259594f87cc91bf015e9086df94f000c265164d6d361beda4ef0e422947d91", "source_git_blob": null, "sha256": "98030bc51d64ec78af93167bb810b09269195b992c9cf9d40883fa797437cf62" }, + { "path": "src/snapshots/linesweeper__topology__tests__merge_monotonic_segs.snap", "source_sha256": "871db61c9bf44a5d50cd63f3682c72ac19b1ae5d4752d911ac75a2e94c9f8cf5", "source_git_blob": null, "sha256": "7f9226189c5894be5cb92a84ba32f32fd67b3ed871a090a6b844eb2a4e54668c" }, + { "path": "src/snapshots/linesweeper__topology__tests__merge_monotonic_segs_with_cut.snap", "source_sha256": "0c67eb18012af31d9d5a46ce16e49f3033a4a7bd986bdc41d14cb3d4ce7adf39", "source_git_blob": null, "sha256": "79759a60168b16613aa82b389c46efb05552be33310ab86e3946593b5f726c34" }, + { "path": "src/snapshots/linesweeper__topology__tests__nested_squares.snap", "source_sha256": "212e53e762e633ae8316ce1ba16d94c4f6608573dac6ec3325bf7a9e592c6f8e", "source_git_blob": null, "sha256": "762ad54b122f96bd94248fe1559ea08d680fc92d7e5965e313c20f875673e827" }, + { "path": "src/snapshots/linesweeper__topology__tests__square.snap", "source_sha256": "c0835f86603b9f3aabcb0da22c1dcf597c6575ce9ca72d5ae95bf125f40020e8", "source_git_blob": null, "sha256": "0dbf29a38ba50187aa23fde34022e849d6eaad393d33da6bd5d23ce037db4f55" }, + { "path": "src/snapshots/linesweeper__topology__tests__square_and_diamond.snap", "source_sha256": "6dffc3dc182e133222481d562de20b5e9e39d0ee343088c42f29868d97d1b304", "source_git_blob": null, "sha256": "83acb5cc2026c9cd2056e7ad09010fa648f85ff6f8f6a310b2d8aadee3c6d26b" }, + { "path": "src/snapshots/linesweeper__topology__tests__square_with_double_back.snap", "source_sha256": "b6709e07eb96d1148269caa9ea39663bb432524e892fffe10f784fa44edb29e0", "source_git_blob": null, "sha256": "2223a32b4b5ce6bc701c4e816664675a74ab7db67c74f078eb2c146e8804fbfa" }, + { "path": "src/snapshots/linesweeper__topology__tests__squares_with_gaps.snap", "source_sha256": "52a5e09ecd081f7ace976692a5d5e3549210441f78ad1dc25cd98a4d9d5dceb6", "source_git_blob": null, "sha256": "0d50f2771f16c5e70e9c2d19e24bae9dd6f7add9caa4a04185478ce69d5c67a8" }, { "path": "src/sweep/mod.rs", "source_sha256": "467f783e605be9c5959b10adc3ff53966ca0e95599b3b509bfacb154e82b9257", "source_git_blob": null, "sha256": "467f783e605be9c5959b10adc3ff53966ca0e95599b3b509bfacb154e82b9257" }, - { "path": "src/sweep/output_event.rs", "source_sha256": "220dc6847871ffcd0f782122b55db0a47522866892fb0fb5dd4255cea975fc83", "source_git_blob": null, "sha256": "220dc6847871ffcd0f782122b55db0a47522866892fb0fb5dd4255cea975fc83" }, - { "path": "src/sweep/range.rs", "source_sha256": "924274de47783179f52cea99b370297e8c8d5f05500df4a6ff31e9b927dadd06", "source_git_blob": null, "sha256": "924274de47783179f52cea99b370297e8c8d5f05500df4a6ff31e9b927dadd06" }, + { "path": "src/sweep/output_event.rs", "source_sha256": "220dc6847871ffcd0f782122b55db0a47522866892fb0fb5dd4255cea975fc83", "source_git_blob": null, "sha256": "066cfd6a028c8494cfe2a40c0e2b44557d6e85a305d9a2e83bde0623c513c45d" }, + { "path": "src/sweep/range.rs", "source_sha256": "924274de47783179f52cea99b370297e8c8d5f05500df4a6ff31e9b927dadd06", "source_git_blob": null, "sha256": "d81d938f94aecd68b2f2fd2d8c76c1f3ccb459f1b96bcac054937e1ba9b16164" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__conservative_line_order.snap", "source_sha256": "236d020f646edc3ab199888fd52a0e7d9939bbb1d8b13b6fed52ce508c0e6667", "source_git_blob": null, "sha256": "236d020f646edc3ab199888fd52a0e7d9939bbb1d8b13b6fed52ce508c0e6667" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__regression_position_state.snap", "source_sha256": "be9535fe81604b59e369e6e2c61a67e0203429166dd23e51cd90c644fa3e09db", "source_git_blob": null, "sha256": "be9535fe81604b59e369e6e2c61a67e0203429166dd23e51cd90c644fa3e09db" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, - { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "819e0c41832e3f7c3e5da956156b4ad1c27c8cedab73d0dc3f13f04afb5d7c6d" }, - { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "8729c2dd5941668f3d2805b6562d2d144d4e5156836b894b887394d9d2961aa7" }, - { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "d7264599d1c21e4c2e53c934a08cf2b0896ad9766cfa832bfba3aaca1b8affcf" }, + { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "aa95cc45cb14a18dbcf36b8153d9fbd712b783a59cafce6feccae37351831bc2" }, + { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "e2ccc6bb0f936ac6c6fd09077164a7c5757edb970c1adeea54b3f2f2f2eb6e78" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, { "path": "tests/fonts.rs", "source_sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400", "source_git_blob": null, "sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400" }, - { "path": "tests/paperjs.rs", "source_sha256": "6ff2a3178f13cde3d7304101ae592ae32b4b2734069f5fc56a532a4883d9f782", "source_git_blob": null, "sha256": "6ff2a3178f13cde3d7304101ae592ae32b4b2734069f5fc56a532a4883d9f782" }, - { "path": "tests/regression.rs", "source_sha256": "b2341934aa001ba26c688a1ca3a7ee55d29105d67b6036bb05bb367b69976fce", "source_git_blob": null, "sha256": "b2341934aa001ba26c688a1ca3a7ee55d29105d67b6036bb05bb367b69976fce" }, + { "path": "tests/paperjs.rs", "source_sha256": "6ff2a3178f13cde3d7304101ae592ae32b4b2734069f5fc56a532a4883d9f782", "source_git_blob": null, "sha256": "f98edbb322355ce6d2e318b73d27777cbe25413708a06429d03eddada91c7908" }, + { "path": "tests/regression.rs", "source_sha256": "b2341934aa001ba26c688a1ca3a7ee55d29105d67b6036bb05bb367b69976fce", "source_git_blob": null, "sha256": "cd54aaed5ceea3e28da6cbdcf34fa9701dd2c94098c65302208862fdd5ebce09" }, { "path": "tests/regression/awesome_0.txt", "source_sha256": "6f7dfbb7ca62463843c058617d557553fdc8d8b3add512bee8f813b37a256611", "source_git_blob": null, "sha256": "6f7dfbb7ca62463843c058617d557553fdc8d8b3add512bee8f813b37a256611" }, { "path": "tests/regression/graphite_0.txt", "source_sha256": "f5d9e94ae6fab7d29f8a3aa0ccd9d96fc9b709c0ee3fbae8b000bec8c33628b9", "source_git_blob": null, "sha256": "f5d9e94ae6fab7d29f8a3aa0ccd9d96fc9b709c0ee3fbae8b000bec8c33628b9" }, { "path": "tests/regression/graphite_1.txt", "source_sha256": "96f147b6fc95a71600f60541cc687598e04e9d810dd8a3c57b0f5d8220a72823", "source_git_blob": null, "sha256": "96f147b6fc95a71600f60541cc687598e04e9d810dd8a3c57b0f5d8220a72823" }, diff --git a/vendor/linesweeper/docs/sweep.typ b/vendor/linesweeper/docs/sweep.typ index 838ac03016..26cd607231 100644 --- a/vendor/linesweeper/docs/sweep.typ +++ b/vendor/linesweeper/docs/sweep.typ @@ -640,18 +640,23 @@ Now, if the result of floating point addition or subtraction is subnormal then i for any floating-point $x$ and $y$, if $x - y$ and $x + y$ don't overflow then after rounding they have relative error at most $epsilon_0$. +// Craft patch (ratio lemma): the finite, nonzero denominator assumption and fl(y_1 - y_0) in the proof. #lemma[ - If $y_0 <= y <= y_1$ are floating-point numbers and $epsilon_0 <= 1/2$ then computing $(y - y_0) / (y_1 - y_0)$ + If $y_0 <= y <= y_1$ are floating-point numbers with $y_0 < y_1$, $fl(y_1 - y_0)$ is finite + and $epsilon_0 <= 1/2$ then computing $(y - y_0) / (y_1 - y_0)$ the naive way gives an absolute error of at most $3 epsilon_0 + 4 epsilon_0^2$. ] #proof[ -The assumption $y_0 <= y <= y_1$ ensures that $y - y_0$ and $y_1 - y_0$ do not overflow. Therefore +The assumption that $fl(y_1 - y_0)$ is finite ensures that $y_1 - y_0$ does not overflow, and since +$0 <= y - y_0 <= y_1 - y_0$, neither does $y - y_0$. (The ordering $y_0 <= y <= y_1$ alone is not +enough: with $y_0 = -10^308$, $y = 0$ and $y_1 = 10^308$, $fl(y_1 - y_0)$ is infinite and the computed +ratio is $0$ instead of $1/2$.) Therefore $ fl(y - y_0) &= (y - y_0) (1 plus.minus epsilon_0) \ -fl(y + y_0) &= (y + y_0) (1 plus.minus epsilon_0) +fl(y_1 - y_0) &= (y_1 - y_0) (1 plus.minus epsilon_0) $ and so $ @@ -715,7 +720,8 @@ Next, let's analyze the computation of the $y$ intersection point. #lemma[ Suppose we have two segments $alpha$ and $beta$. Set $y_0 = y_0(alpha) or y_0(beta)$ and $y_1 = y_1(alpha) and y_1(beta)$ (these can be computed exactly). Suppose that we can compute $alpha(y)$ and $beta(y)$ to additive accuracy $epsilon$, -and assume that $beta(y_0) - alpha(y_0) >= 0$ and +and assume that the floating-point additions forming the denominator below are finite, +that $beta(y_0) - alpha(y_0) >= 0$, and $ alpha(y_1) - beta(y_1) > 16/3 (epsilon + 2 epsilon_0 M). $ @@ -794,9 +800,11 @@ the maximum absolute value of these inverse-slopes. ] Putting all this together (and handling the "chamfers" yet): +// Craft patch (ratio lemma): M is a floating-point number, and the proof shows the ratio lemma's assumptions hold. #lemma[ -Assume all line segments are inside the square $[-M/2, M/2]^2$, -and take $delta = 64 epsilon_0 M$. If $epsilon_0 <= 1/4$ then +Assume $M$ is a floating-point number, all line segments are inside the square $[-M/2, M/2]^2$, +and take $delta = 64 epsilon_0 M$. Assume also that the floating-point additions forming the crossing +denominator in @lem-intersection-height-error are finite. If $epsilon_0 <= 1/4$ then - We can compute $x$ coordinates of line segments to additive accuracy $delta/8$. - If $alpha$ $(3 delta)/4$-crosses $beta$, we can compute a crossing height $hat(y)$ such @@ -808,11 +816,14 @@ and take $delta = 64 epsilon_0 M$. If $epsilon_0 <= 1/4$ then #proof[ We compute $x$ coordinates by first computing $t = (y - y_0) / (y_1 - y_0)$ (with error at most $3 epsilon_0 + 4 epsilon_0^2$ by -@lem-ratio-error). Then we apply @lem-convex-combination-error with $epsilon = 3 epsilon_0 + 4 epsilon_0^2$ to see that we +@lem-ratio-error, which applies because a segment that is not horizontal has $y_0 < y_1$, and $fl(y_1 - y_0)$ +is finite because $0 < y_1 - y_0 <= M$ and $M$ is a floating-point number). Then we apply @lem-convex-combination-error with $epsilon = 3 epsilon_0 + 4 epsilon_0^2$ to see that we can compute the horizontal coordinate with error at most $(6 epsilon_0 + 4 epsilon_0^2)M$. If $epsilon_0 <= 1/4$ as we assumed, this is at most $7 epsilon_0 M <= delta/8$. This proves the first claim. For the second claim, we apply @lem-intersection-height-error with $epsilon = (6 epsilon_0 + 4 epsilon_0^2) M$. +Its denominator additions are finite by the additional assumption. The coordinate bound alone does +not imply this: each horizontal difference can be as large as $M$, and their sum can be as large as $2 M$. With this $epsilon$, $epsilon + 2 epsilon_0 M) <= 9 epsilon_0 M$ and so $16/3 (epsilon + 2 epsilon_0 M) <= 48 epsilon_0 M = (3 delta)/4$. Thus, if $alpha$ $(3 delta)/4$-crosses $beta$ then the assumptions of @lem-intersection-height-error are satisfied (and in the conclusion, $4 (epsilon + 2 epsilon_0) M <= 36 epsilon_0 M = (9 delta) /16 $. diff --git a/vendor/linesweeper/examples/boolean_op.rs b/vendor/linesweeper/examples/boolean_op.rs index 58214183f4..46c8772d82 100644 --- a/vendor/linesweeper/examples/boolean_op.rs +++ b/vendor/linesweeper/examples/boolean_op.rs @@ -135,7 +135,8 @@ pub fn main() -> anyhow::Result<()> { let pad = 1.0 + eps; let one_width = max_x - min_x + 2.0 * pad; let one_height = max_y - min_y + 2.0 * pad; - let stroke_width = (max_y - min_y).max(max_x - max_y) / 512.0; + // Craft patch (example stroke width). + let stroke_width = (max_y - min_y).max(max_x - min_x) / 512.0; let mut document = svg::Document::new().set( "viewBox", (min_x - pad, min_y - pad, one_width * 3.0, one_height * 2.0), diff --git a/vendor/linesweeper/examples/bus.rs b/vendor/linesweeper/examples/bus.rs index 88e246022e..1d9757fa3b 100644 --- a/vendor/linesweeper/examples/bus.rs +++ b/vendor/linesweeper/examples/bus.rs @@ -100,10 +100,8 @@ pub fn main() -> anyhow::Result<()> { let pad = 1.0 + eps; let one_width = max_x - min_x + 2.0 * pad; let one_height = max_y - min_y + 2.0 * pad; - let mut doc = svg::Document::new().set( - "viewBox", - (min_x - pad, min_y - pad, one_width * 3.0, one_height * 2.0), - ); + let mut doc = + svg::Document::new().set("viewBox", (min_x - pad, min_y - pad, one_width, one_height)); let contours = top.contours(|w| { let inside = |winding| winding != 0; diff --git a/vendor/linesweeper/examples/curve_metrics.rs b/vendor/linesweeper/examples/curve_metrics.rs index b285911a1a..5144b43e60 100644 --- a/vendor/linesweeper/examples/curve_metrics.rs +++ b/vendor/linesweeper/examples/curve_metrics.rs @@ -106,8 +106,8 @@ fn compare_curves( g } -pub fn main() { - let curves = [ +fn curves() -> [(CubicBez, CubicBez); 10] { + [ (diagonal(), flip(diagonal())), (diagonal(), shift(diagonal(), 0.01)), (c(), vertical()), @@ -118,13 +118,54 @@ pub fn main() { (horiz_at_midpoint(), c()), (horiz_at_midpoint(), flip(horiz_at_midpoint())), (horiz_at_midpoint(), shift(horiz_at_midpoint(), 0.01)), - ]; - let mut doc = - svg::Document::new().set("viewBox", (0.0, 0.0, 5.5, 1.0 + 2.5 * curves.len() as f64)); + ] +} + +fn row_y(i: usize) -> f64 { + i as f64 * 2.5 + 1.5 +} + +fn view_box(rows: usize) -> (f64, f64, f64, f64) { + (-1.5, 0.0, 5.5, 1.0 + 2.5 * rows as f64) +} + +pub fn main() { + let curves = curves(); + let mut doc = svg::Document::new().set("viewBox", view_box(curves.len())); for (i, &(c0, c1)) in curves.iter().enumerate() { - let y = i as f64 * 2.5 + 1.5; + let y = row_y(i); let g = compare_curves(c0, c1, 1e-6, 6).set("transform", format!("translate(0, {y})",)); doc = doc.add(g); } svg::save("out.svg", &doc).unwrap(); } + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::ParamCurveExtrema as _; + + #[test] + fn view_box_holds_every_curve() { + let curves = curves(); + let (x, y, w, h) = view_box(curves.len()); + for (i, &(c0, c1)) in curves.iter().enumerate() { + for c in [c0, c1] { + let b = c.bounding_box(); + assert!( + b.x0 >= x && b.x1 <= x + w, + "row {i}: x {}..{} is outside {x}..{}", + b.x0, + b.x1, + x + w + ); + let (y0, y1) = (b.y0 + row_y(i), b.y1 + row_y(i)); + assert!( + y0 >= y && y1 <= y + h, + "row {i}: y {y0}..{y1} is outside {y}..{}", + y + h + ); + } + } + } +} diff --git a/vendor/linesweeper/examples/visualize_op.rs b/vendor/linesweeper/examples/visualize_op.rs index ec110069fb..b9207d5da2 100644 --- a/vendor/linesweeper/examples/visualize_op.rs +++ b/vendor/linesweeper/examples/visualize_op.rs @@ -10,6 +10,8 @@ use linesweeper::{ topology::{Contours, Topology}, }; +const FILL_RULE: FillRule = FillRule::EvenOdd; + #[derive(Parser)] struct Cli { #[arg(long)] @@ -45,7 +47,7 @@ pub fn main() -> anyhow::Result<()> { let shape_b = BezPath::from_svg(shape_b)?; let eps = 1e-5; - let contours = binary_op(&shape_a, &shape_b, FillRule::EvenOdd, op)?; + let contours = binary_op(&shape_a, &shape_b, FILL_RULE, op)?; let top = Topology::from_paths_binary(&shape_a, &shape_b, eps)?; let bbox = top.bounding_box(); let min_x = bbox.min_x(); @@ -55,7 +57,8 @@ pub fn main() -> anyhow::Result<()> { let pad = 1.0 + eps; let one_width = max_x - min_x + 2.0 * pad; let one_height = max_y - min_y + 2.0 * pad; - let stroke_width = (max_y - min_y).max(max_x - max_y) / 512.0; + // Craft patch (example stroke width). + let stroke_width = stroke_width(bbox); let mut document = svg::Document::new().set( "viewBox", @@ -64,27 +67,7 @@ pub fn main() -> anyhow::Result<()> { // Draw the original document. for (c, color) in [(&shape_a, "green"), (&shape_b, "blue")] { - let mut data = svg::node::element::path::Data::new(); - for el in c { - let p = |point: kurbo::Point| (point.x, point.y); - data = match el { - kurbo::PathEl::MoveTo(p0) => data.move_to(p(p0)), - kurbo::PathEl::LineTo(p0) => data.line_to(p(p0)), - kurbo::PathEl::QuadTo(p0, p1) => data.quadratic_curve_to((p(p0), p(p1))), - kurbo::PathEl::CurveTo(p0, p1, p2) => data.cubic_curve_to((p(p0), p(p1), p(p2))), - kurbo::PathEl::ClosePath => data.close(), - }; - } - - let path = svg::node::element::Path::new() - .set("stroke", "black") - .set("stroke-width", stroke_width) - .set("stroke-linecap", "round") - .set("stroke-linejoin", "round") - .set("opacity", 0.5) - .set("fill", color) - .set("d", data); - document = document.add(path); + document = document.add(input_path(c, color, stroke_width)); } document = add_op(document, &contours, one_width, stroke_width); @@ -94,6 +77,38 @@ pub fn main() -> anyhow::Result<()> { Ok(()) } +// Craft patch (example fill rule): the inputs are drawn with the fill rule the operation uses. +fn svg_fill_rule(fill_rule: FillRule) -> &'static str { + match fill_rule { + FillRule::EvenOdd => "evenodd", + FillRule::NonZero => "nonzero", + } +} + +fn input_path(shape: &BezPath, color: &str, stroke_width: f64) -> svg::node::element::Path { + let mut data = svg::node::element::path::Data::new(); + for el in shape { + let p = |point: kurbo::Point| (point.x, point.y); + data = match el { + kurbo::PathEl::MoveTo(p0) => data.move_to(p(p0)), + kurbo::PathEl::LineTo(p0) => data.line_to(p(p0)), + kurbo::PathEl::QuadTo(p0, p1) => data.quadratic_curve_to((p(p0), p(p1))), + kurbo::PathEl::CurveTo(p0, p1, p2) => data.cubic_curve_to((p(p0), p(p1), p(p2))), + kurbo::PathEl::ClosePath => data.close(), + }; + } + + svg::node::element::Path::new() + .set("stroke", "black") + .set("stroke-width", stroke_width) + .set("stroke-linecap", "round") + .set("stroke-linejoin", "round") + .set("opacity", 0.5) + .set("fill", color) + .set("fill-rule", svg_fill_rule(FILL_RULE)) + .set("d", data) +} + fn add_op(mut doc: Document, contours: &Contours, x_off: f64, stroke_width: f64) -> Document { for group in contours.grouped() { let mut data = svg::node::element::path::Data::new(); @@ -128,3 +143,40 @@ fn add_op(mut doc: Document, contours: &Contours, x_off: f64, stroke_width: f64) } doc } + +// Craft patch (example stroke width): the larger of the bounding box's width +// and height, divided by 512. +fn stroke_width(bbox: kurbo::Rect) -> f64 { + let (min_x, min_y, max_x, max_y) = (bbox.min_x(), bbox.min_y(), bbox.max_x(), bbox.max_y()); + (max_y - min_y).max(max_x - min_x) / 512.0 +} + +// Craft patch (example stroke width). +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stroke_width_follows_the_larger_side() { + let wide = kurbo::Rect::new(0.0, 1000.0, 512.0, 1001.0); + assert_eq!(stroke_width(wide), 1.0); + let tall = kurbo::Rect::new(100.0, 0.0, 101.0, 512.0); + assert_eq!(stroke_width(tall), 1.0); + } + + #[test] + fn inputs_are_drawn_with_the_operation_fill_rule() { + // Two nested squares with the same orientation. Even-odd leaves the inner square + // empty, and nonzero fills it. + let nested = BezPath::from_svg("M0,0 L10,0 L10,10 L0,10 Z M2,2 L8,2 L8,8 L2,8 Z").unwrap(); + let drawn = input_path(&nested, "green", 0.1).to_string(); + assert_eq!(FILL_RULE, FillRule::EvenOdd); + assert!(drawn.contains(r#"fill-rule="evenodd""#), "{drawn}"); + } + + #[test] + fn svg_fill_rule_names() { + assert_eq!(svg_fill_rule(FillRule::EvenOdd), "evenodd"); + assert_eq!(svg_fill_rule(FillRule::NonZero), "nonzero"); + } +} diff --git a/vendor/linesweeper/examples/winding-numbers.rs b/vendor/linesweeper/examples/winding-numbers.rs index 4db6570aaf..5d998fd5a8 100644 --- a/vendor/linesweeper/examples/winding-numbers.rs +++ b/vendor/linesweeper/examples/winding-numbers.rs @@ -31,7 +31,8 @@ pub fn main() -> anyhow::Result<()> { let max_x = bbox.max_x(); let max_y = bbox.max_y(); let pad = 8.0 + eps; - let stroke_width = (max_y - min_y).max(max_x - max_y) / 512.0; + // Craft patch (example stroke width). + let stroke_width = (max_y - min_y).max(max_x - min_x) / 512.0; let dot_radius = stroke_width * 1.5; let mut document = svg::Document::new().set( "viewBox", diff --git a/vendor/linesweeper/src/arbitrary.rs b/vendor/linesweeper/src/arbitrary.rs index 120c7d8522..806cdc60b0 100644 --- a/vendor/linesweeper/src/arbitrary.rs +++ b/vendor/linesweeper/src/arbitrary.rs @@ -6,18 +6,20 @@ use polycool::Quadratic; use crate::geom; -/// Generate an arbitrary float in some range. +/// Generates a float between finite, strictly increasing bounds. Invalid bounds return an error. pub fn float_in_range( start: f64, end: f64, u: &mut Unstructured<'_>, ) -> Result { - if start >= end { + if !start.is_finite() || !end.is_finite() || start >= end { return Err(arbitrary::Error::EmptyChoose); } let num: u32 = u.arbitrary()?; let t = num as f64 / u32::MAX as f64; - Ok((start + t * (end - start)).clamp(start, end)) + // Craft patch (wide float range): `end - start` overflows for a range wider + // than `f64::MAX`, so the value is interpolated from each end. + Ok((start * (1.0 - t) + end * t).clamp(start, end)) } fn float(u: &mut Unstructured<'_>) -> Result { @@ -86,6 +88,9 @@ pub fn monotonic_bezier(u: &mut Unstructured<'_>) -> Result, first: &CubicBez, @@ -105,11 +110,13 @@ pub fn another_monotonic_bezier( let p2 = point_at_most(p3.y, u)?; let ret = CubicBez::new(p0, p1, p2, p3); - Ok(geom::monotonic_cubic_pieces(ret) + // Craft patch (flat cubic): when every control point has the same y there is + // no increasing piece, and returning `ret` gave a horizontal cubic. + geom::monotonic_cubic_pieces(ret) .into_iter() .find(|x| x.piece.end().y > x.piece.start().y) .map(|c| c.piece.to_kurbo_cubic()) - .unwrap_or(ret)) + .ok_or(arbitrary::Error::IncorrectFormat) } /// Generate an arbitrary quadratic function, with coefficients of roughly the scale `size`. @@ -132,3 +139,75 @@ pub fn quadratic(size: f64, u: &mut Unstructured<'_>) -> Result = (0..=255u8) + .cycle() + .take(4096) + .map(|b| b.wrapping_mul(37)) + .collect(); + let mut u = Unstructured::new(&bytes); + while !u.is_empty() { + if let Ok(c) = another_monotonic_bezier(&mut u, &first) { + assert!(c.p3.y > c.p0.y, "{c:?}"); + } + } + } +} diff --git a/vendor/linesweeper/src/curve/line.rs b/vendor/linesweeper/src/curve/line.rs index 5b22cdf46b..f8cabcc455 100644 --- a/vendor/linesweeper/src/curve/line.rs +++ b/vendor/linesweeper/src/curve/line.rs @@ -1,18 +1,29 @@ //! Special-case curve-comparisons for straight lines. -use kurbo::Line; +use kurbo::{Affine, Line}; use crate::curve::{CurveOrder, MetricsStatus, Order}; fn line_at_ys(line: Line, y0: f64, y1: f64) -> (f64, f64) { - let dy_recip = (line.p1.y - line.p0.y).recip(); - let t0 = (y0 - line.p0.y) * dy_recip; - let t1 = (y1 - line.p0.y) * dy_recip; + let dy = line.p1.y - line.p0.y; + let (t0, t1) = if dy.is_finite() { + ((y0 - line.p0.y) / dy, (y1 - line.p0.y) / dy) + } else { + // The line is more than f64::MAX tall, so work with half of each height. + let half_dy = line.p1.y * 0.5 - line.p0.y * 0.5; + ( + (y0 * 0.5 - line.p0.y * 0.5) / half_dy, + (y1 * 0.5 - line.p0.y * 0.5) / half_dy, + ) + }; (x_at_t(line, t0), x_at_t(line, t1)) } /// Returns `(1 - t) * line.p0.x + t * line.p1.x`. fn x_at_t(line: Line, t: f64) -> f64 { + if line.p0.x == line.p1.x { + return line.p0.x; + } // Craft patch (subnormal x): a product of t and a subnormal x coordinate // loses bits, so x = 5e-324 times 0.5 rounds to 0. When both x coordinates // have a magnitude below 2^-500, take the weighted sum of the x coordinates @@ -34,6 +45,31 @@ fn x_at_t(line: Line, t: f64) -> f64 { /// The two line segments must both be increasing in `y`, and their `y` ranges /// must overlap. pub fn intersect_lines(l0: Line, l1: Line, tolerance: f64) -> CurveOrder { + const SCALE_ABOVE: f64 = f64::from_bits((1023 + 1019) << 52); + const SCALE: f64 = 1.0 / 16.0; + let max_x = [l0.p0, l0.p1, l1.p0, l1.p1] + .iter() + .fold(tolerance.abs(), |m, p| m.max(p.x.abs())); + if max_x > SCALE_ABOVE { + let y0 = l0.p0.y.max(l1.p0.y); + let y1 = l0.p1.y.min(l1.p1.y); + let (l0x0, l0x1) = line_at_ys(l0, y0, y1); + let (l1x0, l1x1) = line_at_ys(l1, y0, y1); + let dx0 = l1x0 - l0x0; + let dx1 = l1x1 - l0x1; + if [dx0, dx1, dx0 - dx1, dx0 + tolerance, dx0 - tolerance] + .iter() + .all(|v| v.is_finite()) + { + return intersect_lines_unscaled(l0, l1, tolerance); + } + let scale = Affine::scale_non_uniform(SCALE, 1.0); + return intersect_lines_unscaled(scale * l0, scale * l1, tolerance * SCALE); + } + intersect_lines_unscaled(l0, l1, tolerance) +} + +fn intersect_lines_unscaled(l0: Line, l1: Line, tolerance: f64) -> CurveOrder { let y0 = l0.p0.y.max(l1.p0.y); let y1 = l0.p1.y.min(l1.p1.y); let mut ret = CurveOrder::new(y0); @@ -66,8 +102,22 @@ pub fn intersect_lines(l0: Line, l1: Line, tolerance: f64) -> CurveOrder { // The t at which l0 crosses l1 - tolerance. let t0 = (dx0 + tolerance) / (dx0 - dx1); let t1 = (dx0 - tolerance) / (dx0 - dx1); - let z0 = y0 + (y1 - y0) * t0; - let z1 = y0 + (y1 - y0) * t1; + let height_at = |t: f64| { + let dy = y1 - y0; + if dy.is_finite() { + y0 + dy * t + } else if (0.0..=1.0).contains(&t) { + y0 * (1.0 - t) + y1 * t + } else if t < 0.0 { + f64::NEG_INFINITY + } else if t > 1.0 { + f64::INFINITY + } else { + f64::NAN + } + }; + let z0 = height_at(t0); + let z1 = height_at(t1); // For a second, consider the whole lines and not the segments. If dx0 < dx1, // l0 starts off Left, then they become Ish, then l0 is Right. If dx1 > dx0, @@ -114,6 +164,18 @@ pub fn intersect_lines(l0: Line, l1: Line, tolerance: f64) -> CurveOrder { mod tests { use super::*; + #[test] + fn affine_endpoints_crossing_preserves_an_uneven_overflowing_span() { + let a = 2f64.powi(1023); + let b = a.next_up(); + let fixed = Line::new((0.0, -a), (0.0, b)); + let moving = Line::new((-1.0, -a), (1.0, b)); + let crossing = a.midpoint(-b).abs(); + let order = intersect_lines(fixed, moving, 0.0); + assert_eq!(order.order_at(crossing * 0.5), Order::Right); + assert_eq!(order.order_at(crossing * 1.5), Order::Left); + } + #[test] fn simple_intersection() { let l0 = Line::new((0.0, 0.0), (0.0, 1.0)); @@ -151,6 +213,111 @@ mod tests { assert_eq!(order.cmps[0].order, Order::Left); } + #[test] + fn coincident_vertical_lines_keep_their_exact_x() { + let whole = Line::new((0.1, 0.0), (0.1, 10.0)); + let part = Line::new((0.1, 3.0), (0.1, 10.0)); + for (left, right) in [(whole, part), (part, whole)] { + let order = intersect_lines(left, right, 1e-18); + assert!( + order.cmps.iter().all(|entry| entry.order == Order::Ish), + "{order:?}" + ); + assert_eq!(line_at_ys(left, 3.0, 10.0), (0.1, 0.1)); + } + } + + #[test] + fn unchanging_with_huge_coordinates() { + for x in [1e300, 1e308, f64::MAX] { + let l0 = Line::new((-x, 0.0), (-x, 1.0)); + let l1 = Line::new((x, 0.0), (x, 1.0)); + + let order = intersect_lines(l0, l1, 1e-6); + assert_eq!(order.cmps.len(), 1, "x = {x}"); + assert_eq!(order.cmps[0].order, Order::Left, "x = {x}"); + assert_eq!(order.cmps[0].end, 1.0, "x = {x}"); + } + } + + #[test] + fn overlap_preserves_a_subnormal_gap_beside_a_distant_endpoint() { + let unit = f64::from_bits(1); + let left = Line::new((1e308, 0.0), (0.0, 1.0)); + let right = Line::new((2.0 * unit, 1.0), (2.0 * unit, 2.0)); + for (a, b, expected) in [(left, right, Order::Left), (right, left, Order::Right)] { + let order = intersect_lines(a, b, unit); + assert_eq!(order.start, 1.0); + assert_eq!(order.cmps.len(), 1); + assert_eq!(order.cmps[0].end, 1.0); + assert_eq!(order.cmps[0].order, expected); + } + } + + #[test] + fn huge_coordinates_on_one_axis() { + // Huge x values with a tiny height. + let l0 = Line::new((1e308, 0.0), (1e308, 1e-307)); + let l1 = Line::new((1.1e308, 0.0), (1.1e308, 1e-307)); + let order = intersect_lines(l0, l1, 0.0); + assert_eq!(order.cmps.len(), 1); + assert_eq!(order.cmps[0].order, Order::Left); + assert_eq!(order.cmps[0].end, 1e-307); + + // Lines more than f64::MAX tall, close together in x. + let l0 = Line::new((0.0, -1e308), (0.0, 1e308)); + let l1 = Line::new((1.0, -1e308), (1.0, 1e308)); + let order = intersect_lines(l0, l1, 1e-6); + assert_eq!(order.start, -1e308); + assert_eq!(order.cmps.len(), 1); + assert_eq!(order.cmps[0].order, Order::Left); + assert_eq!(order.cmps[0].end, 1e308); + + // A very short line beside a line more than f64::MAX tall. + let l0 = Line::new((0.0, 1e-308), (0.0, 2e-308)); + let l1 = Line::new((1.0, -1e308), (1.0, 1e308)); + let order = intersect_lines(l0, l1, 1e-6); + assert_eq!(order.cmps.len(), 1); + assert_eq!(order.cmps[0].order, Order::Left); + assert_eq!(order.cmps[0].end, 2e-308); + + // Lines more than f64::MAX tall that cross at y = 0. + let l0 = Line::new((-1.0, -1e308), (1.0, 1e308)); + let l1 = Line::new((1.0, -1e308), (-1.0, 1e308)); + let order = intersect_lines(l0, l1, 1e-6); + let orders: Vec<_> = order.cmps.iter().map(|c| c.order).collect(); + assert_eq!(orders, [Order::Left, Order::Ish, Order::Right]); + assert!((-1e303..0.0).contains(&order.cmps[0].end), "{order:?}"); + assert!((0.0..1e303).contains(&order.cmps[1].end), "{order:?}"); + assert_eq!(order.cmps[2].end, 1e308); + } + + #[test] + fn subnormal_height() { + let h = 1e-310; + let l0 = Line::new((0.0, 0.0), (0.0, h)); + let l1 = Line::new((1.0, 0.0), (1.0, h)); + let order = intersect_lines(l0, l1, 1e-6); + assert_eq!(order.cmps.len(), 1); + assert_eq!(order.cmps[0].order, Order::Left); + assert_eq!(order.cmps[0].end, h); + } + + #[test] + fn subnormal_sloped_lines_keep_interior_overlap_coordinates() { + let h = 1e-310; + let sloped = Line::new((0.0, 0.0), (4.0, h)); + let (x0, x1) = super::line_at_ys(sloped, h * 0.25, h * 0.75); + assert!((x0 - 1.0).abs() < 1e-12, "{x0}"); + assert!((x1 - 3.0).abs() < 1e-12, "{x1}"); + let other = Line::new((5.0, h * 0.25), (6.0, h * 0.75)); + let order = intersect_lines(sloped, other, 1e-6); + assert_eq!(order.start, h * 0.25); + assert_eq!(order.cmps.len(), 1); + assert_eq!(order.cmps[0].order, Order::Left); + assert_eq!(order.cmps[0].end, h * 0.75); + } + #[test] fn close_near_endpoint() { let l0 = Line::new((0.0, 0.0), (0.0, 1.0)); @@ -172,6 +339,17 @@ mod tests { assert!((order.cmps[0].end - 1.0).abs() < 1e-5); } + #[test] + fn subnormal_span() { + let l0 = Line::new((-1.0, 0.0), (-1.0, 1e-310)); + let l1 = Line::new((1.0, 0.0), (1.0, 1e-310)); + + let order = intersect_lines(l0, l1, 1e-6); + assert_eq!(order.cmps.len(), 1); + assert_eq!(order.cmps[0].order, Order::Left); + assert_eq!(order.cmps[0].end, 1e-310); + } + #[test] fn subnormal_x() { let x = f64::from_bits(1); diff --git a/vendor/linesweeper/src/curve/mod.rs b/vendor/linesweeper/src/curve/mod.rs index 1b6f5f124f..d1bf5318a6 100644 --- a/vendor/linesweeper/src/curve/mod.rs +++ b/vendor/linesweeper/src/curve/mod.rs @@ -30,10 +30,14 @@ impl CurveOrderEntry { /// Observability for the curve comparison algorithm, recording recursion /// depth by y-interval. +/// +/// Entries are recorded only with the `metrics` feature. Without it, +/// `entries` is always empty. #[derive(Clone, Debug, PartialEq, Default)] pub struct Metrics { + // Craft patch (inline metrics): a `SmallVec` replaces the package's `Vec`. /// Each interval records a single recursion depth measurement. - pub entries: Vec, + pub entries: SmallVec<[MetricsEntry; 2]>, } /// A single observability entry. @@ -131,7 +135,7 @@ impl Iterator for CurveOrderIter<'_, T> { // TODO: we've grown a weird set of convenience methods. Design them better. impl CurveOrder { - fn new(start: f64) -> Self { + pub(crate) fn new(start: f64) -> Self { CurveOrder { start, cmps: SmallVec::new(), @@ -139,8 +143,23 @@ impl CurveOrder { } } + // Craft patch (far-apart comparison). + /// A curve order with the same order at all heights between `start` and `end`. + pub(crate) fn constant(start: f64, end: f64, order: Order) -> Self { + let mut ret = CurveOrder::new(start); + ret.push(end, order, MetricsStatus::default()); + ret + } + fn push(&mut self, end: f64, order: Order, status: MetricsStatus) { - self.metrics.entries.push(MetricsEntry::new(end, status)); + // Craft patch (metrics opt-in): an entry is pushed for every interval + // of every comparison, and `flip` clones them, so they are recorded + // only with the `metrics` feature. + if cfg!(feature = "metrics") { + self.metrics.entries.push(MetricsEntry::new(end, status)); + } + #[cfg(test)] + CURVE_ORDER_PUSHES.with(|n| n.set(n.get() + 1)); if let Some(last) = self.cmps.last_mut() { match (last.order, order) { (Order::Right, Order::Right) @@ -157,8 +176,10 @@ impl CurveOrder { // What we do is insert a zero-height "ish" interval. Then // adding y-slop will turn it into a taller interval. debug_assert!(end >= last.end); + // Craft patch (zero-height Ish): the package ended this entry at `end`. + let ish_end = last.end; self.cmps.push(CurveOrderEntry { - end, + end: ish_end, order: Order::Ish, }); self.cmps.push(CurveOrderEntry { end, order }); @@ -192,6 +213,22 @@ impl CurveOrder { } } + // Craft patch (comparison cache size): writes the result of `flip` into + // `out`, reusing the allocations that `out` already holds. + pub(crate) fn flip_into(&self, out: &mut CurveOrder) { + out.start = self.start; + out.cmps.clear(); + out.cmps.extend(self.cmps.iter().map(CurveOrderEntry::flip)); + out.metrics.entries.clone_from(&self.metrics.entries); + } + + pub(crate) fn is_flip_of(&self, other: &CurveOrder) -> bool { + self.start == other.start + && self.metrics == other.metrics + && self.cmps.len() == other.cmps.len() + && self.cmps.iter().zip(&other.cmps).all(|(a, b)| *a == b.flip()) + } + /// Imagine that our curve is to the left of the other curve at height `y`. /// What's the next height at which they touch? /// @@ -202,33 +239,36 @@ impl CurveOrder { &self, y: f64, ) -> Option { - let mut iter = self - .iter() - .skip_while(|(_start, end, _order)| end <= &y) - .skip_while(|(_start, _end, order)| *order == Order::Left); + let mut iter = self.iter().skip_while(|(_start, end, _order)| end <= &y); + // The height that a crossing found right away is reported at. + let mut from = y; - let (y0, y1, order) = iter.next()?; - if order == Order::Right { - return Some(CurveInteraction::Cross(y, y)); - } - - let Some((_, next_y1, next_order)) = iter.next() else { - return Some(CurveInteraction::Touch(y0, y1)); - }; - - match next_order { - Order::Right => Some(CurveInteraction::Cross(y0, y1)), - Order::Left => { - if y < y0 { - Some(CurveInteraction::Touch(y0, y1)) - } else { - self.next_touch_after(next_y1) - } + loop { + let (y0, y1, order) = iter.find(|(_start, _end, order)| *order != Order::Left)?; + if order == Order::Right { + return Some(CurveInteraction::Cross(from, from)); } - Order::Ish => { - // The current order is Ish and adjacent orders get merged, - // so the next one isn't Ish. - unreachable!(); + + let Some((_, next_y1, next_order)) = iter.next() else { + return Some(CurveInteraction::Touch(y0, y1)); + }; + + match next_order { + Order::Right => return Some(CurveInteraction::Cross(y0, y1)), + Order::Left => { + if y < y0 { + return Some(CurveInteraction::Touch(y0, y1)); + } + // `y` is inside this Ish interval, so look for the next + // one. It starts after `y`, so it is compared with `y` + // and not with the end of the Left interval before it. + from = next_y1; + } + Order::Ish => { + // The current order is Ish and adjacent orders get merged, + // so the next one isn't Ish. + unreachable!(); + } } } } @@ -263,8 +303,11 @@ impl CurveOrder { let mut ret = SmallVec::<[CurveOrderEntry; 3]>::new(); - // unwrap: cmps is always non-empty - let last_end = self.cmps.last().unwrap().end; + // Craft patch (input rules): curves with disjoint vertical ranges have + // an empty order. + let Some(last_end) = self.cmps.last().map(|e| e.end) else { + return self; + }; if self.start == last_end || self.cmps.len() <= 1 { return self; @@ -314,14 +357,16 @@ impl CurveOrder { CurveOrder { start: self.start, cmps: ret, - metrics: Metrics::default(), + metrics: self.metrics, } } /// Asserts that we satisfy our internal invariants. For testing only. pub fn check_invariants(&self) { let mut cmps = self.cmps.iter(); - let mut last = cmps.next().unwrap(); + let Some(mut last) = cmps.next() else { + return; + }; for cmp in cmps { assert!(last.end <= cmp.end); assert!(last.order != cmp.order); @@ -365,8 +410,13 @@ impl CurveOrder { /// As a corner case, if this comparison ends exactly at `y` then we return /// the ordering exactly at `y`. pub fn order_after(&self, y: f64) -> Order { - if y == self.cmps.last().unwrap().end { - self.cmps.last().unwrap().order + // Craft patch (input rules): curves with disjoint vertical ranges have + // an empty order. + let Some(last) = self.cmps.last() else { + return Order::Ish; + }; + if y == last.end { + last.order } else { self.iter() .skip_while(|(_start, end, _order)| end <= &y) @@ -377,6 +427,17 @@ impl CurveOrder { } /// Find the parameter `t` at which `c` crosses height `y`. +/// +/// `c` must be y-monotone with `c.p0.y < c.p3.y`, and `y` must be in +/// `c.p0.y..=c.p3.y`. For other inputs, release builds return a parameter in +/// `0.0..=1.0` that need not be a crossing. +/// +/// # Panics +/// +/// Debug builds panic unless `c.p0.y <= y && y <= c.p3.y && c.p0.y < c.p3.y`. +/// They do not check whether `c` is y-monotone. For a curve that is not, they +/// return one of its crossings, or a parameter that is not a crossing, without +/// a panic. pub fn solve_t_for_y(c: CubicBez, y: f64) -> f64 { debug_assert!( c.p0.y <= y && y <= c.p3.y && c.p0.y < c.p3.y, @@ -390,13 +451,34 @@ pub fn solve_t_for_y(c: CubicBez, y: f64) -> f64 { return 1.0; } - let c3 = c.p3.y - 3.0 * c.p2.y + 3.0 * c.p1.y - c.p0.y; - let c2 = 3.0 * (c.p2.y - 2.0 * c.p1.y + c.p0.y); - let c1 = 3.0 * (c.p1.y - c.p0.y); - let c0 = c.p0.y - y; + // The coefficients below, and the derivative and sums that polycool forms from them, reach + // about 28 times the largest height. Above `f64::MAX / 32` they can overflow to infinity, + // and polycool's critical point search then recurses until the stack overflows. Dividing + // every height by 32 is exact and does not move the root. + let heights = [c.p0.y, c.p1.y, c.p2.y, c.p3.y, y]; + let max_height = heights.iter().fold(0.0f64, |m, h| m.max(h.abs())); + let scale = if max_height > f64::MAX / 32.0 { + 1.0 / 32.0 + } else { + 1.0 + }; + let [p0, p1, p2, p3, target] = heights.map(|h| h * scale); + + let c3 = p3 - 3.0 * p2 + 3.0 * p1 - p0; + let c2 = 3.0 * (p2 - 2.0 * p1 + p0); + let c1 = 3.0 * (p1 - p0); + let c0 = p0 - target; let cubic = Cubic::new([c0, c1, c2, c3]); - let eps = 1e-12; + // Craft patch (near-parallel t tolerance): the package asked for `t` to + // within 1e-12. A `t` that is off by `dt` moves x by `|dx/dt| * dt`, + // which grows with the coordinates while the comparison tolerance does + // not, so near 3e7 the pieces that `y_subsegment` cuts moved by tens of + // tolerances and `intersect_cubics_rec` split near-parallel curves into + // y intervals shorter than the tolerance. With an `x_error` of zero the + // root finder stops when its step is zero or its bracket reaches + // adjacent floats. + let eps = 0.0; let roots = cubic.roots_between(0.0, 1.0, eps); if !roots.is_empty() { return roots[0]; @@ -426,6 +508,15 @@ pub fn solve_x_for_y(c: CubicBez, y: f64) -> f64 { /// /// The input curve should be monotonic in `y`, and its range should include /// `y0` and `y1` (which should be ordered). +/// +/// For other inputs, release builds return a curve that starts at height `y0` +/// and ends at height `y1`, but whose ends need not lie on `c`. With `y0 > y1` +/// it runs from `y0` down to `y1`. +/// +/// # Panics +/// +/// Debug builds panic when `y0` is not less than `y1` or when `c` does not +/// cover `y0..=y1`. They do not check whether `c` is y-monotone. pub fn y_subsegment(c: CubicBez, y0: f64, y1: f64) -> CubicBez { debug_assert!(y0 < y1); debug_assert!(c.p0.y <= y0 && y1 <= c.p3.y); @@ -632,6 +723,30 @@ impl ApproxComparison { } } +/// Craft patch (quadratic scale): when `b * b` or `a * c` would underflow or +/// overflow, multiplies `c`, `b` and `a` by one power of two so that the larger +/// of the two is near 1, keeping every coefficient below `2^1021`. Otherwise it +/// returns them unchanged. Multiplying all three by the same power of two does +/// not move the roots. +fn balance_quadratic(c: f64, b: f64, a: f64) -> (f64, f64, f64) { + if !(c.is_finite() && b.is_finite() && a.is_finite()) { + return (c, b, a); + } + let exp = |x: f64| (x != 0.0).then(|| x.abs().log2().floor() as i32); + let (ec, eb, ea) = (exp(c), exp(b), exp(a)); + let square = eb.map(|e| 2 * e); + let product = ea.zip(ec).map(|(ea, ec)| ea + ec); + let (Some(e), Some(max)) = (square.max(product), ec.max(eb).max(ea)) else { + return (c, b, a); + }; + if (-1000..=1000).contains(&e) { + return (c, b, a); + } + let k = (-e.div_euclid(2)).min(1020 - max); + let (s1, s2) = (2f64.powi(k / 2), 2f64.powi(k - k / 2)); + (c * s1 * s2, b * s1 * s2, a * s1 * s2) +} + /// Partitions the real line according to the sign of `q`. The return value is /// `(initially_positive, r0, r1)`, where `r0 < r1`. If `initially_positive`, /// the quadratic is positive up to `r0`, then negative up to `r1`, and then @@ -643,7 +758,8 @@ impl ApproxComparison { /// and then negative from there until `r1`. pub(crate) fn quadratic_signs(q: Quadratic) -> (bool, f64, f64) { let &[c, b, a] = q.coeffs(); - let disc = b * b - 4.0 * a * c; + let (c, b, a) = balance_quadratic(c, b, a); + let disc = b * b - 4.0 * (a * c); // The handling of b here is a little confusing, and it has to do with how // the "roots" come out in the linear case. If a is zero, and b is not we // find roots at `-a.signum() * b.signum() * f64::INFINITY` and something @@ -704,6 +820,34 @@ pub(crate) fn quadratic_signs(q: Quadratic) -> (bool, f64, f64) { (!initially_negative, r1, r2) } +/// Returns true if every coefficient of `q` is finite. +fn has_finite_coeffs(q: Quadratic) -> bool { + q.coeffs().iter().all(|c| c.is_finite()) +} + +/// Pushes `Left` to `out` where `q` is negative and `Ish` where it is positive, +/// restricted to the interval between `y0` and `y1`. If a coefficient of `q` +/// is not finite, the whole interval is `Ish`. +fn push_left_or_ish( + q: Quadratic, + y0: f64, + y1: f64, + out: &mut ArrayVec, CAP>, +) { + if has_finite_coeffs(q) { + push_quadratic_sign(q, Order::Left, Order::Ish, y0, y1, out); + } else if y1 > y0 { + let order = Order::Ish.into(); + if let Some(e) = out.last_mut() + && e.order == order + { + e.end = y1; + } else { + out.push(CurveEntry { end: y1, order }); + } + } +} + /// Populates `out` according to the sign of `q`, restricted to /// the interval between `y0` and `y1`. `neg` is the value to put /// in `out` when `q` is negative, and `pos` is the value to put in @@ -780,6 +924,13 @@ fn push_two_level_quadratic_signs( let lower_q = raise_quadratic(q, -lower); let upper_q = raise_quadratic(q, -upper); + // A coefficient that is NaN or infinite says nothing about the sign, so the + // order over the whole interval is unknown. + if !has_finite_coeffs(lower_q) || !has_finite_coeffs(upper_q) { + push(y1, MaybeOrder::Unknown); + return; + } + let (lower_initially_positive, r_lower, s_lower) = quadratic_signs(lower_q); let (upper_initially_positive, r_upper, s_upper) = quadratic_signs(upper_q); // dbg!(r_lower, s_lower, r_upper, s_upper); @@ -814,7 +965,7 @@ fn push_two_level_quadratic_signs( /// An axis-aligned quadratic approximation to a cubic Bézier. /// -/// The quadratic here gives `y` as a function of `x`. +/// The quadratic here gives `x` as a function of `y`. #[derive(Clone, Copy, Debug)] pub struct QuadraticApprox { /// The quadratic approximation. @@ -882,12 +1033,31 @@ impl QuadraticApprox { let x = cubic_from_bez_x(c); let [y0, y1, y2, y3] = *y.coeffs(); let [x0, x1, x2, x3] = *x.coeffs(); + // A product of two y coefficients overflows once the curve is taller than about + // 1e154. `c2` is then small enough that `c2` times the product is finite, so in + // that case these multiply by `c2` before the second factor. + let c2_times = |a: f64, b: f64| { + let prod = a * b; + if prod.is_finite() { + c2 * prod + } else { + c2 * a * b + } + }; + let c2_times_sum = |k: f64, a: f64, b: f64, c: f64, d: f64| { + let sum = a * b + c * d; + if sum.is_finite() { + c2 * k * sum + } else { + c2 * k * a * b + c2 * k * c * d + } + }; let error = Poly::new([ c0 + c1 * y0 + c2 * y0 * y0 - x0, - c1 * y1 + c2 * (2.0 * y0 * y1) - x1, - c1 * y2 + c2 * (2.0 * y0 * y2 + y1 * y1) - x2, - c1 * y3 + c2 * 2.0 * (y0 * y3 + y1 * y2) - x3, - c2 * (2.0 * y1 * y3 + y2 * y2), + c1 * y1 + c2_times(2.0 * y0, y1) - x1, + c1 * y2 + c2_times_sum(1.0, 2.0 * y0, y2, y1, y1) - x2, + c1 * y3 + c2_times_sum(2.0, y0, y3, y1, y2) - x3, + c2_times_sum(1.0, 2.0 * y1, y3, y2, y2), c2 * 2.0 * y2 * y3, c2 * y3 * y3, ]); @@ -1039,7 +1209,7 @@ impl QuadraticApprox { let r = r.unwrap_or_else(|| self.middle_bound(Bound::Right, tolerance, outer_bound)); let l = l.unwrap_or_else(|| other.middle_bound(Bound::Left, tolerance, outer_bound)); let end = (y0 + tolerance).min(y1); - push_quadratic_sign(r - l, Order::Left, Order::Ish, y0, end, &mut buf.entries); + push_left_or_ish(r - l, y0, end, &mut buf.entries); y0 = end; } @@ -1054,14 +1224,14 @@ impl QuadraticApprox { if end > y0 { let r = self.middle_bound(Bound::Right, tolerance, outer_bound); let l = other.middle_bound(Bound::Left, tolerance, outer_bound); - push_quadratic_sign(r - l, Order::Left, Order::Ish, y0, end, &mut buf.entries); + push_left_or_ish(r - l, y0, end, &mut buf.entries); y0 = end; } if y0 < y1 { let r = r.unwrap_or_else(|| self.middle_bound(Bound::Right, tolerance, outer_bound)); let l = l.unwrap_or_else(|| other.middle_bound(Bound::Left, tolerance, outer_bound)); - push_quadratic_sign(r - l, Order::Left, Order::Ish, y0, y1, &mut buf.entries); + push_left_or_ish(r - l, y0, y1, &mut buf.entries); } buf @@ -1154,17 +1324,64 @@ fn fit_quadratic(c: CubicBez) -> Quadratic { return Quadratic::new([c0, c1, 0.0]); } - let p = interpolate_quadratic(p0.y, p0.x, p1.y, p1.x, p2.y, p2.x); - let q = interpolate_quadratic(p0.y, 1.0, p1.y, -1.0, p2.y, 1.0); + // The interpolation multiplies two heights together, which overflows once a + // height passes about 1.3e154, and the coefficients of `q` below are about + // 1 / height^2, which underflows there. When a height is above 2^500, fit in + // the heights times the power of two `s` that brings the largest height to + // between 2 and 4, and scale the coefficients back at the end. Multiplying + // by a power of two is exact for normal numbers, and multiplying by 1 + // changes nothing. The interpolation divides each x coordinate by a product + // of two height differences, which overflows for x coordinates near f64::MAX + // once the heights are scaled down, so the x coordinates are scaled the same + // way when one of them is above 2^500. + let ys = [p0.y, p1.y, p2.y, p3.y]; + let xs = [p0.x, p1.x, p2.x, p3.x]; + let k_s = pow2_scale_exponent(&ys); + let k_r = pow2_scale_exponent(&xs); + let s = pow2(k_s); + let r = pow2(k_r); + let p = interpolate_quadratic(p0.y * s, p0.x * r, p1.y * s, p1.x * r, p2.y * s, p2.x * r); + let q = interpolate_quadratic(p0.y * s, 1.0, p1.y * s, -1.0, p2.y * s, 1.0); // Note that the denominator won't be small (assuming that p0.y, p1.y, p2.y, // p3.y are ordered), because q(p2.y) is 1, and q has already had two sign // changes before p2.y, so it can't change sign again. - let e = (p.eval(p3.y) - p3.x) / (q.eval(p3.y) + 1.0); + let e = (p.eval(p3.y * s) - p3.x * r) / (q.eval(p3.y * s) + 1.0); let p = p.coeffs(); let q = q.coeffs(); - Quadratic::new([p[0] - q[0] * e, p[1] - q[1] * e, p[2] - q[2] * e]) + Quadratic::new([ + mul_pow2(p[0] - q[0] * e, -k_r), + mul_pow2(p[1] - q[1] * e, k_s - k_r), + mul_pow2(p[2] - q[2] * e, 2 * k_s - k_r), + ]) +} + +/// Returns the exponent `k` for which `2^k` times the largest absolute value in +/// `vals` is between 2 and 4, if that value is finite and above 2^500, and 0 +/// otherwise. The result is in `-1022..=-500` or is 0. +fn pow2_scale_exponent(vals: &[f64]) -> i32 { + let max = vals.iter().fold(0.0f64, |m, v| m.max(v.abs())); + if max > f64::from_bits((1023 + 500) << 52) && max.is_finite() { + // The biased exponent of max is in 1523..=2046. + let biased_exp = ((max.to_bits() >> 52) & 0x7ff) as i32; + 1024 - biased_exp + } else { + 0 + } +} + +/// Returns 2^k for k in `-1022..=1023`. +fn pow2(k: i32) -> f64 { + debug_assert!((-1022..=1023).contains(&k)); + f64::from_bits(((k + 1023) as u64) << 52) +} + +/// Returns `c` times 2^k for k in `-2044..=2046`, in two steps so that no +/// intermediate value overflows or underflows unless the result does. +fn mul_pow2(c: f64, k: i32) -> f64 { + let half = k / 2; + c * pow2(half) * pow2(k - half) } #[allow(dead_code)] @@ -1201,6 +1418,105 @@ fn max_distance(c0: CubicBez, c1: CubicBez) -> f64 { .max(l_infty_distance(c0.p3, c1.p3)) } +/// The largest absolute value of any control point's x coordinate. +fn max_abs_x(c: CubicBez) -> f64 { + [c.p0, c.p1, c.p2, c.p3] + .iter() + .fold(0.0, |m: f64, p| m.max(p.x.abs())) +} + +/// The spacing of the smallest floats, which is also the spacing of all +/// subnormal floats. +const MIN_SPACING: f64 = f64::from_bits(1); + +/// The smallest tolerance that tells apart coordinates of magnitude up to +/// `max_coord`: `64 * f64::EPSILON * max_coord`, the scale [`crate::binary_op`] +/// uses, and never below 64 times the spacing of subnormal floats. +pub(crate) fn resolution_floor(max_coord: f64) -> f64 { + (max_coord * (f64::EPSILON * 64.0)).max(MIN_SPACING * 64.0) +} + +/// `f64::EPSILON * max_coord`, between one and two ulps of `max_coord`, and +/// never below the spacing of subnormal floats. +fn float_spacing(max_coord: f64) -> f64 { + (max_coord * f64::EPSILON).max(MIN_SPACING) +} + +// Craft patch (control point order): two y-subsegments that stay more than +// `ish_tolerance` apart get one order from their control points without +// recursing. At parameter t the gap `x1(t) - x0(t)` lies between the smallest +// and largest control point x gaps, and `|y1(t) - y0(t)|` is at most the +// largest control point y gap `dy`. At one height y = y0(t0) = y1(t1), the gap +// `x1(t1) - x0(t0)` differs from `x1(t1) - x0(t1)` by at most `slope * dy`, +// where `slope` bounds `|dx/dy|` on c0 (and symmetrically for c1). When `dy` +// is zero both curves reach each height at the same t, so no slope is needed. +fn order_from_control_points(c0: CubicBez, c1: CubicBez, ish_tolerance: f64) -> Option { + let gaps = [ + c1.p0.x - c0.p0.x, + c1.p1.x - c0.p1.x, + c1.p2.x - c0.p2.x, + c1.p3.x - c0.p3.x, + ]; + if !gaps.iter().all(|g| g.is_finite()) { + return None; + } + let min_gap = gaps.iter().copied().fold(f64::INFINITY, f64::min); + let max_gap = gaps.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let dy = (c1.p0.y - c0.p0.y) + .abs() + .max((c1.p1.y - c0.p1.y).abs()) + .max((c1.p2.y - c0.p2.y).abs()) + .max((c1.p3.y - c0.p3.y).abs()); + let slack = if dy == 0.0 { + 0.0 + } else { + dy * max_slope(c0).min(max_slope(c1)) + }; + if !slack.is_finite() { + return None; + } + if min_gap - slack > ish_tolerance { + Some(Order::Left) + } else if max_gap + slack < -ish_tolerance { + Some(Order::Right) + } else { + None + } +} + +// Craft patch (control point order): an upper bound on `|dx/dy|` along `c`, +// or infinity unless every leg of the control polygon rises in y. The +// derivative is a positive combination of the legs, so the largest leg ratio +// bounds it. +fn max_slope(c: CubicBez) -> f64 { + let mut ret = 0.0f64; + for (a, b) in [(c.p0, c.p1), (c.p1, c.p2), (c.p2, c.p3)] { + let dy = b.y - a.y; + if !dy.is_finite() || dy <= 0.0 { + return f64::INFINITY; + } + ret = ret.max((b.x - a.x).abs() / dy); + } + ret +} + +#[cfg(test)] +thread_local! { + static SKIP_CONTROL_POINT_ORDER: std::cell::Cell = const { std::cell::Cell::new(false) }; + // Counts `CurveOrder::push` calls on this thread, with or without the `metrics` feature. + static CURVE_ORDER_PUSHES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(not(test))] +fn control_point_order_enabled() -> bool { + true +} + +#[cfg(test)] +fn control_point_order_enabled() -> bool { + !SKIP_CONTROL_POINT_ORDER.with(std::cell::Cell::get) +} + #[derive(Clone, Debug)] struct CubicParams { c: CubicBez, @@ -1246,10 +1562,20 @@ fn intersect_cubics_rec( out.push(y1, order, status); return; } + // Craft patch (control point order): almost-horizontal pieces skip this, + // because their comparison also widens each curve by the tolerance in y. + if control_point_order_enabled() + && cubic0.dir.is_none() + && cubic1.dir.is_none() + && let Some(order) = order_from_control_points(c0, c1, ish_tolerance) + { + out.push(y1, order, status); + return; + } // If the y coordinates are very off-center, the quadratic coefficients become // large and cause instability. So we re-center and then compensate afterwards. - let y_mid = (y0 + y1) / 2.0; + let y_mid = y0.midpoint(y1); c0.p0.y -= y_mid; c0.p1.y -= y_mid; c0.p2.y -= y_mid; @@ -1261,12 +1587,18 @@ fn intersect_cubics_rec( // TODO: document the precomputed approximation let (ep0, ep1) = if use_precomputed_approx { - let orig_y_mid0 = (cubic0.c.p0.y + cubic0.c.p3.y) / 2.0; - let orig_y_mid1 = (cubic1.c.p0.y + cubic1.c.p3.y) / 2.0; - ( - cubic0.approx.shift_y(orig_y_mid0 - y_mid), - cubic1.approx.shift_y(orig_y_mid1 - y_mid), - ) + let orig_y_mid0 = cubic0.c.p0.y.midpoint(cubic0.c.p3.y); + let orig_y_mid1 = cubic1.c.p0.y.midpoint(cubic1.c.p3.y); + let mut ep0 = cubic0.approx.shift_y(orig_y_mid0 - y_mid); + let mut ep1 = cubic1.approx.shift_y(orig_y_mid1 - y_mid); + // Craft patch (cut end bounds): the precomputed approximations carry the + // end x values of the whole pieces, which are not the ends of `c0` and + // `c1` when the y-range is shorter than a piece. They are replaced by + // the end x values of the cut curves, as `QuadraticApprox::from_cubic` + // sets them. + ep0.almost_horiz = ep0.almost_horiz.map(|(d, _, _)| (d, c0.p0.x, c0.p3.x)); + ep1.almost_horiz = ep1.almost_horiz.map(|(d, _, _)| (d, c1.p0.x, c1.p3.x)); + (ep0, ep1) } else { ( QuadraticApprox::from_cubic(c0, cubic0.dir), @@ -1300,6 +1632,11 @@ fn intersect_cubics_rec( } signs.entries.last_mut().unwrap().end = y1; + // Craft patch (end order check): re-centering rounds each interval end, and + // at coordinates near 1e8 the two curves at a rounded end can be on the + // wrong side of the interval's order by up to 69 times `ish_tolerance`. + // This exact check runs only with `slow-asserts`. + #[cfg(feature = "slow-asserts")] for (y0, y1, order) in signs.iter(y0) { match order { MaybeOrder::Right => { @@ -1334,7 +1671,7 @@ fn intersect_cubics_rec( if let Ok(order) = order.try_into() { out.push(new_y1, order, status); } else { - let mid = 0.5 * (new_y0 + new_y1); + let mid = new_y0.midpoint(new_y1); // We test the difference between y1 and y0, not new_y1 and new_y0. // This help reduce false positives where the error in dep is substantial @@ -1342,7 +1679,14 @@ fn intersect_cubics_rec( // "ish" interval that's just an artifact. In this case, new_y0 and new_y1 // will be very close, but we'll recurse one more time to get a better // quadratic approximation. + // + // When `mid` rounds to one of the ends, the interval is one float + // wide and cannot be split, so splitting it would repeat the same + // call until the stack overflows. That happens when `ish_tolerance` + // is below the spacing of floats at this height. if y1 - y0 <= ish_tolerance + || mid <= new_y0 + || mid >= new_y1 || (ep0.dmax + ep1.dmax <= 2.0 * ish_tolerance && ep0.dmin + ep1.dmin >= -2.0 * ish_tolerance) { @@ -1395,13 +1739,20 @@ fn intersect_cubics_rec( /// A decomposition of a cubic Bezier into almost-horizontal and not-almost-horizontal pieces. #[derive(Clone, Debug, Default)] pub struct AlmostHorizontalDecomposition { - pieces: ArrayVec, + // Craft patch (inline pieces): up to two pieces are stored inline and more + // go on the heap. `Segments` stores one decomposition per segment, so this + // size is paid for every segment of the input. + pieces: SmallVec<[CubicParams; 2]>, } impl AlmostHorizontalDecomposition { /// Decompose a cubic into almost-horizontal and not-almost-horizontal pieces. /// /// The cubic `c` must be (approximately) y-monotone and must not be completely horizontal. + /// + /// # Panics + /// + /// Panics if `c` is completely horizontal or if `c.p3.y` is smaller than `c.p0.y`. pub fn from_monotone_cubic(c: CubicBez) -> Self { const THRESHOLD: f64 = 16.0; let dx = cubic_from_bez_x(c).deriv(); @@ -1452,7 +1803,7 @@ impl AlmostHorizontalDecomposition { let mut last_y = c.p0.y; let mut last_end = 0.0; let orig_c = c; - let mut ret = ArrayVec::default(); + let mut ret: SmallVec<[CubicParams; 2]> = SmallVec::new(); for (_, end, order) in subdivision.iter(0.0) { let start = last_end; // If there's no actual subdivision, skip the subsegment operation. @@ -1466,10 +1817,15 @@ impl AlmostHorizontalDecomposition { // Enforce y-monotonicity, from the previous curve to this one, and // also for the initial and final tangents of this subsegment. + // + // Craft patch (monotone handles): the tangents only need to point + // the right way, so p1.y is kept at least p0.y and p2.y at most + // p3.y. A monotone cubic can have handles outside its own y-range, + // and clamping them into that range moves the curve. c.p0.y = c.p0.y.clamp(last_y, orig_c.p3.y); - c.p1.y = c.p1.y.clamp(c.p0.y, orig_c.p3.y); + c.p1.y = c.p1.y.max(c.p0.y); c.p3.y = c.p3.y.clamp(last_y, orig_c.p3.y); - c.p2.y = c.p2.y.clamp(last_y, c.p3.y); + c.p2.y = c.p2.y.min(c.p3.y); last_y = c.p3.y; let approx_horiz = match order { Right => { @@ -1489,7 +1845,7 @@ impl AlmostHorizontalDecomposition { }; if c.p0.y != c.p3.y { let mut recentered_c = c; - let y_mid = (c.p0.y + c.p3.y) / 2.0; + let y_mid = c.p0.y.midpoint(c.p3.y); recentered_c.p0.y -= y_mid; recentered_c.p1.y -= y_mid; recentered_c.p2.y -= y_mid; @@ -1543,12 +1899,33 @@ impl AlmostHorizontalDecomposition { /// The `ish_tolerance` parameter tells us when we're allowed to say that /// the two curves are close: if they're definitely within `ish_tolerance` /// of one another, we can say that they're close. +/// +/// `sure_tolerance` must be positive and no larger than `ish_tolerance`, and +/// `ish_tolerance` must be finite. Otherwise the returned order says that the +/// curves are close over their whole common range. +/// +/// Each curve must be y-monotone. A curve whose `p3.y` is smaller than its +/// `p0.y` is compared as the same curve with its control points reversed. +/// When the vertical ranges of the curves do not overlap, the returned order +/// has no entries. +/// +/// A positive `ish_tolerance` below `4 * f64::EPSILON` times the largest +/// x coordinate magnitude of the two curves (two to four ulps of it, and at +/// least four times the spacing of subnormal floats) is raised to that value, +/// and a positive `sure_tolerance` below half of it is raised to half of it. +/// Below that, rounding in the comparison can report the wrong order. +/// +/// # Panics +/// +/// Panics if either curve is completely horizontal. pub fn intersect_cubics( c0: CubicBez, c1: CubicBez, sure_tolerance: f64, ish_tolerance: f64, ) -> CurveOrder { + let c0 = increasing_in_y(c0); + let c1 = increasing_in_y(c1); intersect_cubics_with_precomputed_decomp( c0, &AlmostHorizontalDecomposition::from_monotone_cubic(c0), @@ -1559,11 +1936,26 @@ pub fn intersect_cubics( ) } +// Craft patch (input rules): `intersect_cubics` compares a curve that runs +// down in y as the same curve reversed. +/// Returns `c`, or `c` with its control points reversed if it decreases in y. +fn increasing_in_y(c: CubicBez) -> CubicBez { + if c.p3.y < c.p0.y { + CubicBez::new(c.p3, c.p2, c.p1, c.p0) + } else { + c + } +} + /// A version of [intersect_cubics] that uses a precomputed almost-horizontal /// decomposition. /// /// Pre-computing the almost-horizontal decomposition can be much faster, because /// then you can do it per-curve instead of per-comparison. +/// +/// `c0_div` and `c1_div` must be the decompositions of `c0` and `c1`, so each +/// curve must have `p0.y < p3.y`. The tolerances follow the same rule as in +/// [intersect_cubics] and are raised as in [intersect_cubics]. pub fn intersect_cubics_with_precomputed_decomp( c0: CubicBez, c0_div: &AlmostHorizontalDecomposition, @@ -1572,11 +1964,84 @@ pub fn intersect_cubics_with_precomputed_decomp( sure_tolerance: f64, ish_tolerance: f64, ) -> CurveOrder { + intersect_decompositions(c0, c0_div, c1, c1_div, sure_tolerance, ish_tolerance, true) +} + +// Craft patch (approximation first): when the precomputed approximations of +// two pieces are more than `ish_tolerance` apart over the whole shared +// y-range, the order is decided without cutting either cubic to that range. +// `intersect_cubics_rec` would cut both cubics first and then compare the same +// approximations with the smaller `sure_tolerance`. +fn order_from_precomputed_approx( + cubic0: &CubicParams, + cubic1: &CubicParams, + y0: f64, + y1: f64, + sure_tolerance: f64, + ish_tolerance: f64, +) -> Option { + // `intersect_cubics_rec` uses bounding boxes for intervals this short. + if y1 - y0 < ish_tolerance { + return None; + } + let y_mid = y0.midpoint(y1); + let orig_y_mid0 = cubic0.c.p0.y.midpoint(cubic0.c.p3.y); + let orig_y_mid1 = cubic1.c.p0.y.midpoint(cubic1.c.p3.y); + let ep0 = cubic0.approx.shift_y(orig_y_mid0 - y_mid); + let ep1 = cubic1.approx.shift_y(orig_y_mid1 - y_mid); + // An almost-horizontal approximation carries the end x values of its whole + // piece, which do not bound a shorter y-range. + if ep0.almost_horiz.is_some() || ep1.almost_horiz.is_some() { + return None; + } + let tolerance = sure_tolerance.max(ish_tolerance); + let signs = ep0.compare(&ep1, tolerance, tolerance, y0 - y_mid, y1 - y_mid); + match signs.entries.as_slice() { + [entry] => match entry.order { + MaybeOrder::Left => Some(Order::Left), + MaybeOrder::Right => Some(Order::Right), + MaybeOrder::Ish | MaybeOrder::Unknown => None, + }, + _ => None, + } +} + +fn intersect_decompositions( + c0: CubicBez, + c0_div: &AlmostHorizontalDecomposition, + c1: CubicBez, + c1_div: &AlmostHorizontalDecomposition, + sure_tolerance: f64, + ish_tolerance: f64, + approx_first: bool, +) -> CurveOrder { + // The rule applies to the tolerances as given: raising them to the floor + // below can make an invalid pair valid. + let valid_tolerances = + sure_tolerance > 0.0 && sure_tolerance <= ish_tolerance && ish_tolerance.is_finite(); + let floor = 4.0 * float_spacing(max_abs_x(c0).max(max_abs_x(c1))); + let ish_tolerance = if ish_tolerance > 0.0 && ish_tolerance < floor { + floor + } else { + ish_tolerance + }; + let sure_tolerance = if sure_tolerance > 0.0 && sure_tolerance < floor / 2.0 { + floor / 2.0 + } else { + sure_tolerance + }; + let y0 = c0.p0.y.max(c1.p0.y); let y1 = c0.p3.y.min(c1.p3.y); let mut ret = CurveOrder::new(y0); - if y0 < y1 { + if !valid_tolerances { + // Craft patch (input rules): with a negative `ish_tolerance`, + // `intersect_cubics_rec` can recurse without end. + if y0 <= y1 { + ret.push(y1, Order::Ish, MetricsStatus::default()); + } + } else if y0 < y1 { let c0_div = c0_div .pieces .iter() @@ -1591,17 +2056,26 @@ pub fn intersect_cubics_with_precomputed_decomp( let y0 = c0.c.p0.y.max(c1.c.p0.y); let y1 = c0.c.p3.y.min(c1.c.p3.y); if y0 < y1 { - intersect_cubics_rec( - c0, - c1, - true, - y0, - y1, - sure_tolerance, - ish_tolerance, - &mut ret, - MetricsStatus::default(), - ); + let settled = if approx_first { + order_from_precomputed_approx(c0, c1, y0, y1, sure_tolerance, ish_tolerance) + } else { + None + }; + if let Some(order) = settled { + ret.push(y1, order, MetricsStatus::default()); + } else { + intersect_cubics_rec( + c0, + c1, + true, + y0, + y1, + sure_tolerance, + ish_tolerance, + &mut ret, + MetricsStatus::default(), + ); + } } } } else if y0 == y1 { @@ -1625,7 +2099,7 @@ pub fn intersect_cubics_with_precomputed_decomp( ret.push(y1, order, MetricsStatus::default()); } //fix_up_endpoints(&mut ret, c0, c1, eps); - debug_assert_eq!(ret.cmps.last().unwrap().end, y1); + debug_assert!(y0 > y1 || ret.cmps.last().map(|e| e.end) == Some(y1)); ret } @@ -1724,6 +2198,65 @@ mod test { assert!(dbg!(c.eval(t).y - y).abs() < 1e-8); } + #[test] + fn solve_for_t_near_the_float_limit() { + let line = |y0: f64, y1: f64| { + let a = Point::new(0.0, y0); + let b = Point::new(10.0, y1); + CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b) + }; + + // Without scaling, `3.0 * p1` or `3.0 * p2` overflows to infinity for every line here + // except the one from -8e307 to 8e307, whose coefficients stay finite. + for (y0, y1) in [ + (5.5e307, 6.5e307), + (-6.5e307, -5.5e307), + (-8e307, 8e307), + (f64::MAX / 2.0, f64::MAX), + ] { + let t = solve_t_for_y(line(y0, y1), y0 / 2.0 + y1 / 2.0); + assert!((t - 0.5).abs() < 1e-9, "t = {t} from {y0} to {y1}"); + } + + // Curves from `a` to `a + b` whose height is `a + b * t^3` (control points a, a, a, + // a + b) or `a + b * (3t^2 - 2t^3)` (control points a, a, a + b, a + b), solved at a + // height that is not the midpoint. The last value in each row is the polynomial at + // `t`: 0.75^3 = 0.421875, 3 * 0.25^2 - 2 * 0.25^3 = 0.15625 and + // 3 * 0.75^2 - 2 * 0.75^3 = 0.84375. Without scaling, `3.0 * p1` or `3.0 * p2` + // overflows to infinity for each of them. + for (a, b, [s1, s2, s3], t, fraction) in [ + (7e307, 8e307, [0.0, 0.0, 1.0], 0.75, 0.421875), + (-1.5e308, 1e308, [0.0, 1.0, 1.0], 0.25, 0.15625), + (-8e307, 1.6e308, [0.0, 1.0, 1.0], 0.75, 0.84375), + ] { + let c = CubicBez::new( + Point::new(0.0, a), + Point::new(2.0, a + b * s1), + Point::new(5.0, a + b * s2), + Point::new(10.0, a + b * s3), + ); + let got = solve_t_for_y(c, a + b * fraction); + assert!((got - t).abs() < 1e-9, "t = {got}, expected {t}, from {a} to {}", a + b); + } + } + + #[test] + fn compare_near_the_float_limit() { + let h = 1e306; + // Without `f64::midpoint`, the sum of two heights overflows to infinity for every + // start here except 0.0. The comparison then has no entries, and a release build + // panics on the empty list. + for y in [0.0, 1e308, 1.5e308, 1.7e308] { + let a = PathSeg::Line(Line::new((10.0 * h, y + h), (9.0 * h, y + 4.0 * h))).to_cubic(); + let b = PathSeg::Line(Line::new((0.0, y), (h, y + 3.0 * h))).to_cubic(); + + let entries: Vec<_> = intersect_cubics(a, b, 1e-6, 2e-6).iter().collect(); + assert_eq!(entries.first().map(|e| e.0), Some(y + h), "start {y}"); + assert_eq!(entries.last().map(|e| e.1), Some(y + 3.0 * h), "start {y}"); + assert!(entries.iter().all(|e| e.2 == Order::Right), "start {y}: {entries:?}"); + } + } + #[test] fn solve_for_t_arbtest() { arbtest::arbtest(arbtests::solve_for_t); @@ -1742,6 +2275,130 @@ mod test { assert_eq!(cmp.order_at(1.0), Order::Left); } + #[test] + fn far_apart_with_huge_coordinates() { + // Two bulging vertical curves a distance s apart, with heights from 0 to s. + let curve = |x: f64, s: f64| { + CubicBez::new( + (x, 0.0), + (x + s * 0.01, s / 3.0), + (x + s * 0.01, 2.0 * s / 3.0), + (x, s), + ) + }; + for s in [1.0, 1e155, 1e200, 1e300] { + let tol = s * 64.0 * f64::EPSILON; + let cmp = intersect_cubics(curve(-s / 2.0, s), curve(s / 2.0, s), tol, tol); + assert!( + cmp.iter().all(|(_, _, order)| order == Order::Left), + "s = {s}: {cmp:?}" + ); + } + } + + #[test] + fn quadratic_approx_error_bounds_on_tall_curves() { + // An S-shaped curve from y = -h/2 to y = h/2 and w wide, which no quadratic + // in y fits exactly. + let approx = |h: f64, w: f64| { + let c = CubicBez::new( + (0.0, -h / 2.0), + (w, -h / 6.0), + (-w, h / 6.0), + (0.0, h / 2.0), + ); + let a = QuadraticApprox::from_cubic(c, None); + assert!( + a.q.coeffs().iter().all(|c| c.is_finite()), + "h = {h}, w = {w}: {:?}", + a.q + ); + (a.dmin / w, a.dmax / w) + }; + let (dmin, dmax) = approx(1.0, 1.0); + assert!(dmin < -0.01 && dmax > 0.01, "{dmin} {dmax}"); + for (h, w) in [ + (1e154, 1e154), + (1e155, 1e155), + (1e200, 1e200), + (1e300, 1e300), + (1e151, 1e300), + (1e200, 1.0), + ] { + let (hmin, hmax) = approx(h, w); + assert!( + (hmin - dmin).abs() < 1e-9 && (hmax - dmax).abs() < 1e-9, + "h = {h}, w = {w}: ({hmin}, {hmax}) != ({dmin}, {dmax})" + ); + } + } + + #[test] + fn tall_lines_at_any_height() { + // A line from (0, 0) to (h, 3h) is left of a line from (10h, h) to (9h, 4h), + // with both moved up by `dy`. + for h in [1.0f64, 1e154, 1e155, 1e200, 1e300] { + for dy in [0.0f64, -2.0 * h, 1e5 * h] { + let a = Line::new((0.0, dy), (h, 3.0 * h + dy)); + let b = Line::new((10.0 * h, h + dy), (9.0 * h, 4.0 * h + dy)); + let a = PathSeg::Line(a).to_cubic(); + let b = PathSeg::Line(b).to_cubic(); + let tol = h.max(dy.abs()) * 64.0 * f64::EPSILON; + let cmp = intersect_cubics(a, b, tol, tol); + assert!( + !cmp.cmps.is_empty() && cmp.iter().all(|(_, _, order)| order == Order::Left), + "h = {h}, dy = {dy}: {cmp:?}" + ); + } + } + } + + #[test] + fn non_finite_quadratics_have_no_definite_order() { + for c in [f64::NAN, f64::INFINITY] { + let q = Quadratic::new([c, 0.0, 0.0]); + + let mut out = QuadApproxComparison::default(); + push_two_level_quadratic_signs(q, -1.0, 1.0, 0.0, 1.0, &mut out); + assert!( + out.entries.iter().all(|e| e.order == MaybeOrder::Unknown), + "c = {c}: {:?}", + out.entries + ); + + let mut out = ApproxComparison::<3>::default(); + push_left_or_ish(q, 0.0, 1.0, &mut out.entries); + assert!( + out.entries.iter().all(|e| e.order == MaybeOrder::Ish), + "c = {c}: {:?}", + out.entries + ); + } + } + + #[test] + fn fit_quadratic_with_huge_x() { + // A vertical curve at x with y(t) = h * t^3, which a quadratic in y fits + // with the constant x. + for x in [1e307, -1e307, 5e307] { + for h in [1.0, 2.0f64.powi(501), 1e300] { + let c = CubicBez::new((x, 0.0), (x, 0.0), (x, 0.0), (x, h)); + let q = fit_quadratic(c); + assert!( + q.coeffs().iter().all(|c| c.is_finite()), + "x = {x}, h = {h}: {q:?}" + ); + for y in [0.0, 0.25 * h, 0.5 * h, h] { + let fx = q.eval(y); + assert!( + (fx - x).abs() <= 1e-9 * x.abs(), + "x = {x}, h = {h}, y = {y}: {fx}" + ); + } + } + } + } + #[test] fn almost_touching() { let sure_tol = 0.25; @@ -1752,6 +2409,422 @@ mod test { assert_eq!(cmp.iter().count(), 3); } + // Craft patch (approximation first) test: deciding the order of two pieces + // from their precomputed approximations gives the same `CurveOrder` as + // cutting the cubics first, for curves that are far apart, close, touching + // and crossing, and for generated pairs. + #[test] + fn approximation_first_keeps_the_curve_order() { + fn orders( + c0: CubicBez, + c1: CubicBez, + sure: f64, + ish: f64, + approx_first: bool, + ) -> Vec<(f64, f64, Order)> { + let d0 = AlmostHorizontalDecomposition::from_monotone_cubic(c0); + let d1 = AlmostHorizontalDecomposition::from_monotone_cubic(c1); + intersect_decompositions(c0, &d0, c1, &d1, sure, ish, approx_first) + .iter() + .collect() + } + + // Counts the pieces whose order the approximations decide. + fn settled(c0: CubicBez, c1: CubicBez, sure: f64, ish: f64) -> (usize, usize) { + let d0 = AlmostHorizontalDecomposition::from_monotone_cubic(c0); + let d1 = AlmostHorizontalDecomposition::from_monotone_cubic(c1); + let (mut hits, mut misses) = (0, 0); + for p0 in &d0.pieces { + for p1 in &d1.pieces { + let y0 = p0.c.p0.y.max(p1.c.p0.y); + let y1 = p0.c.p3.y.min(p1.c.p3.y); + if y0 < y1 { + match order_from_precomputed_approx(p0, p1, y0, y1, sure, ish) { + Some(_) => hits += 1, + None => misses += 1, + } + } + } + } + (hits, misses) + } + + fn shifted(c: CubicBez, dx: f64, dy: f64) -> CubicBez { + let v = Vec2::new(dx, dy); + CubicBez::new(c.p0 + v, c.p1 + v, c.p2 + v, c.p3 + v) + } + + let sure = 1e-4; + let ish = 1e-3; + let curves = [ + CubicBez::new((0.0, 0.0), (1.0, 0.3), (-1.0, 0.7), (0.0, 1.0)), + CubicBez::new((-1.0, 0.0), (0.5, 0.6), (0.5, 0.4), (-1.0, 1.0)), + CubicBez::new((0.0, 0.0), (30.0, 0.01), (60.0, 0.02), (90.0, 1.0)), + CubicBez::new((90.0, 0.0), (60.0, 0.98), (30.0, 0.99), (0.0, 1.0)), + CubicBez::new((0.0, 0.0), (0.0, 1.0 / 3.0), (0.0, 2.0 / 3.0), (0.0, 1.0)), + ]; + let (mut hits, mut misses) = (0, 0); + for c0 in curves { + for c1 in curves { + for k in [ + -1000.0, -10.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 10.0, 1000.0, + ] { + for dy in [0.0, 0.25] { + let c1 = shifted(c1, k * ish, dy); + assert_eq!( + orders(c0, c1, sure, ish, true), + orders(c0, c1, sure, ish, false), + "{c0:?} {c1:?}" + ); + let (h, m) = settled(c0, c1, sure, ish); + hits += h; + misses += m; + } + } + } + } + assert!( + hits > 0 && misses > 0, + "{hits} settled, {misses} not settled" + ); + + // Generated pairs, from a fixed sequence of bytes. + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let mut bytes = vec![0u8; 256]; + let mut compared = 0; + for _ in 0..2000 { + for b in &mut bytes { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + *b = state as u8; + } + let mut u = arbitrary::Unstructured::new(&bytes); + let Ok(c0) = crate::arbitrary::monotonic_bezier(&mut u) else { + continue; + }; + let Ok(c1) = crate::arbitrary::another_monotonic_bezier(&mut u, &c0) else { + continue; + }; + // The curves must be y-monotone and share a y-range. + if c1.p0.y >= c1.p3.y || c0.p0.y.max(c1.p0.y) >= c0.p3.y.min(c1.p3.y) { + continue; + } + for (sure, ish) in [(1e-3, 1e-2), (0.25, 1.0), (100.0, 1000.0)] { + assert_eq!( + orders(c0, c1, sure, ish, true), + orders(c0, c1, sure, ish, false), + "{c0:?} {c1:?} {sure} {ish}" + ); + compared += 1; + } + } + assert!(compared > 3000, "{compared} generated comparisons"); + } + + #[test] + fn next_touch_after_a_touch_that_contains_y() { + let mut cmp = CurveOrder::new(0.0); + for (end, order) in [ + (1.0, Order::Ish), + (2.0, Order::Left), + (3.0, Order::Ish), + (4.0, Order::Left), + ] { + cmp.push(end, order, MetricsStatus::default()); + } + + let touch = |y: f64| match cmp.next_touch_after(y) { + Some(CurveInteraction::Touch(y0, y1)) => (y0, y1), + other => panic!("expected a touch after {y}, got {other:?}"), + }; + // `y` inside the first touch or after it: the next one is the touch + // from 2 to 3. + assert_eq!(touch(0.0), (2.0, 3.0)); + assert_eq!(touch(0.5), (2.0, 3.0)); + assert_eq!(touch(1.5), (2.0, 3.0)); + // `y` inside the second touch, with no touch after it. + assert!(cmp.next_touch_after(2.5).is_none()); + assert!(cmp.next_touch_after(4.0).is_none()); + } + + #[test] + fn next_touch_after_a_crossing_after_a_touch_that_contains_y() { + let mut cmp = CurveOrder::new(0.0); + for (end, order) in [ + (1.0, Order::Ish), + (2.0, Order::Left), + (3.0, Order::Ish), + (4.0, Order::Right), + ] { + cmp.push(end, order, MetricsStatus::default()); + } + + let cross = |y: f64| match cmp.next_touch_after(y) { + Some(CurveInteraction::Cross(y0, y1)) => (y0, y1), + other => panic!("expected a crossing after {y}, got {other:?}"), + }; + // `y` inside the first touch or after it, and the touch from 2 to 3 + // ends on the right: the curves cross somewhere from 2 to 3. + assert_eq!(cross(0.0), (2.0, 3.0)); + assert_eq!(cross(0.5), (2.0, 3.0)); + assert_eq!(cross(1.5), (2.0, 3.0)); + } + + #[test] + fn next_touch_after_on_two_curves_that_start_together() { + // The cubic starts on the line, moves left of it and comes back to + // touch it again near y = 2.4. + let a = CubicBez::new((0.0, 0.0), (-1.2, 4.0 / 3.0), (1.6, 8.0 / 3.0), (-1.6, 4.0)); + let b = CubicBez::new((0.0, 0.0), (0.0, 4.0 / 3.0), (0.0, 8.0 / 3.0), (0.0, 4.0)); + let cmp = intersect_cubics(a, b, 1e-3, 0.02); + let orders: Vec<_> = cmp.iter().map(|(_, _, order)| order).collect(); + assert_eq!(orders, [Order::Ish, Order::Left, Order::Ish, Order::Left]); + + let (touch_y0, touch_y1, _) = cmp.iter().nth(2).unwrap(); + match cmp.next_touch_after(0.0) { + Some(CurveInteraction::Touch(y0, y1)) => assert_eq!((y0, y1), (touch_y0, touch_y1)), + other => panic!("expected the second touch, got {other:?}"), + } + } + + fn shifted(c: CubicBez, dx: f64, dy: f64) -> CubicBez { + let v = Vec2::new(dx, dy); + CubicBez::new(c.p0 + v, c.p1 + v, c.p2 + v, c.p3 + v) + } + + fn without_control_point_order(f: impl FnOnce() -> T) -> T { + SKIP_CONTROL_POINT_ORDER.with(|s| s.set(true)); + let ret = f(); + SKIP_CONTROL_POINT_ORDER.with(|s| s.set(false)); + ret + } + + // Craft patch (control point order) test: a tall S-shaped cubic and a copy + // moved 10 * ish_tolerance sideways are ordered in one step. Without the + // patch the recursion splits the range into thousands of pieces. + #[test] + fn near_parallel_cubics_are_ordered_without_recursing() { + let s = 1e6; + let ish = 1e-6; + let c0 = CubicBez::new((0.0, 0.0), (s, s / 3.0), (-s, 2.0 * s / 3.0), (0.0, s)); + for (dx, dy, order) in [ + (10.0 * ish, 0.0, Order::Left), + (10.0 * ish, 0.5 * ish, Order::Left), + (-10.0 * ish, 0.0, Order::Right), + (-10.0 * ish, 0.5 * ish, Order::Right), + ] { + let c1 = shifted(c0, dx, dy); + CURVE_ORDER_PUSHES.with(|n| n.set(0)); + let cmp = intersect_cubics(c0, c1, ish / 2.0, ish); + let pushes = CURVE_ORDER_PUSHES.with(std::cell::Cell::get); + let y0 = c1.p0.y; + assert_eq!(cmp.iter().collect::>(), vec![(y0, s, order)]); + assert!(pushes <= 4, "{pushes} pushes for ({dx}, {dy})"); + } + } + + // Craft patch (control point order) test: whenever the control points of + // two y-subsegments give an order, the subsegments are more than + // `sure_tolerance` apart in that order at sample heights, and a curve and + // a copy moved 10 * ish_tolerance or more sideways get the same + // `CurveOrder` as without the patch. + #[test] + fn control_point_order_is_sound() { + // Returns how many subsegment pairs the control points ordered. + fn check(c0: CubicBez, c1: CubicBez, sure: f64, ish: f64) -> usize { + let y0 = c0.p0.y.max(c1.p0.y); + let y1 = c0.p3.y.min(c1.p3.y); + let mut ordered = 0; + for parts in [1u32, 3, 16] { + for j in 0..parts { + let a = y0 + (y1 - y0) * f64::from(j) / f64::from(parts); + let b = if j + 1 == parts { + y1 + } else { + y0 + (y1 - y0) * f64::from(j + 1) / f64::from(parts) + }; + if a >= b { + continue; + } + let s0 = y_subsegment(c0, a, b); + let s1 = y_subsegment(c1, a, b); + let Some(order) = order_from_control_points(s0, s1, ish) else { + continue; + }; + ordered += 1; + for i in 0..=8 { + let y = (a + (b - a) * f64::from(i) / 8.0).min(b); + let gap = solve_x_for_y(s1, y) - solve_x_for_y(s0, y); + match order { + Order::Left => assert!(gap > sure, "{s0:?} {s1:?} {y} {gap}"), + Order::Right => assert!(gap < -sure, "{s0:?} {s1:?} {y} {gap}"), + Order::Ish => panic!("control points gave Ish for {s0:?} {s1:?}"), + } + } + } + } + ordered + } + + let sure = 1e-4; + let ish = 1e-3; + let curves = [ + CubicBez::new((0.0, 0.0), (1.0, 0.3), (-1.0, 0.7), (0.0, 1.0)), + CubicBez::new((-1.0, 0.0), (0.5, 0.6), (0.5, 0.4), (-1.0, 1.0)), + CubicBez::new((0.0, 0.0), (30.0, 0.01), (60.0, 0.02), (90.0, 1.0)), + CubicBez::new((90.0, 0.0), (60.0, 0.98), (30.0, 0.99), (0.0, 1.0)), + CubicBez::new((0.0, 0.0), (0.0, 1.0 / 3.0), (0.0, 2.0 / 3.0), (0.0, 1.0)), + ]; + let mut ordered = 0; + for (i0, c0) in curves.into_iter().enumerate() { + for (i1, c1) in curves.into_iter().enumerate() { + for k in [-1000.0, -10.0, -2.0, -1.0, 0.0, 1.0, 2.0, 10.0, 1000.0] { + for dy in [0.0, 0.25 * ish, 0.25] { + let c1 = shifted(c1, k * ish, dy); + ordered += check(c0, c1, sure, ish); + if i0 != i1 || k.abs() < 10.0 || dy >= ish { + continue; + } + let with = intersect_cubics(c0, c1, sure, ish) + .iter() + .collect::>(); + let without = without_control_point_order(|| { + intersect_cubics(c0, c1, sure, ish) + .iter() + .collect::>() + }); + assert_eq!(with, without, "{c0:?} {c1:?}"); + } + } + } + } + assert!( + ordered > 100, + "{ordered} hand-built subsegment pairs ordered" + ); + + // Generated pairs, from a fixed sequence of bytes: a curve and either + // another curve or a copy of it moved sideways and up. + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let mut bytes = vec![0u8; 256]; + let mut compared = 0; + let mut ordered = 0; + for n in 0..2000 { + for b in &mut bytes { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + *b = state as u8; + } + let mut u = arbitrary::Unstructured::new(&bytes); + let Ok(c0) = crate::arbitrary::monotonic_bezier(&mut u) else { + continue; + }; + for (sure, ish) in [(1e-3, 1e-2), (0.25, 1.0), (100.0, 1000.0)] { + let c1 = if n % 2 == 0 { + let Ok(c1) = crate::arbitrary::another_monotonic_bezier(&mut u, &c0) else { + continue; + }; + c1 + } else { + let k = f64::from(u.int_in_range(-40..=40).unwrap_or(20)); + let dy = f64::from(u.int_in_range(0..=8).unwrap_or(0)) * 0.125 * ish; + shifted(c0, k * ish, dy) + }; + if c1.p0.y >= c1.p3.y || c0.p0.y.max(c1.p0.y) >= c0.p3.y.min(c1.p3.y) { + continue; + } + ordered += check(c0, c1, sure, ish); + compared += 1; + } + } + assert!(compared > 3000, "{compared} generated comparisons"); + assert!( + ordered > 1000, + "{ordered} generated subsegment pairs ordered" + ); + } + + // Craft patch (control point order) test: the contours of a tall wavy band + // and a copy moved 10 * eps sideways are the same with and without the + // patch. + #[test] + fn control_point_order_keeps_band_contours() { + let (n, l) = (50, 1e6); + let eps = 1e-6; + let amp = l * 0.05; + let lam = l / 3.0; + let width = l * 0.1; + let x = |y: f64| amp * (std::f64::consts::TAU * y / lam).sin(); + let dx = + |y: f64| amp * std::f64::consts::TAU / lam * (std::f64::consts::TAU * y / lam).cos(); + let h = l / f64::from(n); + let mut band = kurbo::BezPath::new(); + band.move_to((x(0.0), 0.0)); + for i in 0..n { + let (y0, y1) = (f64::from(i) * h, f64::from(i + 1) * h); + band.curve_to( + (x(y0) + dx(y0) * h / 3.0, y0 + h / 3.0), + (x(y1) - dx(y1) * h / 3.0, y1 - h / 3.0), + (x(y1), y1), + ); + } + band.line_to((x(l) + width, l)); + for i in (0..n).rev() { + let (y0, y1) = (f64::from(i) * h, f64::from(i + 1) * h); + band.curve_to( + (x(y1) + width - dx(y1) * h / 3.0, y1 - h / 3.0), + (x(y0) + width + dx(y0) * h / 3.0, y0 + h / 3.0), + (x(y0) + width, y0), + ); + } + band.close_path(); + + for (kx, ky) in [(10.0, 0.0), (10.0, 1.0), (-10.0, 0.3)] { + let mut both = band.clone(); + let mut copy = band.clone(); + copy.apply_affine(kurbo::Affine::translate((kx * eps, ky * eps))); + both.extend(copy.iter()); + let contours = || { + let top = crate::topology::Topology::::from_path(&both, eps).unwrap(); + top.contours(|w| *w != 0) + .contours() + .map(|c| c.path.clone()) + .collect::>() + }; + let with = contours(); + let without = without_control_point_order(contours); + assert!(!with.is_empty()); + assert_eq!(with, without, "copy moved by ({kx}, {ky}) * eps"); + } + } + + // Craft patch (control point order) test: an almost-horizontal cubic and a + // copy moved 16 sideways are 0.25 apart in y. The comparison of + // almost-horizontal pieces widens each curve by the tolerance in y, so it + // reports them as close, and the control points must not order them. + #[test] + fn control_point_order_skips_almost_horizontal_pieces() { + let c0 = CubicBez::new( + (0.0, 0.0), + (65536.0, 1024.0), + (131072.0, 2048.0), + (196608.0, 3072.0), + ); + let c1 = shifted(c0, 16.0, 0.0); + let with = intersect_cubics(c0, c1, 1.0, 2.0) + .iter() + .collect::>(); + let without = without_control_point_order(|| { + intersect_cubics(c0, c1, 1.0, 2.0) + .iter() + .collect::>() + }); + assert_eq!(with, without); + assert!(with.iter().any(|&(_, _, order)| order == Order::Ish), "{with:?}"); + } + #[test] fn quad_approximation() { let c = CubicBez { @@ -1776,6 +2849,18 @@ mod test { assert!(diff >= ep.dmin); } + // The curve x = y^2 for y in [0, 1]: the quadratic takes y and returns x. + #[test] + fn quad_approximation_gives_x_of_y() { + let c = CubicBez::new((0.0, 0.0), (0.0, 1.0 / 3.0), (1.0 / 3.0, 2.0 / 3.0), (1.0, 1.0)); + let ep = QuadraticApprox::from_cubic(c, None); + + assert!((ep.q.eval(0.5) - 0.25).abs() < 1e-9); + assert!((ep.q.eval(1.0) - 1.0).abs() < 1e-9); + assert!(ep.dmin.abs() < 1e-9); + assert!(ep.dmax.abs() < 1e-9); + } + #[test] fn short_curve_chord_with_huge_x() { // A vertical curve one ulp tall at y = 1e4, so `fit_quadratic` takes a @@ -1814,6 +2899,87 @@ mod test { dbg!(intersect_cubics(c0, c1, 0.5e-6, 1.5e-6)); } + // Craft patch (input rules) tests: curves that run down in y, tolerances + // outside the documented rule, and curves with no common y-range. + fn vertical(x: f64, y0: f64, y1: f64) -> CubicBez { + PathSeg::Line(Line::new((x, y0), (x, y1))).to_cubic() + } + + #[test] + fn curves_decreasing_in_y() { + let up0 = vertical(0.0, 0.0, 1.0); + let up1 = vertical(1.0, 0.0, 1.0); + let down0 = vertical(0.0, 1.0, 0.0); + let down1 = vertical(1.0, 1.0, 0.0); + for (c0, c1) in [(down0, down1), (down0, up1), (up0, down1)] { + let cmp = intersect_cubics(c0, c1, 1e-6, 2e-6); + assert_eq!(cmp.iter().collect::>(), [(0.0, 1.0, Order::Left)]); + } + } + + #[test] + fn curved_crossing_decreasing_in_y() { + // The curve runs down in y and bulges to the right across the line at + // x = 0.5, while its chord stays on x = 0, left of the line. + let down = CubicBez::new((0.0, 1.0), (2.0, 2.0 / 3.0), (2.0, 1.0 / 3.0), (0.0, 0.0)); + let up = CubicBez::new(down.p3, down.p2, down.p1, down.p0); + let line = vertical(0.5, 0.0, 1.0); + for (c0, c1, u0, u1) in [(down, line, up, line), (line, down, line, up)] { + let cmp: Vec<_> = intersect_cubics(c0, c1, 1e-6, 2e-6).iter().collect(); + let expected: Vec<_> = intersect_cubics(u0, u1, 1e-6, 2e-6).iter().collect(); + assert_eq!(cmp, expected); + assert!(cmp.iter().any(|&(_, _, o)| o == Order::Left)); + assert!(cmp.iter().any(|&(_, _, o)| o == Order::Right)); + } + } + + #[test] + fn invalid_tolerances() { + let c0 = vertical(0.0, 0.0, 1.0); + let parallel = vertical(1.0, 0.0, 1.0); + let crossing = CubicBez::new( + (1.0, 0.0), + (2.0 / 3.0, 1.0 / 3.0), + (1.0 / 3.0, 2.0 / 3.0), + (0.0, 1.0), + ); + let tolerances = [ + (-1.0, -1.0), + (-1.0, 1e-6), + (1e-6, -1.0), + (-1e-9, -1e-9), + (0.0, 0.0), + (2e-6, 1e-6), + (1e-6, f64::INFINITY), + (f64::NAN, 1e-6), + ]; + for (sure, ish) in tolerances { + for c1 in [c0, parallel, crossing] { + let cmp = intersect_cubics(c0, c1, sure, ish); + assert_eq!(cmp.iter().collect::>(), [(0.0, 1.0, Order::Ish)]); + } + } + } + + // Raising the tolerances for large x coordinates must not turn an invalid + // pair into a valid one. + #[test] + fn invalid_tolerances_at_large_x() { + let c0 = vertical(1e15, 0.0, 1.0); + let c1 = vertical(1e15 + 1e6, 0.0, 1.0); + let cmp = intersect_cubics(c0, c1, 2e-6, 1e-6); + assert_eq!(cmp.iter().collect::>(), [(0.0, 1.0, Order::Ish)]); + } + + #[test] + fn disjoint_vertical_ranges() { + let cmp = intersect_cubics(vertical(0.0, 0.0, 1.0), vertical(1.0, 2.0, 3.0), 1e-6, 2e-6); + assert_eq!(cmp.iter().count(), 0); + cmp.check_invariants(); + assert_eq!(cmp.order_after(0.5), Order::Ish); + assert_eq!(cmp.with_y_slop(0.5).iter().count(), 0); + } + #[test] fn y_slop_single_seg() { let order = CurveOrder { @@ -1846,6 +3012,32 @@ mod test { assert_eq!(order.clone().with_y_slop(0.5).cmps, order.cmps); } + // Craft patch (y-slop metrics): the recursion-depth observations survive + // the slop, including when it changes the entries. + #[test] + fn y_slop_keeps_metrics() { + let metrics = Metrics { + entries: vec![MetricsEntry { end: 1.0, depth: 3 }].into(), + }; + let order = CurveOrder { + start: 0.0, + cmps: [ + CurveOrderEntry { + end: 0.5, + order: Order::Left, + }, + CurveOrderEntry { + end: 1.0, + order: Order::Ish, + }, + ] + .into_iter() + .collect(), + metrics: metrics.clone(), + }; + assert_eq!(order.with_y_slop(0.1).metrics, metrics); + } + #[test] fn y_slop_short_start_order() { let order = CurveOrder { @@ -1918,6 +3110,33 @@ mod test { assert_eq!(order.clone().with_y_slop(0.5).cmps, order.cmps); } + // c0 is almost horizontal and only its first 0.0158 of height overlaps c1. + // The curves stay more than 4.4 apart there, so the whole overlap is Left. + #[test] + fn almost_horizontal_piece_cut_to_the_overlap() { + let c0 = CubicBez::new( + (311.848, 248.7972), + (313.515, 248.9023), + (315.181, 248.9698), + (316.848, 248.9988), + ); + let c1 = CubicBez::new( + (316.909, 243.813), + (316.818, 245.48), + (316.698, 247.146), + (316.549, 248.813), + ); + let order = intersect_cubics(c0, c1, 5e-7, 1e-6); + assert_eq!(order.start, 248.7972); + assert_eq!( + &order.cmps[..], + &[CurveOrderEntry { + end: 248.813, + order: Order::Left + }] + ); + } + // Cases where two curves share just a single y coordinate. #[test] fn curve_order_no_overlap() { @@ -1935,6 +3154,13 @@ mod test { }; let order = intersect_cubics(c0, c1, 0.125, 0.25); assert_eq!(order.start, 1.0); + // Craft patch (metrics opt-in): a single-y comparison records one + // entry at depth zero. + #[cfg(feature = "metrics")] + assert_eq!( + order.metrics.entries.as_slice(), + &[MetricsEntry { end: 1.0, depth: 0 }] + ); assert_eq!( &order.cmps[..], &[CurveOrderEntry { @@ -1976,6 +3202,49 @@ mod test { ); } + // Craft patch (inline pieces) tests: a decomposition is no larger than two + // inline pieces, one or two pieces stay inline, and one with more pieces + // than that keeps all of them on the heap. + #[test] + fn horizontal_decomposition_stores_two_pieces_inline() { + assert!( + std::mem::size_of::() + <= 2 * std::mem::size_of::() + 2 * std::mem::size_of::() + ); + } + + #[test] + fn horizontal_decomposition_keeps_every_piece() { + let cases = [ + ( + CubicBez::new((0.0, 0.0), (10.0, 10.0), (20.0, 20.0), (30.0, 30.0)), + 1, + ), + ( + CubicBez::new((0.0, 0.0), (10.0, 10.0), (20.0, 20.0), (500.0, 30.0)), + 2, + ), + ( + CubicBez::new((0.0, 0.0), (2000.0, 10.0), (-1000.0, 20.0), (1000.0, 30.0)), + 5, + ), + ( + CubicBez::new((0.0, 0.0), (2000.0, 0.0), (-1000.0, 30.0), (1000.0, 30.0)), + 5, + ), + ]; + for (c, count) in cases { + let decomp = AlmostHorizontalDecomposition::from_monotone_cubic(c); + assert_eq!(decomp.pieces.len(), count); + assert_eq!(decomp.pieces.spilled(), count > 2); + assert_eq!(decomp.pieces[0].c.p0, c.p0); + assert_eq!(decomp.pieces[count - 1].c.p3, c.p3); + for pair in decomp.pieces.windows(2) { + assert_eq!(pair[0].c.p3.y, pair[1].c.p0.y); + } + } + } + // This test recurses a bit too deeply. The two curves are quite close, // and near the end they're just a bit more than eps apart. #[test] @@ -1998,6 +3267,193 @@ mod test { dbg!(intersect_cubics(c0, c1, sure_tol, ish_tol)); } + // Craft patch (monotone handles) test: after the shape is split into + // y-monotone pieces, some pieces have a handle outside their own y-range. + // The outline must still follow the input curves, for the shape and for + // its mirror image in y. + #[test] + fn decomposition_keeps_handles_outside_the_y_range() { + use kurbo::{BezPath, ParamCurve as _, ParamCurveNearest as _, Shape as _}; + + for svg in [ + "M0,5 C5,0 2,0 1,1 C0,2 4,0 5,5 Z", + "M0,0 C5,5 2,5 1,4 C0,3 4,5 5,0 Z", + ] { + let input = BezPath::from_svg(svg).unwrap(); + let topology = crate::topology::Topology::::from_path(&input, 1e-6).unwrap(); + let contours = topology.contours(|w| *w != 0); + let mut output = BezPath::new(); + for contour in contours.contours() { + output.extend(contour.path.iter()); + } + + let area = output.area().abs(); + assert!((area - 10.9122).abs() < 1e-3, "{svg}: area {area}"); + + let input_segs: Vec<_> = input.segments().collect(); + for seg in output.segments() { + for i in 0..=16 { + let p = seg.eval(i as f64 / 16.0); + let dist = input_segs + .iter() + .map(|s| s.nearest(p, 1e-9).distance_sq) + .fold(f64::INFINITY, f64::min) + .sqrt(); + assert!(dist < 1e-6, "{svg}: {p:?} is {dist} from the input"); + } + } + } + } + + // With `t` found to within 1e-12, x on this curve 1e9 tall was off by up + // to 166 times `64 * f64::EPSILON * l`. + #[test] + fn solve_x_for_y_on_tall_curve() { + let l = 1e9; + let eps = 64.0 * f64::EPSILON * l; + let c = CubicBez::new( + (0.0, 0.0), + (0.8 * l, 0.33 * l), + (-0.8 * l, 0.66 * l), + (0.1 * l, l), + ); + for i in 1..200 { + let y = l * f64::from(i) / 200.0; + let (mut lo, mut hi) = (0.0f64, 1.0f64); + loop { + let mid = lo + (hi - lo) / 2.0; + if mid <= lo || mid >= hi { + break; + } + if c.eval(mid).y < y { + lo = mid; + } else { + hi = mid; + } + } + let exact = c.eval(lo).x; + let x = solve_x_for_y(c, y); + assert!( + (x - exact).abs() <= eps / 4.0, + "y {y}: x {x}, bisection {exact}" + ); + } + } + + // Two copies of one S-shaped curve 2e7 tall, 1.2 tolerances apart. With + // `t` found to within 1e-12 the comparison split them into 16,549 + // entries; at 3e7 it took 950,130 entries and 9 s, and at 1e8 it ran for + // minutes. + #[test] + fn near_parallel_tall_curves() { + let l = 2e7; + let eps = (64.0 * f64::EPSILON * l).max(1e-6); + let c0 = CubicBez::new( + (0.0, 0.0), + (0.8 * l, 0.33 * l), + (-0.8 * l, 0.66 * l), + (0.1 * l, l), + ); + let shift = kurbo::Vec2::new(1.2 * eps, 0.0); + let c1 = CubicBez::new(c0.p0 + shift, c0.p1 + shift, c0.p2 + shift, c0.p3 + shift); + + let cmp = intersect_cubics(c0, c1, eps / 2.0, eps); + let entries = cmp.iter().count(); + assert!(entries <= 64, "{entries} entries"); + assert!(cmp.iter().all(|(_, _, order)| order != Order::Right)); + } + + // At a height of 1.5e8 one ulp is about 3e-8, more than `ish_tolerance`. + // Splitting the close interval around a crossing used to repeat the same + // one-ulp interval until the stack overflowed. + #[test] + fn ish_tolerance_below_float_spacing() { + let offset = 1.5e8; + let mut segs = crate::Segments::default(); + segs.add_bez_path(&kurbo::Circle::new((offset, offset), 1.0).to_path(1e-9)) + .unwrap(); + segs.add_bez_path(&kurbo::Circle::new((offset + 1.0, offset), 1.0).to_path(1e-9)) + .unwrap(); + let cubics: Vec<_> = segs.segments().map(|s| s.to_kurbo_cubic()).collect(); + let mut compared = 0; + for c0 in &cubics { + for c1 in &cubics { + let y1 = c0.p3.y.min(c1.p3.y); + if c0.p0.y.max(c1.p0.y) >= y1 { + continue; + } + let order = intersect_cubics(*c0, *c1, 5e-11, 1e-10); + order.check_invariants(); + assert_eq!(order.iter().last().map(|(_, end, _)| end), Some(y1)); + compared += 1; + } + } + assert!(compared > 0); + } + + // Raising tiny tolerances must not merge curves that are a few ulps + // apart: at 1e15 one ulp is 0.125, and these lines are 1.0 apart. + #[test] + fn raised_tolerance_keeps_far_curves_apart() { + let x = 1e15; + let c0 = PathSeg::Line(Line::new((x, 0.0), (x, 1.0))).to_cubic(); + let c1 = PathSeg::Line(Line::new((x + 1.0, 0.0), (x + 1.0, 1.0))).to_cubic(); + let order = intersect_cubics(c0, c1, 1e-12, 1e-11); + let entries: Vec<_> = order.iter().collect(); + assert_eq!(entries, vec![(0.0, 1.0, Order::Left)]); + } + + // The floor depends on the x coordinates only: large y coordinates do + // not make lines 1.0 apart close. + #[test] + fn raised_tolerance_ignores_large_y() { + let y = 2e15; + let c0 = PathSeg::Line(Line::new((0.0, y), (0.0, y + 1.0))).to_cubic(); + let c1 = PathSeg::Line(Line::new((1.0, y), (1.0, y + 1.0))).to_cubic(); + let order = intersect_cubics(c0, c1, 1e-12, 1e-11); + let entries: Vec<_> = order.iter().collect(); + assert_eq!(entries, vec![(y, y + 1.0, Order::Left)]); + } + + // Subnormal coordinates keep their order: the floor goes down to the + // spacing of subnormal floats, not to `f64::MIN_POSITIVE`. + #[test] + fn raised_tolerance_keeps_subnormal_curves_apart() { + let x = 1e-310; + let c0 = PathSeg::Line(Line::new((x, 0.0), (x, 1.0))).to_cubic(); + let c1 = PathSeg::Line(Line::new((2.0 * x, 0.0), (2.0 * x, 1.0))).to_cubic(); + let order = intersect_cubics(c0, c1, 1e-320, 2e-320); + let entries: Vec<_> = order.iter().collect(); + assert_eq!(entries, vec![(0.0, 1.0, Order::Left)]); + } + + // Craft patch (end order check): two finite curves near 1e8 that cross + // once. Without `slow-asserts`, a debug build compares them without a + // panic and gives the order on each side of the crossing. + #[cfg(not(feature = "slow-asserts"))] + #[test] + fn crossing_at_large_coordinates() { + let sure_tol = 8.993802161699384e-7; + let ish_tol = 1.7987604323398767e-6; + let c0 = CubicBez::new( + (125383211.83146076, 66386026.504549935), + (83601374.51512215, 98950975.47591528), + (59801634.505237974, 115174249.23969136), + (54096217.42598602, 115174249.23969136), + ); + let c1 = CubicBez::new( + (73570041.209444, 57614167.78993744), + (90770853.19226673, 60905254.4942346), + (107971665.17508946, 64196341.19853177), + (125172477.1579122, 67487427.90282893), + ); + + let cmp = intersect_cubics(c0, c1, sure_tol, ish_tol); + assert_eq!(cmp.iter().last().unwrap().1, c1.p3.y); + assert_eq!(cmp.order_at(c0.p0.y), Order::Right); + assert_eq!(cmp.order_at(c1.p3.y), Order::Left); + } + #[test] fn quadratic_comparison() { let c0 = CubicBez::new((0.0, 0.0), (10.0, 10.0), (20.0, 20.0), (30.0, 30.0)); @@ -2038,6 +3494,49 @@ mod test { ); } + // Craft patch (metrics opt-in) tests: the order is the same with and + // without the `metrics` feature, and entries are recorded only with it. + fn crossing_cubics_order() -> CurveOrder { + let c0 = CubicBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 0.5), (1.0, 1.0)); + let c1 = CubicBez::new((1.0, 0.0), (1.0, 0.5), (0.0, 0.5), (0.0, 1.0)); + intersect_cubics(c0, c1, 1e-6, 1e-4) + } + + #[test] + fn crossing_cubics_order_does_not_depend_on_metrics() { + let order = crossing_cubics_order(); + let intervals: Vec<_> = order.iter().collect(); + assert_eq!(intervals.iter().map(|entry| entry.2).collect::>(), [Order::Left, Order::Ish, Order::Right]); + assert_eq!(intervals.first().unwrap().0, 0.0); + assert_eq!(intervals.last().unwrap().1, 1.0); + assert!(intervals.iter().all(|(start, end, _)| start < end)); + assert!(intervals.windows(2).all(|pair| pair[0].1 == pair[1].0)); + assert_eq!(order.order_at(0.25), Order::Left); + assert_eq!(order.order_at(0.5), Order::Ish); + assert_eq!(order.order_at(0.75), Order::Right); + } + + #[test] + fn crossing_cubics_metrics_follow_the_feature() { + let order = crossing_cubics_order(); + assert_eq!(order.metrics.entries.is_empty(), !cfg!(feature = "metrics")); + assert_eq!(order.flip().metrics, order.metrics); + } + + // The comparison recurses toward the crossing at y = 0.5, and each + // interval records the depth it was decided at. + #[cfg(feature = "metrics")] + #[test] + fn crossing_cubics_metrics_record_the_recursion_depth() { + let order = crossing_cubics_order(); + let entries = &order.metrics.entries; + assert!(!entries.is_empty()); + assert!(entries.iter().all(|entry| entry.end > 0.0 && entry.end <= 1.0)); + assert!(entries.windows(2).all(|pair| pair[0].end <= pair[1].end)); + assert_eq!(entries.last().unwrap().end, 1.0); + assert!(entries.iter().any(|entry| entry.depth > 0)); + } + // TODO: improve this test #[test] fn break_horizontal() { @@ -2053,4 +3552,64 @@ mod test { let c0 = CubicBez::new((0.0, 0.0), (2000.0, 0.0), (-1000.0, 30.0), (1000.0, 30.0)); dbg!(AlmostHorizontalDecomposition::from_monotone_cubic(c0)); } + + #[test] + fn opposite_orders_get_a_zero_height_ish() { + let mut order = CurveOrder::new(0.0); + order.push(1.0, Order::Right, MetricsStatus::default()); + order.push(2.0, Order::Left, MetricsStatus::default()); + order.check_invariants(); + + let entries: Vec<_> = order.iter().collect(); + assert_eq!( + entries, + vec![ + (0.0, 1.0, Order::Right), + (1.0, 1.0, Order::Ish), + (1.0, 2.0, Order::Left) + ] + ); + assert_eq!(order.order_at(1.5), Order::Left); + } + + #[test] + fn extreme_numeric_quadratic_discriminant_keeps_large_coefficient_roots() { + let q = Quadratic::new([-2f64.powi(-29), 0.0, 2f64.powi(1023)]); + let (positive, left, right) = quadratic_signs(q); + let expected = 2f64.powi(-526); + assert!(positive); + assert!((left / expected + 1.0).abs() < 1e-12, "{left}"); + assert!((right / expected - 1.0).abs() < 1e-12, "{right}"); + } + + #[test] + fn extreme_numeric_overflowing_control_leg_has_unbounded_slope() { + let c = CubicBez::new((0.0, -1e308), (0.0, -9e307), (1.0, 9e307), (1.0, 1e308)); + assert!(max_slope(c).is_infinite()); + } + + // Craft patch (quadratic scale) test: the cubic with y = [0, -s, -2s, s] + // turns at t = 0.5 for every scale s. + #[test] + fn quadratic_signs_at_extreme_scales() { + for s in [1e-200, 1.0, 1e160] { + let q = Quadratic::new([-s, 0.0, 4.0 * s]); + assert_eq!(quadratic_signs(q), (true, -0.5, 0.5), "scale {s}"); + + let c = CubicBez::new((0.0, 0.0), (1.0, -s), (2.0, -2.0 * s), (3.0, s)); + let ends: Vec = crate::geom::monotonic_cubic_pieces(c) + .iter() + .map(|p| p.end_t) + .collect(); + assert_eq!(ends, [0.5, 1.0], "scale {s}"); + } + + // Coefficients far apart in size whose products are in range keep + // their roots, +-2^-1021.5 (about 3.147e-308). + let q = Quadratic::new([-(2f64.powi(-1022)), 0.0, 2f64.powi(1021)]); + let (initially_positive, r0, r1) = quadratic_signs(q); + assert!(initially_positive); + assert!((r0 + r1).abs() <= 1e-15 * r1, "{r0} {r1}"); + assert!(r1 > 3.14e-308 && r1 < 3.15e-308, "{r1}"); + } } diff --git a/vendor/linesweeper/src/generators.rs b/vendor/linesweeper/src/generators.rs index 1451369fdb..44d28c0cd7 100644 --- a/vendor/linesweeper/src/generators.rs +++ b/vendor/linesweeper/src/generators.rs @@ -56,9 +56,11 @@ fn squares((x0, y0): (f64, f64), size: f64, offset: f64, slant: f64, count: usiz /// non-overlapping squares, and the inner collection of `(n - 1) x (n - 1)` /// non-overlapping squares. pub fn checkerboard(n: usize) -> (Contours, Contours) { + // Craft patch (empty checkerboard): `n - 1` overflows for `n = 0`, so the + // inner count saturates at zero. ( squares((0.0, 0.0), 30.0, 40.0, 0.0, n), - squares((20.0, 20.0), 30.0, 40.0, 0.0, n - 1), + squares((20.0, 20.0), 30.0, 40.0, 0.0, n.saturating_sub(1)), ) } @@ -67,9 +69,10 @@ pub fn checkerboard(n: usize) -> (Contours, Contours) { /// Horizontal lines have special handling in the sweep-line algorithm, so /// their presence or absence can affect performance. pub fn slanted_checkerboard(n: usize) -> (Contours, Contours) { + // Craft patch (empty checkerboard). ( squares((0.0, 0.0), 30.0, 40.0, 1.0, n), - squares((20.0, 20.0), 30.0, 40.0, 1.0, n - 1), + squares((20.0, 20.0), 30.0, 40.0, 1.0, n.saturating_sub(1)), ) } @@ -145,3 +148,21 @@ pub fn star(n: usize) -> (BezPath, BezPath) { (straight, bent) } + +// Craft patch (empty checkerboard). +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn checkerboards_of_size_zero_and_one() { + for generate in [checkerboard, slanted_checkerboard] { + let (outer, inner) = generate(0); + assert!(outer.is_empty() && inner.is_empty()); + let (outer, inner) = generate(1); + assert_eq!((outer.len(), inner.len()), (1, 0)); + let (outer, inner) = generate(3); + assert_eq!((outer.len(), inner.len()), (9, 4)); + } + } +} diff --git a/vendor/linesweeper/src/geom.rs b/vendor/linesweeper/src/geom.rs index 6aa0bdabe4..2794462bfc 100644 --- a/vendor/linesweeper/src/geom.rs +++ b/vendor/linesweeper/src/geom.rs @@ -368,8 +368,18 @@ impl Segment { SegmentInner::Line { p0: q0, p1: q1 } => { let p0 = q0.to_kurbo(); let p3 = q1.to_kurbo(); - let p1 = p0 + (1. / 3.) * (p3 - p0); - let p2 = p0 + (2. / 3.) * (p3 - p0); + // On an axis where the segment is more than f64::MAX long, + // take the weighted sum of the end points instead. + let at = |a: f64, b: f64, t: f64| { + let d = b - a; + if d.is_finite() { + a + t * d + } else { + (1. - t) * a + t * b + } + }; + let p1 = kurbo::Point::new(at(p0.x, p3.x, 1. / 3.), at(p0.y, p3.y, 1. / 3.)); + let p2 = kurbo::Point::new(at(p0.x, p3.x, 2. / 3.), at(p0.y, p3.y, 2. / 3.)); kurbo::CubicBez { p0, p1, p2, p3 } } SegmentInner::Quadratic { @@ -476,8 +486,41 @@ impl Segment { if self.is_horizontal() { p1.x } else { - let t = (y - p0.y) / (p1.y - p0.y); - p0.x + t * (p1.x - p0.x) + // On an axis where the segment is more than f64::MAX + // long, work with half of each height, and take the + // weighted sum of the x coordinates. + let dy = p1.y - p0.y; + if !dy.is_finite() { + if y == p0.y { + return p0.x; + } + if y == p1.y { + return p1.x; + } + let half_y = p1.y * 0.5 - p0.y * 0.5; + let half_x = p1.x * 0.5 - p0.x * 0.5; + let slope = half_x / half_y; + if !slope.is_normal() { + let t = (y * 0.5 - p0.y * 0.5) / half_y; + return (1.0 - t) * p0.x + t * p1.x; + } + let middle = p0.y.midpoint(p1.y); + let (anchor_y, anchor_x) = if y < p0.y.midpoint(middle) { + (p0.y, p0.x) + } else if y > middle.midpoint(p1.y) { + (p1.y, p1.x) + } else { + (middle, p0.x.midpoint(p1.x)) + }; + return (y - anchor_y).mul_add(slope, anchor_x); + } + let t = (y - p0.y) / dy; + let dx = p1.x - p0.x; + if dx.is_finite() { + p0.x + t * dx + } else { + (1.0 - t) * p0.x + t * p1.x + } } } // We could have a more optimized implementation for qudratics. @@ -492,6 +535,11 @@ impl Segment { let end_y = (y + eps).min(self.end().y); match self.inner { + // Craft patch (horizontal line bounds): a horizontal line is bounded by both + // endpoints. `at_y` returns only its right end. + SegmentInner::Line { p0, p1 } if self.is_horizontal() => { + kurbo::Rect::from_points((p0.x, p0.y), (p1.x, p1.y)) + } SegmentInner::Line { .. } => { let start_x = self.at_y(start_y); let end_x = self.at_y(end_y); @@ -540,3 +588,82 @@ impl Segment { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn affine_endpoints_line_height_keeps_a_small_nonzero_offset() { + let line = Segment::straight(Point::new(-1e308, -1e308), Point::new(1e308, 1e308)); + assert!((line.at_y(1.0) - 1.0).abs() <= 8.0 * f64::EPSILON); + assert!(line.upper(1.0, 0.0) >= 1.0); + assert!(line.lower(-1.0, 0.0) <= -1.0); + } + + #[test] + fn extreme_line_height_preserves_a_tiny_horizontal_span() { + let line = Segment::straight(Point::new(0.0, -1e308), Point::new(1e-20, 1e308)); + for (y, expected) in [(-1e308, 0.0), (-5e307, 2.5e-21), (0.0, 5e-21), (5e307, 7.5e-21), (1e308, 1e-20)] { + let actual = line.at_y(y); + assert!((actual - expected).abs() <= 1e-35, "at {y}: {actual}, expected {expected}"); + } + } + + #[test] + fn extreme_line_height_preserves_uneven_endpoint_coordinates() { + for line in [ + Segment::straight(Point::new(1.0, -1e308), Point::new(1e308, 1e308)), + Segment::straight(Point::new(-1e308, -1e308), Point::new(-1.0, 1e308)), + ] { + assert_eq!(line.at_y(line.start().y), line.start().x); + assert_eq!(line.at_y(line.end().y), line.end().x); + assert!(line.lower(line.start().y, 0.0) <= line.start().x); + assert!(line.upper(line.end().y, 0.0) >= line.end().x); + } + } + + // Craft patch (horizontal line bounds) + #[test] + fn horizontal_line_bounds_cover_both_endpoints() { + let s = Segment::straight(Point::new(0.0, 0.0), Point::new(10.0, 0.0)); + assert_eq!(s.lower(0.0, 0.25), -0.25); + assert_eq!(s.upper(0.0, 0.25), 10.25); + } + + #[test] + fn line_wider_and_taller_than_f64_max() { + let s = 1e308; + let seg = Segment::straight(Point::new(-s, -s), Point::new(s, s)); + assert_eq!(seg.at_y(0.0), 0.0); + assert_eq!(seg.at_y(-s), -s); + assert_eq!(seg.at_y(s), s); + + let c = seg.to_kurbo_cubic(); + let third = s / 3.0; + for (p, expected) in [(c.p1, -third), (c.p2, third)] { + assert!((p.x - expected).abs() <= 1e-15 * s, "{p:?}"); + assert!((p.y - expected).abs() <= 1e-15 * s, "{p:?}"); + } + } + + #[test] + fn line_wider_than_f64_max_and_very_short() { + let s = 1e308; + let tiny = f64::from_bits(1); + let seg = Segment::straight(Point::new(-s, 0.0), Point::new(s, 3.0 * tiny)); + let x = seg.at_y(tiny); + assert!((x + s / 3.0).abs() <= 1e-15 * s, "{x}"); + } + + #[test] + fn line_wider_than_f64_max_with_uneven_ends() { + let left = -(2.0f64.powi(1023)); + let seg = Segment::straight(Point::new(left, 0.0), Point::new(f64::MAX, 1.0)); + assert_eq!(seg.at_y(0.0), left); + assert_eq!(seg.at_y(1.0), f64::MAX); + let x = seg.at_y(0.5); + let expected = f64::MAX * 0.5 + left * 0.5; + assert!((x - expected).abs() <= 1e-15 * f64::MAX, "{x}"); + } +} diff --git a/vendor/linesweeper/src/lib.rs b/vendor/linesweeper/src/lib.rs index 7d2500d095..ae667e4efe 100644 --- a/vendor/linesweeper/src/lib.rs +++ b/vendor/linesweeper/src/lib.rs @@ -19,7 +19,6 @@ pub mod topology; pub mod generators; pub use geom::{Point, Segment}; -use kurbo::Shape; pub use segments::{SegIdx, Segments}; // pub so that we can use it in fuzz tests, but it's really private @@ -74,6 +73,56 @@ pub enum Error { NaN, /// One of the inputs had a non-closed path. NonClosedPath(NonClosedPath), + /// The sweep gave winding numbers that disagree around a point, so the + /// contours of the output set could not be walked. + InconsistentWindingNumbers, + /// At least one of the inputs had a coordinate with a magnitude above [`MAX_COORDINATE`]. + TooLarge, + /// The sweep did more work (segment comparisons, position checks, searches of the + /// sweep line and visits of horizontal segments) than its work limit allows, or the + /// topology's output would pass its output limit. + WorkLimitExceeded, + /// The accuracy parameter was NaN, infinite, zero or negative. + InvalidEps, + /// [`binary_op`] chose an accuracy parameter `eps` from the largest + /// coordinate of the inputs, and one input subpath is narrower than + /// [`FEATURE_EPS_RATIO`] times `eps` in x or y. The sweep could merge + /// that subpath away or drop it, while the smallest automatic `eps` would + /// keep it. Call [`binary_op_with_eps`] to choose `eps` yourself. + // Craft patch (far-point eps). + FeatureBelowTolerance { + /// The accuracy parameter that `binary_op` chose. + eps: f64, + }, +} + +/// The largest coordinate magnitude that [`Topology`] and [`binary_op`] accept. +/// +/// The curve arithmetic overflows for coordinates above about `f64::MAX / 3`. +pub const MAX_COORDINATE: f64 = f64::MAX / 16.0; + +/// Checks that every point of `path` is finite and at most [`MAX_COORDINATE`] in magnitude. +pub(crate) fn check_coordinates(path: &kurbo::BezPath) -> Result<(), Error> { + for el in path.iter() { + let (p0, p1, p2) = match el { + kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => (p, p, p), + kurbo::PathEl::QuadTo(p0, p1) => (p0, p1, p1), + kurbo::PathEl::CurveTo(p0, p1, p2) => (p0, p1, p2), + kurbo::PathEl::ClosePath => continue, + }; + for v in [p0.x, p0.y, p1.x, p1.y, p2.x, p2.y] { + if v.is_nan() { + return Err(Error::NaN); + } + if v.is_infinite() { + return Err(Error::Infinity); + } + if v.abs() > MAX_COORDINATE { + return Err(Error::TooLarge); + } + } + } + Ok(()) } impl From for Error { @@ -88,6 +137,21 @@ impl std::fmt::Display for Error { Error::Infinity => write!(f, "one of the inputs was infinite"), Error::NaN => write!(f, "one of the inputs had a NaN"), Error::NonClosedPath(_) => write!(f, "one of the inputs had a non-closed path"), + Error::InconsistentWindingNumbers => { + write!(f, "the winding numbers disagree around a point") + } + Error::TooLarge => write!(f, "one of the inputs had a coordinate that was too large"), + Error::WorkLimitExceeded => { + write!(f, "the sweep did more work or made more output than its limits allow") + } + Error::InvalidEps => { + write!(f, "the accuracy parameter was not a positive finite number") + } + // Craft patch (far-point eps). + Error::FeatureBelowTolerance { eps } => write!( + f, + "one of the inputs had a subpath too small for the accuracy {eps} that its largest coordinate needs" + ), } } } @@ -100,32 +164,118 @@ impl std::error::Error for Error {} /// This function calls [`binary_op_with_eps`] with an automatically-chosen /// accuracy parameter. The automatically-chosen accuracy is fairly /// conservative, so you may get better performance by choosing your own. +/// +/// The accuracy parameter is `64 * f64::EPSILON` times the largest coordinate +/// magnitude of either input, and at least [`MIN_AUTO_EPS`]. The sweep uses it +/// for every segment, so one far point coarsens the result everywhere. When it +/// is above [`MIN_AUTO_EPS`] and an input subpath that is at least +/// [`FEATURE_EPS_RATIO`] times [`MIN_AUTO_EPS`] wide and high is narrower than +/// [`FEATURE_EPS_RATIO`] times the accuracy parameter in x or y, this function +/// returns [`Error::FeatureBelowTolerance`] instead of a result without that +/// subpath. The check uses each subpath's bounding box, so a thin part of a +/// larger subpath, or a gap narrower than the accuracy parameter between two +/// subpaths, can still be merged without an error. +// Craft patch (far-point eps): the doc paragraph above and the check below. pub fn binary_op( set_a: &kurbo::BezPath, set_b: &kurbo::BezPath, fill_rule: FillRule, op: BinaryOp, ) -> Result { - // Find the extremal values, to figure out how much precision we can support. - let bbox = set_a.bounding_box().union(set_b.bounding_box()); - let min = bbox.min_x().min(bbox.min_y()); - let max = bbox.max_x().max(bbox.max_y()); - if min.is_infinite() || max.is_infinite() { - return Err(Error::Infinity); - } - // If there was any NaN in the input, it should have propagated to the min and max. - if min.is_nan() || max.is_nan() { - return Err(Error::NaN); - } + let top = Topology::from_paths_with_automatic_accuracy( + [ + (set_a, topology::OneOfTwo::A), + (set_b, topology::OneOfTwo::B), + ], + None, + )?; + binary_contours(top, fill_rule, op) +} - // TODO: we did some analysis for error bounds in the case of polylines. - // Think more about what makes sense for curves. - let m_2 = min.abs().max(max.abs()); - let eps = m_2 * (f64::EPSILON * 64.0); - let eps = eps.max(1e-6); +/// Returns the automatic accuracy for [`binary_op`]. Nonfinite coordinates and +/// subpaths that fail that function's feature-size check return its errors. +/// Accuracy queries also accept open paths. +/// Bounded sweeps use [`Topology::from_paths_with_automatic_limits`]. +pub fn binary_op_accuracy(set_a: &kurbo::BezPath, set_b: &kurbo::BezPath) -> Result { + automatic_accuracy(&[set_a, set_b]) +} + +fn automatic_accuracy(paths: &[&kurbo::BezPath]) -> Result { + for path in paths { + check_coordinates(path)?; + } + let max_coord = paths + .iter() + .flat_map(|path| kurbo::segments(segments::skip_leading_close_paths(path.iter()))) + .flat_map(geom::monotonic_pieces) + .map(|piece| { + let seg = piece.piece; + seg.min_x() + .abs() + .max(seg.max_x().abs()) + .max(seg.start().y.abs()) + .max(seg.end().y.abs()) + }) + .fold(0.0, f64::max); + let eps = MIN_AUTO_EPS.max(curve::resolution_floor(max_coord)); debug_assert!(eps.is_finite()); - binary_op_with_eps(set_a, set_b, fill_rule, op, eps) + // Craft patch (far-point eps). + if eps > MIN_AUTO_EPS { + let kept = MIN_AUTO_EPS * FEATURE_EPS_RATIO; + let limit = eps * FEATURE_EPS_RATIO; + let too_small = paths + .iter() + .flat_map(|path| subpath_bounding_boxes(path)) + .map(|rect| rect.width().min(rect.height())) + .any(|size| size >= kept && size < limit); + if too_small { + return Err(Error::FeatureBelowTolerance { eps }); + } + } + Ok(eps) +} + +/// The smallest accuracy parameter that [`binary_op`] chooses. +// Craft patch (far-point eps). +pub const MIN_AUTO_EPS: f64 = 1e-6; + +/// [`binary_op`] returns [`Error::FeatureBelowTolerance`] for an input +/// subpath narrower than this many times its accuracy parameter in x or y. +/// The sweep widens each segment by `eps` on both sides, and the output can +/// move by up to `eps`. +// Craft patch (far-point eps). +pub const FEATURE_EPS_RATIO: f64 = 4.0; + +/// The exact bounding box of each subpath of `path`, with its closing segment. +// Craft patch (far-point eps). +fn subpath_bounding_boxes(path: &kurbo::BezPath) -> Vec { + use kurbo::{CubicBez, Line, ParamCurve, ParamCurveExtrema, PathEl, PathSeg, QuadBez, Rect}; + + let mut boxes = Vec::new(); + let mut current: Option = None; + let mut start = kurbo::Point::ZERO; + let mut last = start; + for el in path.elements() { + let seg = match *el { + PathEl::MoveTo(p) => { + boxes.extend(current.take()); + start = p; + last = p; + current = Some(Rect::from_points(p, p)); + continue; + } + PathEl::LineTo(p) => PathSeg::Line(Line::new(last, p)), + PathEl::QuadTo(p1, p2) => PathSeg::Quad(QuadBez::new(last, p1, p2)), + PathEl::CurveTo(p1, p2, p3) => PathSeg::Cubic(CubicBez::new(last, p1, p2, p3)), + PathEl::ClosePath => PathSeg::Line(Line::new(last, start)), + }; + last = seg.end(); + let rect = ParamCurveExtrema::bounding_box(&seg); + current = Some(current.map_or(rect, |r| r.union(rect))); + } + boxes.extend(current); + boxes } /// Computes a boolean operation between two sets, each of which is described as @@ -133,6 +283,21 @@ pub fn binary_op( /// /// The output paths will not exactly agree with the input paths in general. /// The accuracy parameter `eps` bounds how much they can differ. +/// +/// Returns [`Error::InvalidEps`] when `eps` is NaN, infinite, zero or +/// negative. A positive `eps` below `64 * f64::EPSILON` times the largest +/// coordinate magnitude is raised to that value. +/// +/// The [`Topology`] constructors and [`sweep::Sweeper::new_with_correctness`] +/// handle an invalid `eps` differently: they return no error for it and use +/// that floor in its place. Call this function when an invalid `eps` should be +/// reported as an error, and a [`Topology`] constructor or the [`sweep::Sweeper`] +/// when it should be replaced. +/// +/// `eps` is one absolute tolerance for every segment, so a part of the input +/// narrower than about `eps`, or a gap narrower than about `eps`, can be +/// merged away or dropped. +// Craft patch (far-point eps): the doc paragraph above. pub fn binary_op_with_eps( set_a: &kurbo::BezPath, set_b: &kurbo::BezPath, @@ -140,7 +305,18 @@ pub fn binary_op_with_eps( op: BinaryOp, eps: f64, ) -> Result { + if !(eps.is_finite() && eps > 0.0) { + return Err(Error::InvalidEps); + } let top = Topology::from_paths_binary(set_a, set_b, eps)?; + binary_contours(top, fill_rule, op) +} + +fn binary_contours( + top: Topology, + fill_rule: FillRule, + op: BinaryOp, +) -> Result { #[cfg(feature = "debug-svg")] { svg::save( @@ -170,13 +346,136 @@ pub fn binary_op_with_eps( } }; - Ok(top.contours(inside)) + top.try_contours(inside) } #[cfg(test)] mod tests { + #[test] + fn automatic_accuracy_does_not_prepare_sweep_metadata() { + let small = kurbo::Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1); + let far = kurbo::Rect::new(1e14, 1e14, 1e14 + 10.0, 1e14 + 10.0).to_path(0.1); + super::segments::PREPARED_SEGMENTS.with(|count| count.set(0)); + assert_eq!(binary_op_accuracy(&small, &BezPath::new()).unwrap(), MIN_AUTO_EPS); + assert_eq!(super::segments::PREPARED_SEGMENTS.with(|count| count.get()), 0); + let result = Topology::::from_paths_with_automatic_limits([(&small, ()), (&far, ())], 1, 1); + assert!(matches!(result, Err(Error::FeatureBelowTolerance { .. }))); + assert_eq!(super::segments::PREPARED_SEGMENTS.with(|count| count.get()), 0); + } + + #[test] + fn automatic_accuracy_accepts_open_paths() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((1.0, 1.0)); + assert_eq!(binary_op_accuracy(&path, &BezPath::new()).unwrap(), MIN_AUTO_EPS); + assert!(matches!( + Topology::::from_paths_with_automatic_limits([(&path, ())], 1, 1), + Err(Error::NonClosedPath(_)) + )); + } + + #[test] + fn automatic_feature_rejection_does_not_sort_events() { + let small = kurbo::Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1); + let far = kurbo::Rect::new(1e14, 1e14, 1e14 + 10.0, 1e14 + 10.0).to_path(0.1); + super::segments::ENTER_COMPARISONS.with(|count| count.set(0)); + let result = Topology::::from_paths_with_automatic_limits([(&small, ()), (&far, ())], 1, 1); + assert!(matches!(result, Err(Error::FeatureBelowTolerance { .. }))); + assert_eq!(super::segments::ENTER_COMPARISONS.with(|count| count.get()), 0); + } + + #[test] + fn automatic_accuracy_does_not_sort_events() { + let path = kurbo::Rect::new(0.0, 0.0, 10.0, 10.0).to_path(0.1); + super::segments::ENTER_COMPARISONS.with(|count| count.set(0)); + assert!(binary_op_accuracy(&path, &BezPath::new()).is_ok()); + assert_eq!(super::segments::ENTER_COMPARISONS.with(|count| count.get()), 0); + } + + #[test] + fn automatic_boolean_reuses_the_prepared_segment_events() { + let mut path = BezPath::new(); + for i in 0..64 { + let x = f64::from(i) * 20.0; + path.extend(kurbo::Rect::new(x, 0.0, x + 10.0, 10.0).to_path(0.1).iter()); + } + let empty = BezPath::new(); + super::segments::ENTER_COMPARISONS.with(|count| count.set(0)); + let eps = binary_op_accuracy(&path, &empty).unwrap(); + super::segments::ENTER_COMPARISONS.with(|count| count.set(0)); + let prepared_topology = Topology::::from_paths([(&path, ())], eps).unwrap(); + assert_eq!(prepared_topology.contours(|winding| *winding != 0).len(), 64); + let prepared = super::segments::ENTER_COMPARISONS.with(|count| count.replace(0)); + assert!(prepared > 0); + let contours = binary_op(&path, &empty, FillRule::NonZero, BinaryOp::Union).unwrap(); + assert_eq!(contours.len(), 64); + let swept = super::segments::ENTER_COMPARISONS.with(|count| count.get()); + assert_eq!(swept, prepared, "the input event sort must be reused"); + super::segments::ENTER_COMPARISONS.with(|count| count.set(0)); + let bounded = Topology::::from_paths_with_automatic_limits([(&path, ())], 1, 4); + assert!(matches!(bounded, Err(Error::WorkLimitExceeded))); + let bounded = super::segments::ENTER_COMPARISONS.with(|count| count.get()); + assert_eq!( + bounded, prepared, + "a bounded sweep must reuse the same input sort" + ); + } + + #[test] + fn automatic_accuracy_ignores_discarded_horizontal_handles() { + let flat = BezPath::from_svg("M0 0 C1e14 0 1e14 0 0 0 Z").unwrap(); + for size in [1.0, 5.0] { + let square = kurbo::Rect::new(0.0, 0.0, size, size).to_path(0.1); + let expected = binary_op_accuracy(&square, &BezPath::new()).unwrap(); + for (a, b) in [(&flat, &square), (&square, &flat)] { + assert_eq!(binary_op_accuracy(a, b).unwrap(), expected); + let contours = binary_op(a, b, FillRule::NonZero, BinaryOp::Union).unwrap(); + assert_eq!(contours.contours().map(|c| c.path.area()).sum::(), size * size); + } + } + } + + #[test] + fn automatic_accuracy_checks_control_point_scale() { + let mut path = BezPath::new(); + path.move_to((-1e14, 0.0)); + path.curve_to((5e14, 1e14 / 3.0), (-5e14, 2e14 / 3.0), (1e14, 1e14)); + path.close_path(); + let narrow = kurbo::Rect::new(0.0, -100.0, 6.0, -90.0).to_path(0.1); + for (a, b) in [(&path, &narrow), (&narrow, &path)] { + assert!(matches!( + binary_op_accuracy(a, b), + Err(Error::FeatureBelowTolerance { .. }) + )); + } + let wide = kurbo::Rect::new(0.0, -100.0, 64.0, -36.0).to_path(0.1); + assert!(binary_op_accuracy(&path, &wide).is_ok()); + } + + #[test] + fn automatic_accuracy_checks_move_only_coordinates() { + let empty = kurbo::BezPath::new(); + for (coordinate, error) in [ + (f64::INFINITY, super::Error::Infinity), + (f64::NEG_INFINITY, super::Error::Infinity), + (f64::NAN, super::Error::NaN), + (super::MAX_COORDINATE * 2.0, super::Error::TooLarge), + ] { + let mut path = kurbo::BezPath::new(); + path.move_to((coordinate, 0.0)); + assert_eq!(super::binary_op_accuracy(&path, &empty), Err(error)); + assert_eq!(super::binary_op_accuracy(&empty, &path), Err(error)); + } + let mut path = kurbo::BezPath::new(); + path.move_to((super::MAX_COORDINATE, 0.0)); + assert_eq!( + super::binary_op_accuracy(&path, &empty), + Ok(super::MIN_AUTO_EPS) + ); + } use insta::assert_ron_snapshot; - use kurbo::BezPath; + use kurbo::{BezPath, Shape}; use super::*; @@ -205,6 +504,41 @@ mod tests { insta::assert_ron_snapshot!(output); } + // Craft patch (leading ClosePath). + #[test] + fn leading_close_path() { + // `BezPath`'s own constructors reject these, but deserializing does not. + let close_only: BezPath = serde_json::from_str(r#"["ClosePath"]"#).unwrap(); + let triangle = r#"{"MoveTo":{"x":0.0,"y":0.0}},{"LineTo":{"x":10.0,"y":0.0}},{"LineTo":{"x":0.0,"y":10.0}},"ClosePath""#; + let plain: BezPath = serde_json::from_str(&format!("[{triangle}]")).unwrap(); + let leading: BezPath = + serde_json::from_str(&format!(r#"["ClosePath",{triangle}]"#)).unwrap(); + + let empty = Topology::::from_path(&close_only, 1e-6).unwrap(); + assert_eq!(empty.contours(|w| *w != 0).contours().count(), 0); + + let expected = Topology::::from_path(&plain, 1e-6) + .unwrap() + .contours(|w| *w != 0); + let actual = Topology::::from_path(&leading, 1e-6) + .unwrap() + .contours(|w| *w != 0); + let paths = + |c: &topology::Contours| c.contours().map(|c| c.path.clone()).collect::>(); + assert_eq!(paths(&actual), paths(&expected)); + assert_eq!(paths(&actual).len(), 1); + + for (a, b) in [ + (&close_only, &plain), + (&plain, &close_only), + (&leading, &plain), + (&plain, &leading), + ] { + let output = binary_op(a, b, FillRule::NonZero, BinaryOp::Union).unwrap(); + assert_eq!(output.contours().count(), 1); + } + } + // This example has a union of two not-quite-axis-aligned crosses. It // suffers from some extra quadratic segments near the intersection points, // but it used to be worse. @@ -267,6 +601,24 @@ mod tests { Topology::from_path(&path, 0.001).unwrap(); } + // Craft patch (add_bez_path error). + #[test] + fn add_bez_path_error_leaves_segments_unchanged() { + let mut segments = Segments::default(); + let open = BezPath::from_svg("M0,0 L10,0 L5,10 Z M20,0 L30,5 L25,10").unwrap(); + assert!(segments.add_bez_path(&open).is_err()); + assert_eq!(segments.len(), 0); + segments.check_invariants(); + + let square = BezPath::from_svg("M40,0 L50,0 L50,10 L40,10 Z").unwrap(); + segments.add_bez_path(&square).unwrap(); + segments.check_invariants(); + assert_eq!(segments.len(), 4); + let mut entered: Vec<_> = segments.entrances().iter().map(|(_, idx)| *idx).collect(); + entered.sort(); + assert_eq!(entered, segments.indices().collect::>()); + } + #[test] fn empty_paths() { let contours = binary_op( @@ -279,6 +631,21 @@ mod tests { assert!(contours.contours().next().is_none()); } + // With `slow-asserts`, building the topology checks the winding numbers + // and panics on this path, so the test runs only without that feature. + #[test] + #[cfg(not(feature = "slow-asserts"))] + fn inconsistent_winding_numbers_are_an_error() { + // `binary_op` on this path returns either contours or + // `InconsistentWindingNumbers`, and does not panic or loop forever. + let path = BezPath::from_svg("M4,-1 C8,1 -7,-2 5,8 L-4,-8 L2,1 L1,1 Z").unwrap(); + let result = binary_op(&path, &BezPath::new(), FillRule::EvenOdd, BinaryOp::Union); + assert!(matches!( + result, + Ok(_) | Err(Error::InconsistentWindingNumbers) + )); + } + #[test] fn repeated_points() { Topology::from_polylines_binary( @@ -333,4 +700,245 @@ mod tests { 4 ); } + + #[test] + fn coordinates_above_max_coordinate() { + let shape = |y: f64| { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.curve_to((y / 4.0, y), (y / 2.0, y), (y, y)); + path.line_to((0.0, y)); + path.close_path(); + path + }; + + assert_eq!(check_coordinates(&shape(MAX_COORDINATE)), Ok(())); + let above = f64::from_bits(MAX_COORDINATE.to_bits() + 1); + assert_eq!(check_coordinates(&shape(above)), Err(Error::TooLarge)); + assert_eq!(check_coordinates(&shape(-above)), Err(Error::TooLarge)); + assert_eq!( + check_coordinates(&shape(f64::INFINITY)), + Err(Error::Infinity) + ); + assert_eq!(check_coordinates(&shape(f64::NAN)), Err(Error::NaN)); + + for y in [6e307, 7e307, 1.7e308] { + let path = shape(y); + let top = Topology::::from_path(&path, y * f64::EPSILON * 64.0); + assert!(matches!(top, Err(Error::TooLarge))); + let op = binary_op(&path, &path, FillRule::NonZero, BinaryOp::Union); + assert!(matches!(op, Err(Error::TooLarge))); + } + } + + /// Two unit circles whose centers are one unit apart, at `(offset, offset)` + /// and `(offset + 1, offset)`. + fn crossing_circles(offset: f64) -> (BezPath, BezPath) { + ( + kurbo::Circle::new((offset, offset), 1.0).to_path(1e-9), + kurbo::Circle::new((offset + 1.0, offset), 1.0).to_path(1e-9), + ) + } + + /// The single contour's area, measured after moving it back to the origin. + fn single_contour_area(contours: &topology::Contours, offset: f64) -> f64 { + let contours: Vec<_> = contours.contours().collect(); + assert_eq!(contours.len(), 1); + (kurbo::Affine::translate((-offset, -offset)) * contours[0].path.clone()) + .area() + .abs() + } + + const UNION_AREA: f64 = 5.054816; + + #[test] + fn binary_op_with_eps_rejects_invalid_eps() { + let (a, b) = crossing_circles(0.0); + // -inf goes last: before the check it made the sweep loop forever. + for eps in [ + f64::NAN, + -1.0, + -1e-6, + 0.0, + -0.0, + f64::INFINITY, + f64::NEG_INFINITY, + ] { + let result = binary_op_with_eps(&a, &b, FillRule::NonZero, BinaryOp::Union, eps); + assert_eq!(result.err(), Some(Error::InvalidEps), "eps = {eps}"); + } + } + + #[test] + fn union_with_huge_coordinates() { + use kurbo::{Affine, Circle, Rect}; + + // A circle overlapping a rectangle. The union is one contour whose area is + // s^2 * (pi / 9 + 4 / 9 - pi / 36), give or take the circle's flattening. + let union_area = |s: f64| { + let r = s / 3.0; + let circle = Circle::new((r, r), r).to_path(1e-3 * r); + let rect = Rect::new(r, r, s, s).to_path(0.0); + let contours = binary_op(&circle, &rect, FillRule::NonZero, BinaryOp::Union).unwrap(); + let paths: Vec<_> = contours.contours().map(|c| c.path.clone()).collect(); + let area: f64 = paths + .iter() + .map(|p| (Affine::scale(1.0 / s) * p.clone()).area()) + .sum(); + (paths.len(), area.abs()) + }; + + let (count, expected) = union_area(1.0); + assert_eq!(count, 1); + for s in [1e155, 1e200, 1e300] { + let (count, area) = union_area(s); + assert_eq!(count, 1, "s = {s}"); + assert!( + (area - expected).abs() < 1e-4, + "s = {s}: {area} != {expected}" + ); + } + } + + #[test] + fn topology_raises_unusable_eps() { + let inside = |w: &BinaryWindingNumber| w.shape_a != 0 || w.shape_b != 0; + // At 1.5e8 one ulp is about 3e-8, so 1e-10 used to recurse in + // intersect_cubics_rec until the stack overflowed. + for (offset, eps) in [ + (0.0, f64::NAN), + (0.0, -1.0), + (0.0, 0.0), + (1.5e8, 1e-10), + (1.5e8, 0.0), + (0.0, f64::NEG_INFINITY), + (0.0, f64::INFINITY), + ] { + let (a, b) = crossing_circles(offset); + for correctness in [ + sweep::Correctness::GoodEnough, + sweep::Correctness::ReallyCorrect, + ] { + let top = Topology::from_paths_with_correctness( + [(&a, topology::OneOfTwo::A), (&b, topology::OneOfTwo::B)], + eps, + correctness, + ) + .unwrap(); + let area = single_contour_area(&top.contours(inside), offset); + assert!( + (area - UNION_AREA).abs() < 1e-3, + "offset {offset}, eps {eps}, {correctness:?}: area {area}" + ); + } + } + } + + #[test] + fn binary_op_with_eps_raises_eps_below_coordinate_resolution() { + let (a, b) = crossing_circles(1.5e8); + let contours = + binary_op_with_eps(&a, &b, FillRule::NonZero, BinaryOp::Union, 1e-10).unwrap(); + let area = single_contour_area(&contours, 1.5e8); + assert!((area - UNION_AREA).abs() < 1e-3, "area {area}"); + } + + // Craft patch (far-point eps). + #[test] + fn far_point_eps() { + let rect = |x0, y0, x1, y1| kurbo::Rect::new(x0, y0, x1, y1).to_path(0.0); + let far_triangle = |at: f64| { + let mut path = BezPath::new(); + path.move_to((at, at)); + path.line_to((at + 1.0e3, at)); + path.line_to((at, at + 1.0e3)); + path.close_path(); + path + }; + let with = |base: &BezPath, extra: &BezPath| { + let mut path = base.clone(); + path.extend(extra.iter()); + path + }; + let auto_eps = |far: f64| ((far + 1.0e3) * (f64::EPSILON * 64.0)).max(MIN_AUTO_EPS); + let union = |a: &BezPath, b: &BezPath| binary_op(a, b, FillRule::NonZero, BinaryOp::Union); + let inside = |contours: &topology::Contours, p: (f64, f64)| { + contours + .contours() + .map(|c| c.path.winding(p.into())) + .sum::() + != 0 + }; + + // A 10 x 10 square and a 0.3 x 10 sliver, united with another square. + let near = with(&rect(0.0, 0.0, 10.0, 10.0), &rect(40.0, 0.0, 40.3, 10.0)); + let other = rect(5.0, 5.0, 15.0, 15.0); + let out = union(&near, &other).unwrap(); + assert!(inside(&out, (40.15, 5.0))); + assert!(inside(&out, (2.0, 2.0))); + + // A triangle at 3e13 raises eps to about 0.43, and the sliver is + // narrower than 4 * eps. + let far = 3.0e13; + assert_eq!( + union(&with(&near, &far_triangle(far)), &other).unwrap_err(), + Error::FeatureBelowTolerance { eps: auto_eps(far) } + ); + assert_eq!( + union(&other, &with(&near, &far_triangle(far))).unwrap_err(), + Error::FeatureBelowTolerance { eps: auto_eps(far) } + ); + + // A triangle at 1e12 gives eps about 0.014, and nothing is that small. + let out = union(&with(&near, &far_triangle(1.0e12)), &other).unwrap(); + assert!(inside(&out, (40.15, 5.0))); + + // Every subpath at least 4 * eps wide and high: no error at eps about 14. + let far = 1.0e15; + let big = with(&rect(0.0, 0.0, 100.0, 100.0), &far_triangle(far)); + assert!(union(&big, &rect(200.0, 0.0, 300.0, 100.0)).is_ok()); + + // A zero-width subpath is lost at any eps, so it is not reported. + let mut line_and_back = kurbo::Line::new((0.0, 50.0), (100.0, 50.0)).to_path(0.0); + line_and_back.close_path(); + assert!(union(&with(&big, &line_and_back), &BezPath::new()).is_ok()); + + // A subpath below 4 * MIN_AUTO_EPS is lost at any eps, so it is not reported. + let tiny = rect(50.0, 50.0, 50.0 + 1.0e-7, 50.0 + 1.0e-7); + assert!(union(&with(&big, &tiny), &BezPath::new()).is_ok()); + assert!(union(&tiny, &far_triangle(1.0e8)).is_ok()); + + // The check measures curves, not control points: this cubic's control + // points span 10 in x and the curve about 2.9, below 4 * eps (about 3.98). + let mut thin_curve = BezPath::new(); + thin_curve.move_to((40.0, 0.0)); + thin_curve.curve_to((45.0, 10.0 / 3.0), (35.0, 20.0 / 3.0), (40.0, 10.0)); + thin_curve.close_path(); + let width = subpath_bounding_boxes(&thin_curve)[0].width(); + assert!(width > 2.8 && width < 2.9, "{width}"); + let far = 7.0e13; + assert!(union(&thin_curve, &other).is_ok()); + assert_eq!( + union(&with(&thin_curve, &far_triangle(far)), &other).unwrap_err(), + Error::FeatureBelowTolerance { eps: auto_eps(far) } + ); + + // One box per subpath, with the closing segment. + let mut open_close = BezPath::new(); + open_close.move_to((0.0, 0.0)); + open_close.line_to((5.0, 1.0)); + open_close.close_path(); + open_close.line_to((0.0, 3.0)); + open_close.close_path(); + open_close.move_to((10.0, 10.0)); + open_close.line_to((12.0, 11.0)); + open_close.close_path(); + assert_eq!( + subpath_bounding_boxes(&open_close), + vec![ + kurbo::Rect::new(0.0, 0.0, 5.0, 3.0), + kurbo::Rect::new(10.0, 10.0, 12.0, 11.0) + ] + ); + } } diff --git a/vendor/linesweeper/src/order.rs b/vendor/linesweeper/src/order.rs index b421bd885f..75b6a8fe5c 100644 --- a/vendor/linesweeper/src/order.rs +++ b/vendor/linesweeper/src/order.rs @@ -3,18 +3,41 @@ use rustc_hash::FxHashMap; use crate::{ - SegIdx, Segments, - curve::{self, CurveOrder}, + SegIdx, Segment, Segments, + curve::{self, CurveOrder, Order}, }; /// A cache for curve comparisons, so that each pair of curves needs to be compared at most once. +/// +/// The cache holds the comparisons of one [`Segments`] arena. When it is given +/// a different arena, a clone included, it drops the comparisons it holds and +/// starts again with that arena. #[derive(Clone, Debug)] pub struct ComparisonCache { - inner: FxHashMap<(SegIdx, SegIdx), (CurveOrder, CurveOrder)>, + // Craft patch (comparison cache size): each pair stores the order of its + // lower-indexed segment relative to the other. A lookup in the other + // direction flips it into `flipped`. + inner: FxHashMap<(SegIdx, SegIdx), CurveOrder>, + flipped: Option, + flipped_key: Option<(SegIdx, SegIdx)>, + edited_flipped: FxHashMap<(SegIdx, SegIdx), CurveOrder>, + // Craft patch (comparison cache size): `evict_ended` scans the cache once + // it holds this many pairs. + next_purge: usize, accuracy: f64, tolerance: f64, + // Craft patch (work limit): the number of calls to + // `compare_non_horizontal_segments` and `with_order`, cached or not, which `Sweeper` checks against its work + // limit. + pub(crate) calls: u64, + // Craft patch (comparison cache arena): the arena that `inner` describes. + arena: Option, } +// Craft patch (comparison cache size): the smallest cache that `evict_ended` +// scans. Unit tests use a small value so that the sweep tests evict. +const MIN_PURGE: usize = if cfg!(test) { 8 } else { 4096 }; + impl ComparisonCache { /// Creates a new comparison cache. /// @@ -27,8 +50,14 @@ impl ComparisonCache { pub fn new(tolerance: f64, accuracy: f64) -> Self { ComparisonCache { inner: FxHashMap::default(), + flipped: None, + flipped_key: None, + edited_flipped: FxHashMap::default(), + next_purge: MIN_PURGE, accuracy, tolerance, + calls: 0, + arena: None, } } @@ -43,72 +72,571 @@ impl ComparisonCache { pub fn new_without_y_slop(tolerance: f64, accuracy: f64) -> Self { ComparisonCache { inner: FxHashMap::default(), + flipped: None, + flipped_key: None, + edited_flipped: FxHashMap::default(), + next_purge: MIN_PURGE, accuracy, tolerance, + calls: 0, + arena: None, } } /// Compares two segments, returning their order. + /// + /// Returns `None` if either segment is horizontal. + /// Edits to the returned order persist until its pair is evicted or the arena changes. pub fn compare_segments( &mut self, segments: &Segments, i: SegIdx, j: SegIdx, + ) -> Option<&mut CurveOrder> { + // Craft patch (horizontal comparison): horizontal segments are + // rejected with `None` instead of reaching the comparison. + if segments[i].is_horizontal() || segments[j].is_horizontal() { + return None; + } + self.compare_non_horizontal_segments(segments, i, j); + if i.0 < j.0 { + self.inner.get_mut(&(i, j)) + } else { + let key = (j, i); + if self.edited_flipped.contains_key(&key) { + self.edited_flipped.get_mut(&key) + } else { + self.flipped_key = Some(key); + self.flipped.as_mut() + } + } + } + + fn save_flipped_edits(&mut self) { + let Some(key) = self.flipped_key.take() else { + return; + }; + if self.flipped.as_ref().zip(self.inner.get(&key)) + .is_some_and(|(reverse, forward)| !reverse.is_flip_of(forward)) + && let Some(reverse) = self.flipped.take() + { + self.edited_flipped.insert(key, reverse); + } + } + + /// Compares two segments that are not horizontal, returning their order. + /// + /// The sweep line, `position` and `topology` hold only segments that are + /// not horizontal, and call this directly. + pub(crate) fn compare_non_horizontal_segments( + &mut self, + segments: &Segments, + i: SegIdx, + j: SegIdx, ) -> &mut CurveOrder { use std::collections::hash_map::Entry; + self.calls = self.calls.saturating_add(1); + // Craft patch (comparison cache arena): comparisons cached for + // another arena do not describe this one. + let arena = segments.arena_id(); + if self.arena != Some(arena) { + self.inner.clear(); + self.edited_flipped.clear(); + self.flipped_key = None; + self.arena = Some(arena); + } else { + self.save_flipped_edits(); + } + let (i, j, flipped) = if i.0 < j.0 { (i, j, false) } else { (j, i, true) }; - match self.inner.entry((i, j)) { - Entry::Occupied(o) => { - if flipped { - &mut o.into_mut().1 - } else { - &mut o.into_mut().0 - } - } - Entry::Vacant(v) => { - let segi = &segments[i]; - let segj = &segments[j]; + if flipped && let Some(order) = self.edited_flipped.get_mut(&(i, j)) { + return order; + } - let forward = - if let (Some(l0), Some(l1)) = (segi.as_kurbo_line(), segj.as_kurbo_line()) { - curve::line::intersect_lines(l0, l1, self.tolerance) - } else { - let c0 = segi.to_kurbo_cubic(); - let c0_div = segments.horiz_decomp(i); - let c1 = segj.to_kurbo_cubic(); - let c1_div = segments.horiz_decomp(j); - curve::intersect_cubics_with_precomputed_decomp( - c0, - c0_div, - c1, - c1_div, - self.accuracy, - self.tolerance, - ) - }; - debug_assert_eq!( - forward.iter().last().unwrap().1, - segi.end().y.min(segj.end().y) - ); - let reverse = forward.flip(); - let v = v.insert((forward, reverse)); - if flipped { &mut v.1 } else { &mut v.0 } + let stored = match self.inner.entry((i, j)) { + Entry::Occupied(o) => o.into_mut(), + Entry::Vacant(v) => { + v.insert(compute(segments, i, j, self.tolerance, self.accuracy)) } + }; + if flipped { + if let Some(out) = self.flipped.as_mut() { + stored.flip_into(out); + } + self.flipped.get_or_insert_with(|| stored.flip()) + } else { + stored } } + + // Craft patch (comparison cache size): removes the pairs in which a + // segment ends above `y`. Callers pass heights that never decrease, so + // such a pair is not compared again; if it were, the comparison would be + // computed again with the same result. The cache is scanned only after it + // has doubled since the last scan, so the scans take time proportional to + // the number of comparisons. + pub(crate) fn evict_ended(&mut self, segments: &Segments, y: f64) { + if self.inner.len() < self.next_purge { + return; + } + self.save_flipped_edits(); + self.inner + .retain(|(i, j), _| segments[*i].end().y >= y && segments[*j].end().y >= y); + self.edited_flipped.retain(|key, _| self.inner.contains_key(key)); + if self.inner.len() * 4 < self.inner.capacity() { + self.inner.shrink_to_fit(); + } + if self.edited_flipped.len() * 4 < self.edited_flipped.capacity() { + self.edited_flipped.shrink_to_fit(); + } + self.next_purge = self.inner.len().saturating_mul(2).max(MIN_PURGE); + } + + #[cfg(test)] + pub(crate) fn cached_pairs(&self) -> usize { + self.inner.len() + } + + #[cfg(test)] + pub(crate) fn never_evict(&mut self) { + self.next_purge = usize::MAX; + } + + /// Compares two segments that are not horizontal without storing a new result. + /// + /// `f` receives the order that [`ComparisonCache::compare_non_horizontal_segments`] would + /// return: the stored one if there is one, otherwise one computed the same way and dropped + /// after `f` returns. Each call counts as one comparison toward the sweep's work limit, as a + /// call to [`ComparisonCache::compare_non_horizontal_segments`] does. + pub(crate) fn with_order( + &mut self, + segments: &Segments, + i: SegIdx, + j: SegIdx, + f: impl FnOnce(&CurveOrder) -> R, + ) -> R { + self.calls = self.calls.saturating_add(1); + self.save_flipped_edits(); + let (i, j, flipped) = if i.0 < j.0 { + (i, j, false) + } else { + (j, i, true) + }; + + // Comparisons cached for another arena do not describe this one. + if self.arena == Some(segments.arena_id()) && flipped + && let Some(order) = self.edited_flipped.get(&(i, j)) + { + return f(order); + } + let stored = (self.arena == Some(segments.arena_id())) + .then(|| self.inner.get(&(i, j))) + .flatten(); + if let Some(forward) = stored { + return if flipped { + f(&forward.flip()) + } else { + f(forward) + }; + } + let forward = compute(segments, i, j, self.tolerance, self.accuracy); + if flipped { + f(&forward.flip()) + } else { + f(&forward) + } + } + + /// Returns the number of stored segment pairs. + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.inner.len() + } +} + +// Craft patch (far-apart comparison): compares two segments, at least one of +// which is not a line. A pair that is far apart skips the full comparison. +fn compare_curves( + segments: &Segments, + i: SegIdx, + j: SegIdx, + accuracy: f64, + tolerance: f64, +) -> CurveOrder { + let margin = far_apart_margin(tolerance, accuracy); + let Some(ret) = order_if_far_apart(&segments[i], &segments[j], margin) else { + return full_comparison(segments, i, j, accuracy, tolerance); + }; + + // The full comparison can split the heights of a far-apart pair and report + // some of them as `Ish`. It covers the same heights and never finds the + // opposite order. + #[cfg(any(test, feature = "slow-asserts"))] + { + let far: Vec<_> = ret.iter().collect(); + let full: Vec<_> = full_comparison(segments, i, j, accuracy, tolerance) + .iter() + .collect(); + assert_eq!(far[0].0, full[0].0); + assert_eq!(far[0].1, full[full.len() - 1].1); + assert!(full.iter().all(|entry| entry.2 != far[0].2.flip())); + } + + ret +} + +// Craft patch (far-apart comparison). +fn full_comparison( + segments: &Segments, + i: SegIdx, + j: SegIdx, + accuracy: f64, + tolerance: f64, +) -> CurveOrder { + curve::intersect_cubics_with_precomputed_decomp( + segments[i].to_kurbo_cubic(), + segments.horiz_decomp(i), + segments[j].to_kurbo_cubic(), + segments.horiz_decomp(j), + accuracy, + tolerance, + ) +} + +// Craft patch (far-apart comparison). +fn far_apart_margin(tolerance: f64, accuracy: f64) -> f64 { + 4.0 * tolerance.max(accuracy) +} + +// Craft patch (far-apart comparison): the order of two segments whose horizontal +// bounds are more than `margin` apart, and which overlap vertically. Control points +// bound each segment, so the segments keep this order at every height they share. +// +// The full comparison does not always give this answer. Its quadratic approximation +// has a large error on a steep curve, and it can report part of such a pair as `Ish`. +fn order_if_far_apart(segi: &Segment, segj: &Segment, margin: f64) -> Option { + let order = if segi.max_x() + margin < segj.min_x() { + Order::Left + } else if segj.max_x() + margin < segi.min_x() { + Order::Right + } else { + return None; + }; + let start = segi.start().y.max(segj.start().y); + let end = segi.end().y.min(segj.end().y); + (start <= end).then(|| CurveOrder::constant(start, end, order)) +} + +/// Computes the order of segment `i` relative to segment `j`. +fn compute(segments: &Segments, i: SegIdx, j: SegIdx, tolerance: f64, accuracy: f64) -> CurveOrder { + let segi = &segments[i]; + let segj = &segments[j]; + // Craft patch (horizontal comparison): `compare_segments` returns `None` + // for horizontal segments, and the crate calls this only for segments + // that are not horizontal. + debug_assert!(!segi.is_horizontal() && !segj.is_horizontal()); + + if segi.start().y.max(segj.start().y) > segi.end().y.min(segj.end().y) { + return CurveOrder::new(segi.start().y.max(segj.start().y)); + } + + let forward = if let (Some(l0), Some(l1)) = (segi.as_kurbo_line(), segj.as_kurbo_line()) { + curve::line::intersect_lines(l0, l1, tolerance) + } else { + compare_curves(segments, i, j, accuracy, tolerance) + }; + debug_assert_eq!( + forward.iter().last().unwrap().1, + segi.end().y.min(segj.end().y) + ); + forward } #[cfg(test)] mod tests { - use crate::{SegIdx, Segments, curve::Order}; + use kurbo::BezPath; + use proptest::prelude::*; - use super::ComparisonCache; + use crate::{ + SegIdx, Segments, + curve::{CurveOrder, MetricsEntry, Order}, + }; + + use super::{ComparisonCache, far_apart_margin, full_comparison, order_if_far_apart}; + + // Two closed paths with curves that bulge toward each other. The control points of + // the left curve reach `bulge` and those of the right curve start `gap` after that. + fn facing_curves(height: f64, bulge: f64, gap: f64) -> Segments { + let (left, right) = (0.0, bulge + gap); + let mut a = BezPath::new(); + a.move_to((left, 0.0)); + a.curve_to( + (bulge, height / 3.0), + (bulge, 2.0 * height / 3.0), + (left, height), + ); + a.line_to((left - 1.0, height / 2.0)); + a.close_path(); + + let mut b = BezPath::new(); + b.move_to((right + bulge, 0.0)); + b.curve_to( + (right, height / 3.0), + (right, 2.0 * height / 3.0), + (right + bulge, height), + ); + b.line_to((right + bulge + 1.0, height / 2.0)); + b.close_path(); + + let mut segments = Segments::default(); + segments.add_bez_path(&a).unwrap(); + segments.add_bez_path(&b).unwrap(); + segments + } + + // A closed path with a y-monotone cubic from `(x0, 0)` to `(x3, height)`. Its other + // control points are at the heights `a * height` and `b * height`. + fn steep_curve(xs: [f64; 4], a: f64, b: f64, height: f64) -> BezPath { + let mut path = BezPath::new(); + path.move_to((xs[0], 0.0)); + path.curve_to((xs[1], a * height), (xs[2], b * height), (xs[3], height)); + path.close_path(); + path + } + + fn intervals(order: &crate::curve::CurveOrder) -> Vec<(f64, f64, Order)> { + order.iter().collect() + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(2_000))] + + // Steep S-shaped and asymmetric curves, with heights that include the + // tolerance. Every pair goes through `compare_curves`, which checks in test + // builds that the full comparison covers the same heights and never finds the + // opposite order. The full comparison finds `Ish` in only some of these pairs. + #[test] + fn far_apart_steep_curves_never_reverse( + (tolerance, accuracy) in prop_oneof![ + Just((0.1f64, 0.05f64)), + Just((0.4, 0.05)), + Just((1e-6, 5e-7)), + ], + height in prop_oneof![Just(1.0f64), 1.0f64..4.0, 4.0f64..100.0], + widths in (-1.0f64..3.0, -1.0f64..3.0), + shapes in (0usize..3, 0usize..3), + x_controls in (0.0f64..1.0, 0.0f64..1.0, 0.0f64..1.0, 0.0f64..1.0), + y_controls in (0.0f64..0.5, 0.5f64..1.0, 0.0f64..0.5, 0.5f64..1.0), + gap in 1.0001f64..1.5, + swap: bool, + ) { + let height = height * tolerance; + let shape = |index: usize, x: f64, width: f64, controls: (f64, f64)| match index { + 0 => [x, x + width, x, x + width], + 1 => [x + width, x, x + width, x], + _ => [x, x + width * controls.0, x + width * controls.1, x + width], + }; + let w0 = tolerance * 10f64.powf(widths.0); + let w1 = tolerance * 10f64.powf(widths.1); + let right = w0 + gap * far_apart_margin(tolerance, accuracy); + let mut a = steep_curve( + shape(shapes.0, 0.0, w0, (x_controls.0, x_controls.1)), + y_controls.0, + y_controls.1, + height, + ); + let mut b = steep_curve( + shape(shapes.1, right, w1, (x_controls.2, x_controls.3)), + y_controls.2, + y_controls.3, + height, + ); + if swap { + std::mem::swap(&mut a, &mut b); + } + let mut segments = Segments::default(); + segments.add_bez_path(&a).unwrap(); + segments.add_bez_path(&b).unwrap(); + + let mut cmp = ComparisonCache::new(tolerance, accuracy); + for i in segments.indices() { + for j in segments.indices() { + if i != j { + cmp.compare_segments(&segments, i, j); + } + } + } + } + } + + proptest! { + // Every pair goes through `compare_curves`. The quadratic approximation of + // these curves has no error to speak of, so the full comparison gives a pair + // beyond the margin the same single order. The gaps include the margin of each + // tolerance and accuracy below. + #[test] + fn far_apart_curves_compare_like_the_full_comparison( + height in 0.001f64..10.0, + bulge in prop_oneof![Just(0.001f64), 0.001f64..0.5, 0.5f64..5.0], + gap in prop_oneof![ + 0.0f64..0.2, + 0.39f64..0.41, + 1.59f64..1.61, + 3.99f64..4.01, + 1.0f64..100.0, + ], + ) { + let segments = facing_curves(height, bulge, gap); + let eps = 0.1; + for (tolerance, accuracy) in [(eps, eps / 2.0), (4.0 * eps, eps / 2.0)] { + let mut cmp = ComparisonCache::new(tolerance, accuracy); + for i in segments.indices() { + for j in segments.indices() { + if i != j { + let compared = + intervals(cmp.compare_non_horizontal_segments(&segments, i, j)); + let margin = far_apart_margin(tolerance, accuracy); + if order_if_far_apart(&segments[i], &segments[j], margin).is_some() { + let full = full_comparison(&segments, i, j, accuracy, tolerance); + prop_assert_eq!(compared, intervals(&full)); + } + } + } + } + } + } + } + + // The full comparison reports part of this pair as `Ish`, so a far-apart answer + // shows that `compare_curves` did not use it. + #[test] + fn far_apart_steep_curves_skip_the_full_comparison() { + let height = 1.7356316808658495e-6; + let a = steep_curve( + [ + 0.0, + 2.487438508389841e-5, + 7.989789511893805e-5, + 2.5251761348508994e-4, + ], + 4.1143632201699014e-7 / height, + 1.3944624441448228e-6 / height, + height, + ); + let b = steep_curve( + [ + 2.5693176647313107e-4, + 2.7157585226714214e-4, + 2.9262618025363465e-4, + 4.220260171548132e-4, + ], + 1.1589752235482678e-6 / height, + 1.6934571328972848e-6 / height, + height, + ); + let mut segments = Segments::default(); + segments.add_bez_path(&a).unwrap(); + let curve_b = SegIdx(segments.len()); + segments.add_bez_path(&b).unwrap(); + let (tolerance, accuracy) = (1e-6, 5e-7); + + let full = full_comparison(&segments, SegIdx(0), curve_b, accuracy, tolerance); + assert!(intervals(&full).iter().any(|entry| entry.2 == Order::Ish)); + + let mut cmp = ComparisonCache::new(tolerance, accuracy); + assert_eq!( + intervals(cmp.compare_non_horizontal_segments(&segments, SegIdx(0), curve_b)), + vec![(0.0, height, Order::Left)] + ); + } + + #[test] + fn far_apart_order() { + let mut segments = Segments::default(); + segments.add_points([(0.0, 0.0), (1.0, 2.0)]); + segments.add_points([(2.0, 1.0), (3.0, 3.0)]); + segments.add_points([(1.5, 2.0), (1.5, 4.0)]); + segments.add_points([(9.0, 3.0), (9.0, 4.0)]); + let (a, b, c, d) = ( + &segments[SegIdx(0)], + &segments[SegIdx(1)], + &segments[SegIdx(2)], + &segments[SegIdx(3)], + ); + let intervals = + |o: Option| o.map(|o| o.iter().collect::>()); + + // The horizontal gap between `a` and `b` is 1. + assert_eq!( + intervals(order_if_far_apart(a, b, 0.8)), + Some(vec![(1.0, 2.0, Order::Left)]) + ); + assert_eq!( + intervals(order_if_far_apart(b, a, 0.8)), + Some(vec![(1.0, 2.0, Order::Right)]) + ); + assert_eq!(intervals(order_if_far_apart(a, b, 1.0)), None); + + // `a` and `c` meet only at the height 2. + assert_eq!( + intervals(order_if_far_apart(a, c, 0.4)), + Some(vec![(2.0, 2.0, Order::Left)]) + ); + + // `a` and `d` have no height in common. + assert_eq!(intervals(order_if_far_apart(a, d, 0.4)), None); + } + + #[test] + fn unstored_order_matches_stored_order() { + let mut segments = Segments::default(); + let ends = [ + (-3.0, 5.0), + (-1e-7, 5.0), + (0.0, 5.0), + (1e-7, 4.0), + (2.5e-7, 7.0), + (2.0, 1e-3), + (3.0, 5.0), + (1e6, 1e6), + ]; + for &end in &ends { + segments.add_points([(0.0, 0.0), end]); + } + segments + .add_bez_path(&kurbo::BezPath::from_svg("M0 0 Q 1 1 0 2 Z").unwrap()) + .unwrap(); + + for (tolerance, accuracy) in [(1e-6, 5e-7), (4e-6, 5e-7), (0.25, 0.125)] { + let mut stored = ComparisonCache::new(tolerance, accuracy); + let mut unstored = ComparisonCache::new(tolerance, accuracy); + for i in segments.indices() { + for j in segments.indices() { + if i == j { + continue; + } + let computed = + unstored.with_order(&segments, i, j, |c| c.iter().collect::>()); + let expected = stored + .compare_non_horizontal_segments(&segments, i, j) + .iter() + .collect::>(); + assert_eq!(computed, expected); + // A stored result is passed on as it is. + let reused = + stored.with_order(&segments, i, j, |c| c.iter().collect::>()); + assert_eq!(reused, expected); + } + } + assert_eq!(unstored.len(), 0); + } + } #[test] fn slop_regression() { @@ -120,6 +648,7 @@ mod tests { assert_eq!( cmp_cache .compare_segments(&segments, SegIdx(0), SegIdx(1)) + .unwrap() .iter() .next() .unwrap() @@ -127,4 +656,243 @@ mod tests { Order::Left ); } + + #[test] + fn comparison_contract_disjoint_cubics_have_empty_orders() { + let mut segments = Segments::default(); + for y in [0.0, 2.0] { + let mut path = BezPath::new(); + path.move_to((0.0, y)); + path.curve_to((0.1, y + 0.25), (-0.1, y + 0.75), (0.0, y + 1.0)); + segments.add_non_closed_bez_path(&path).unwrap(); + } + let mut cache = ComparisonCache::new(0.01, 0.005); + for (a, b) in [(0, 1), (1, 0)] { + assert!(cache.compare_segments(&segments, SegIdx(a), SegIdx(b)).unwrap().iter().next().is_none()); + } + } + + #[test] + fn mutable_reverse_comparisons_keep_their_edits() { + let mut segments = Segments::default(); + for x in [0.0, 1.0, 2.0] { + let mut path = BezPath::new(); + path.move_to((x, 0.0)); + path.line_to((x, 1.0)); + segments.add_non_closed_bez_path(&path).unwrap(); + } + let mut cache = ComparisonCache::new(0.01, 0.005); + let forward = cache.compare_segments(&segments, SegIdx(0), SegIdx(1)).unwrap().clone(); + let reverse = cache.compare_segments(&segments, SegIdx(1), SegIdx(0)).unwrap(); + reverse.metrics.entries.push(MetricsEntry { end: 0.5, depth: 7 }); + let expected = reverse.metrics.clone(); + let mut cloned = cache.clone(); + assert_eq!(cache.compare_segments(&segments, SegIdx(0), SegIdx(1)).unwrap().metrics, forward.metrics); + cache.compare_segments(&segments, SegIdx(2), SegIdx(0)).unwrap(); + assert_eq!(cache.compare_segments(&segments, SegIdx(1), SegIdx(0)).unwrap().metrics, expected); + assert_eq!(cloned.compare_segments(&segments, SegIdx(1), SegIdx(0)).unwrap().metrics, expected); + let other_arena = segments.clone(); + assert_eq!(cache.compare_segments(&other_arena, SegIdx(1), SegIdx(0)).unwrap().metrics, forward.metrics); + } + + #[test] + fn horizontal_and_cubic() { + let mut segments = Segments::default(); + segments.add_points([(-1.0, 1.0), (2.0, 1.0)]); + let mut path = kurbo::BezPath::new(); + path.move_to((0.0, 0.0)); + path.curve_to((1.0, 0.5), (-1.0, 1.5), (0.0, 2.0)); + segments.add_non_closed_bez_path(&path).unwrap(); + let mut cmp_cache = ComparisonCache::new(0.1, 0.05); + assert!( + cmp_cache + .compare_segments(&segments, SegIdx(0), SegIdx(1)) + .is_none() + ); + assert!( + cmp_cache + .compare_segments(&segments, SegIdx(1), SegIdx(0)) + .is_none() + ); + } + + #[test] + fn horizontal_and_line() { + let mut segments = Segments::default(); + segments.add_points([(-1.0, 1.0), (2.0, 1.0)]); + segments.add_points([(0.0, 0.0), (0.0, 2.0)]); + let mut cmp_cache = ComparisonCache::new(0.1, 0.05); + assert!( + cmp_cache + .compare_segments(&segments, SegIdx(1), SegIdx(0)) + .is_none() + ); + assert!( + cmp_cache + .compare_segments(&segments, SegIdx(0), SegIdx(1)) + .is_none() + ); + } + + fn first_order(cmp_cache: &mut ComparisonCache, segments: &Segments) -> Order { + cmp_cache + .compare_non_horizontal_segments(segments, SegIdx(0), SegIdx(1)) + .iter() + .next() + .unwrap() + .2 + } + + #[test] + fn other_arena_is_compared_again() { + let mut left_first = Segments::default(); + left_first.add_points([(0.0, 0.0), (0.0, 1.0)]); + left_first.add_points([(1.0, 0.0), (1.0, 1.0)]); + let mut right_first = Segments::default(); + right_first.add_points([(1.0, 0.0), (1.0, 1.0)]); + right_first.add_points([(0.0, 0.0), (0.0, 1.0)]); + + let mut cmp_cache = ComparisonCache::new(0.1, 0.05); + assert_eq!(first_order(&mut cmp_cache, &left_first), Order::Left); + assert_eq!(first_order(&mut cmp_cache, &right_first), Order::Right); + assert_eq!(first_order(&mut cmp_cache, &left_first), Order::Left); + } + + #[test] + fn diverged_clone_is_compared_again() { + let mut original = Segments::default(); + original.add_points([(0.0, 0.0), (0.0, 1.0)]); + let mut copy = original.clone(); + original.add_points([(1.0, 0.0), (1.0, 1.0)]); + copy.add_points([(-1.0, 0.0), (-1.0, 1.0)]); + + let mut cmp_cache = ComparisonCache::new(0.1, 0.05); + assert_eq!(first_order(&mut cmp_cache, &original), Order::Left); + assert_eq!(first_order(&mut cmp_cache, ©), Order::Right); + } + + #[test] + fn appending_keeps_cached_comparisons() { + let mut segments = Segments::default(); + segments.add_points([(0.0, 0.0), (0.0, 1.0)]); + segments.add_points([(1.0, 0.0), (1.0, 1.0)]); + let mut cmp_cache = ComparisonCache::new(0.1, 0.05); + assert_eq!(first_order(&mut cmp_cache, &segments), Order::Left); + + segments.add_points([(2.0, 0.0), (2.0, 1.0)]); + cmp_cache.compare_non_horizontal_segments(&segments, SegIdx(1), SegIdx(2)); + assert_eq!(cmp_cache.inner.len(), 2); + } + + // Two cubics that cross each other twice, and a vertical line that + // crosses both. + fn crossing_segments() -> Segments { + let mut segments = Segments::default(); + let mut path = kurbo::BezPath::new(); + path.move_to((0.0, 0.0)); + path.curve_to((3.0, 1.0), (-3.0, 2.0), (0.0, 3.0)); + segments.add_non_closed_bez_path(&path).unwrap(); + let mut path = kurbo::BezPath::new(); + path.move_to((0.5, 0.0)); + path.curve_to((-2.5, 1.0), (3.5, 2.0), (0.5, 3.0)); + segments.add_non_closed_bez_path(&path).unwrap(); + segments.add_points([(0.2, -0.5), (0.3, 3.5)]); + segments + } + + #[test] + fn one_order_per_pair() { + let segments = crossing_segments(); + let mut cmp_cache = ComparisonCache::new(0.1, 0.05); + for i in segments.indices() { + for j in segments.indices() { + if i != j { + cmp_cache.compare_non_horizontal_segments(&segments, i, j); + } + } + } + let n = segments.len(); + assert_eq!(cmp_cache.inner.len(), n * (n - 1) / 2); + for stored in cmp_cache.inner.values() { + assert_eq!( + std::mem::size_of_val(stored), + std::mem::size_of::() + ); + } + for i in segments.indices() { + for j in segments.indices() { + if i != j { + cmp_cache.compare_segments(&segments, i, j).unwrap(); + } + } + } + cmp_cache.save_flipped_edits(); + assert_eq!(cmp_cache.inner.len(), n * (n - 1) / 2); + assert!(cmp_cache.edited_flipped.is_empty()); + } + + #[test] + fn reversed_lookup_flips_the_stored_order() { + let segments = crossing_segments(); + let mut forward_first = ComparisonCache::new(0.1, 0.05); + let mut reverse_first = ComparisonCache::new(0.1, 0.05); + let entries = |order: &CurveOrder| order.iter().collect::>(); + for i in segments.indices() { + for j in segments.indices() { + if i.0 >= j.0 { + continue; + } + let reverse_before = + entries(reverse_first.compare_non_horizontal_segments(&segments, j, i)); + let forward = forward_first + .compare_non_horizontal_segments(&segments, i, j) + .clone(); + let reverse_after = forward_first + .compare_non_horizontal_segments(&segments, j, i) + .clone(); + let forward_again = + entries(forward_first.compare_non_horizontal_segments(&segments, i, j)); + let flipped: Vec<_> = entries(&forward) + .into_iter() + .map(|(y0, y1, order)| (y0, y1, order.flip())) + .collect(); + + assert_eq!(entries(&reverse_after), flipped); + assert_eq!(reverse_before, flipped); + assert_eq!(forward_again, entries(&forward)); + assert_eq!(reverse_after.metrics, forward.metrics); + } + } + } + + #[test] + fn reversed_lookups_reuse_the_flipped_buffers() { + let segments = crossing_segments(); + let mut cmp_cache = ComparisonCache::new(0.1, 0.05); + let entries = |order: &CurveOrder| order.iter().collect::>(); + let forward = cmp_cache + .compare_non_horizontal_segments(&segments, SegIdx(0), SegIdx(1)) + .clone(); + // Metrics are recorded only with the `metrics` feature. + #[cfg(feature = "metrics")] + assert!(!forward.metrics.entries.is_empty()); + + let first = cmp_cache.compare_non_horizontal_segments(&segments, SegIdx(1), SegIdx(0)); + let first_entries = entries(first); + let first_metrics = first.metrics.entries.as_ptr(); + let second = cmp_cache.compare_non_horizontal_segments(&segments, SegIdx(1), SegIdx(0)); + assert_eq!(second.metrics.entries.as_ptr(), first_metrics); + assert_eq!(entries(second), first_entries); + assert_eq!(second.metrics, forward.metrics); + + // A buffer that held another pair's order gives the same result as + // `flip`. + let other = cmp_cache + .compare_non_horizontal_segments(&segments, SegIdx(0), SegIdx(2)) + .clone(); + let mut out = other.flip(); + forward.flip_into(&mut out); + assert_eq!(entries(&out), entries(&forward.flip())); + assert_eq!(out.metrics, forward.metrics); + } } diff --git a/vendor/linesweeper/src/perturbation.rs b/vendor/linesweeper/src/perturbation.rs index ffb4aea5e4..7c2b22a605 100644 --- a/vendor/linesweeper/src/perturbation.rs +++ b/vendor/linesweeper/src/perturbation.rs @@ -44,12 +44,16 @@ impl FloatPerturbation for F64Perturbation { } std::num::FpCategory::Subnormal => { let bits = f.abs().to_bits(); + // Craft patch (ulp across zero): a step toward zero that is larger + // than `f` ends on the other side of zero. + let crosses_zero = !same_sign && u64::from(n.unsigned_abs()) > bits; let bits = if same_sign { bits + u64::from(n.unsigned_abs()) } else { bits.abs_diff(u64::from(n.unsigned_abs())) }; - f.signum() * f64::from_bits(bits) + let sign = if crosses_zero { -f.signum() } else { f.signum() }; + sign * f64::from_bits(bits) } std::num::FpCategory::Normal => { let delta = if same_sign { @@ -60,7 +64,10 @@ impl FloatPerturbation for F64Perturbation { // Taking the absolute value sets the sign bit to zero, so the // addition should never overflow. let bits = f.abs().to_bits().checked_add_signed(delta).unwrap(); - let x = if bits & sign_bit != 0 { + // Craft patch (ulp overflow): a step past `f64::MAX` reaches the + // infinity and NaN encodings, not the sign bit, so it is clamped to + // infinity there. + let x = if bits >= f64::INFINITY.to_bits() { f64::INFINITY } else { f64::from_bits(bits) @@ -198,3 +205,47 @@ pub fn realize_perturbation( } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn subnormal_ulp_step_crosses_zero() { + let tiny = f64::from_bits(1); + + assert_eq!(F64Perturbation::Ulp(-2).apply(&tiny), -tiny); + assert_eq!(F64Perturbation::Ulp(2).apply(&-tiny), tiny); + assert_eq!(F64Perturbation::Ulp(-3).apply(&tiny), -f64::from_bits(2)); + assert_eq!(F64Perturbation::Ulp(3).apply(&-tiny), f64::from_bits(2)); + + assert_eq!(F64Perturbation::Ulp(-1).apply(&tiny).to_bits(), 0.0_f64.to_bits()); + assert_eq!(F64Perturbation::Ulp(1).apply(&-tiny).to_bits(), (-0.0_f64).to_bits()); + + assert_eq!(F64Perturbation::Ulp(-1).apply(&f64::from_bits(3)), f64::from_bits(2)); + assert_eq!(F64Perturbation::Ulp(1).apply(&-f64::from_bits(3)), -f64::from_bits(2)); + } +} + +// Craft patch (ulp overflow). +#[cfg(test)] +mod ulp_overflow_tests { + use super::*; + + #[test] + fn ulp_step_past_f64_max_is_infinite() { + for (n, f, expected) in [ + (2, f64::MAX, f64::INFINITY), + (127, f64::MAX, f64::INFINITY), + (-2, -f64::MAX, f64::NEG_INFINITY), + (1, f64::from_bits(f64::MAX.to_bits() - 1), f64::MAX), + (-1, f64::MAX, f64::from_bits(f64::MAX.to_bits() - 1)), + ] { + assert_eq!( + F64Perturbation::Ulp(n).apply(&f), + expected, + "Ulp({n}) of {f}" + ); + } + } +} diff --git a/vendor/linesweeper/src/position.rs b/vendor/linesweeper/src/position.rs index f4cbd773d5..cc479d141e 100644 --- a/vendor/linesweeper/src/position.rs +++ b/vendor/linesweeper/src/position.rs @@ -9,7 +9,7 @@ use std::collections::BinaryHeap; -use kurbo::{BezPath, CubicBez, ParamCurve}; +use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveDeriv, ParamCurveNearest, QuadBez}; use polycool::Quadratic; use crate::{ @@ -168,7 +168,10 @@ fn approximate( let factor = horizontal_error_weight(cubic); - let too_short = y1 <= y0 + accuracy; + // An interval whose midpoint rounds to one of its ends cannot be + // halved. Halving it anyway would leave `y1` where it is, or return + // `y0` and stop the caller's loop from advancing. + let too_short = y1 <= y0 + accuracy || y_mid <= y0 || y_mid >= y1; let accurate = approx.dmax.max(-approx.dmin) * factor < accuracy; if !too_short && !accurate { // TODO: can we be smarter about this? @@ -218,14 +221,179 @@ fn bez_end_y(path: &BezPath) -> f64 { fn next_subsegment(seg: &Segment, out: &BezPath, y1: f64, endpoint: kurbo::Point) -> CubicBez { let p0 = bez_end(out); - let mut c = y_subsegment(seg.to_kurbo_cubic(), p0.y, y1); - c.p0 = p0; - if endpoint.y == y1 { - c.p3 = endpoint; + let orig = seg.to_kurbo_cubic(); + let mut c = y_subsegment(orig, p0.y, y1); + let p3 = if endpoint.y == y1 { endpoint } else { c.p3 }; + + // Craft patch (flat-end shear) + if (p0 != c.p0 || p3 != c.p3) + && let Some(piece) = settled_cubic( + orig, + solve_t_for_y(orig, p0.y), + solve_t_for_y(orig, y1), + p0, + p3, + ) + { + return piece; } + + c.p0 = p0; + c.p3 = p3; c } +// Craft patch (flat-end shear): where a curve is almost horizontal at an end, a +// tiny error in that end's height is a large error in the parameter that +// `solve_t_for_y` returns, and so a large horizontal gap between the cut and +// the end point. Moving the inner control points by their height's share of +// that gap moves the steep part of the curve sideways, and moving only the end +// point, as `next_subsegment` did, bends the curve near it. `settled_cubic` cuts +// the curve at the points nearest the end points instead, moves each end +// sideways with its handle and maps the heights linearly, so the piece moves +// no further than its ends do and stays monotonic in `y`. + +/// The parameter between `lo` and `hi` of the point of `c` nearest `target`, found by +/// Newton steps from `t`, restarting once from the nearest point of the whole curve where a +/// step cannot leave, such as at a repeated handle. Returns `t` when no closer point is found. +fn settle_end(c: CubicBez, t: f64, target: kurbo::Point, lo: f64, hi: f64) -> f64 { + let d1 = c.deriv(); + let d2 = d1.deriv(); + let mut best = t; + let mut best_gap = (c.eval(t) - target).hypot2(); + let mut s = t; + let mut restarted = false; + for _ in 0..32 { + if best_gap == 0.0 { + break; + } + let r = c.eval(s) - target; + let v = d1.eval(s).to_vec2(); + let a = d2.eval(s).to_vec2(); + let slope = r.dot(v); + let bend = v.hypot2() + r.dot(a); + // A Newton step cannot leave a point where the derivative is zero, such + // as a repeated handle at an end. Restart once from the nearest point of + // the whole curve, within the bounds, and keep it only if it is closer. + if bend <= 0.0 || bend.is_nan() || v.hypot2() == 0.0 { + let near = c.nearest(target, 1e-12).t.clamp(lo, hi); + let gap = (c.eval(near) - target).hypot2(); + if restarted || gap >= best_gap { + break; + } + restarted = true; + best = near; + best_gap = gap; + s = near; + continue; + } + let next = (s - slope / bend).clamp(lo, hi); + if !next.is_finite() || next == s { + break; + } + s = next; + let gap = (c.eval(s) - target).hypot2(); + if gap < best_gap { + best = s; + best_gap = gap; + } + } + best +} + +/// The parameters of the points of `c` nearest `p0` and `p3`, searching from `t0` and +/// `t3`, or `None` when they are not in order. Both ends may settle past `t3`, as when +/// both end points are moved along a flat start. +fn settled_range( + c: CubicBez, + t0: f64, + t3: f64, + p0: kurbo::Point, + p3: kurbo::Point, +) -> Option<(f64, f64)> { + let s0 = settle_end(c, t0, p0, 0.0, 1.0); + let s3 = settle_end(c, t3.max(s0), p3, s0, 1.0); + (s0 < s3).then_some((s0, s3)) +} + +/// The increasing map of heights that takes `from0` to `to0` and `from1` to `to1`, or +/// `None` when either range is empty or the map is not finite. +fn height_map(from0: f64, from1: f64, to0: f64, to1: f64) -> Option f64> { + let from_span = from1 - from0; + let to_span = to1 - to0; + let scale = if from_span.is_finite() && to_span.is_finite() { + to_span / from_span + } else { + (to1 * 0.5 - to0 * 0.5) / (from1 * 0.5 - from0 * 0.5) + }; + let middle = from0.midpoint(from1); + (from0 < from1 && to0 < to1 && scale.is_finite()).then_some(move |y: f64| { + if y == from0 { + to0 + } else if y == from1 { + to1 + } else if scale == 0.0 { + let t = if from_span.is_finite() { + (y - from0) / from_span + } else { + (y * 0.5 - from0 * 0.5) / (from1 * 0.5 - from0 * 0.5) + }; + to0 * (1.0 - t) + to1 * t + } else if y < from0.midpoint(middle) { + (y - from0).mul_add(scale, to0) + } else if y > middle.midpoint(from1) { + (y - from1).mul_add(scale, to1) + } else { + (y - middle).mul_add(scale, to0.midpoint(to1)) + } + }) +} + +/// Cuts `c` between the points nearest `p0` and `p3`, searching from `t0` and `t3`, and +/// moves the piece onto `p0` and `p3`: each end moves sideways together with its handle, +/// and the heights are mapped linearly, so a curve that is monotonic in `y` stays so. +/// Returns `None` when the two cut points are not in order. +fn settled_cubic( + c: CubicBez, + t0: f64, + t3: f64, + p0: kurbo::Point, + p3: kurbo::Point, +) -> Option { + let (s0, s3) = settled_range(c, t0, t3, p0, p3)?; + let mut piece = c.subsegment(s0..s3); + let fit = height_map(piece.p0.y, piece.p3.y, p0.y, p3.y)?; + piece.p1.x += p0.x - piece.p0.x; + piece.p2.x += p3.x - piece.p3.x; + piece.p1.y = fit(piece.p1.y); + piece.p2.y = fit(piece.p2.y); + piece.p0 = p0; + piece.p3 = p3; + Some(piece) +} + +/// Cuts `q` between the points nearest `p0` and `p2`, searching from `t0` and `t2`, and +/// moves the piece onto `p0` and `p2`: its control point moves sideways by the mean of the +/// two ends' moves, and the heights are mapped linearly, so a curve that is monotonic in +/// `y` stays so. Returns `None` when the two cut points are not in order. +fn settled_quad( + q: QuadBez, + t0: f64, + t2: f64, + p0: kurbo::Point, + p2: kurbo::Point, +) -> Option { + // A raised quadratic keeps its parameters. + let (s0, s2) = settled_range(q.raise(), t0, t2, p0, p2)?; + let mut piece = q.subsegment(s0..s2); + let fit = height_map(piece.p0.y, piece.p2.y, p0.y, p2.y)?; + piece.p1.x += 0.5 * ((p0.x - piece.p0.x) + (p2.x - piece.p2.x)); + piece.p1.y = fit(piece.p1.y); + piece.p0 = p0; + piece.p2 = p2; + Some(piece) +} + /// A positioned output segment, possibly perturbed from the original. /// /// We perturb output segments in order to strictly enforce ordering. @@ -274,6 +442,10 @@ impl PositionedOutputSeg { /// both must be in the `y`-range of the cubic. The cubic is truncated to be between /// the heights `p0.y` and `p3.y`, and then perturbed horizontally so that it starts /// exactly and at `p0` and ends exactly at `p3`. + /// + /// Craft patch (flat-end shear): when `p0` or `p3` is off the curve, the cubic is cut + /// at the points nearest `p0` and `p3` instead, each end of the piece moves sideways + /// with its handle, and its heights are mapped linearly onto `p0.y..p3.y`. pub fn from_cubic(c: kurbo::CubicBez, p0: kurbo::Point, p3: kurbo::Point) -> Self { debug_assert!(p0.y >= c.p0.y); debug_assert!(p3.y <= c.p3.y); @@ -281,11 +453,25 @@ impl PositionedOutputSeg { let t0 = solve_t_for_y(c, p0.y); let t3 = solve_t_for_y(c, p3.y); + let orig = c; let mut c = c.subsegment(t0..t3); let dx0 = p0.x - c.p0.x; let dx3 = p3.x - c.p3.x; + // Craft patch (flat-end shear) + if (dx0 != 0.0 || dx3 != 0.0) + && let Some(piece) = settled_cubic(orig, t0, t3, p0, p3) + { + let mut path = BezPath::with_capacity(2); + path.move_to(p0); + path.curve_to(piece.p1, piece.p2, p3); + return PositionedOutputSeg { + path, + copied_idx: Some(0), + }; + } + let s1 = ((c.p1.y - p0.y) / (p3.y - p0.y)).clamp(0.0, 1.0); let s2 = ((c.p2.y - p0.y) / (p3.y - p0.y)).clamp(0.0, 1.0); @@ -307,6 +493,11 @@ impl PositionedOutputSeg { /// both must be in the `y`-range of the cubic. The cubic is truncated to be between /// the heights `p0.y` and `p2.y`, and then perturbed horizontally so that it starts /// exactly and at `p0` and ends exactly at `p2`. + /// + /// Craft patch (flat-end shear): when `p0` or `p2` is off the curve, the quadratic is + /// cut at the points nearest `p0` and `p2` instead, its control point moves sideways + /// by the mean of the two ends' moves, and its heights are mapped linearly onto + /// `p0.y..p2.y`. pub fn from_quad(q: kurbo::QuadBez, p0: kurbo::Point, p2: kurbo::Point) -> Self { debug_assert!(p0.y >= q.p0.y); debug_assert!(p2.y <= q.p2.y); @@ -334,11 +525,25 @@ impl PositionedOutputSeg { } let t0 = solve_t_for_y(q, p0.y); let t2 = solve_t_for_y(q, p2.y); + let orig = q; let mut q = q.subsegment(t0..t2); let dx0 = p0.x - q.p0.x; let dx2 = p2.x - q.p2.x; + // Craft patch (flat-end shear) + if (dx0 != 0.0 || dx2 != 0.0) + && let Some(piece) = settled_quad(orig, t0, t2, p0, p2) + { + let mut path = BezPath::with_capacity(2); + path.move_to(p0); + path.quad_to(piece.p1, p2); + return PositionedOutputSeg { + path, + copied_idx: Some(0), + }; + } + let s = ((q.p1.y - p0.y) / (p2.y - p0.y)).clamp(0.0, 1.0); q.p1.x += (1.0 - s) * dx0 + s * dx2; @@ -384,6 +589,8 @@ pub(crate) fn compute_positions( continue; } out[idx].path.move_to(p); + // Craft patch (start height): a segment that starts at y < 0 is not skipped. + last_y[idx] = p.y; queue.push(HeapEntry { y: p.y.into(), idx }); } @@ -393,12 +600,17 @@ pub(crate) fn compute_positions( if last_y[entry.idx] > y0 { continue; } + // Craft patch (comparison cache size): the heights popped from the + // queue never decrease, and every neighbor compared from here on + // extends below `y0`. + cmp.evict_ended(segs, y0); let mut y1 = endpoints[entry.idx.second_half()].y; let mut west_scan = vec![entry.idx]; let mut cur = entry.idx; while let Some(nbr) = scan_order.west_neighbor_after(cur, y0) { - let order = cmp.compare_segments(segs, orig_seg_map[nbr], orig_seg_map[cur]); + let order = + cmp.compare_non_horizontal_segments(segs, orig_seg_map[nbr], orig_seg_map[cur]); let (_, cmp_end_y, cmp_order) = order.iter().find(|(_, end_y, _)| *end_y > y0).unwrap(); if cmp_order == Order::Left { @@ -417,7 +629,8 @@ pub(crate) fn compute_positions( let mut east_scan = vec![]; let mut cur = entry.idx; while let Some(nbr) = scan_order.east_neighbor_after(cur, y0) { - let order = cmp.compare_segments(segs, orig_seg_map[cur], orig_seg_map[nbr]); + let order = + cmp.compare_non_horizontal_segments(segs, orig_seg_map[cur], orig_seg_map[nbr]); let (_, cmp_end_y, cmp_order) = order.iter().find(|(_, end_y, _)| *end_y > y0).unwrap(); if cmp_order == Order::Left { @@ -504,11 +717,14 @@ pub(crate) fn compute_positions( #[cfg(test)] mod tests { - use kurbo::{BezPath, CubicBez, Line, PathSeg}; + use kurbo::{ + Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveExtrema, ParamCurveNearest, PathEl, + PathSeg, Point, QuadBez, Shape, + }; - use crate::Segments; + use crate::{Segments, sweep::Correctness, topology::Topology}; - use super::horizontal_error_weight; + use super::{PositionedOutputSeg, height_map, horizontal_error_weight, settled_cubic}; #[test] fn error_weight() { @@ -558,4 +774,275 @@ mod tests { let next_y0 = super::approximate(90.03645987646233, y1, &[s0, s1], &segs, 2.5e-7, &mut out); assert_eq!(next_y0, y1); } + + // Counts the path elements of each kind in the correct positions of two + // lenses that run close together, moved down by `dy`. + fn close_lens_elements(dy: f64) -> [usize; 4] { + fn lens(dx: f64, dy: f64) -> BezPath { + let mut p = BezPath::new(); + p.move_to((dx, dy)); + p.curve_to( + (10.0 + dx, 3.0 + dy), + (10.0 + dx, 7.0 + dy), + (dx, 10.0 + dy), + ); + p.curve_to((-10.0 + dx, 7.0 + dy), (-10.0 + dx, 3.0 + dy), (dx, dy)); + p.close_path(); + p + } + let a = lens(0.0, dy); + let b = lens(0.001, dy); + let top = Topology::::from_paths_with_correctness( + [(&a, ()), (&b, ())], + 0.01, + Correctness::ReallyCorrect, + ) + .unwrap(); + let positions = top.compute_positions(); + let mut counts = [0; 4]; + for idx in positions.indices() { + for el in positions[idx].path.elements() { + match el { + PathEl::MoveTo(_) => counts[0] += 1, + PathEl::LineTo(_) => counts[1] += 1, + PathEl::QuadTo(..) => counts[2] += 1, + PathEl::CurveTo(..) => counts[3] += 1, + PathEl::ClosePath => {} + } + } + } + counts + } + + // Craft patch (start height): moving the input up or down must not change + // how the close segments are positioned, including when the segments start + // at y < 0. + #[test] + fn correct_positions_at_negative_y() { + let below = close_lens_elements(100.0); + let above = close_lens_elements(-100.0); + assert!(below[2] > 0, "{below:?}"); + assert_eq!(below, above); + } + + // With an accuracy that no approximation meets, the interval is halved + // until it is one float wide. At 1.5e8 the midpoint of such an interval + // rounds to its start, and `approximate` used to return the start, which + // left the loop in `compute_positions_correct` without progress. + #[test] + fn approx_stops_at_one_float() { + let y0 = 1.5e8; + let mut p = BezPath::new(); + p.move_to((y0, y0)); + p.curve_to((y0 + 1.0, y0 + 0.3), (y0 - 1.0, y0 + 0.7), (y0, y0 + 1.0)); + p.close_path(); + + let mut segs = Segments::default(); + segs.add_bez_path(&p).unwrap(); + let s0 = segs.indices().next().unwrap(); + + let mut out = Vec::new(); + let next_y0 = super::approximate(y0, y0 + 1.0, &[s0], &segs, 0.0, &mut out); + assert!(next_y0 > y0, "next_y0 = {next_y0}"); + assert_eq!(out.len(), 1); + } + + // The largest distance from a point of `path` to the nearest of `inputs`. + fn farthest_from(path: &BezPath, inputs: &[PathSeg]) -> f64 { + let mut worst = 0.0f64; + for seg in path.segments() { + for k in 0..=200 { + let p = seg.eval(k as f64 / 200.0); + let d = inputs + .iter() + .map(|c| c.nearest(p, 1e-12).distance_sq.sqrt()) + .fold(f64::INFINITY, f64::min); + worst = worst.max(d); + } + } + worst + } + + // Places `seg` between `p0` and `p1` and checks that the result runs from `p0` + // to `p1` and stays within `tol` of `seg`. + fn assert_placed_near(seg: PathSeg, p0: Point, p1: Point, tol: f64) { + let out = PositionedOutputSeg::from_seg(seg, p0, p1); + let same_kind = |s: PathSeg| std::mem::discriminant(&s) == std::mem::discriminant(&seg); + assert!(out.path.segments().all(same_kind)); + assert_eq!(out.path.segments().next().unwrap().start(), p0); + assert_eq!(out.path.segments().last().unwrap().end(), p1); + let d = farthest_from(&out.path, &[seg]); + assert!(d < tol, "{seg:?} from {p0:?} to {p1:?}: {d}"); + } + + // Craft patch (flat-end shear): a curve with a repeated handle at its flat + // end has zero derivative there, so a Newton step from that end cannot + // leave it. The end point is moved along the flat part. + #[test] + fn repeated_end_handle_stays_near_the_end() { + let origin = Point::new(0.0, 0.0); + let top_right = Point::new(1000.0, 1000.0); + let c = CubicBez::new(origin, Point::new(0.0, 1000.0), top_right, top_right); + // Moved along the flat part, the end point is 0.0127 from the curve. + let end = Point::new(998.37, 1000.0); + assert_placed_near(PathSeg::Cubic(c), origin, end, 0.02); + + let start = Point::new(1.63, 0.0); + let corner = Point::new(1000.0, 0.0); + let c = CubicBez::new(origin, origin, corner, top_right); + assert_placed_near(PathSeg::Cubic(c), start, top_right, 0.02); + } + + // Craft patch (flat-end shear): a curve that is almost flat at one end and + // steep at the other, with the flat end's point moved along the flat part, + // keeps its steep part in place. + #[test] + fn flat_end_shift_stays_near_the_end() { + // Steep start, flat end, as cubic and quadratic. + let origin = Point::new(0.0, 0.0); + let (top_left, top_right) = (Point::new(0.0, 1000.0), Point::new(1000.0, 1000.0)); + let c = CubicBez::new(origin, top_left, Point::new(300.0, 1000.0), top_right); + let end = Point::new(998.37, 1000.0); + assert_placed_near(PathSeg::Cubic(c), origin, end, 1e-5); + let q = QuadBez::new(origin, top_left, top_right); + let end = Point::new(999.95, 1000.0); + assert_placed_near(PathSeg::Quad(q), origin, end, 1e-5); + + // Flat start, steep end. + let corner = Point::new(1000.0, 0.0); + let c = CubicBez::new(origin, Point::new(700.0, 0.0), corner, top_right); + assert_placed_near(PathSeg::Cubic(c), Point::new(1.63, 0.0), top_right, 1e-5); + let q = QuadBez::new(origin, corner, top_right); + assert_placed_near(PathSeg::Quad(q), Point::new(0.05, 0.0), top_right, 1e-5); + + // The end point just below the flat end, as the sweep places it: the cut + // from `solve_t_for_y` lies 0.75 to the left of it. + let c = CubicBez::new(origin, top_left, Point::new(300.0, 1000.0), top_right); + let end = Point::new(999.99999674, 999.9999999534); + assert_placed_near(PathSeg::Cubic(c), origin, end, 1e-6); + } + + // Craft patch (flat-end shear): when both end points are moved along a flat + // start, past the parameter of the end's height, the piece is cut at the + // points nearest both ends and runs left to right, as the curve does there. + // `x` is checked at the piece's ends and extrema, between which it is + // monotonic. + #[test] + fn flat_start_piece_past_the_end_height_does_not_turn_back() { + let origin = Point::new(0.0, 0.0); + let (corner, top_right) = (Point::new(1000.0, 0.0), Point::new(1000.0, 1000.0)); + let c = CubicBez::new(origin, Point::new(700.0, 0.0), corner, top_right); + let q = QuadBez::new(origin, corner, top_right); + let (p0, p1) = (Point::new(10.0, 0.0), Point::new(11.0, 1e-6)); + for seg in [PathSeg::Cubic(c), PathSeg::Quad(q)] { + assert_placed_near(seg, p0, p1, 0.05); + let out = PositionedOutputSeg::from_seg(seg, p0, p1); + for piece in out.path.segments() { + let mut last = piece.start().x; + let extrema = piece.extrema(); + for t in extrema.iter().copied().chain([1.0]) { + let x = piece.eval(t).x; + assert!(x >= last && x <= p1.x, "{seg:?}: {x} at {t} after {last}"); + last = x; + } + } + } + } + + // Craft patch (flat-end shear): a piece placed between end points off its + // curve stays monotonic in `y`. Between two neighboring extrema `y` is + // monotonic, so the piece is monotonic in `y` exactly when `y` does not + // decrease along its ends and extrema. + #[test] + fn flat_end_pieces_stay_monotonic() { + let (p0, p1, p2) = ( + Point::new(0.0, 0.0), + Point::new(100.0, 200.0), + Point::new(200.0, 200.0), + ); + let end = Point::new(200.0, 199.0); + let segs = [ + PathSeg::Quad(QuadBez::new(p0, p1, p2)), + PathSeg::Cubic(QuadBez::new(p0, p1, p2).raise()), + ]; + for seg in segs { + let out = PositionedOutputSeg::from_seg(seg, p0, end); + for piece in out.path.segments() { + let mut last = piece.start().y; + let extrema = piece.extrema(); + for t in extrema.iter().copied().chain([1.0]) { + let y = piece.eval(t).y; + assert!(y >= last && y <= end.y, "{seg:?}: {y} at {t} after {last}"); + last = y; + } + } + } + } + + #[test] + fn affine_endpoints_flat_handles_keep_the_exact_target_height() { + let curve = CubicBez::new((0.0, -1.0), (1.0, 1.0), (2.0, 1.0), (3.0, 1.0)); + let end = Point::new(10.0, -1e-20); + let placed = settled_cubic(curve, 0.0, 1.0, curve.p0, end).unwrap(); + assert!(placed.p2.y <= placed.p3.y, "{placed:?}"); + assert_eq!(height_map(-1.0, 1.0, -1.0, end.y).unwrap()(1.0), end.y); + } + + // Craft patch (flat-end shear): the union of a shape with a copy moved by + // less than `eps` stays on the two shapes, and keeps their area. + #[test] + fn flat_end_union_stays_on_the_inputs() { + let svg = "M0,0 C0,1000 300,1000 1000,1000 L1000,2000 L-1000,2000 Z"; + let a = BezPath::from_svg(svg).unwrap(); + let mut b = a.clone(); + b.apply_affine(Affine::translate((-3.26e-6, -4.66e-8))); + let inputs: Vec = a.segments().chain(b.segments()).collect(); + let (fill, op) = (crate::FillRule::NonZero, crate::BinaryOp::Union); + let out = crate::binary_op_with_eps(&a, &b, fill, op, 1e-6).unwrap(); + let mut area = 0.0; + for contour in out.contours() { + area += contour.path.area().abs(); + let d = farthest_from(&contour.path, &inputs); + assert!(d < 1e-5, "{d}"); + } + assert!((area - 2_095_000.006_5).abs() < 1e-3, "{area}"); + } + + // Craft patch (flat-end shear): a rectangle whose left side crosses the flat + // end of a curve, away from its anchors, leaves the curve in place in its + // union, with both layouts. + #[test] + fn flat_end_crossing_stays_on_the_inputs() { + use crate::sweep::Correctness; + use crate::topology::{BinaryWindingNumber, OneOfTwo, Topology}; + + let svg = "M0,0 C0,1000 300,1000 1000,1000 L1000,2000 L-1000,2000 Z"; + let a = BezPath::from_svg(svg).unwrap(); + for xv in [998.37, 990.37] { + let rect = format!("M{xv},500 L1500,500 L1500,1500 L{xv},1500 Z"); + let b = BezPath::from_svg(&rect).unwrap(); + let inputs: Vec = a.segments().chain(b.segments()).collect(); + for correctness in [Correctness::GoodEnough, Correctness::ReallyCorrect] { + let paths = [(&a, OneOfTwo::A), (&b, OneOfTwo::B)]; + let top = Topology::::from_paths_with_correctness( + paths, + 1e-6, + correctness, + ) + .unwrap(); + let out = top.contours(|w| w.shape_a != 0 || w.shape_b != 0); + let mut area = 0.0; + for contour in out.contours() { + area += contour.path.area().abs(); + let d = farthest_from(&contour.path, &inputs); + assert!(d < 1e-5, "{xv} {correctness:?}: {d}"); + } + let expected = 2_595_000.0 + (1000.0 - xv) * 500.0; + assert!( + (area - expected).abs() < 1e-2, + "{xv} {correctness:?}: {area}" + ); + } + } + } } diff --git a/vendor/linesweeper/src/segments.rs b/vendor/linesweeper/src/segments.rs index 37c4f8f573..24e696a031 100644 --- a/vendor/linesweeper/src/segments.rs +++ b/vendor/linesweeper/src/segments.rs @@ -1,4 +1,5 @@ use std::iter::Peekable; +use std::sync::atomic::{AtomicU64, Ordering}; use kurbo::BezPath; @@ -30,11 +31,37 @@ pub struct SegVec { impl_typed_vec!(SegVec, SegIdx, "s"); +// Craft patch (comparison cache arena): each arena gets its own number, and +// a clone gets a new one, so that `ComparisonCache` can tell arenas apart. +#[derive(Debug, PartialEq, Eq)] +struct ArenaId(u64); + +impl ArenaId { + fn fresh() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + ArenaId(NEXT.fetch_add(1, Ordering::Relaxed)) + } +} + +impl Default for ArenaId { + fn default() -> Self { + ArenaId::fresh() + } +} + +impl Clone for ArenaId { + fn clone(&self) -> Self { + ArenaId::fresh() + } +} + /// An arena of segments, each of which is a cubic Bézier. /// /// Segments are indexed by [`SegIdx`] and can be retrieved by indexing (i.e. with square brackets). #[derive(Clone, Default)] pub struct Segments { + // Craft patch (comparison cache arena): see `ArenaId`. + id: ArenaId, segs: SegVec, horizontal_decomps: SegVec, contour_prev: SegVec>, @@ -131,10 +158,20 @@ fn pairs(xs: &[T]) -> impl Iterator { xs.windows(2).map(|pair| (&pair[0], &pair[1])) } +// Craft patch (leading ClosePath): `kurbo::segments` panics on a ClosePath that comes before +// any point, so such ClosePaths are dropped first. They draw nothing. +pub(crate) fn skip_leading_close_paths( + path: impl IntoIterator, +) -> impl Iterator { + path.into_iter() + .skip_while(|el| matches!(el, kurbo::PathEl::ClosePath)) +} + // Craft patch (batch paths): counts calls to `enter_order` in tests. #[cfg(test)] thread_local! { - static ENTER_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static ENTER_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static PREPARED_SEGMENTS: std::cell::Cell = const { std::cell::Cell::new(0) }; } // Craft patch (batch paths): the order of `Segments::enter`, by entrance @@ -234,6 +271,12 @@ where } impl Segments { + // Craft patch (comparison cache arena): the arena's number, which no + // other arena has, a clone included. + pub(crate) fn arena_id(&self) -> u64 { + self.id.0 + } + /// The number of segments in this arena. #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { @@ -313,6 +356,10 @@ impl Segments { } for (p, q) in pairs(&ps) { + // Craft patch (repeated points): skip a point equal to the one before it. + if p == q { + continue; + } let (a, b, orient) = if p < q { (p, q, true) } else { (q, p, false) }; self.push_seg(Segment::straight(*a, *b)); self.orientation.push(orient); @@ -358,13 +405,21 @@ impl Segments { /// Add a Bézier path to this arena. /// /// The path can contain multiple subpaths, and each of them must be closed. + /// If one of them is not closed, this returns an error and leaves the arena + /// unchanged. /// /// Each call merges the path's entrances and exits into the sorted ones /// already in the arena, which moves every existing entry that sorts after /// them. To add many paths, call [`Segments::add_bez_paths`] once instead. pub fn add_bez_path(&mut self, p: &BezPath) -> Result<(), NonClosedPath> { let old_len = self.segs.len(); - self.add_path_without_updating_enter_exit(p, true)?; + // Craft patch (add_bez_path error): segments pushed before the open + // subpath was found are removed, so no segment is left with a link + // past the end of the arena or without an entrance. + if let Err(e) = self.add_path_without_updating_enter_exit(p, true) { + self.truncate(old_len); + return Err(e); + } self.update_enter_exit(old_len); Ok(()) } @@ -421,18 +476,32 @@ impl Segments { must_be_closed: bool, ) -> Result<(), NonClosedPath> { let old_len = self.segs.len(); + struct UnenteredBatch<'a> { + arena: &'a mut Segments, + start: usize, + complete: bool, + } + impl Drop for UnenteredBatch<'_> { + fn drop(&mut self) { + if !self.complete { + self.arena.truncate_unentered(self.start); + } + } + } + let mut batch = UnenteredBatch { arena: self, start: old_len, complete: false }; let mut result = Ok(()); for p in ps { - let path_start = self.segs.len(); - result = self.add_path_without_updating_enter_exit(p, must_be_closed); + let path_start = batch.arena.segs.len(); + result = batch.arena.add_path_without_updating_enter_exit(p, must_be_closed); if result.is_err() { // The failing path's segments are removed, so none is left // linked to an index past the end of the arena. - self.truncate_unentered(path_start); + batch.arena.truncate_unentered(path_start); break; } } - self.update_enter_exit(old_len); + batch.arena.update_enter_exit(old_len); + batch.complete = true; result } @@ -459,7 +528,7 @@ impl Segments { }; while let Some(subpath) = subpaths.next() { let old_len = self.segs.len(); - for seg in kurbo::segments(subpath) { + for seg in kurbo::segments(skip_leading_close_paths(subpath)) { let pieces = monotonic_pieces(seg); for monotonic in pieces { self.push_seg(monotonic.piece); @@ -532,6 +601,8 @@ impl Segments { } fn push_seg(&mut self, seg: Segment) { + #[cfg(test)] + PREPARED_SEGMENTS.with(|count| count.set(count.get() + 1)); let decomp = if seg.is_horizontal() { AlmostHorizontalDecomposition::default() } else { @@ -541,6 +612,13 @@ impl Segments { self.segs.push(seg); } + // Craft patch (add_bez_path error): drops every segment at index `len` or + // above. `enter` and `exit` are left alone, so this is only for segments + // that `update_enter_exit` has not seen yet. + fn truncate(&mut self, len: usize) { + self.truncate_unentered(len); + } + /// Construct a segment arena from a single closed polyline. pub fn from_closed_polyline>(ps: impl IntoIterator) -> Self { let mut ret = Self::default(); @@ -608,6 +686,33 @@ impl Segments { debug_assert!(!self.segs[idx].is_horizontal()); &self.horizontal_decomps[idx] } + + /// The sweep tolerance to use for these segments when the caller asks for `eps`. + /// + /// Returns `eps` when it is at least `64 * f64::EPSILON` times the largest + /// coordinate magnitude (the scale [`crate::binary_op`] uses), and that + /// floor otherwise. The floor replaces an `eps` that is NaN, infinite, + /// negative, zero, or too small to tell coordinates of this size apart. It + /// is never below 64 times the spacing of subnormal floats. + pub(crate) fn usable_eps(&self, eps: f64) -> f64 { + let max_coord = self + .segs + .iter() + .map(|(_, seg)| { + seg.min_x() + .abs() + .max(seg.max_x().abs()) + .max(seg.start().y.abs()) + .max(seg.end().y.abs()) + }) + .fold(0.0, f64::max); + let floor = crate::curve::resolution_floor(max_coord); + if eps.is_finite() && eps >= floor { + eps + } else { + floor + } + } } impl std::ops::Index for Segments { @@ -618,6 +723,23 @@ impl std::ops::Index for Segments { } } +// Craft patch (repeated points). +#[cfg(test)] +mod repeated_point_tests { + use super::{SegIdx, Segments}; + + #[test] + fn add_points_skips_repeated_points() { + let mut segments = Segments::default(); + segments.add_points([(0.0, 0.0), (0.0, 0.0), (1.0, 1.0), (1.0, 1.0), (2.0, 0.0)]); + segments.check_invariants(); + assert_eq!(segments.segs.len(), 2); + assert_eq!(segments.contour_prev(SegIdx(0)), None); + assert_eq!(segments.contour_next(SegIdx(0)), Some(SegIdx(1))); + assert_eq!(segments.contour_next(SegIdx(1)), None); + } +} + // Craft patch (batch paths). #[cfg(test)] mod tests { @@ -731,6 +853,36 @@ mod tests { ); } + #[test] + fn batch_iterator_panic_preserves_the_existing_arena() { + for closed in [false, true] { + let paths = grid_paths(4, true); + let mut arena = Segments::default(); + arena.add_bez_path(&paths[0]).unwrap(); + let expected = arena.clone(); + let mut count = 0; + let iter = std::iter::from_fn(|| { + count += 1; + assert_ne!(count, 3, "iterator panic after two paths"); + Some(&paths[count]) + }); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if closed { + arena.add_bez_paths(iter).unwrap(); + } else { + arena.add_non_closed_bez_paths(iter).unwrap(); + } + })); + assert!(result.is_err()); + assert_same_arena(&expected, &arena); + assert_eq!(arena.input_segs, expected.input_segs); + assert_eq!(arena.split_from_predecessor, expected.split_from_predecessor); + arena.check_invariants(); + arena.add_bez_path(&paths[3]).unwrap(); + arena.check_invariants(); + } + } + type Events = Vec<(f64, SegIdx)>; // The entrance and exit order that sorting every entry in index order diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__diamond.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__diamond.snap index 2549d694ea..c6817caf2f 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__diamond.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__diamond.snap @@ -11,12 +11,6 @@ Topology( A, A, ], - open_segs: [ - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__inner_loop.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__inner_loop.snap index 452a9c7e23..4ac5fba220 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__inner_loop.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__inner_loop.snap @@ -17,18 +17,6 @@ expression: "(top, contours)" B, B, ], - open_segs: [ - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs.snap index cd300ba95c..1ba0fb98c5 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs.snap @@ -13,14 +13,6 @@ expression: "(top, contours)" (), (), ], - open_segs: [ - [], - [], - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs_with_cut.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs_with_cut.snap index f2e0cce287..a8f9b14dac 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs_with_cut.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__merge_monotonic_segs_with_cut.snap @@ -11,12 +11,6 @@ expression: "(top, contours)" (), (), ], - open_segs: [ - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__nested_squares.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__nested_squares.snap index 3b86b37981..b7fc658ec1 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__nested_squares.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__nested_squares.snap @@ -15,16 +15,6 @@ expression: "(&top, contours, top.build_scan_line_orders())" B, B, ], - open_segs: [ - [], - [], - [], - [], - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square.snap index f7faeb1724..b462e8ab6b 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square.snap @@ -11,12 +11,6 @@ Topology( A, A, ], - open_segs: [ - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_and_diamond.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_and_diamond.snap index 07e060ba86..f1e8178fdf 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_and_diamond.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_and_diamond.snap @@ -15,16 +15,6 @@ Topology( B, B, ], - open_segs: [ - [], - [], - [], - [], - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_with_double_back.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_with_double_back.snap index 1ca10e4a73..a70bec1398 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_with_double_back.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__square_with_double_back.snap @@ -14,15 +14,6 @@ Topology( A, A, ], - open_segs: [ - [], - [], - [], - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__squares_with_gaps.snap b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__squares_with_gaps.snap index 9ebc976f03..bc7c641c4f 100644 --- a/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__squares_with_gaps.snap +++ b/vendor/linesweeper/src/snapshots/linesweeper__topology__tests__squares_with_gaps.snap @@ -23,24 +23,6 @@ expression: "(&top, contours, top.build_scan_line_orders())" B, B, ], - open_segs: [ - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - [], - ], winding: OutputSegVec( inner: [ HalfSegmentWindingNumbers( diff --git a/vendor/linesweeper/src/sweep/output_event.rs b/vendor/linesweeper/src/sweep/output_event.rs index 1574406b30..a67be48e71 100644 --- a/vendor/linesweeper/src/sweep/output_event.rs +++ b/vendor/linesweeper/src/sweep/output_event.rs @@ -11,13 +11,16 @@ use crate::{SegIdx, num::CheapOrderedFloat}; /// /// `OutputEvent` is ordered by the smallest horizontal coordinate where /// it intersects the sweep-line (i.e. [`OutputEvent::smaller_x`]). +/// Events with the same horizontal range are ordered by segment and then by +/// their other fields, so two events compare equal only when they are equal. +/// NaN coordinates use total floating-point order; signed zeros compare equal. /// /// The two points, `x0` and `x1`, are in sweep-line order. This doesn't /// necessarily mean that `x0` is smaller than `x1`! Instead, it means that /// when traversing the segment in sweep-line order (i.e. in increasing `y`, /// and increasing `x` if the segment is horizontal) then it visits `x0` /// before `x1`. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug)] pub struct OutputEvent { /// The first horizontal coordinate on this sweep-line that we'd hit if /// we were traversing the segment in sweep-line orientation. @@ -45,6 +48,20 @@ pub struct OutputEvent { impl Eq for OutputEvent {} +impl PartialEq for OutputEvent { + fn eq(&self, other: &Self) -> bool { + self.cmp(other).is_eq() + } +} + +fn coordinate_order(a: f64, b: f64) -> std::cmp::Ordering { + if a == b { + std::cmp::Ordering::Equal + } else { + a.total_cmp(&b) + } +} + impl OutputEvent { /// The smallest `x` coordinate at which the line segment touches the sweep-line. pub fn smaller_x(&self) -> f64 { @@ -85,10 +102,12 @@ impl OutputEvent { pub fn connected_below_at(&self, x: f64) -> bool { x == self.x1 && self.connected_below } -} -impl Ord for OutputEvent { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + // Craft patch (output event order): the package's `Ord`, which compares the + // horizontal ranges only. + /// Compares the horizontal ranges only: [`OutputEvent::smaller_x`], then + /// [`OutputEvent::larger_x`]. + pub(crate) fn cmp_x(&self, other: &Self) -> std::cmp::Ordering { CheapOrderedFloat::from(self.smaller_x()) .cmp(&CheapOrderedFloat::from(other.smaller_x())) .then_with(|| { @@ -98,8 +117,76 @@ impl Ord for OutputEvent { } } +// Craft patch (output event order): events with the same horizontal range are +// ordered by segment and then by the other fields, so `cmp` agrees with `==`. +impl Ord for OutputEvent { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + coordinate_order(self.smaller_x(), other.smaller_x()) + .then_with(|| coordinate_order(self.larger_x(), other.larger_x())) + .then_with(|| self.seg_idx.cmp(&other.seg_idx)) + .then_with(|| coordinate_order(self.x0, other.x0)) + .then_with(|| coordinate_order(self.x1, other.x1)) + .then_with(|| self.connected_above.cmp(&other.connected_above)) + .then_with(|| self.connected_below.cmp(&other.connected_below)) + .then_with(|| self.sweep_idx.cmp(&other.sweep_idx)) + .then_with(|| self.old_sweep_idx.cmp(&other.old_sweep_idx)) + } +} + impl PartialOrd for OutputEvent { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + + use super::*; + + #[test] + fn comparison_contract_public_events_order_nan_coordinates_consistently() { + let values = [ + -f64::NAN, + f64::NEG_INFINITY, + -1.0, + -0.0, + 0.0, + 1.0, + f64::INFINITY, + f64::NAN, + f64::from_bits(f64::NAN.to_bits() + 1), + ]; + let events: Vec<_> = values.into_iter().map(|x| OutputEvent::new(SegIdx(0), x, true, 2.0, true, Some(0), Some(0))).collect(); + for a in &events { + assert_eq!(a, &a.clone()); + for b in &events { + assert_eq!(a == b, a.cmp(b).is_eq()); + assert_eq!(a.cmp(b), b.cmp(a).reverse()); + } + } + assert_eq!(events.iter().cloned().collect::>().len(), 8); + } + + // Craft patch (output event order) + #[test] + fn events_on_different_segments_with_the_same_range_are_not_equal() { + let a = OutputEvent::new(SegIdx(0), 1.0, true, 2.0, true, Some(0), Some(0)); + let b = OutputEvent::new(SegIdx(1), 1.0, true, 2.0, true, Some(1), Some(1)); + assert_ne!(a, b); + assert_ne!(a.cmp(&b), std::cmp::Ordering::Equal); + assert_eq!(a.cmp_x(&b), std::cmp::Ordering::Equal); + + let set: BTreeSet<_> = [a.clone(), b.clone()].into_iter().collect(); + assert_eq!(set.len(), 2); + } + + #[test] + fn events_differing_only_in_flags_are_not_equal() { + let a = OutputEvent::new(SegIdx(0), 1.0, true, 1.0, false, None, Some(0)); + let b = OutputEvent::new(SegIdx(0), 1.0, false, 1.0, true, Some(0), None); + assert_ne!(a.cmp(&b), std::cmp::Ordering::Equal); + assert_eq!(a.cmp(&a.clone()), std::cmp::Ordering::Equal); + } +} diff --git a/vendor/linesweeper/src/sweep/range.rs b/vendor/linesweeper/src/sweep/range.rs index 60c7ff258a..3f95e7c6f8 100644 --- a/vendor/linesweeper/src/sweep/range.rs +++ b/vendor/linesweeper/src/sweep/range.rs @@ -223,18 +223,22 @@ impl<'bufs, 'state, 'segs> SweepLineRange<'bufs, 'state, 'segs> { /// Returns the collection of all output events that end at the current /// position, or `None` if this batcher is finished. /// - /// All the returned events start at the previous `x` position and end - /// at the current `x` position. In particular, if you alternate between + /// Each returned horizontal fragment ends at the current `x` position or + /// at its own end, whichever comes first. Before this method has run once, + /// each fragment starts at its own start. After that, each one starts at + /// the `x` position of the previous call or at its own start, whichever + /// comes later. In particular, if you alternate between /// calling [`SweepLineRange::increase_x`] and this method, you'll /// receive non-overlapping batches of output events. pub fn events(&mut self) -> Option> { let next_x = self.x()?; + self.count_active_horizontals(); let mut ret = Vec::new(); for h in &self.bufs.active_horizontals { - // unwrap: on the first event of this sweep line, active_horizontals is empty. So - // we only get here after last_x is populated. - let x0 = self.last_x.unwrap(); + // last_x is unset until this method has run once, and it does not move in + // increase_x, so a fragment that increase_x added starts at its own start. + let x0 = self.last_x.map_or(h.start, |last_x| last_x.max(h.start)); let x1 = next_x.min(h.end); let connected_end = x1 == h.end && h.connected_at_end; let connected_start = x0 == h.start && h.connected_at_start; @@ -287,12 +291,17 @@ impl<'bufs, 'state, 'segs> SweepLineRange<'bufs, 'state, 'segs> { .active_horizontals .sort_by_key(|a| CheapOrderedFloat::from(a.end)); self.last_x = Some(next_x); + self.count_active_horizontals(); Some(ret) } /// Move along to the next horizontal position. + /// + /// [`SweepLineRange::events`] does not return the point events at the + /// position this moves past, or the horizontal fragments that end there. pub fn increase_x(&mut self) { if let Some(x) = self.x() { + self.count_active_horizontals(); self.drain_active_horizontals(x); while let Some(ev) = self.output_events.first() { @@ -309,6 +318,25 @@ impl<'bufs, 'state, 'segs> SweepLineRange<'bufs, 'state, 'segs> { self.bufs .active_horizontals .sort_by_key(|a| CheapOrderedFloat::from(a.end)); + self.count_active_horizontals(); + } + + // Craft patch (work limit): every step visits the active horizontal + // segments before and after it moves, and a caller visits them again at + // each position, so each step counts them toward the sweep's work limit. + // Overlapping horizontal segments are split at every position of the + // others, which makes about n^2 visits for n of them. + fn count_active_horizontals(&self) { + self.line.state.count_range_horizontals(self.bufs.active_horizontals.len()); + } + + /// Returns `true` once the sweep has done more work than the limit given to + /// [`Sweeper::set_work_limit`](crate::sweep::Sweeper::set_work_limit), counting + /// the horizontal segments that the steps of this range visit. + /// + /// The caller should then stop processing this range and the sweep. + pub fn work_limit_exceeded(&self) -> bool { + self.line.state.work_limit_exceeded() } fn drain_active_horizontals(&mut self, x: f64) { @@ -443,3 +471,59 @@ impl SweepLineRangeBuffers { self.active_horizontals.clear(); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + Segments, + sweep::{SweepLineBuffers, Sweeper}, + }; + + fn rect(x0: f64, x1: f64) -> [(f64, f64); 4] { + [(x0, 0.0), (x1, 0.0), (x1, 2.0), (x0, 2.0)] + } + + /// Runs `check` on the first range of the sweep-line at y = 0. + fn with_first_range(segs: &Segments, check: impl FnOnce(&mut SweepLineRange<'_, '_, '_>)) { + let mut sweeper = Sweeper::new(segs, 0.01); + let mut line_bufs = SweepLineBuffers::default(); + let mut range_bufs = SweepLineRangeBuffers::default(); + let mut line = sweeper.next_line(&mut line_bufs).unwrap(); + let mut range = line.next_range(&mut range_bufs, segs).unwrap(); + check(&mut range); + } + + fn fragments(events: &[OutputEvent]) -> Vec<(f64, f64)> { + let mut ret: Vec<_> = events + .iter() + .filter(|ev| ev.x0 != ev.x1) + .map(|ev| (ev.smaller_x(), ev.larger_x())) + .collect(); + ret.sort_by(|a, b| a.partial_cmp(b).unwrap()); + ret + } + + #[test] + fn events_after_increase_x_at_the_first_position() { + let segs = Segments::from_closed_polyline(rect(0.0, 2.0)); + with_first_range(&segs, |range| { + range.increase_x(); + let events = range.events().unwrap(); + assert_eq!(fragments(&events), [(0.0, 2.0)]); + }); + } + + #[test] + fn events_after_increase_x_start_a_new_fragment_at_its_own_start() { + let mut segs = Segments::default(); + segs.add_closed_polyline(rect(0.0, 3.0)); + segs.add_closed_polyline(rect(1.0, 4.0)); + with_first_range(&segs, |range| { + range.events().unwrap(); + range.increase_x(); + let events = range.events().unwrap(); + assert_eq!(fragments(&events), [(0.0, 3.0), (1.0, 3.0)]); + }); + } +} diff --git a/vendor/linesweeper/src/sweep/sweep_line.rs b/vendor/linesweeper/src/sweep/sweep_line.rs index 6d286daa17..3ad9fff198 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -2,7 +2,8 @@ //! //! This algorithm is documented in `docs/sweep.typ`. -use std::cell::{RefCell, RefMut}; +use std::cell::{Cell, RefCell, RefMut}; +use std::collections::{BTreeMap, btree_map::Entry}; #[cfg(feature = "slow-asserts")] use std::ops::DerefMut; @@ -14,7 +15,7 @@ use crate::{ geom::Segment, num::CheapOrderedFloat, order::ComparisonCache, - segments::{SegIdx, Segments}, + segments::{SegIdx, SegVec, Segments}, treevec::TreeVec, }; @@ -144,6 +145,10 @@ pub(crate) struct SegmentOrderEntry { /// /// If this is `Some`, both `enter` and `exit` will be true. old_seg: Option, + // Craft patch (sweep position). + /// Keys strictly increase along the sweep line. See [`SegmentOrder::keys`]. + #[cfg_attr(test, serde(skip))] + key: u64, } impl std::fmt::Debug for SegmentOrderEntry { @@ -170,6 +175,7 @@ impl SegmentOrderEntry { in_changed_interval: false, old_idx: None, old_seg: None, + key: 0, } } @@ -204,6 +210,15 @@ impl SegmentOrderEntry { #[derive(Clone, Default)] pub(crate) struct SegmentOrder { pub(crate) segs: TreeVec, + // Craft patch (sweep position). + /// For each segment, the key of the entry that last held it, or zero if no + /// entry has held it. Entries are sorted by key, so this finds a segment on + /// a wide sweep line by binary search. + /// + /// Removing an entry leaves its keys here, and `position` ignores any key + /// whose entry no longer holds the segment. + #[cfg_attr(test, serde(skip))] + keys: SegVec, } impl std::fmt::Debug for SegmentOrder { @@ -213,6 +228,14 @@ impl std::fmt::Debug for SegmentOrder { } impl SegmentOrder { + // Craft patch (sweep position). + fn new(num_segments: usize) -> Self { + Self { + segs: TreeVec::new(), + keys: SegVec::with_size(num_segments), + } + } + fn seg(&self, i: usize) -> SegIdx { self.segs[i].seg } @@ -254,6 +277,9 @@ impl PartialOrd for IntersectionEvent { } } +// Craft patch (repeated intersection): see `Sweeper::repeat_key`. +type RepeatKey = (SegIdx, SegIdx, Option, Option, u64); + #[derive(Clone, Debug, Default)] struct EventQueue { /// The enter events are stored in `Segments`; this is the index of the first @@ -325,6 +351,30 @@ pub struct SweepLineBuffers { output_events: Vec, } +// Craft patch (work limit): a linear search of the sweep line steps over a +// segment in under a sixteenth of the time of a segment comparison. +const SEGMENTS_PASSED_PER_UNIT: u64 = 16; + +/// Craft patch (removal scan): the runs of positions on the sweep line whose +/// segments all end at the current height, found by `scan_for_removal`. +/// +/// Each run is keyed by `live`, the nearest position to its left whose segment +/// does not end here (`None` when there is none), and maps to `end`. The run +/// covers the positions after `live` and before `end`. +#[derive(Debug, Default)] +struct EndedRuns(BTreeMap, usize>); + +impl EndedRuns { + /// The `live` key of the run that covers `pos`, if a run covers it. + fn live_before(&self, pos: usize) -> Option> { + self.0 + .range(..Some(pos)) + .next_back() + .filter(|&(_, &end)| pos < end) + .map(|(&live, _)| live) + } +} + /// Encapsulates the state of the sweep-line algorithm and allows iterating over sweep lines. #[derive(Clone, Debug)] pub struct Sweeper<'a> { @@ -363,6 +413,32 @@ pub struct Sweeper<'a> { touch_scans: rustc_hash::FxHashSet<(SegIdx, bool)>, #[cfg(test)] touch_scan_count: usize, + #[cfg(test)] + repeat_span_visits: u64, + // Craft patch (work limit): the most work that `next_line` lets the sweep + // do, and whether it stopped there. The work is the segment comparisons, + // which the two caches count, plus `position_checks`: the segment positions + // checked against horizontal segments and contour endpoints while finding + // the changed intervals, with n log2 n more for sorting a sweep line's n + // horizontal segments. `segments_passed` counts the segments that linear + // searches of the sweep line step over without comparing them, and the + // entries that the binary searches for a segment's position probe; each + // `SEGMENTS_PASSED_PER_UNIT` of them counts as one unit of work. + // `range_horizontals` counts the horizontal segments that the steps of a + // `SweepLineRange` visit; a range borrows the sweeper, so it is a `Cell`, + // and so is `range_stopped`, which records that a range step passed the limit. + work_limit: Option, + stopped_at_work_limit: bool, + position_checks: u64, + segments_passed: u64, + range_horizontals: Cell, + range_stopped: Cell, + // Craft patch (removal scan): how many positions `scan_for_removal` looked at, + // and how many times it started the intersection scans. + #[cfg(test)] + removal_scan_steps: usize, + #[cfg(test)] + removal_scans: usize, } impl<'segs> Sweeper<'segs> { @@ -372,15 +448,21 @@ impl<'segs> Sweeper<'segs> { /// The really correct mode doesn't actually change any of the /// output orders, but it does emit extra events whenever lines /// touch without crossing. + /// + /// An `eps` that is NaN, infinite, not positive, or below `64 * f64::EPSILON` + /// times the segments' largest coordinate magnitude is replaced by that value. + /// No error is returned for it; [`crate::binary_op_with_eps`] returns + /// [`crate::Error::InvalidEps`] for an invalid `eps` instead. pub fn new_with_correctness( segments: &'segs Segments, eps: f64, correctness: Correctness, ) -> Self { + let eps = segments.usable_eps(eps); let events = EventQueue::default(); Sweeper { eps, - line: SegmentOrder::default(), + line: SegmentOrder::new(segments.len()), correctness, y: events.next_y(segments).unwrap_or(f64::INFINITY), events, @@ -393,6 +475,18 @@ impl<'segs> Sweeper<'segs> { touch_scans: rustc_hash::FxHashSet::default(), #[cfg(test)] touch_scan_count: 0, + #[cfg(test)] + repeat_span_visits: 0, + work_limit: None, + stopped_at_work_limit: false, + position_checks: 0, + segments_passed: 0, + range_horizontals: Cell::new(0), + range_stopped: Cell::new(false), + #[cfg(test)] + removal_scan_steps: 0, + #[cfg(test)] + removal_scans: 0, } } @@ -402,18 +496,167 @@ impl<'segs> Sweeper<'segs> { Self::new_with_correctness(segments, eps, Correctness::GoodEnough) } + /// Limits the work the sweep may do. + /// + /// The work is the number of segment comparisons plus the number of segment + /// positions checked against horizontal segments and contour endpoints while + /// finding a sweep line's changed intervals, plus n log2 n for sorting the n + /// horizontal segments of a sweep line, plus one unit for every 16 segments + /// that linear searches of the sweep line step over without comparing them + /// or that binary searches for a segment's position probe, + /// plus the horizontal segments that each step of a [`SweepLineRange`] + /// visits. A caller stops processing a range once + /// [`SweepLineRange::work_limit_exceeded`] returns `true`. + /// Once the sweep has done more than `limit`, + /// [`Sweeper::next_line`] returns `None` and + /// [`Sweeper::work_limit_exceeded`] returns `true`. The sweep checks the limit + /// between events and between the comparisons and position checks that find a + /// sweep line's changed intervals, so it can pass the limit by the comparisons + /// and searches of one event, which grow with the number of segments in the + /// sweep line. It + /// never returns a sweep line once it has passed the limit. It stops partway + /// through a sweep line, so its output is incomplete, and it stays stopped if + /// the limit is raised afterwards. + pub fn set_work_limit(&mut self, limit: u64) { + self.work_limit = Some(limit); + } + + /// Returns `true` if the sweep has done more work than the limit given to + /// [`Sweeper::set_work_limit`], or has stopped at that limit. + pub fn work_limit_exceeded(&self) -> bool { + self.stopped_at_work_limit + || self.range_stopped.get() + || self.work_limit.is_some_and(|limit| self.work() > limit) + } + + /// Returns `true`, and keeps the sweep stopped, once the work limit is exceeded. + fn stop_at_work_limit(&mut self) -> bool { + self.stopped_at_work_limit = self.work_limit_exceeded(); + self.stopped_at_work_limit + } + + /// The work done so far: the segment comparisons, cached or not, the + /// position checks, the segments that linear searches passed, the entries + /// that position searches probed, and the horizontal segments that range + /// steps visited. + fn work(&self) -> u64 { + let calls = self.comparisons.borrow().calls; + calls + .saturating_add(self.conservative_comparisons.borrow().calls) + .saturating_add(self.position_checks) + .saturating_add(self.segments_passed / SEGMENTS_PASSED_PER_UNIT) + .saturating_add(self.range_horizontals.get()) + } + + /// Counts `n` horizontal segments visited by a step of a [`SweepLineRange`], + /// and keeps the sweep stopped once that passes the work limit, so raising + /// the limit afterwards does not resume it. + pub(crate) fn count_range_horizontals(&self, n: usize) { + let total = self.range_horizontals.get().saturating_add(n as u64); + self.range_horizontals.set(total); + if self.work_limit_exceeded() { + self.range_stopped.set(true); + } + } + + /// Finds `seg_idx` on the sweep line, counting the entries the binary search probes. + fn find_position(&mut self, seg_idx: SegIdx) -> Option { + let (pos, probes) = self.line.position_with_probes(seg_idx); + self.segments_passed = self.segments_passed.saturating_add(probes); + pos + } + + /// Counts one position check and returns `true`, stopping the sweep, once + /// the work limit is exceeded. + fn check_position(&mut self) -> bool { + self.position_checks = self.position_checks.saturating_add(1); + self.stop_at_work_limit() + } + fn compare_segments(&self, i: SegIdx, j: SegIdx) -> RefMut<'_, CurveOrder> { RefMut::map(self.comparisons.borrow_mut(), |c| { - c.compare_segments(self.segments, i, j) + c.compare_non_horizontal_segments(self.segments, i, j) }) } fn compare_segments_conservatively(&self, i: SegIdx, j: SegIdx) -> RefMut<'_, CurveOrder> { RefMut::map(self.conservative_comparisons.borrow_mut(), |c| { - c.compare_segments(self.segments, i, j) + c.compare_non_horizontal_segments(self.segments, i, j) }) } + /// Returns true if segments `i` and `j` start at the same point and the sweep line is at + /// that point. + /// + /// Every pair of segments that start at one point compares "ish" there, so a scan or an + /// insertion search from one of them passes all the others. Comparisons of such pairs made + /// at that point are not stored, so `n` segments that start at one point and do not cross + /// later store `O(n)` comparisons instead of `O(n^2)`. A comparison made at a later crossing + /// is stored as usual. + fn start_together_here(&self, i: SegIdx, j: SegIdx, y: f64) -> bool { + let start = self.segments[i].start(); + start.y == y && start == self.segments[j].start() + } + + /// Returns the next touch of `i` and `j` after `y`, and the first interval of their + /// conservative order that ends after `y`. + fn scan_comparison( + &self, + i: SegIdx, + j: SegIdx, + y: f64, + ) -> (Option, Option<(f64, f64, Order)>) { + if self.start_together_here(i, j, y) { + let touch = self + .comparisons + .borrow_mut() + .with_order(self.segments, i, j, |c| c.next_touch_after(y)); + let first = + self.conservative_comparisons + .borrow_mut() + .with_order(self.segments, i, j, |c| c.iter().find(|(_, y1, _)| *y1 > y)); + return (touch, first); + } + + let touch = self.compare_segments(i, j).next_touch_after(y); + let first = self + .compare_segments_conservatively(i, j) + .iter() + .find(|(_, y1, _)| *y1 > y); + (touch, first) + } + + // Craft patch (repeated intersection): the key under which `next_line` + // records a handled intersection event. It holds the pair, the positions + // of both segments in the sweep line, and a 64-bit SipHash of the segments + // from one of those positions to the other, in order. The hash keeps each + // key the same size however many segments lie between the pair. The + // position searches and the segments hashed count toward the work limit. + #[cfg(test)] + fn repeat_key(&mut self, left: SegIdx, right: SegIdx) -> RepeatKey { + let left_pos = self.find_position(left); + let right_pos = self.find_position(right); + self.repeat_key_at(left, right, left_pos, right_pos) + } + + fn repeat_key_at(&mut self, left: SegIdx, right: SegIdx, left_pos: Option, right_pos: Option) -> RepeatKey { + use std::hash::{Hash, Hasher}; + + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + if let (Some(a), Some(b)) = (left_pos, right_pos) { + let hashed = u64::try_from(a.abs_diff(b)).unwrap_or(u64::MAX).saturating_add(1); + self.segments_passed = self.segments_passed.saturating_add(hashed); + for entry in self.line.segs.range(a.min(b)..=a.max(b)) { + #[cfg(test)] + { + self.repeat_span_visits += 1; + } + entry.seg.hash(&mut hasher); + } + } + (left, right, left_pos, right_pos, hasher.finish()) + } + /// Moves the sweep forward, returning the next sweep line. /// /// Returns `None` when sweeping is complete. @@ -421,6 +664,14 @@ impl<'segs> Sweeper<'segs> { &'slf mut self, bufs: &'buf mut SweepLineBuffers, ) -> Option> { + // Craft patch (work limit): a sweep past its work limit stops here, and + // also partway through a sweep line, since one line of stacked or nearly + // coincident segments can take billions of comparisons. The sweep's + // state is left half updated, so every later call returns `None` too. + if self.stop_at_work_limit() { + return None; + } + self.check_invariants(); let y = self.events.next_y(self.segments)?; @@ -433,6 +684,9 @@ impl<'segs> Sweeper<'segs> { let enters = self.events.entrances_at_y(&y, self.segments); for (enter_y, idx) in enters { debug_assert_eq!(enter_y, &y); + if self.stop_at_work_limit() { + return None; + } self.handle_enter(*idx); self.check_invariants(); } @@ -441,9 +695,16 @@ impl<'segs> Sweeper<'segs> { // Process all the exit events. { let exits = self.events.exits_at_y(&y, self.segments); + // Craft patch (removal scan): the sweep line's positions do not + // change while exits are handled, so the runs of ended segments + // found for one exit also serve the others. + let mut ended_runs = EndedRuns::default(); for (exit_y, idx) in exits { debug_assert_eq!(exit_y, &y); - self.handle_exit(*idx); + if self.stop_at_work_limit() { + return None; + } + self.handle_exit(*idx, &mut ended_runs); self.check_invariants(); } } @@ -454,13 +715,18 @@ impl<'segs> Sweeper<'segs> { // do not compare transitively, handling one pair can queue another // pair at this same y again, and the pairs can cycle forever through // the same positions. A pair is handled at most once per y for each - // pair of positions it holds in the sweep line; a repeat is queued - // again at the pair's next order change instead, if that comes before - // both ends. + // arrangement of the sweep line from one segment of the pair to the + // other (see `repeat_key`). When the segments between the pair change, + // the key changes and `handle_intersection` checks them again. A + // repeat of the same arrangement is queued again at the pair's next + // order change instead, if that comes before both ends. let mut handled = FxHashSet::default(); #[cfg(test)] let mut events_at_y = 0usize; while let Some(intersection) = self.events.next_intersection_at_y(y) { + if self.stop_at_work_limit() { + return None; + } #[cfg(test)] { events_at_y += 1; @@ -471,8 +737,9 @@ impl<'segs> Sweeper<'segs> { ); } let (left, right) = (intersection.left, intersection.right); - let positions = (self.line.position(left), self.line.position(right)); - if !handled.insert((left, right, positions)) { + let left_idx = self.find_position(left).unwrap(); + let right_idx = self.find_position(right).unwrap(); + if left_idx < right_idx && !handled.insert(self.repeat_key_at(left, right, Some(left_idx), Some(right_idx))) { let next_y = self .compare_segments(left, right) .iter() @@ -490,11 +757,15 @@ impl<'segs> Sweeper<'segs> { } continue; } - self.handle_intersection(left, right); + self.handle_intersection(left, right, left_idx, right_idx); self.check_invariants(); } - self.compute_changed_intervals(); + // Craft patch (work limit): finding the changed intervals compares + // segments too, so the sweep can stop before or during it. + if self.stop_at_work_limit() || !self.compute_changed_intervals() { + return None; + } Some(SweepLine { state: self, next_changed_interval: 0, @@ -523,6 +794,12 @@ impl<'segs> Sweeper<'segs> { self.line.segs.remove(idx); } self.y = y; + // Craft patch (comparison cache size): the sweep line holds no + // segment that ends above `y`, so their cached pairs are dropped. + self.comparisons.get_mut().evict_ended(self.segments, y); + self.conservative_comparisons + .get_mut() + .evict_ended(self.segments, y); self.segs_needing_positions.clear(); self.horizontals.clear(); self.touch_scans.clear(); @@ -545,12 +822,32 @@ impl<'segs> Sweeper<'segs> { } let mut height_bound = seg.end().y; - for j in (start_idx + 1)..self.line.segs.len() { - let other_idx = self.line.seg(j); - let other = &self.segments[other_idx]; - if other.end().y == y { - continue; + // Craft patch (scan runs): when the next segment ends at `y`, the run + // of segments that end at `y` is stepped over with one pass of the + // tree iterator, instead of one indexed lookup per segment. Such a segment is not a barrier for the + // far-apart `break` below, because it leaves the line at `y`. + let len = self.line.segs.len(); + let segments = self.segments; + let mut next = start_idx + 1; + while next < len { + let mut other_idx = self.line.seg(next); + if segments[other_idx].end().y == y { + let passed = self + .line + .segs + .range(next..) + .take_while(|entry| segments[entry.seg].end().y == y) + .count(); + self.segments_passed = self.segments_passed.saturating_add(passed as u64); + next += passed; + if next >= len { + break; + } + other_idx = self.line.seg(next); } + let j = next; + next += 1; + let other = &self.segments[other_idx]; // Our basic comparisons use eps tolerance and eps/2 accuracy, so if // our max_x is 1.5 eps less than their min_x then we're guaranteed @@ -564,9 +861,7 @@ impl<'segs> Sweeper<'segs> { // event queue between actual intersections and near-touches? For // now, no. We will distinguish them in handle_intersection - let touch = self - .compare_segments(seg_idx, other_idx) - .next_touch_after(y); + let (touch, first_after_y) = self.scan_comparison(seg_idx, other_idx, y); if let Some(int_y) = touch.and_then(|touch| choose_cross_height(touch, y, which)) { let (left_idx, right_idx) = match touch { Some(curve::CurveInteraction::Touch(..)) => (j, start_idx), @@ -588,8 +883,7 @@ impl<'segs> Sweeper<'segs> { } } - let cmp = self.compare_segments_conservatively(seg_idx, other_idx); - if let Some((_y0, y1, order)) = cmp.iter().find(|(_, y1, _)| *y1 > y) + if let Some((_y0, y1, order)) = first_after_y && order == Order::Left && y1 >= height_bound { @@ -609,21 +903,35 @@ impl<'segs> Sweeper<'segs> { } let mut height_bound = seg.end().y; - for j in (0..start_idx).rev() { - let other_idx = self.line.seg(j); - let other = &self.segments[other_idx]; - if other.end().y == y { - continue; + // Craft patch (scan runs): see `intersection_scan_right`. + let segments = self.segments; + let mut next = start_idx; + while next > 0 { + let mut other_idx = self.line.seg(next - 1); + if segments[other_idx].end().y == y { + let passed = self + .line + .segs + .range_rev_to(next) + .take_while(|entry| segments[entry.seg].end().y == y) + .count(); + self.segments_passed = self.segments_passed.saturating_add(passed as u64); + next -= passed; + if next == 0 { + break; + } + other_idx = self.line.seg(next - 1); } + next -= 1; + let j = next; + let other = &self.segments[other_idx]; if seg.min_x() - 2.0 * self.eps > other.max_x() { break; } height_bound = height_bound.min(other.end().y); - let touch = self - .compare_segments(other_idx, seg_idx) - .next_touch_after(y); + let (touch, first_after_y) = self.scan_comparison(other_idx, seg_idx, y); if let Some(int_y) = touch.and_then(|touch| choose_cross_height(touch, y, which)) { let (left_idx, right_idx) = match touch { Some(curve::CurveInteraction::Touch(..)) => (start_idx, j), @@ -639,8 +947,7 @@ impl<'segs> Sweeper<'segs> { } } - let cmp = self.compare_segments_conservatively(other_idx, seg_idx); - if let Some((_y0, y1, order)) = cmp.iter().find(|(_, y1, _)| *y1 > y) + if let Some((_y0, y1, order)) = first_after_y && order == Order::Left && y1 >= height_bound { @@ -649,15 +956,59 @@ impl<'segs> Sweeper<'segs> { } } - fn scan_for_removal(&mut self, pos: usize) { - if pos > 0 { - self.intersection_scan_right(pos - 1, WhichTouch::Mid); - self.intersection_scan_left(pos - 1, WhichTouch::Mid); + fn scan_for_removal(&mut self, pos: usize, ended_runs: &mut EndedRuns) { + // Craft patch (removal scan): segments that end at this y stay in the + // sweep line until `advance`, and a scan from one of them returns at + // once. The scans start from the nearest segment left of `pos` that + // does not end here, so the live segments on both sides of the gap + // are compared. When there is none, nothing on the left can cross. + // + // The scans skip every segment that ends at this y, so while the + // positions do not change, a scan from the same segment finds the + // same pairs. `ended_runs` records the starts already scanned. + let y = self.y; + let mut live = None; + let mut i = pos; + while i > 0 { + i -= 1; + #[cfg(test)] + { + self.removal_scan_steps += 1; + } + // Each entry the scan visits counts toward the work limit. + self.segments_passed = self.segments_passed.saturating_add(1); + if let Some(run_live) = ended_runs.live_before(i) { + live = run_live; + break; + } + if self.segments[self.line.seg(i)].end().y != y { + live = Some(i); + break; + } + } + let scanned = match ended_runs.0.entry(live) { + Entry::Occupied(mut run) => { + let end = run.get_mut(); + *end = (*end).max(pos); + true + } + Entry::Vacant(run) => { + run.insert(pos); + false + } + }; + if !scanned && let Some(start) = live { + #[cfg(test)] + { + self.removal_scans += 1; + } + self.intersection_scan_right(start, WhichTouch::Mid); + self.intersection_scan_left(start, WhichTouch::Mid); } } fn insert(&mut self, pos: usize, seg: SegmentOrderEntry) { - self.line.segs.insert(pos, seg); + self.line.insert(pos, seg); self.intersection_scan_right(pos, WhichTouch::Mid); self.intersection_scan_left(pos, WhichTouch::Mid); } @@ -684,11 +1035,11 @@ impl<'segs> Sweeper<'segs> { if let Some(contour_prev_idx) = contour_prev_idx { let contour_prev = &self.segments[contour_prev_idx]; if contour_prev.start().y < self.y { - let pos = self.line.position(contour_prev_idx).unwrap(); + let pos = self.find_position(contour_prev_idx).unwrap(); debug_assert!(contour_prev.end() == new_seg.start()); self.handle_contour_continuation(seg_idx, new_seg, pos); return; - } else if let Some(contour_prev_pos) = self.line.position(contour_prev_idx) { + } else if let Some(contour_prev_pos) = self.find_position(contour_prev_idx) { // Both of us entered on this sweep-line. debug_assert!(contour_prev.start() == new_seg.start()); pos = match self @@ -768,6 +1119,8 @@ impl<'segs> Sweeper<'segs> { let x1 = seg.max_x(); self.line.segs[pos].old_seg = Some(self.line.segs[pos].seg); self.line.segs[pos].seg = seg_idx; + // Craft patch (sweep position). + self.line.keys[seg_idx] = self.line.segs[pos].key; self.line.segs[pos].enter = true; self.line.segs[pos].exit = true; self.line.segs[pos].lower_bound = x0.min(x1) - self.eps; @@ -779,8 +1132,8 @@ impl<'segs> Sweeper<'segs> { /// Marks a segment as needing to exit, but doesn't actually remove it /// from the sweep-line. See `SegmentOrderEntry::exit` for an explanation. - fn handle_exit(&mut self, seg_idx: SegIdx) { - let pos = self.line.position(seg_idx).unwrap(); + fn handle_exit(&mut self, seg_idx: SegIdx, ended_runs: &mut EndedRuns) { + let pos = self.find_position(seg_idx).unwrap(); if self.line.segs[pos].old_seg == Some(seg_idx) { return; @@ -790,13 +1143,11 @@ impl<'segs> Sweeper<'segs> { // the scan doesn't get confused by the segment that should be marked // for exit. self.line.segs[pos].exit = true; - self.scan_for_removal(pos); + self.scan_for_removal(pos, ended_runs); self.segs_needing_positions.push(pos); } - fn handle_intersection(&mut self, left: SegIdx, right: SegIdx) { - let left_idx = self.line.position(left).unwrap(); - let right_idx = self.line.position(right).unwrap(); + fn handle_intersection(&mut self, left: SegIdx, right: SegIdx, left_idx: usize, right_idx: usize) { if left_idx < right_idx { // We're going to put `left_seg` after `right_seg` in the // sweep line, and while doing so we need to "push" along @@ -806,6 +1157,7 @@ impl<'segs> Sweeper<'segs> { for j in (left_idx + 1)..right_idx { let seg_j_entry = &self.line.segs[j]; if seg_j_entry.will_really_exit() { + self.segments_passed = self.segments_passed.saturating_add(1); continue; } @@ -858,7 +1210,7 @@ impl<'segs> Sweeper<'segs> { let mut removed = Vec::with_capacity(to_move.len()); for &j in to_move.iter().rev() { removed.push(self.line.segs.remove(j)); - self.scan_for_removal(j); + self.scan_for_removal(j, &mut EndedRuns::default()); } // We want to insert them at what was previously `right_idx + 1`, but the @@ -882,7 +1234,7 @@ impl<'segs> Sweeper<'segs> { // larger `y` than our current `y` (if not, it would // violate the cyclic order property). let which = WhichTouch::Late; - self.line.segs.insert(insertion_pos, seg); + self.line.insert(insertion_pos, seg); self.intersection_scan_right(insertion_pos, which); self.intersection_scan_left(insertion_pos, which); } @@ -966,6 +1318,11 @@ impl<'segs> Sweeper<'segs> { #[cfg(feature = "slow-asserts")] fn check_invariants(&self) { + // Craft patch (work limit): the comparisons made by these checks do not + // count toward the work limit. + let calls = self.comparisons.borrow().calls; + let conservative_calls = self.conservative_comparisons.borrow().calls; + for seg_entry in self.line.segs.iter() { let seg_idx = seg_entry.seg; let seg = &self.segments[seg_idx]; @@ -1062,29 +1419,53 @@ impl<'segs> Sweeper<'segs> { } self.check_changed_interval_closeness(); + + self.comparisons.borrow_mut().calls = calls; + self.conservative_comparisons.borrow_mut().calls = conservative_calls; } #[cfg(not(feature = "slow-asserts"))] fn check_invariants(&self) {} - fn compute_horizontal_changed_intervals(&mut self) { + /// Craft patch (work limit): returns `false`, leaving the changed intervals + /// incomplete, if the sweep passes its work limit. + fn compute_horizontal_changed_intervals(&mut self) -> bool { + // Sorting the n horizontal segments counts as n log2 n position checks, + // and the sweep stops before the sort once that passes the work limit. + let n = self.horizontals.len() as u64; + let sort_work = n.saturating_mul(n.checked_ilog2().map_or(0, u64::from)); + self.position_checks = self.position_checks.saturating_add(sort_work); + if self.stop_at_work_limit() { + return false; + } self.horizontals .sort_by_key(|seg_idx| CheapOrderedFloat::from(self.segments[*seg_idx].start().x)); let mut last_end = f64::NEG_INFINITY; - for (idx, &seg_idx) in self.horizontals.iter().enumerate() { - let seg = &self.segments[seg_idx]; + let segments = self.segments; + for idx in 0..self.horizontals.len() { + let seg_idx = self.horizontals[idx]; + let seg = &segments[seg_idx]; // Find the index of some segment that might overlap with this // horizontal segment, but the index before definitely doesn't. + let mut probes = 0u64; let start_idx = self.line.segs.partition_point(|other_entry| { + probes += 1; let other_seg = &self.segments[other_entry.seg]; other_seg.upper(self.y, self.eps) + self.eps <= seg.start().x }); + self.position_checks = self.position_checks.saturating_add(probes); + if self.stop_at_work_limit() { + return false; + } let mut end_idx = start_idx; for j in start_idx..self.line.segs.len() { + if self.check_position() { + return false; + } let other_entry = &mut self.line.segs[j]; let other_seg = &self.segments[other_entry.seg]; @@ -1118,6 +1499,7 @@ impl<'segs> Sweeper<'segs> { last_end = last_end.max(seg.end().x); } + true } /// When a segment enters or exits, we insert a horizontal line from @@ -1127,8 +1509,12 @@ impl<'segs> Sweeper<'segs> { /// interval. /// /// This method adds all the changed intervals that are needed to handle this case. - fn compute_contour_adjacent_changed_intervals(&mut self) { - for &j in &self.segs_needing_positions { + /// + /// Craft patch (work limit): returns `false`, leaving the changed intervals + /// incomplete, if the sweep passes its work limit. + fn compute_contour_adjacent_changed_intervals(&mut self) -> bool { + for n in 0..self.segs_needing_positions.len() { + let j = self.segs_needing_positions[n]; let seg_entry = self.line.segs[j]; if seg_entry.old_seg.is_some() { @@ -1155,6 +1541,9 @@ impl<'segs> Sweeper<'segs> { let mut start_idx = j; let mut end_idx = j; for i in (0..j).rev() { + if self.check_position() { + return false; + } let other_entry = &mut self.line.segs[i]; let other_seg = &self.segments[other_entry.seg]; @@ -1168,6 +1557,9 @@ impl<'segs> Sweeper<'segs> { } } for k in (j + 1)..self.line.segs.len() { + if self.check_position() { + return false; + } let other_entry = &mut self.line.segs[k]; let other_seg = &self.segments[other_entry.seg]; @@ -1188,6 +1580,7 @@ impl<'segs> Sweeper<'segs> { }); } } + true } /// Updates our internal `changed_intervals` state based on the segments marked @@ -1195,10 +1588,16 @@ impl<'segs> Sweeper<'segs> { /// /// For each segment marked as needing a position, we expand it to a range of /// physically nearby segments, and then we deduplicate and merge those ranges. - fn compute_changed_intervals(&mut self) { + /// + /// Craft patch (work limit): returns `false`, leaving the changed intervals + /// incomplete, if the sweep passes its work limit. + fn compute_changed_intervals(&mut self) -> bool { debug_assert!(self.changed_intervals.is_empty()); - self.compute_horizontal_changed_intervals(); - self.compute_contour_adjacent_changed_intervals(); + if !self.compute_horizontal_changed_intervals() + || !self.compute_contour_adjacent_changed_intervals() + { + return false; + } for &idx in &self.segs_needing_positions { if self.line.segs[idx].in_changed_interval { @@ -1219,6 +1618,10 @@ impl<'segs> Sweeper<'segs> { // that we most recently added to the changed interval. Modulo some subtleties // involving conservative/non-conservative comparisons, this will usually be // `i - 1`. + if self.work_limit_exceeded() { + self.stopped_at_work_limit = true; + return false; + } let seg_idx = self.line.seg(end_idx - 1); let next_seg_idx = self.line.seg(i); let strong_order = self @@ -1245,6 +1648,10 @@ impl<'segs> Sweeper<'segs> { } for i in (0..start_idx).rev() { + if self.work_limit_exceeded() { + self.stopped_at_work_limit = true; + return false; + } let prev_seg_idx = self.line.seg(i); // Note that start_idx is mutated in the loop, so this points to the segment // that we most recently added to the changed interval. @@ -1278,6 +1685,7 @@ impl<'segs> Sweeper<'segs> { // cross as needing a position. Any collection of subranges that are crossed by // a horizontal segment are therefore adjacent and will be merged here. merge_adjacent(&mut self.changed_intervals); + !self.stop_at_work_limit() } } @@ -1340,8 +1748,12 @@ impl SegmentOrder { continue; } - let order = cmp.compare_segments(segments, segi, segj); - if order.order_at(y) == Order::Right { + let order = cmp.compare_non_horizontal_segments(segments, segi, segj); + // A zero-height touch includes its boundary. + let touches_here = order.iter().any(|(start, end, relation)| { + relation == Order::Ish && start <= y && y <= end + }); + if order.order_at(y) == Order::Right && !touches_here { return Some((segi, segj)); } } @@ -1379,7 +1791,8 @@ impl SegmentOrder { // will be in the future, so as to minimize swapping. // (We could also try checking whether the new segment is a contour neighbor of // the segment at pos. That should be a pretty common case.) - let cmp = comparer.compare_segments(segments, seg_idx, self.segs[pos].seg); + let cmp = + comparer.compare_non_horizontal_segments(segments, seg_idx, self.segs[pos].seg); return match cmp.order_after(y) { Order::Right => pos + 1, Order::Ish => pos, @@ -1387,12 +1800,32 @@ impl SegmentOrder { }; } - // A predicate that tests whether `other` is definitely to the left of `seg` at `y`. - let lower_pred = |other: &SegmentOrderEntry| -> bool { - let cmp = comparer.compare_segments(segments, other.seg, seg_idx); - cmp.order_at(y) == Order::Left + // Every segment that starts where the new one starts compares "ish" to it here, so the + // search below can pass all of them. Comparisons with those segments are made without + // storing them (see `Sweeper::start_together_here`). `order` returns the order of `other` + // relative to the new segment at `y` and, if that is "ish", the order after `y`. + let start = seg.start(); + let order = |comparer: &mut ComparisonCache, other: SegIdx| -> (Order, Order) { + let orders = |cmp: &CurveOrder| { + let at = cmp.order_at(y); + let after = if at == Order::Ish { + cmp.order_after(y) + } else { + at + }; + (at, after) + }; + if start.y == y && segments[other].start() == start { + comparer.with_order(segments, other, seg_idx, orders) + } else { + orders(comparer.compare_non_horizontal_segments(segments, other, seg_idx)) + } }; + // A predicate that tests whether `other` is definitely to the left of `seg` at `y`. + let lower_pred = + |other: &SegmentOrderEntry| -> bool { order(comparer, other.seg).0 == Order::Left }; + // The rust stdlib docs say that we're not allowed to do this, because // our array isn't sorted with respect to `lower_pred`. // But for now at least, their implementation does a normal @@ -1404,8 +1837,8 @@ impl SegmentOrder { let search_start = self.segs.partition_point(lower_pred); let mut idx = search_start; for i in search_start..self.segs.len() { - let cmp = comparer.compare_segments(segments, self.segs[i].seg, seg_idx); - match cmp.order_at(y) { + let (order_at, order_after) = order(comparer, self.segs[i].seg); + match order_at { Order::Right => { // The segment at i is definitely to the right of the new one. break; @@ -1413,7 +1846,7 @@ impl SegmentOrder { Order::Ish => { // We could go either way, and we'll update our preference based on the // future ordering. - if cmp.order_after(y) == Order::Left { + if order_after == Order::Left { idx = i + 1; } } @@ -1430,10 +1863,121 @@ impl SegmentOrder { // // Returns an index pointing to a `SegmentOrderEntry` for which // `seg_idx` is either the `seg` or the `old_seg`. + // + // Craft patch (sweep position): a binary search over the keys replaces + // the package's linear scan. + #[cfg(any(test, feature = "slow-asserts"))] fn position(&self, seg_idx: SegIdx) -> Option { - self.segs - .iter() - .position(|x| x.seg == seg_idx || x.old_seg == Some(seg_idx)) + self.position_with_probes(seg_idx).0 + } + + fn position_with_probes(&self, seg_idx: SegIdx) -> (Option, u64) { + let key = self.keys[seg_idx]; + let mut probes = 0u64; + let pos = self.segs.partition_point(|entry| { + probes = probes.saturating_add(1); + entry.key < key + }); + let ret = self + .segs + .get(pos) + .is_some_and(|x| x.seg == seg_idx || x.old_seg == Some(seg_idx)) + .then_some(pos); + + #[cfg(any(test, feature = "slow-asserts"))] + assert_eq!( + ret, + self.segs + .iter() + .position(|x| x.seg == seg_idx || x.old_seg == Some(seg_idx)) + ); + + (ret, probes) + } + + // Craft patch (sweep position): inserts an entry at the given index, + // assigning it a key that keeps the keys sorted. + fn insert(&mut self, pos: usize, mut entry: SegmentOrderEntry) { + let (mut before, mut after) = self.neighbor_keys(pos); + if after - before < 2 { + self.spread_keys(pos); + (before, after) = self.neighbor_keys(pos); + } + entry.key = before + (after - before) / 2; + self.keys[entry.seg] = entry.key; + if let Some(old_seg) = entry.old_seg { + self.keys[old_seg] = entry.key; + } + self.segs.insert(pos, entry); + } + + // Craft patch (sweep position): the keys of the entries on either side of + // the given index, or zero and `u64::MAX` at the ends of the sweep line. No entry has either of those + // keys, so there is always a key to give an entry inserted at either end. + fn neighbor_keys(&self, pos: usize) -> (u64, u64) { + let before = pos.checked_sub(1).map_or(0, |i| self.segs[i].key); + let after = self.segs.get(pos).map_or(u64::MAX, |entry| entry.key); + (before, after) + } + + // Craft patch (sweep position): makes space for inserting an entry at the + // given index, by evenly spacing the keys around it. + // + // This follows the tag-range relabeling of Bender et al., "Two Simplified + // Algorithms for Maintaining Order in a List" (ESA 2002): take the smallest + // aligned power-of-two range of keys around the index that is sparse enough, + // and spread out the keys inside it. The amortized number of keys changed by + // an insertion is logarithmic in the length of the sweep line. + fn spread_keys(&mut self, pos: usize) { + // How quickly the allowed density falls as the range grows. Each doubling + // of the range allows `2.0 / OVERFLOW` times as many entries, so a range + // of `2^bits` keys holds up to `(2.0 / OVERFLOW)^bits` of them. + const OVERFLOW: f64 = 1.4; + + let len = self.segs.len(); + let center = self.segs[pos.min(len - 1)].key; + let mut start = pos; + let mut end = pos; + let mut max_entries = 1.0; + for bits in 1..u64::BITS { + let range_len = 1u64 << bits; + let first = center & !(range_len - 1); + let last = first + (range_len - 1); + while start > 0 && self.segs[start - 1].key >= first { + start -= 1; + } + while end < len && self.segs[end].key <= last { + end += 1; + } + + max_entries *= 2.0 / OVERFLOW; + let count = (end - start) as u64; + let step = range_len / (count + 1); + // A step of 3 leaves a gap of at least 2 after the last key, even if + // the range ends at `u64::MAX`. + if count as f64 <= max_entries && step >= 3 { + self.assign_keys(start..end, first, step); + return; + } + } + + // Even the largest range is too dense for its limit, which takes about + // 6 * 10^9 entries. The whole key space still has room for all of them. + self.assign_keys(0..len, 0, u64::MAX / (len as u64 + 1)); + } + + // Craft patch (sweep position): gives the entries in a range of indices the + // keys `first + step`, `first + 2 * step`, and so on. + fn assign_keys(&mut self, range: std::ops::Range, first: u64, step: u64) { + let mut key = first; + for entry in self.segs.range_mut(range) { + key += step; + entry.key = key; + self.keys[entry.seg] = key; + if let Some(old_seg) = entry.old_seg { + self.keys[old_seg] = key; + } + } } } @@ -1674,6 +2218,7 @@ impl<'segs> SweepLine<'_, '_, 'segs> { in_changed_interval: false, old_idx: None, old_seg: None, + key: 0, }; let buffers = &mut self.bufs; @@ -1799,7 +2344,9 @@ impl<'segs> SweepLine<'_, '_, 'segs> { }); } } - events.sort(); + // Craft patch (output event order): sort by horizontal range alone, as the + // package's `Ord` did, so events with the same range keep their order. + events.sort_by(OutputEvent::cmp_x); bufs.clear(); Some(SweepLineRange::new( @@ -1850,7 +2397,7 @@ fn choose_cross_height( // We could just emit y0. That would be safe, but give less pretty results // in practice. let (mid, end) = match interaction { - CurveInteraction::Cross(y0, y1) | CurveInteraction::Touch(y0, y1) => ((y0 + y1) / 2.0, y1), + CurveInteraction::Cross(y0, y1) | CurveInteraction::Touch(y0, y1) => (y0.midpoint(y1), y1), }; debug_assert!(end >= cur_y); match (interaction, which, mid <= cur_y) { @@ -1917,6 +2464,7 @@ mod tests { segs: (0..xs.len()) .map(|i| SegmentOrderEntry::new(SegIdx(i), &segs, eps)) .collect(), + ..Default::default() }; let mut cmp = ComparisonCache::new(eps, eps / 2.0); @@ -1930,6 +2478,11 @@ mod tests { assert!(check_order(crossing, 0.5, eps).is_none()); assert_eq!(check_order(crossing, 0.99, eps), Some((0, 1))); + let reversed_crossing = &[(1.0, -1.0), (-1.0, 1.0)]; + assert_eq!(check_order(reversed_crossing, 0.49, 0.0), Some((0, 1))); + assert_eq!(check_order(reversed_crossing, 0.5, 0.0), None); + assert_eq!(check_order(reversed_crossing, 0.51, 0.0), None); + let not_quite_crossing = &[(-0.5 * eps, 0.5 * eps), (0.5 * eps, -0.5 * eps)]; assert!(check_order(not_quite_crossing, 0.0, eps).is_none()); assert!(check_order(not_quite_crossing, 0.5, eps).is_none()); @@ -1969,6 +2522,7 @@ mod tests { segs: (0..(xs.len() - 1)) .map(|i| SegmentOrderEntry::new(SegIdx(i), &segs, eps)) .collect(), + ..Default::default() }; let mut comparer = ComparisonCache::new(eps, eps / 2.0); let idx = line.insertion_idx(y, &segs, new_idx, &mut comparer); @@ -2035,6 +2589,173 @@ mod tests { }); } + fn check_positions(line: &SegmentOrder, num_segs: usize) { + let keys: Vec<_> = line.segs.iter().map(|entry| entry.key).collect(); + assert!(keys.is_sorted_by(|a, b| a < b)); + assert!(keys.iter().all(|key| 0 < *key && *key < u64::MAX)); + + // `position` compares its answer with a linear scan. + for seg in (0..num_segs).map(SegIdx) { + line.position(seg); + } + } + + #[derive(Clone, Debug)] + enum LineEdit { + Insert(prop::sample::Index), + InsertRepeatedly(prop::sample::Index, usize), + Remove(prop::sample::Index), + Move(prop::sample::Index, prop::sample::Index), + ContinueContour(prop::sample::Index), + } + + fn line_edit() -> impl Strategy { + let idx = any::; + prop_oneof![ + idx().prop_map(LineEdit::Insert), + (idx(), 0usize..100).prop_map(|(at, n)| LineEdit::InsertRepeatedly(at, n)), + idx().prop_map(LineEdit::Remove), + (idx(), idx()).prop_map(|(from, to)| LineEdit::Move(from, to)), + idx().prop_map(LineEdit::ContinueContour), + ] + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + // Applies the same kinds of edits as `Sweeper`, in any order. + #[test] + fn position_after_edits(edits in prop::collection::vec(line_edit(), 0..20)) { + let num_segs = 2000; + let segs = mk_segs(&vec![(0.0, 0.0); num_segs]); + let eps = 0.01; + + let mut line = SegmentOrder::new(num_segs); + let mut next_seg = 0; + let mut new_entry = || { + next_seg += 1; + SegmentOrderEntry::new(SegIdx(next_seg - 1), &segs, eps) + }; + for edit in edits { + let len = line.segs.len(); + match edit { + LineEdit::Insert(at) => line.insert(at.index(len + 1), new_entry()), + LineEdit::InsertRepeatedly(at, n) => { + let at = at.index(len + 1); + for _ in 0..n { + line.insert(at, new_entry()); + } + } + LineEdit::Remove(at) if len > 0 => { + line.segs.remove(at.index(len)); + } + LineEdit::Move(from, to) if len > 0 => { + let entry = line.segs.remove(from.index(len)); + line.insert(to.index(len), entry); + } + LineEdit::ContinueContour(at) if len > 0 => { + let pos = at.index(len); + let new_seg = new_entry().seg; + line.segs[pos].old_seg = Some(line.segs[pos].seg); + line.segs[pos].seg = new_seg; + line.keys[new_seg] = line.segs[pos].key; + } + _ => {} + } + check_positions(&line, 10); + for (i, entry) in line.segs.iter().enumerate() { + assert_eq!(line.position(entry.seg), Some(i)); + if let Some(old_seg) = entry.old_seg { + assert_eq!(line.position(old_seg), Some(i)); + } + } + } + check_positions(&line, next_seg); + } + } + + #[test] + fn position_after_repeated_insertion() { + let num_segs = 2000; + let segs = mk_segs(&vec![(0.0, 0.0); num_segs]); + let eps = 0.01; + let entry = |i| SegmentOrderEntry::new(SegIdx(i), &segs, eps); + + for insertion_pos in [ + // Always at the start of the line. + |_| 0, + // Always at the end of the line. + |i| i, + // Always in the same gap in the middle of the line. + |i: usize| i.min(1), + // Alternating on both sides of the most recent entry. + |i: usize| i.div_ceil(2), + ] { + let mut line = SegmentOrder::new(num_segs); + for i in 0..num_segs { + line.insert(insertion_pos(i), entry(i)); + } + check_positions(&line, num_segs); + } + } + + #[test] + fn position_after_insertion_next_to_the_extreme_keys() { + let segs = mk_segs(&[(0.0, 0.0); 2]); + let eps = 0.01; + for (key, pos) in [(u64::MAX - 1, 1), (1, 0)] { + let mut line = SegmentOrder::new(2); + line.insert(0, SegmentOrderEntry::new(SegIdx(0), &segs, eps)); + line.segs[0].key = key; + line.keys[SegIdx(0)] = key; + + line.insert(pos, SegmentOrderEntry::new(SegIdx(1), &segs, eps)); + check_positions(&line, 2); + } + } + + #[test] + fn position_after_moving_a_contour_continuation() { + let segs = mk_segs(&[(0.0, 0.0); 3]); + let eps = 0.01; + let mut line = SegmentOrder::new(3); + line.insert(0, SegmentOrderEntry::new(SegIdx(0), &segs, eps)); + line.insert(1, SegmentOrderEntry::new(SegIdx(1), &segs, eps)); + + line.segs[0].old_seg = Some(SegIdx(0)); + line.segs[0].seg = SegIdx(2); + line.keys[SegIdx(2)] = line.segs[0].key; + + let entry = line.segs.remove(0); + line.insert(1, entry); + assert_eq!(line.position(SegIdx(0)), Some(1)); + assert_eq!(line.position(SegIdx(2)), Some(1)); + } + + #[test] + fn position_on_a_wide_sweep_line() { + // Two overlapping sawtooths. About 160 of their segments are on the sweep + // line at one height, more than fit in a `TreeVec` node, and each kink, + // exit and crossing looks up a position. + let mut path = BezPath::new(); + for offset in [0.0, 0.25] { + path.move_to((offset, 0.0)); + for i in 0..40 { + let i_f = i as f64; + let height = 10.0 + (i_f * 0.618).fract(); + path.line_to((offset + i_f + 0.3, 5.0 + (i_f * 0.5).fract())); + path.line_to((offset + i_f + 0.5, height)); + path.line_to((offset + i_f + 0.8, 5.0 + (i_f * 0.25).fract())); + path.line_to((offset + i_f + 1.0, (i_f * 0.755).fract())); + } + path.close_path(); + } + + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + crate::sweep::sweep(&segs, 1e-6, |_, _| {}); + } + fn p(x: f64, y: f64) -> Point { Point::new(x, y) } @@ -2091,6 +2812,81 @@ mod tests { insta::assert_ron_snapshot!(snapshot_outputs(segs, 0.01)); } + // Craft patch (scan runs). + fn closed_polygon(path: &mut BezPath, points: &[(f64, f64)]) { + path.move_to(points[0]); + for &q in &points[1..] { + path.line_to(q); + } + path.close_path(); + } + + fn total_area(contours: &crate::topology::Contours) -> f64 { + use kurbo::Shape; + contours + .contours() + .map(|c| c.path.area()) + .sum::() + .abs() + } + + // Craft patch (scan runs): a triangle ends at y = 1 between a vertical + // edge that starts there and an edge that crosses that vertical lower down. + // The right scan from the vertical steps over the ending edges and still + // finds the crossing. + #[test] + fn scans_step_over_segments_that_end() { + let mut a = BezPath::new(); + closed_polygon(&mut a, &[(9.0, 0.0), (11.0, 0.0), (10.0, 1.0)]); + closed_polygon(&mut a, &[(0.0, 1.0), (0.0, 3.0), (-1.0, 3.0)]); + let mut b = BezPath::new(); + closed_polygon(&mut b, &[(11.0, 0.9), (12.0, 3.0), (-5.0, 3.0)]); + + let out = crate::binary_op( + &a, + &b, + crate::FillRule::NonZero, + crate::BinaryOp::Intersection, + ) + .unwrap(); + assert_eq!(out.contours().count(), 1); + let area = total_area(&out); + assert!((area - 0.51688).abs() < 1e-4, "area {area}"); + } + + // Craft patch (scan runs): 400 edges end and 400 start at y = 1. + #[test] + fn runs_of_ending_segments_keep_the_output() { + let n = 200; + let mut points = Vec::new(); + for i in 0..=2 * n { + points.push((i as f64, if i % 2 == 0 { 0.0 } else { 1.0 })); + } + for i in (0..=2 * n).rev() { + points.push((i as f64 + 0.5, if i % 2 == 0 { 2.0 } else { 1.0 })); + } + let mut wave = BezPath::new(); + closed_polygon(&mut wave, &points); + let expected = { + use kurbo::Shape; + wave.area().abs() + }; + + let out = crate::binary_op( + &wave, + &BezPath::new(), + crate::FillRule::NonZero, + crate::BinaryOp::Union, + ) + .unwrap(); + assert_eq!(out.contours().count(), 1); + let area = total_area(&out); + assert!( + (area - expected).abs() < 1e-6, + "area {area}, expected {expected}" + ); + } + #[test] fn square_and_diamond() { let square = [p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 1.0)]; @@ -2159,11 +2955,92 @@ mod tests { segs.add_bez_path(&circles).unwrap(); let mut sweep = Sweeper::new(&segs, 1e-6); let mut bufs = SweepLineBuffers::default(); - let mut lines = 0; - while sweep.next_line(&mut bufs).is_some() { - lines += 1; + let mut seen = FxHashSet::default(); + while let Some(line) = sweep.next_line(&mut bufs) { + let y = line.y(); + let mut idx = 0; + while let Some(seg) = line.line_segment(idx) { + let s = &segs[seg]; + assert!( + s.start().y <= y && y <= s.end().y, + "segment {seg:?} is in the sweep line at y={y}" + ); + seen.insert(seg); + idx += 1; + } + } + for seg in segs.indices() { + assert!( + segs[seg].is_horizontal() || seen.contains(&seg), + "segment {seg:?} never entered the sweep line" + ); + } + + // The five circles overlap almost entirely: their union has one + // boundary, the area all five cover is not empty, and no region is + // wound negatively or more than five times. + let top = crate::topology::Topology::from_path(&circles, 1e-6).unwrap(); + for idx in top.segment_indices() { + let half = idx.first_half(); + for w in [top.winding_clockwise(half), top.winding_counter_clockwise(half)] { + assert!((0..=5).contains(w), "winding number {w} on {idx:?}"); + } + } + assert_eq!(top.contours(|w| *w != 0).contours().count(), 1); + assert!(top.contours(|w| *w == 5).contours().count() > 0); + let bbox = top.bounding_box(); + let corners = [(bbox.x0, 450.0), (bbox.y0, 450.0), (bbox.x1, 550.0), (bbox.y1, 550.0)]; + for (got, want) in corners { + assert!((got - want).abs() < 1e-3, "{bbox:?}"); + } + } + + // A pair with the same two positions but different segments between them + // gets a new repeat key, so `next_line` hands it to `handle_intersection`, + // which checks the segments between the pair again. + #[test] + fn repeat_key_includes_segments_between_the_pair() { + let segs = mk_segs(&[(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0)]); + let ids: Vec = segs.indices().collect(); + let (a, b, c, d, e) = (ids[0], ids[1], ids[2], ids[3], ids[4]); + let mut sweep = Sweeper::new(&segs, 0.1); + let set_line = |sweep: &mut Sweeper, order: &[SegIdx]| { + sweep.line.segs = TreeVec::default(); + for (pos, &seg) in order.iter().enumerate() { + sweep.line.insert(pos, SegmentOrderEntry::new(seg, &segs, 0.1)); + } + }; + + set_line(&mut sweep, &[a, b, c, d]); + let first = sweep.repeat_key(a, d); + set_line(&mut sweep, &[a, c, b, d]); + assert_ne!(sweep.repeat_key(a, d), first); + set_line(&mut sweep, &[a, e, c, d]); + assert_ne!(sweep.repeat_key(a, d), first); + set_line(&mut sweep, &[a, b, c, d]); + assert_eq!(sweep.repeat_key(a, d), first); + assert_eq!(sweep.repeat_key(d, a).4, first.4); + } + + #[test] + fn position_work_counts_every_tree_predicate_probe() { + let xs: Vec<_> = (0..1024).map(|n| (f64::from(n), f64::from(n))).collect(); + let segs = mk_segs(&xs); + let mut sweep = Sweeper::new(&segs, 0.1); + for (pos, seg) in segs.indices().enumerate() { + sweep.line.insert(pos, SegmentOrderEntry::new(seg, &segs, 0.1)); + } + for seg in segs.indices() { + let key = sweep.line.keys[seg]; + let mut probes = 0u64; + let expected = sweep.line.segs.partition_point(|entry| { + probes += 1; + entry.key < key + }); + let before = sweep.segments_passed; + assert_eq!(sweep.find_position(seg), Some(expected)); + assert_eq!(sweep.segments_passed - before, probes, "segment {seg:?}"); } - assert!(lines > 0); } // Wide, flat shapes (x up to 1e12, y below 1e-3) whose sweep delays an @@ -2254,6 +3131,7 @@ mod tests { while sweep.next_line(&mut bufs).is_some() { lines += 1; } + assert_eq!(sweep.repeat_span_visits, 0, "ordinary coincident touches must not hash intervening spans"); assert!( sweep.touch_scan_count <= 2 * segs.len() * lines, "{} touch scans for {} segments on {lines} sweep lines", @@ -2348,6 +3226,129 @@ mod tests { } } + /// `n` thin triangles that share the apex (0, 0), with bases on y = 500, 10 apart. + /// No two of them cross. With `curved`, the left edge of each one bows out by 0.5. + fn shared_apex_triangles(n: u32, curved: bool) -> BezPath { + let mut path = BezPath::new(); + for i in 0..n { + let x = f64::from(i) * 10.0; + path.move_to((0.0, 0.0)); + if curved { + path.quad_to(((x - 3.0) / 2.0 - 1.0, 250.0), (x - 3.0, 500.0)); + } else { + path.line_to((x - 3.0, 500.0)); + } + path.line_to((x + 3.0, 500.0)); + path.close_path(); + } + path + } + + /// Sweeps `path` and asserts that each comparison cache stores at most `max` comparisons + /// after every sweep line. + /// + /// The `slow-asserts` checks compare every pair of segments on the sweep line with the + /// regular comparisons, so with that feature only the conservative ones are counted. + fn assert_stored_at_most(path: &BezPath, max: usize) { + let mut segs = Segments::default(); + segs.add_bez_path(path).unwrap(); + + let mut sweeper = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + let mut lines = 0; + while sweeper.next_line(&mut bufs).is_some() { + lines += 1; + let regular = sweeper.comparisons.borrow().len(); + let conservative = sweeper.conservative_comparisons.borrow().len(); + assert!( + (cfg!(feature = "slow-asserts") || regular <= max) && conservative <= max, + "{regular} regular and {conservative} conservative stored after line {lines}" + ); + } + } + + #[test] + fn segments_starting_at_one_point_are_not_stored() { + // Storing every pair of the 400 edges that start at the apex gives 79,800 entries. + let n: u32 = 200; + let path = shared_apex_triangles(n, false); + assert_stored_at_most(&path, 2 * n as usize); + + let top = crate::topology::Topology::::from_path(&path, 1e-6).unwrap(); + let contours = top.contours(|w| *w != 0); + assert_eq!(contours.contours().count(), n as usize); + let area: f64 = contours + .contours() + .map(|c| kurbo::Shape::area(&c.path).abs()) + .sum(); + assert!((area - f64::from(n) * 1500.0).abs() < 1e-3, "area {area}"); + } + + #[test] + fn segments_starting_at_one_point_sweep_as_with_stored_comparisons() { + // 40 overlapping triangles share the apex (0, 0); their bases cross the neighbors' edges. + let frac = |x: f64| x - x.floor(); + for curved in [false, true] { + let mut path = BezPath::new(); + for i in 0..40 { + let i = f64::from(i); + let left = (i * 4.0 - 6.0, 500.0 + 50.0 * frac(i * 0.618)); + let right = (i * 4.0 + 6.0, 500.0 + 50.0 * frac(i * 0.75)); + path.move_to((0.0, 0.0)); + if curved { + path.quad_to((left.0 / 2.0 - 3.0, left.1 / 2.0), left); + } else { + path.line_to(left); + } + path.line_to(right); + path.close_path(); + } + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + + let sweep = |store_first: bool| { + let sweeper = Sweeper::new(&segs, 1e-6); + if store_first { + // With every comparison of segments that start together already stored, the + // sweep uses the stored ones, as it did when it stored all of them. + for i in segs.indices() { + for j in segs.indices() { + if i.0 < j.0 && segs[i].start() == segs[j].start() { + sweeper.compare_segments(i, j); + sweeper.compare_segments_conservatively(i, j); + } + } + } + } + let mut sweeper = sweeper; + let mut outputs = Vec::new(); + let mut bufs = SweepLineBuffers::default(); + while let Some(line) = sweeper.next_line(&mut bufs) { + outputs.push(format!( + "{} {:?} {:?}", + line.y(), + line.state.line, + line.state.changed_intervals + )); + } + outputs + }; + assert_eq!(sweep(false), sweep(true), "curved: {curved}"); + } + } + + #[test] + fn curves_starting_at_one_point_are_not_stored() { + // Storing every pair of the 120 edges that start at the apex gives 7,140 entries. + let n: u32 = 60; + let path = shared_apex_triangles(n, true); + assert_stored_at_most(&path, 2 * n as usize); + + let top = crate::topology::Topology::::from_path(&path, 1e-6).unwrap(); + let contours = top.contours(|w| *w != 0); + assert_eq!(contours.contours().count(), n as usize); + } + #[test] fn empty_sweep_line() { let segs = Segments::default(); @@ -2356,6 +3357,500 @@ mod tests { assert!(sweep.next_line(&mut bufs).is_none()); } + #[test] + fn cross_height_near_f64_max() { + let (y0, y1) = (1e308, 1.5e308); + assert_eq!( + choose_cross_height(CurveInteraction::Cross(y0, y1), 0.0, WhichTouch::Mid), + Some(1.25e308) + ); + assert_eq!( + choose_cross_height(CurveInteraction::Touch(y0, y1), 0.0, WhichTouch::Late), + Some(1.25e308) + ); + } + + // Craft patch (work limit). Disjoint rectangles sharing their top and bottom + // heights need almost no comparisons. Each exit finds its segment by binary + // search, so the work counts the search's probes, and doubling the + // rectangles about doubles the work. + #[test] + fn work_limit_counts_position_searches_by_their_probes() { + use kurbo::{Rect, Shape}; + + let work = |n: u32| { + let mut path = BezPath::new(); + for i in 0..n { + let x = f64::from(i) * 3.0; + path.extend(Rect::new(x, 0.0, x + 1.0, 10.0).to_path(0.1).iter()); + } + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + + let mut bufs = SweepLineBuffers::default(); + let mut sweep = Sweeper::new(&segs, 1e-6); + while sweep.next_line(&mut bufs).is_some() {} + assert!(!sweep.work_limit_exceeded()); + let total = sweep.work(); + + let mut sweep = Sweeper::new(&segs, 1e-6); + sweep.set_work_limit(total / 2); + while sweep.next_line(&mut bufs).is_some() {} + assert!(sweep.work_limit_exceeded()); + total + }; + // `slow-asserts` checks all pairs after each insertion. + let small_n = if cfg!(feature = "slow-asserts") { 100 } else { 2000 }; + let large_n = 2 * small_n; + let (small, large) = (work(small_n), work(large_n)); + assert!(large < small * 5 / 2, "{small} units for {small_n} rectangles, {large} for {large_n}"); + } + + // Craft patch (work limit). The circles are stacked, so the first sweep + // lines handle every segment and compare it with all the others. + #[test] + fn work_limit_stops_within_a_sweep_line() { + use kurbo::{Circle, Shape}; + + let circle = Circle::new((100.0, 100.0), 50.0).to_path(1e-3); + let mut circles = BezPath::new(); + for _ in 0..20 { + circles.extend(circle.iter()); + } + let mut segs = Segments::default(); + segs.add_bez_path(&circles).unwrap(); + + let mut sweep = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + let mut range_bufs = SweepLineRangeBuffers::default(); + let mut most_in_a_line = 0; + let mut prev = 0; + while let Some(mut line) = sweep.next_line(&mut bufs) { + while line.next_range(&mut range_bufs, &segs).is_some() {} + let now = line.state.work(); + most_in_a_line = most_in_a_line.max(now - prev); + prev = now; + } + assert!(!sweep.work_limit_exceeded()); + + // One sweep line takes far more comparisons than the limit, so the + // sweep has to stop between the events of that line to stay near it. + let limit = 1_000; + assert!(most_in_a_line > 10 * limit, "{most_in_a_line} comparisons"); + let mut sweep = Sweeper::new(&segs, 1e-6); + sweep.set_work_limit(limit); + while let Some(mut line) = sweep.next_line(&mut bufs) { + while line.next_range(&mut range_bufs, &segs).is_some() {} + } + assert!(sweep.work_limit_exceeded()); + assert!(sweep.next_line(&mut bufs).is_none()); + let work = sweep.work(); + assert!(work <= limit + 200, "{work} comparisons"); + + // A sweep stopped partway through a line stays stopped. + sweep.set_work_limit(u64::MAX); + assert!(sweep.work_limit_exceeded()); + assert!(sweep.next_line(&mut bufs).is_none()); + } + + // Craft patch (work limit). Comparisons of segments that start at one point + // are made without storing them, and they count toward the work limit too. + #[test] + fn work_limit_counts_comparisons_of_segments_that_start_together() { + let path = shared_apex_triangles(200, false); + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + + // The first sweep line is at the apex, where all 400 edges start and + // the scans and insertion searches compare most pairs of them. + let mut sweep = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + assert!(sweep.next_line(&mut bufs).is_some()); + let comparisons = + sweep.comparisons.borrow().calls + sweep.conservative_comparisons.borrow().calls; + assert!(comparisons > 100_000, "{comparisons} comparisons"); + while sweep.next_line(&mut bufs).is_some() {} + assert!(!sweep.work_limit_exceeded()); + + // The sweep stops while the edges enter, before it checks the + // positions of the changed intervals. + let limit = 10_000; + let mut sweep = Sweeper::new(&segs, 1e-6); + sweep.set_work_limit(limit); + assert!(sweep.next_line(&mut bufs).is_none()); + assert!(sweep.work_limit_exceeded()); + assert_eq!(sweep.position_checks, 0); + let work = sweep.work(); + assert!(work <= limit + 200, "{work} units of work"); + } + + // Craft patch (work limit). Every limit below the sweep's total work stops + // it somewhere: in an event, or while finding a line's changed intervals. + // Wherever it stops, `next_line` returns no line past the limit. + #[test] + fn work_limit_returns_no_line_past_the_limit() { + use kurbo::{Circle, Shape}; + + let circle = Circle::new((100.0, 100.0), 50.0).to_path(0.1); + let mut circles = BezPath::new(); + for _ in 0..3 { + circles.extend(circle.iter()); + } + let mut segs = Segments::default(); + segs.add_bez_path(&circles).unwrap(); + + let mut bufs = SweepLineBuffers::default(); + let mut range_bufs = SweepLineRangeBuffers::default(); + let mut sweep = Sweeper::new(&segs, 1e-6); + while let Some(mut line) = sweep.next_line(&mut bufs) { + while line.next_range(&mut range_bufs, &segs).is_some() {} + } + let total = sweep.work(); + assert!(total > 100, "{total} comparisons"); + + for limit in 0..total { + let mut sweep = Sweeper::new(&segs, 1e-6); + sweep.set_work_limit(limit); + while let Some(mut line) = sweep.next_line(&mut bufs) { + let work = line.state.work(); + assert!( + work <= limit, + "limit {limit}: a line came back after {work} comparisons" + ); + while line.next_range(&mut range_bufs, &segs).is_some() {} + } + assert!(sweep.work_limit_exceeded(), "limit {limit}"); + } + } + + // Craft patch (work limit). Wide rectangles whose top and bottom edges + // cross many bars: finding the changed intervals at those heights checks + // the position of every bar for every horizontal edge, with few segment + // comparisons. Those checks count toward the work limit. + #[test] + fn work_limit_counts_the_horizontal_scans() { + use kurbo::{Rect, Shape}; + + let bars = 150; + let wide = 30; + let mut path = BezPath::new(); + for i in 0..bars { + let x = 3.0 * i as f64; + path.extend(Rect::new(x, 0.0, x + 1.0, 10.0).to_path(0.1).iter()); + } + let right = 3.0 * bars as f64; + for k in 0..wide { + let k = k as f64; + path.extend(Rect::new(-1.0 - k, 4.0, right + k, 6.0).to_path(0.1).iter()); + } + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + + let mut bufs = SweepLineBuffers::default(); + let mut range_bufs = SweepLineRangeBuffers::default(); + let mut sweep = Sweeper::new(&segs, 1e-6); + while let Some(mut line) = sweep.next_line(&mut bufs) { + while line.next_range(&mut range_bufs, &segs).is_some() {} + } + // Each of the 60 horizontal edges crosses all 300 bar edges. + let total = sweep.work(); + let crossings = 2 * wide * 2 * bars; + assert!(total >= crossings as u64, "{total} units of work"); + + let limit = total / 2; + let mut sweep = Sweeper::new(&segs, 1e-6); + sweep.set_work_limit(limit); + while let Some(mut line) = sweep.next_line(&mut bufs) { + let work = line.state.work(); + assert!(work <= limit, "a line came back after {work} units of work"); + while line.next_range(&mut range_bufs, &segs).is_some() {} + } + // It stops within two comparisons, one position check, or the n log2 n + // charged before sorting a sweep line's n horizontal segments, after the + // limit. Each of the two sweep lines with horizontals holds `wide` of them. + assert!(sweep.work_limit_exceeded()); + let work = sweep.work(); + let wide = wide as u64; + let sort_charge = wide * u64::from(wide.ilog2()); + assert!(work <= limit + sort_charge.max(2), "{work} units of work, limit {limit}"); + } + + // A tall closed band whose sides zigzag: each segment shares heights with + // only a few others. + fn zigzag_band(rows: usize) -> Segments { + let left = (0..=rows).map(|k| p((k % 2) as f64, k as f64)); + let right = (0..=rows).rev().map(|k| p(10.0 + (k % 2) as f64, k as f64)); + let mut segs = Segments::default(); + segs.add_closed_polyline(left.chain(right)); + segs + } + + // A star polygon in which every edge crosses every edge it does not share a + // vertex with. + fn star(points: usize) -> Segments { + let step = (points - 1) / 2; + let mut segs = Segments::default(); + segs.add_closed_polyline((0..points).map(|k| { + let angle = std::f64::consts::TAU * ((k * step) % points) as f64 / points as f64 + 0.1; + p(1000.0 * angle.cos(), 1000.0 * angle.sin()) + })); + segs + } + + // Two wavy closed paths of cubics that cross each other many times. + fn wavy_cubics() -> Segments { + let mut segs = Segments::default(); + for offset in [0.0, 0.7] { + let mut path = BezPath::new(); + path.move_to((offset, 0.0)); + for k in 0..40 { + let y = 4.0 * k as f64; + let x = offset + (k % 3) as f64 * 0.5; + path.curve_to( + (offset + 3.0, y + 1.0), + (offset - 3.0, y + 3.0), + (x, y + 4.0), + ); + } + path.line_to((offset + 5.0, 160.0)); + path.line_to((offset + 5.0, 0.0)); + path.close_path(); + segs.add_bez_path(&path).unwrap(); + } + segs + } + + // Runs a sweep and records every sweep line, its changed intervals and its + // output events. Also returns the largest number of pairs the comparison + // caches held after a step. + fn sweep_record(segs: &Segments, eps: f64, evict: bool) -> (Vec, usize) { + let mut record = Vec::new(); + let mut most_pairs = 0; + let mut sweeper = Sweeper::new(segs, eps); + if !evict { + sweeper.comparisons.get_mut().never_evict(); + sweeper.conservative_comparisons.get_mut().never_evict(); + } + let mut line_bufs = SweepLineBuffers::default(); + let mut range_bufs = crate::sweep::SweepLineRangeBuffers::default(); + while let Some(mut line) = sweeper.next_line(&mut line_bufs) { + record.push(format!( + "{} {:?} {:?}", + line.y(), + line.state.line, + line.state.changed_intervals + )); + while let Some(mut range) = line.next_range(&mut range_bufs, segs) { + while let Some(events) = range.events() { + record.extend(events.into_iter().map(|ev| format!("{ev:?}"))); + } + } + most_pairs = most_pairs.max( + line.state.comparisons.borrow().cached_pairs() + + line.state.conservative_comparisons.borrow().cached_pairs(), + ); + } + (record, most_pairs) + } + + #[test] + fn ended_pairs_leave_the_comparison_cache() { + let segs = zigzag_band(400); + let (_, kept) = sweep_record(&segs, 0.1, false); + let (_, evicted) = sweep_record(&segs, 0.1, true); + assert!(kept >= 400, "{kept}"); + assert!(evicted * 10 < kept, "{evicted} {kept}"); + } + + #[test] + fn evicting_comparisons_keeps_the_sweep_lines() { + for (segs, eps) in [ + (zigzag_band(400), 0.1), + (star(31), 1e-6), + (star(31), 1.0), + (wavy_cubics(), 0.01), + (wavy_cubics(), 0.25), + ] { + let (kept, _) = sweep_record(&segs, eps, false); + let (evicted, _) = sweep_record(&segs, eps, true); + assert!(kept == evicted); + } + } + + // Craft patch (removal scan): many segments ending at one height share the + // walk to the nearest live segment instead of each repeating it. + #[test] + fn removal_scans_share_the_run_of_ended_segments() { + use kurbo::Shape as _; + + let mut path = BezPath::new(); + for i in 0..200 { + let x = f64::from(i) * 3.0; + path.extend(kurbo::Rect::new(x, 0.0, x + 1.0, 10.0).to_path(0.1)); + } + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + + let mut sweep = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + while sweep.next_line(&mut bufs).is_some() {} + // Walking the 400 vertical edges for every exit is 80,000 steps. + assert!( + sweep.removal_scan_steps < 1_600, + "{} steps", + sweep.removal_scan_steps + ); + } + + // The removal scan's walk over segments that end at this y counts toward the work limit. + #[test] + fn removal_scan_counts_the_entries_it_visits() { + let segs = mk_segs(&[(0.0, 0.0), (1.0, 1.0), (2.0, 2.0), (3.0, 3.0)]); + let ids: Vec = segs.indices().collect(); + let mut sweep = Sweeper::new(&segs, 0.1); + for (pos, &seg) in ids.iter().enumerate() { + sweep.line.insert(pos, SegmentOrderEntry::new(seg, &segs, 0.1)); + } + sweep.y = 1.0; + let before = sweep.segments_passed; + sweep.scan_for_removal(ids.len(), &mut EndedRuns::default()); + assert_eq!(sweep.segments_passed - before, ids.len() as u64); + } + + // Craft patch (removal scan): two groups of segments end at y = 10, each + // beside a taller rectangle whose edges continue, and their exits arrive + // interleaved. Each group's walk is shared, and the intersection scans run + // once from each taller rectangle instead of once per exit. + #[test] + fn removal_scans_run_once_from_each_live_segment() { + use kurbo::Shape as _; + + let mut path = BezPath::new(); + for i in 0..100 { + let x = f64::from(i) * 3.0; + path.extend(kurbo::Rect::new(x, 0.0, x + 1.0, 10.0).to_path(0.1)); + path.extend(kurbo::Rect::new(x + 320.0, 0.0, x + 321.0, 10.0).to_path(0.1)); + } + path.extend(kurbo::Rect::new(-10.0, 0.0, -5.0, 20.0).to_path(0.1)); + path.extend(kurbo::Rect::new(305.0, 0.0, 310.0, 20.0).to_path(0.1)); + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + + let mut sweep = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + while sweep.next_line(&mut bufs).is_some() {} + // One scan per exit is 400 scans, and each walks a whole group. + assert!(sweep.removal_scans <= 4, "{} scans", sweep.removal_scans); + assert!( + sweep.removal_scan_steps < 1_600, + "{} steps", + sweep.removal_scan_steps + ); + } + + // At y = 1, removing a segment from a swap left a gap whose left + // neighbor ended at y = 1, so the removal scans returned at once and a's + // edge (0, 1)-(3, 3) and b's edge (3, 0)-(0, 2) became neighbors with no + // event queued for their crossing at (0.75, 1.5). + #[test] + fn removal_scan_skips_segments_that_end() { + use crate::{BinaryOp, FillRule, binary_op_with_eps, topology::Topology}; + use kurbo::Shape as _; + + fn poly(pts: &[(f64, f64)]) -> BezPath { + let mut path = BezPath::new(); + path.move_to(pts[0]); + for &q in &pts[1..] { + path.line_to(q); + } + path.close_path(); + path + } + + let a = poly(&[(3.0, 1.0), (3.0, 3.0), (0.0, 1.0)]); + let b = poly(&[(3.0, 0.0), (0.0, 2.0), (3.0, 2.0), (0.0, 0.0), (0.0, 1.0)]); + let eps = 1e-6; + + let top = Topology::from_paths_binary(&a, &b, eps).unwrap(); + let has_crossing = top.segment_indices().any(|s| { + let h = s.first_half(); + [top.point(h), top.point(h.other_half())] + .iter() + .any(|p| (p.x - 0.75).abs() < 1e-4 && (p.y - 1.5).abs() < 1e-4) + }); + assert!(has_crossing, "no output vertex at (0.75, 1.5)"); + + let out = + binary_op_with_eps(&a, &b, FillRule::NonZero, BinaryOp::Intersection, eps).unwrap(); + let area: f64 = out.contours().map(|c| c.path.area()).sum(); + assert!( + (area.abs() - 1.125).abs() < 1e-4, + "intersection area {area}" + ); + } + + // Craft patch (work limit). Overlapping horizontal segments at one height: + // the steps of the sweep line's range pass the limit, and the sweep stays + // stopped when the limit is raised afterwards. + #[test] + fn work_limit_stays_exceeded_after_a_range_passes_it() { + let n: u32 = 300; + let mut segs = Segments::default(); + for i in 0..n { + let x = f64::from(i); + segs.add_points([Point::new(x, 0.0), Point::new(2.0 * f64::from(n) + x, 0.0)]); + } + // A vertical segment gives the sweep a second line, at y = 10. + segs.add_points([Point::new(-5.0, 0.0), Point::new(-5.0, 10.0)]); + let mut bufs = SweepLineBuffers::default(); + let mut range_bufs = SweepLineRangeBuffers::default(); + + let mut sweep = Sweeper::new(&segs, 1e-6); + let line = sweep.next_line(&mut bufs).unwrap(); + let line_work = line.state.work(); + + let mut sweep = Sweeper::new(&segs, 1e-6); + sweep.set_work_limit(line_work + 10); + { + let mut line = sweep.next_line(&mut bufs).unwrap(); + let mut range = line.next_range(&mut range_bufs, &segs).unwrap(); + while !range.work_limit_exceeded() { + assert!(range.x().is_some(), "the range ended within the limit"); + range.increase_x(); + } + } + + sweep.set_work_limit(u64::MAX); + assert!(sweep.work_limit_exceeded()); + assert!(sweep.next_line(&mut bufs).is_none()); + } + + // Craft patch (work limit). Many horizontal segments at one height and no + // other segments: the sweep line stays empty, so finding the changed + // intervals checks no positions, but sorting the horizontals counts. + #[test] + fn work_limit_counts_sorting_the_horizontals() { + let count: u32 = 4096; + let mut segs = Segments::default(); + for i in 0..count { + let x = 3.0 * f64::from(i); + segs.add_points([Point::new(x, 0.0), Point::new(x + 1.0, 0.0)]); + } + + let mut bufs = SweepLineBuffers::default(); + let mut sweep = Sweeper::new(&segs, 1e-6); + while sweep.next_line(&mut bufs).is_some() {} + assert!(!sweep.work_limit_exceeded()); + let n = u64::from(count); + let total = sweep.work(); + assert!(total >= n * u64::from(n.ilog2()), "{total} units of work"); + + let mut sweep = Sweeper::new(&segs, 1e-6); + sweep.set_work_limit(total / 2); + assert!(sweep.next_line(&mut bufs).is_none()); + assert!(sweep.work_limit_exceeded()); + } + proptest! { #[test] fn perturbation_test_f64(perturbations in prop::collection::vec(perturbation(f64_perturbation(0.1)), 1..5)) { diff --git a/vendor/linesweeper/src/topology.rs b/vendor/linesweeper/src/topology.rs index 10a892733a..1a1ddf0abd 100644 --- a/vendor/linesweeper/src/topology.rs +++ b/vendor/linesweeper/src/topology.rs @@ -3,17 +3,16 @@ //! This consumes the output of the sweep-line algorithm and does things //! like winding number computations and boolean operations. -use std::collections::VecDeque; - -use kurbo::{BezPath, ParamCurve, Rect, Shape}; +use kurbo::{Affine, BezPath, ParamCurve, PathEl, Rect, Shape}; +use smallvec::SmallVec; use crate::{ - FillRule, + Error, FillRule, curve::{Order, solve_t_for_y, y_subsegment}, geom::Point, order::ComparisonCache, position::PositionedOutputSeg, - segments::{NonClosedPath, SegIdx, SegVec, Segments}, + segments::{SegIdx, SegVec, Segments}, sweep::{ Correctness, SegmentsConnectedAtX, SweepLineBuffers, SweepLineRange, SweepLineRangeBuffers, Sweeper, @@ -50,6 +49,23 @@ pub trait WindingNumber: /// What if we restrict this winding number to only look at the set with tag `tag`? fn of_tag(&self, tag: Self::Tag) -> Self; + + /// Craft patch (work limit): the units of storage this winding number holds, which + /// [`Topology::from_paths_with_limits`] counts toward its output limit. The default is 1; + /// a winding number that keeps one entry per tag returns its entry count. + fn storage_units(&self) -> usize { + 1 + } +} + +#[cfg(test)] +thread_local! { + /// The number of scan-west links that `Topology::west_boundary` has followed on this thread. + static WEST_STEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The number of path elements that `contours_for_positions` has run winding tests over + /// on this thread, to find the piece that holds a loop split off a contour walk. + static CONTAINER_TEST_ELEMENTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static OUTPUT_UNITS_BEFORE_MERGE: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Winding numbers for binary set operations. @@ -161,6 +177,52 @@ pub struct HalfSegmentWindingNumbers { pub clockwise: W, } +/// Craft patch (work limit): the output units a topology has used and the most it may use, if +/// it has a limit. Each output segment takes one unit plus the storage units of its two winding +/// numbers. +struct OutputLimit { + used: usize, + limit: Option, +} + +impl OutputLimit { + /// Takes the units of a new output segment with `windings`, or returns `false` and takes + /// nothing if they would pass the limit. Without a limit it counts nothing. + fn take(&mut self, windings: &HalfSegmentWindingNumbers) -> bool { + let Some(limit) = self.limit else { + return true; + }; + let Some(units) = 1usize + .checked_add(windings.clockwise.storage_units()) + .and_then(|units| units.checked_add(windings.counter_clockwise.storage_units())) + else { + return false; + }; + match self.used.checked_add(units) { + Some(used) if used <= limit => { + self.used = used; + true + } + _ => false, + } + } + + fn replace_winding(&mut self, before: &W, after: &W) -> bool { + let Some(limit) = self.limit else { + return true; + }; + let used = self.used.checked_sub(before.storage_units()) + .and_then(|used| used.checked_add(after.storage_units())); + match used { + Some(used) if used <= limit => { + self.used = used; + true + } + _ => false, + } + } +} + impl HalfSegmentWindingNumbers { /// A half-segment's winding numbers are trivial if they're the same on both sides. /// In this case, the segment is invisible to the topology of the sets. @@ -380,14 +442,45 @@ impl std::fmt::Debug for PointNeighbors { } } -/// Consumes sweep-line output and computes topology. -#[cfg_attr(test, derive(serde::Serialize))] -#[derive(Clone, Debug)] -pub struct Topology { - eps: f64, - correctness: Correctness, - /// The user-provided tags for each segment. - tag: SegVec, +/// The open output segments of one input segment, oldest first. +/// +/// A segment has at most three of them at a time (see `TopologyBuffers::open_segs`), +/// so they are stored inline and a segment's queue does not allocate unless +/// it holds more than three. +#[derive(Default)] +struct OpenSegs(SmallVec<[OutputSegIdx; 3]>); + +impl OpenSegs { + fn front(&self) -> Option<&OutputSegIdx> { + self.0.first() + } + + fn is_empty(&self) -> bool { + self.0.is_empty() + } + + #[cfg(test)] + fn push_front(&mut self, idx: OutputSegIdx) { + self.0.insert(0, idx); + } + + fn push_back(&mut self, idx: OutputSegIdx) { + self.0.push(idx); + } + + fn pop_front(&mut self) -> Option { + if self.0.is_empty() { + None + } else { + Some(self.0.remove(0)) + } + } +} + +/// The state that `Topology::from_segments` keeps while it sweeps, passed to +/// `Topology::process_sweep_line_range` so that each sweep-line range does not +/// allocate its own buffers. It is dropped when the sweep ends. +struct TopologyBuffers { /// For each input segment, this is the list of output segments that we've started /// recording but haven't finished with. There can be up to three of them, because /// consider a segment that passes through a sweep-line like this: @@ -405,7 +498,57 @@ pub struct Topology { /// first encounter the output segment pointing down and add an unfinished segment /// for that. Then we'll add an output segment for the horizontal line and so /// at that point there will be three unfinished output segments. - open_segs: SegVec>, + open_segs: SegVec, + /// A buffer for the half-segments that start at the current point. They are + /// collected while their output segments are created, and then added around + /// the point. + seg_buf: Vec, + connected_segs: SegmentsConnectedAtX, +} + +/// Writes the elements of `path.reverse_subpaths()` to `out`, replacing its +/// contents. +/// +/// A path made of one `MoveTo` followed by lines and curves (which is what +/// output segment paths are) is reversed into `out` directly, so a re-used +/// `out` does not allocate. Any other path goes through `reverse_subpaths`. +fn reverse_path_into(path: &BezPath, out: &mut Vec) { + out.clear(); + let els = path.elements(); + let Some((&PathEl::MoveTo(start), rest)) = els.split_first() else { + out.extend(path.reverse_subpaths()); + return; + }; + if rest + .iter() + .any(|el| matches!(el, PathEl::MoveTo(_) | PathEl::ClosePath)) + { + out.extend(path.reverse_subpaths()); + return; + } + let end = rest.last().and_then(PathEl::end_point).unwrap_or(start); + out.push(PathEl::MoveTo(end)); + for (i, el) in rest.iter().enumerate().rev() { + let end = i + .checked_sub(1) + .and_then(|j| rest[j].end_point()) + .unwrap_or(start); + out.push(match *el { + PathEl::QuadTo(c0, _) => PathEl::QuadTo(c0, end), + PathEl::CurveTo(c0, c1, _) => PathEl::CurveTo(c1, c0, end), + _ => PathEl::LineTo(end), + }); + } +} + +/// Consumes sweep-line output and computes topology. +#[cfg_attr(test, derive(serde::Serialize))] +#[derive(Clone, Debug)] +pub struct Topology { + eps: f64, + correctness: Correctness, + /// The user-provided tags for each segment. + tag: SegVec, /// Winding numbers of each segment. /// /// This is sort of logically indexed by `HalfOutputSegIdx`, because we can look at the @@ -496,13 +639,28 @@ pub struct Topology { /// In principle, this is redundant with the winding numbers. But since the winding /// numbers are generic, that information isn't available to us. positively_oriented: OutputSegVec, + // Craft patch (coincident horizontals): a run of coincident horizontal fragments gets + // at most one output segment. This marks the input segments with a fragment that got + // none and that `has_normal_contours` rejects, judged by the winding numbers on either + // side of its run. + #[cfg_attr(test, serde(skip))] + folded_abnormal: SegVec, + // Craft patch (coincident horizontals): the fragments that got no output segment, for + // the continuity check, as (input segment, number of output segments created before it, + // start point, end point, orientation). + #[cfg(feature = "slow-asserts")] + #[cfg_attr(test, serde(skip))] + folded_pieces: Vec<(SegIdx, usize, PointIdx, PointIdx, bool)>, } impl Topology { /// Construct a new topology from a collection of paths and tags. /// /// See [`WindingNumber`] about the tags are for. - pub fn from_paths<'a, Iter>(paths: Iter, eps: f64) -> Result + /// + /// Returns an error if a path is not closed, or if a coordinate is not finite or has a + /// magnitude above [`crate::MAX_COORDINATE`]. + pub fn from_paths<'a, Iter>(paths: Iter, eps: f64) -> Result where Iter: IntoIterator, { @@ -512,13 +670,23 @@ impl Topology { /// Construct a new topology from a collection of paths and tags. /// /// See [`WindingNumber`] about the tags are for. - pub fn from_paths_with_correctness<'a, Iter>(paths: Iter, eps: f64, correctness: Correctness) -> Result + /// + /// Returns an error if a path is not closed, or if a coordinate is not finite or has a + /// magnitude above [`crate::MAX_COORDINATE`]. + /// + /// An `eps` that is NaN, infinite, not positive, or below `64 * f64::EPSILON` + /// times the paths' largest coordinate magnitude is replaced by that value. The + /// other constructors pass `eps` through here, or follow the same rule. None of + /// them returns an error for an invalid `eps`; [`crate::binary_op_with_eps`] + /// returns [`crate::Error::InvalidEps`] for one instead. + pub fn from_paths_with_correctness<'a, Iter>(paths: Iter, eps: f64, correctness: Correctness) -> Result where Iter: IntoIterator, { let mut segments = Segments::default(); let mut tag = Vec::new(); for (p, t) in paths { + crate::check_coordinates(p)?; segments.add_path_without_updating_enter_exit(p, true)?; tag.resize(segments.len(), t); } @@ -529,37 +697,167 @@ impl Topology { SegVec::from_vec(tag), eps, correctness, - )) + None, + ) + .expect("a sweep without a work limit always finishes")) } + /// Construct a new topology from a collection of paths and tags, doing at most + /// `work_limit` units of sweep work. + /// + /// This is [`Topology::from_paths`], except that it returns + /// [`Error::WorkLimitExceeded`](crate::Error::WorkLimitExceeded) once the sweep has done + /// more than `work_limit` units, counted as in + /// [`Sweeper::set_work_limit`](crate::sweep::Sweeper::set_work_limit): segment comparisons, + /// segment position checks, and the segments that linear searches pass or binary searches probe. Stacked copies of a shape and nearly coincident segments + /// can need billions of comparisons, and the limit bounds the time a caller waits. + pub fn from_paths_with_work_limit<'a, Iter>( + paths: Iter, + eps: f64, + work_limit: u64, + ) -> Result + where + Iter: IntoIterator, + { + Self::from_paths_with_optional_limits(paths, eps, work_limit, None) + } + + /// [`Topology::from_paths_with_work_limit`], which also returns + /// [`Error::WorkLimitExceeded`](crate::Error::WorkLimitExceeded) before the topology's + /// output passes `output_limit` units. + /// + /// Each output segment counts as one unit plus the + /// [`WindingNumber::storage_units`] of its two winding numbers, so this limit bounds the + /// memory the output segments and their winding numbers use. The points the sweep + /// records are not counted; the work limit bounds them. + pub fn from_paths_with_limits<'a, Iter>( + paths: Iter, + eps: f64, + work_limit: u64, + output_limit: usize, + ) -> Result + where + Iter: IntoIterator, + { + Self::from_paths_with_optional_limits(paths, eps, work_limit, Some(output_limit)) + } + + /// Builds a bounded topology with [`crate::binary_op`]'s automatic accuracy and + /// feature-size check. The accuracy check and sweep use the same prepared segments. + pub fn from_paths_with_automatic_limits<'a, Iter>( + paths: Iter, + work_limit: u64, + output_limit: usize, + ) -> Result + where + Iter: IntoIterator, + { + Self::from_paths_with_automatic_accuracy(paths, Some((work_limit, Some(output_limit)))) + } + + pub(crate) fn from_paths_with_automatic_accuracy<'a, Iter>( + paths: Iter, + limits: Option<(u64, Option)>, + ) -> Result + where + Iter: IntoIterator, + { + let paths: Vec<_> = paths.into_iter().collect(); + let inputs: Vec<_> = paths.iter().map(|&(path, _)| path).collect(); + let eps = crate::automatic_accuracy(&inputs)?; + let (mut segments, tags) = Self::prepare_paths(paths.iter().copied())?; + segments.update_enter_exit(0); + segments.check_invariants(); + Self::from_segments(segments, tags, eps, Correctness::GoodEnough, limits) + } + + fn prepare_paths<'a, Iter>(paths: Iter) -> Result<(Segments, SegVec), Error> + where + Iter: IntoIterator, + { + let mut segments = Segments::default(); + let mut tags = Vec::new(); + for (path, tag) in paths { + crate::check_coordinates(path)?; + segments.add_path_without_updating_enter_exit(path, true)?; + tags.resize(segments.len(), tag); + } + Ok((segments, SegVec::from_vec(tags))) + } + + /// Builds the topology with a work limit and, if given, an output limit in units. + fn from_paths_with_optional_limits<'a, Iter>( + paths: Iter, + eps: f64, + work_limit: u64, + output_limit: Option, + ) -> Result + where + Iter: IntoIterator, + { + let (mut segments, tag) = Self::prepare_paths(paths)?; + segments.update_enter_exit(0); + segments.check_invariants(); + Self::from_segments( + segments, + tag, + eps, + Correctness::GoodEnough, + Some((work_limit, output_limit)), + ) + } + + /// Returns [`crate::Error::WorkLimitExceeded`] if `limits` is given and the sweep does + /// more work than its first value, or its second value is given and the topology's output + /// would pass it in units. fn from_segments( segments: Segments, tag: SegVec, eps: f64, correctness: Correctness, - ) -> Self { + limits: Option<(u64, Option)>, + ) -> Result { + let eps = segments.usable_eps(eps); + // Craft patch (work limit): each output segment takes at least one + // unit of an output limit, so the preallocation stays within it. + let cap = match limits { + Some((_, Some(output_limit))) => segments.len().min(output_limit), + _ => segments.len(), + }; let mut ret = Self { eps, correctness, tag, - open_segs: SegVec::with_size(segments.len()), // We have at least as many output segments as input segments, so preallocate enough for them. - winding: OutputSegVec::with_capacity(segments.len()), - points: PointVec::with_capacity(segments.len()), - point_idx: HalfOutputSegVec::with_capacity(segments.len()), - point_neighbors: HalfOutputSegVec::with_capacity(segments.len()), - deleted: OutputSegVec::with_capacity(segments.len()), - scan_west: OutputSegVec::with_capacity(segments.len()), - scan_east: OutputSegVec::with_capacity(segments.len()), + winding: OutputSegVec::with_capacity(cap), + points: PointVec::with_capacity(cap), + point_idx: HalfOutputSegVec::with_capacity(cap), + point_neighbors: HalfOutputSegVec::with_capacity(cap), + deleted: OutputSegVec::with_capacity(cap), + scan_west: OutputSegVec::with_capacity(cap), + scan_east: OutputSegVec::with_capacity(cap), scan_after: Vec::new(), - orig_seg: OutputSegVec::with_capacity(segments.len()), - positively_oriented: OutputSegVec::with_capacity(segments.len()), + orig_seg: OutputSegVec::with_capacity(cap), + positively_oriented: OutputSegVec::with_capacity(cap), segments: Segments::default(), + folded_abnormal: SegVec::with_size(segments.len()), + #[cfg(feature = "slow-asserts")] + folded_pieces: Vec::new(), }; let mut sweep_state = Sweeper::new_with_correctness(&segments, eps, correctness); + let mut output = OutputLimit { used: 0, limit: None }; + if let Some((work_limit, output_limit)) = limits { + sweep_state.set_work_limit(work_limit); + output.limit = output_limit; + } let mut range_bufs = SweepLineRangeBuffers::default(); let mut line_bufs = SweepLineBuffers::default(); + let mut topo_bufs = TopologyBuffers { + open_segs: SegVec::with_size(segments.len()), + seg_buf: Vec::new(), + connected_segs: SegmentsConnectedAtX::default(), + }; while let Some(mut line) = sweep_state.next_line(&mut line_bufs) { while let Some(positions) = line.next_range(&mut range_bufs, &segments) { let range = positions.seg_range(); @@ -567,23 +865,32 @@ impl Topology { None } else { let prev_seg = positions.line().line_segment(range.segs.start - 1).unwrap(); - debug_assert!(!ret.open_segs[prev_seg].is_empty()); - ret.open_segs[prev_seg].front().copied() + debug_assert!(!topo_bufs.open_segs[prev_seg].is_empty()); + topo_bufs.open_segs[prev_seg].front().copied() }; - ret.process_sweep_line_range(positions, &segments, scan_west_seg); + if !ret.process_sweep_line_range(positions, &segments, scan_west_seg, &mut topo_bufs, &mut output) { + return Err(crate::Error::WorkLimitExceeded); + } } } + if sweep_state.work_limit_exceeded() { + return Err(crate::Error::WorkLimitExceeded); + } ret.segments = segments; #[cfg(feature = "slow-asserts")] ret.check_invariants(); - ret.merge_coincident(); + #[cfg(test)] + OUTPUT_UNITS_BEFORE_MERGE.with(|count| count.set(output.used)); + if !ret.merge_coincident(&mut output) { + return Err(crate::Error::WorkLimitExceeded); + } #[cfg(feature = "slow-asserts")] ret.check_invariants(); - ret + Ok(ret) } /// We're working on building up a list of half-segments that all meet at a point. @@ -668,12 +975,12 @@ impl Topology { /// so how do we know which one is ready for its second half? The short /// answer is that we use a double-ended queue, and see `new_half_seg` /// for how we use it. - fn second_half_segs<'a, 'slf: 'a>( - &'slf mut self, + fn second_half_segs<'a>( + open_segs: &'a mut SegVec, segs: impl Iterator + 'a, ) -> impl Iterator + 'a { segs.map(|s| { - self.open_segs[s] + open_segs[s] .pop_front() .expect("should be open") .second_half() @@ -688,12 +995,16 @@ impl Topology { /// horizontal segments will be closed first, followed by segments coming /// from an earlier sweep-line, followed by segments extending down from /// this sweep-line (which won't be closed until we move on to the next - /// sweep-line). Therefore, we push horizontal half-segments to the front - /// of the queue so that they can be taken next. We push non-horizontal - /// half-segments to the back of the queue, so that the older ones (coming - /// from the previous sweep-line) will get taken before the new ones. + /// sweep-line). We push non-horizontal half-segments to the back of the + /// queue, so that the older ones (coming from the previous sweep-line) will + /// get taken before the new ones. + /// + /// Craft patch (coincident horizontals): horizontal half-segments are not + /// queued here. `process_sweep_line_range` keeps them in its own list and + /// closes them at the next point. fn new_half_seg( &mut self, + open_segs: &mut SegVec, idx: SegIdx, p: PointIdx, winding: HalfSegmentWindingNumbers, @@ -701,10 +1012,8 @@ impl Topology { positively_oriented: bool, ) -> OutputSegIdx { let out_idx = OutputSegIdx(self.winding.inner.len()); - if horizontal { - self.open_segs[idx].push_front(out_idx); - } else { - self.open_segs[idx].push_back(out_idx); + if !horizontal { + open_segs[idx].push_back(out_idx); } self.point_idx.start.push(p); self.point_idx @@ -727,26 +1036,66 @@ impl Topology { out_idx } + /// Craft patch (coincident horizontals): records the horizontal fragments of a run + /// that start at `p` and get no output segment, as (input segment, orientation). + /// `before` and `after` are the winding numbers on either side of the run. + fn note_folded(&mut self, folded: &[(SegIdx, bool)], before: &W, after: &W, p: PointIdx) { + for &(seg, positively_oriented) in folded { + // The winding number to the right of the fragment, as `has_normal_contours` + // reads it from an output segment. + let right = if positively_oriented { before } else { after }; + let tag = self.tag[seg]; + if !self.folded_abnormal[seg] && right.of_tag(tag) != W::single(tag, true) { + self.folded_abnormal[seg] = true; + } + #[cfg(feature = "slow-asserts")] + self.folded_pieces.push(( + seg, + self.winding.inner.len(), + p, + PointIdx(usize::MAX), + positively_oriented, + )); + } + #[cfg(not(feature = "slow-asserts"))] + let _ = p; + } + + /// Craft patch (work limit): returns `false`, leaving the topology + /// incomplete, if the sweep passes its work limit while visiting the + /// horizontal segments of this range, or a new output segment would take + /// the output past `output`'s limit. fn process_sweep_line_range( &mut self, mut pos: SweepLineRange, segments: &Segments, mut scan_west: Option, - ) { + bufs: &mut TopologyBuffers, + output: &mut OutputLimit, + ) -> bool { let y = pos.line().y(); let mut winding = scan_west .map(|idx| self.winding[idx].counter_clockwise.clone()) .unwrap_or_default(); - // A re-usable buffer for holding temporary lists of segment indices. We - // need to collect the output of second_half_segments because it holds - // a &mut self reference. - let mut seg_buf = Vec::new(); - let mut connected_segs = SegmentsConnectedAtX::default(); + let TopologyBuffers { + open_segs, + seg_buf, + connected_segs, + } = bufs; // The last segment we saw that points down from this sweep line. let mut last_connected_down_seg: Option = None; + // Craft patch (coincident horizontals): the horizontal output segments started at + // the previous point, which the next point closes. + let mut open_horizontals: Vec = Vec::new(); + // Craft patch (coincident horizontals): the fragments of the current run that get + // no output segment. + let mut folded: Vec<(SegIdx, bool)> = Vec::new(); while let Some(next_x) = pos.x() { + if pos.work_limit_exceeded() { + return false; + } let p = PointIdx(self.points.inner.len()); self.points.inner.push(Point::new(next_x, y)); // The first segment at our current point, in clockwise order. @@ -755,16 +1104,23 @@ impl Topology { let mut last_seg = None; // Close off the horizontal segments from the previous point in this sweep-line. - let hsegs = pos.active_horizontals(); seg_buf.clear(); - seg_buf.extend(self.second_half_segs(hsegs)); + seg_buf.extend(open_horizontals.drain(..).map(OutputSegIdx::second_half)); self.add_segs_clockwise(&mut first_seg, &mut last_seg, seg_buf.iter().copied(), p); + #[cfg(feature = "slow-asserts")] + for piece in self + .folded_pieces + .iter_mut() + .rev() + .take_while(|piece| piece.3 == PointIdx(usize::MAX)) + { + piece.3 = p; + } // Find all the segments that are connected to something above this sweep-line at next_x. - pos.update_segments_at_x(&mut connected_segs); - seg_buf.clear(); - seg_buf.extend(self.second_half_segs(connected_segs.connected_up())); - self.add_segs_clockwise(&mut first_seg, &mut last_seg, seg_buf.iter().copied(), p); + pos.update_segments_at_x(connected_segs); + let closed = Self::second_half_segs(open_segs, connected_segs.connected_up()); + self.add_segs_clockwise(&mut first_seg, &mut last_seg, closed, p); // Then: gather the output segments from half-segments starting here and moving // to later sweep-lines. Allocate new output segments for them. @@ -778,7 +1134,11 @@ impl Topology { clockwise: prev_winding, counter_clockwise: winding.clone(), }; - let half_seg = self.new_half_seg(new_seg, p, windings, false, orientation); + if !output.take(&windings) { + return false; + } + let half_seg = + self.new_half_seg(open_segs, new_seg, p, windings, false, orientation); self.scan_west[half_seg] = scan_west; scan_west = Some(half_seg); seg_buf.push(half_seg.first_half()); @@ -795,27 +1155,65 @@ impl Topology { // Bump the current x position, which will get rid of horizontals ending here // and add any horizontals starting here. pos.increase_x(); + if pos.work_limit_exceeded() { + return false; + } // Gather the output segments from horizontal segments starting // here. Allocate new output segments for them and calculate their // winding numbers. - let hsegs = pos.active_horizontals_and_orientations(); + let mut hsegs = pos.active_horizontals_and_orientations().peekable(); + if hsegs.peek().is_none() { + // No horizontal segment starts here, so there is nothing more to + // add at this point. + continue; + } // We don't want to update our "global" winding number state because that's supposed // to keep track of the winding number below the current sweep line. let mut w = winding.clone(); seg_buf.clear(); + // Craft patch (coincident horizontals): every active horizontal runs from this + // point to the next one, so they are all coincident, and `merge_coincident` + // would merge their output segments. Instead of allocating an output segment per + // fragment, this allocates one per run of fragments: the run's first fragment, + // with the winding numbers before and after the run. When a run's winding + // numbers cancel, it gets no output segment and the next fragment starts a new + // run. + let mut run: Option<(SegIdx, bool, W)> = None; for (new_seg, same_orientation) in hsegs { let prev_w = w.clone(); let orientation = same_orientation == segments.positively_oriented(new_seg); w += W::single(self.tag[new_seg], !orientation); + match &run { + None => run = Some((new_seg, orientation, prev_w)), + Some((first, first_orientation, start)) => { + // This fragment gets no output segment of its own. + folded.push((new_seg, orientation)); + if *start == w { + // The run cancels, so its first fragment gets none either. + folded.push((*first, *first_orientation)); + self.note_folded(&folded, &w, &w, p); + folded.clear(); + run = None; + } + } + } + } + if let Some((first, orientation, start)) = run { + self.note_folded(&folded, &start, &w, p); + folded.clear(); let windings = HalfSegmentWindingNumbers { counter_clockwise: w.clone(), - clockwise: prev_w, + clockwise: start, }; - let half_seg = self.new_half_seg(new_seg, p, windings, true, orientation); + if !output.take(&windings) { + return false; + } + let half_seg = self.new_half_seg(open_segs, first, p, windings, true, orientation); self.scan_west[half_seg] = scan_west; seg_buf.push(half_seg.first_half()); + open_horizontals.push(half_seg); } self.add_segs_counter_clockwise( &mut first_seg, @@ -829,7 +1227,7 @@ impl Topology { && let Some(east_nbr) = pos.line().line_entry(pos.seg_range().segs.end) && !east_nbr.is_in_changed_interval() { - self.scan_east[seg] = self.open_segs[east_nbr.seg].front().copied() + self.scan_east[seg] = open_segs[east_nbr.seg].front().copied() } // If something was connected up but nothing was connected down, let's remember that @@ -841,12 +1239,13 @@ impl Topology { .checked_sub(1) .and_then(|idx| pos.line().line_segment(idx)); let east_nbr = pos.line().line_segment(pos.seg_range().segs.end); - let west = west_nbr.map(|idx| *self.open_segs[idx].front().unwrap()); - let east = east_nbr.map(|idx| *self.open_segs[idx].front().unwrap()); + let west = west_nbr.map(|idx| *open_segs[idx].front().unwrap()); + let east = east_nbr.map(|idx| *open_segs[idx].front().unwrap()); if west.is_some() || east.is_some() { self.scan_after.push((y, west, east)); } } + true } fn delete_half(&mut self, half_seg: HalfOutputSegIdx) { @@ -875,7 +1274,10 @@ impl Topology { /// makes it a little bit tricky is that (except for horizontal segments) /// we don't know whether two segments are coincident until we've processed /// their second endpoint. - fn merge_coincident(&mut self) { + fn merge_coincident(&mut self, output: &mut OutputLimit) -> bool { + // `scan_west` stays as built, because `build_scan_line_orders` reads it. This copy + // is pointed past deleted segments as the loop finds them. + let mut live_west = self.scan_west.clone(); for idx in 0..self.winding.inner.len() { let idx = OutputSegIdx(idx); if self.deleted[idx] { @@ -896,7 +1298,11 @@ impl Topology { // b and c aren't. Then merging a and d would be bad -- even if they're clockwise // neighbors by going around the way that avoids b and c -- because it would mess up // the winding numbers of b and c. - if y0 != y1 && self.scan_west[idx] != Some(cw_nbr.idx) { + // + // An earlier merge may have deleted the west neighbor, so skip deleted segments + // to reach the nearest live one. + let west = Self::nearest_live_west(&mut live_west, &self.deleted, idx); + if y0 != y1 && west != Some(cw_nbr.idx) { continue; } if y0 != y1 { @@ -916,6 +1322,12 @@ impl Topology { // All output segments are in sweep line order, so if they're // coincident then they'd better both be first halves. debug_assert!(cw_nbr.first_half); + if !output.replace_winding( + &self.winding[cw_nbr.idx].counter_clockwise, + &self.winding[idx].counter_clockwise, + ) { + return false; + } self.delete(idx); self.winding[cw_nbr.idx].counter_clockwise = self.winding[idx].counter_clockwise.clone(); @@ -925,6 +1337,35 @@ impl Topology { } } } + true + } + + /// Returns the nearest segment west of `seg` that is not deleted, following + /// `live_west` past deleted segments, and points every segment passed on the way + /// at the result. + /// + /// Deleted segments stay deleted, so a shortened link still skips only deleted + /// segments. If the result is deleted later, the next call continues from it. + fn nearest_live_west( + live_west: &mut OutputSegVec>, + deleted: &OutputSegVec, + seg: OutputSegIdx, + ) -> Option { + let mut west = live_west[seg]; + while let Some(w) = west + && deleted[w] + { + west = live_west[w]; + } + let mut cur = live_west[seg]; + while let Some(w) = cur + && deleted[w] + { + cur = live_west[w]; + live_west[w] = west; + } + live_west[seg] = west; + west } /// Iterates over indices of all output segments. @@ -972,17 +1413,20 @@ impl Topology { /// of [`Topology::contours`] because there are approximations involved. /// For example, we might return `true` even when the contours are just /// barely overlapping. + /// + /// Craft patch (coincident horizontals): coincident horizontal pieces that run + /// between the same two points share one output segment, so this sees the winding + /// numbers on either side of all of them and not the ones between them. pub fn is_disjoint_tags( &self, inside1: impl Fn(&W) -> bool, inside2: impl Fn(&W) -> bool, ) -> bool { - self.winding.indices().all(|out_idx| { + self.segment_indices().all(|out_idx| { let w = &self.winding[out_idx]; let touches1 = inside1(&w.clockwise) || inside1(&w.counter_clockwise); let touches2 = inside2(&w.clockwise) || inside2(&w.counter_clockwise); - dbg!(touches1, touches2); !(touches1 && touches2) }) } @@ -1047,7 +1491,19 @@ impl Topology { /// `true`, you can decide that the intersection is just `a`. This isn't /// a hard guarantee that `Topology::contours` will return `a` exactly: /// it probably won't, because of perturbations and ordering changes. + /// + /// Craft patch (coincident horizontals): coincident horizontal pieces that run + /// between the same two points share at most one output segment. This checks each + /// of those pieces with the winding numbers on either side of all of them, not the + /// ones between them. pub fn has_normal_contours(&self, tag: W::Tag) -> bool { + if self + .folded_abnormal + .iter() + .any(|(seg, &abnormal)| abnormal && self.tag[seg] == tag) + { + return false; + } self.out_segments_of(tag).all(|out_idx| { let w = &self.winding[out_idx]; @@ -1074,29 +1530,30 @@ impl Topology { segs: &[HalfOutputSegIdx], positions: &OutputSegVec, ) -> BezPath { - let mut ret = BezPath::default(); + let mut ret = BezPath::with_capacity(segs.len() + 2); let mut unfinished: Option = None; + // A re-usable buffer for the reversed paths of first halves. + let mut rev_buf: Vec = Vec::new(); - // Find a segment that can't be merged into the previous one. + // Find a segment that can't be merged into the previous one. If every segment can be + // merged, start at the first one. let start_idx = segs .iter() .position(|s| self.can_merge(s.other_half(), positions).is_none()) - .unwrap(); + .unwrap_or(0); ret.move_to(self.point(segs[start_idx].other_half()).to_kurbo()); for seg in segs[start_idx..].iter().chain(&segs[..start_idx]) { let path = &positions[seg.idx]; - // TODO: avoid the allocation in reverse_subpaths - let rev_path; - let oriented_path = if seg.is_first_half() { - rev_path = path.path.reverse_subpaths(); - &rev_path + let oriented_path: &[PathEl] = if seg.is_first_half() { + reverse_path_into(&path.path, &mut rev_buf); + &rev_buf } else { - &path.path + path.path.elements() }; // skip(1) leaves off the initial MoveTo, which is unnecessary // because this path starts where the last one ended. - let mut elems = oriented_path.iter().skip(1); + let mut elems = oriented_path.iter().copied().skip(1); if let (Some(our_t), Some(unfinished_t)) = (self.can_merge(seg.other_half(), positions), unfinished) { @@ -1214,6 +1671,11 @@ impl Topology { return None; } + // Only a simple point can merge, so skip solving for `t` anywhere else. + if !self.is_simple_point(seg) { + return None; + } + let extremal_seg_is_copied = if seg.is_first_half() { pos.copied_idx == Some(0) } else { @@ -1256,7 +1718,16 @@ impl Topology { None } }; - if self.is_simple_point(seg) { + // The neighbor must be the adjacent piece of the same input element. After coincident + // segments are deleted, pieces of two different input elements can meet at a simple + // point, and their parameters cannot be combined. + let nbr = self.point_neighbors[seg].clockwise; + let expected = if has_orig_orientation { + self.segments.contour_prev(orig_idx) + } else { + self.segments.contour_next(orig_idx) + }; + if self.is_simple_point(seg) && nbr != seg && Some(self.orig_seg[nbr.idx]) == expected { can_merge } else { None @@ -1274,22 +1745,86 @@ impl Topology { ret.clamp(0.0, 1.0) } + /// Returns the nearest segment on `idx`'s scan-west chain (not counting `idx` itself) + /// for which `is_bdy` returns true. + /// + /// `memo[i]` holds the answer for segment `i` once it is known. Every segment passed + /// over on the way gets the same answer, so a chain shared by several starting segments + /// is walked only once. `stack` is scratch space. + fn west_boundary( + &self, + idx: OutputSegIdx, + is_bdy: &mut impl FnMut(OutputSegIdx) -> bool, + memo: &mut [Option>], + stack: &mut Vec, + ) -> Option { + stack.clear(); + let mut cur = idx; + let found = loop { + if let Some(known) = memo[cur.0] { + break known; + } + #[cfg(test)] + WEST_STEPS.with(|n| n.set(n.get() + 1)); + match self.scan_west[cur] { + None => break None, + Some(left) if is_bdy(left) => break Some(left), + Some(left) => { + stack.push(cur); + cur = left; + } + } + }; + memo[cur.0] = Some(found); + for seg in stack.drain(..) { + memo[seg.0] = Some(found); + } + found + } + /// Returns the contours of some set defined by this topology. /// /// The callback function `inside` takes a winding number and returns `true` /// if a point with that winding number should be in the resulting set. For example, /// to compute a boolean "and" using the non-zero winding rule, `inside` should be /// `|w| w.shape_a != 0 && w.shape_b != 0`. + /// + /// When the winding numbers disagree around a point, this returns no + /// contours. [`Topology::try_contours`] reports that case as an error. pub fn contours(&self, inside: impl Fn(&W) -> bool) -> Contours { - let positions = self.compute_positions(); + self.try_contours(inside).unwrap_or_default() + } + + /// Returns the contours of some set defined by this topology, as + /// [`Topology::contours`] does, or [`Error::InconsistentWindingNumbers`] + /// when the winding numbers disagree around a point. + pub fn try_contours(&self, inside: impl Fn(&W) -> bool) -> Result { + let positions = self.contour_positions(&inside); self.contours_for_positions(inside, positions) } + /// Computes paths for the output segments that [`Topology::contours`] reads. + /// + /// With [`Correctness::GoodEnough`], only the segments on the boundary of + /// the set that `inside` defines get a path; the others keep an empty one. + /// With [`Correctness::ReallyCorrect`], every segment gets a path, because + /// the perturbation of one segment depends on its neighbors. + fn contour_positions(&self, inside: &impl Fn(&W) -> bool) -> OutputSegVec { + match self.correctness { + Correctness::GoodEnough => self.compute_positions_good_enough_where(|idx| { + !self.deleted[idx] + && inside(&self.winding[idx].clockwise) + != inside(&self.winding[idx].counter_clockwise) + }), + Correctness::ReallyCorrect => self.compute_positions_correct(), + } + } + fn contours_for_positions( &self, inside: impl Fn(&W) -> bool, positions: OutputSegVec, - ) -> Contours { + ) -> Result { // We walk contours in sweep-line order of their smallest point. This mostly ensures // that we visit outer contours before we visit their children. However, when the inner // and outer contours share a point, we run into a problem. For example: @@ -1321,6 +1856,16 @@ impl Topology { let bdy = |idx: OutputSegIdx| -> bool { inside(&self.winding[idx].clockwise) != inside(&self.winding[idx].counter_clockwise) }; + // Whether a segment is a live boundary segment, tested the first time it is asked + // for, and a memo of the nearest one on each segment's scan-west chain, so that each + // link of a chain is followed at most once per call instead of once per contour that + // starts east of it. + let mut bdy_memo: Vec> = vec![None; self.winding.inner.len()]; + let mut is_bdy = |idx: OutputSegIdx| -> bool { + *bdy_memo[idx.0].get_or_insert_with(|| !self.deleted[idx] && bdy(idx)) + }; + let mut west_bdy: Vec>> = vec![None; self.winding.inner.len()]; + let mut west_stack = Vec::new(); let mut visited = vec![false; self.winding.inner.len()]; // Keep track of the points that were visited on this walk, so that if we re-visit a @@ -1332,7 +1877,7 @@ impl Topology { continue; } - if !bdy(idx) { + if !is_bdy(idx) { continue; } @@ -1340,14 +1885,7 @@ impl Topology { // are relative to existing contours. let contour_idx = ContourIdx(ret.contours.len()); let mut contour = Contour::default(); - let mut west_seg = self.scan_west[idx]; - while let Some(left) = west_seg { - if self.deleted[left] || !bdy(left) { - west_seg = self.scan_west[left]; - } else { - break; - } - } + let west_seg = self.west_boundary(idx, &mut is_bdy, &mut west_bdy, &mut west_stack); if let Some(west) = west_seg { if let Some(west_contour) = seg_contour[west.0] { // Is the thing just to our west inside or outside the output set? @@ -1358,7 +1896,9 @@ impl Topology { // That means they're our sibling. contour.parent = ret.contours[west_contour.0].parent; contour.outer = outside; - debug_assert!(outside || contour.parent.is_some()); + if !outside && contour.parent.is_none() { + return Err(Error::InconsistentWindingNumbers); + } } else { // They're an outer contour, and there's interior between us and them, // or they're an inner contour and there's exterior between us. @@ -1367,7 +1907,8 @@ impl Topology { contour.outer = !ret.contours[west_contour.0].outer; } } else { - panic!("I'm {idx:?}, west is {west:?}. Y u no have contour?"); + // The boundary segment to our west has no contour yet. + return Err(Error::InconsistentWindingNumbers); } }; // Reserve a space for the unfinished outer contour, as described above. @@ -1384,27 +1925,43 @@ impl Topology { // "endpoint" here means "as we walk the contour;" it could be either a first_half // or a second_half as far as `HalfOutputSegIdx` is concerned. let mut segs = Vec::new(); + // The loops split off the walk at repeated points. + let mut loops: Vec> = Vec::new(); last_visit[self.point_idx[start]] = Some(0); debug_assert!(inside(self.winding_clockwise(start))); loop { visited[next.idx.0] = true; - debug_assert!(inside(self.winding_counter_clockwise(next))); - debug_assert!(!inside(self.winding_clockwise(next))); + if !inside(self.winding_counter_clockwise(next)) + || inside(self.winding_clockwise(next)) + { + return Err(Error::InconsistentWindingNumbers); + } // Walk counter-clockwise around the point until we find the next segment // that's on the boundary. let mut nbr = self.point_neighbors[next].counter_clockwise; - debug_assert!(inside(self.winding_clockwise(nbr))); + if !inside(self.winding_clockwise(nbr)) { + return Err(Error::InconsistentWindingNumbers); + } + let first_nbr = nbr; while inside(self.winding_counter_clockwise(nbr)) { nbr = self.point_neighbors[nbr].counter_clockwise; + if nbr == first_nbr { + // No boundary segment leaves this point. + return Err(Error::InconsistentWindingNumbers); + } } segs.push(next); if nbr == start { break; } + if visited[nbr.idx.0] { + // The walk re-entered a segment it already walked. + return Err(Error::InconsistentWindingNumbers); + } let p = self.point_idx[nbr]; let last_visit_idx = last_visit[p] @@ -1422,15 +1979,7 @@ impl Topology { // seg_idx should point to the end of a segment whose start is at p. debug_assert_eq!(self.point_idx[segs[seg_idx].other_half()], p); - let loop_contour_idx = ContourIdx(ret.contours.len()); - for &seg in &segs[seg_idx..] { - seg_contour[seg.idx.0] = Some(loop_contour_idx); - } - ret.contours.push(Contour { - path: self.segs_to_path(&segs[seg_idx..], &positions), - parent: Some(contour_idx), - outer: !ret.contours[contour_idx.0].outer, - }); + loops.push(segs[seg_idx..].to_vec()); segs.truncate(seg_idx); // In principle, we should also be unsetting `last_visit` // for all points in the contour we just removed. I *think* @@ -1443,17 +1992,137 @@ impl Topology { next = nbr.other_half(); } - for &seg in &segs { - seg_contour[seg.idx.0] = Some(contour_idx); + if loops.is_empty() { + for &seg in &segs { + seg_contour[seg.idx.0] = Some(contour_idx); + } + ret.contours[contour_idx.0].path = self.segs_to_path(&segs, &positions); + continue; + } + + // The walk split into pieces at repeated points. A piece that winds like the + // contour being walked (clockwise when it is outer) is a sibling of it, as when + // two holes touch at a point. A piece that winds the other way is a child of the + // same-kind piece that contains it, as when a hole touches its outer contour. The + // first same-kind piece takes `contour_idx`; it need not be the rest of the walk. + let walked_outer = ret.contours[contour_idx.0].outer; + let walked_parent = ret.contours[contour_idx.0].parent; + let mut pieces = loops; + pieces.insert(0, segs); + let paths: Vec = pieces + .iter() + .map(|piece| self.segs_to_path(piece, &positions)) + .collect(); + let boxes: Vec = paths.iter().map(|path| path.bounding_box()).collect(); + // The area is measured from the piece's own corner, so that large coordinates + // do not swamp its sign. + let clockwise = |path: &BezPath, bbox: &Rect| { + let mut local = path.clone(); + local.apply_affine(Affine::translate(-bbox.origin().to_vec2())); + local.area() > 0.0 + }; + let same_kind: Vec = paths + .iter() + .zip(&boxes) + .map(|(path, bbox)| clockwise(path, bbox) == walked_outer) + .collect(); + let same_kind_count = same_kind.iter().filter(|&&s| s).count(); + let keep = same_kind.iter().position(|&s| s).unwrap_or(0); + // The points of the same-kind pieces, each with the piece through it, sorted + // by point. They order the winding queries that pick a parent among several + // same-kind pieces. + let mut touching: Vec<(usize, usize)> = Vec::new(); + if same_kind[keep] && same_kind_count > 1 { + for (j, piece) in pieces.iter().enumerate().filter(|&(j, _)| same_kind[j]) { + touching.extend(piece.iter().map(|&seg| (self.point_idx[seg].0, j))); + } + touching.sort_unstable(); + touching.dedup(); + } + let mut idxs = vec![contour_idx; pieces.len()]; + for (i, idx) in idxs.iter_mut().enumerate() { + if i != keep { + *idx = ContourIdx(ret.contours.len()); + ret.contours.push(Contour::default()); + } + } + let links: Vec<(Option, bool)> = paths + .iter() + .enumerate() + .map(|(i, path)| { + if same_kind[i] || i == keep { + (walked_parent, walked_outer) + } else if !same_kind[keep] { + // No piece winds like the walked contour, so the loops stay + // children of the rest of the walk. + (Some(contour_idx), !walked_outer) + } else if same_kind_count == 1 { + // Craft patch (touching holes): `keep` is the only piece that can + // hold the loop, as for holes touching their outer contour, so no + // winding test runs. + (Some(contour_idx), !walked_outer) + } else { + // Craft patch (touching holes): a piece whose bounding box does not + // hold the probe has a winding number of 0 around it, so the winding + // test runs only for the pieces whose box holds it. + let probe = path.segments().next().map(|s| s.eval(0.5)); + let holds = |j: usize| { + probe.is_some_and(|pt| { + let b = &boxes[j]; + same_kind[j] + && b.x0 <= pt.x + && pt.x <= b.x1 + && b.y0 <= pt.y + && pt.y <= b.y1 + && { + #[cfg(test)] + CONTAINER_TEST_ELEMENTS + .with(|n| n.set(n.get() + paths[j].elements().len())); + paths[j].winding(pt) != 0 + } + }) + }; + // The same-kind pieces that share a point with this piece are + // tried first, and the others only when none of them holds it. + let touched = pieces[i].iter().flat_map(|&seg| { + let p = self.point_idx[seg].0; + let start = touching.partition_point(|&(q, _)| q < p); + touching[start..] + .iter() + .take_while(move |&&(q, _)| q == p) + .map(|&(_, j)| j) + }); + let container = touched + .chain(0..paths.len()) + .find(|&j| holds(j)) + .unwrap_or(keep); + (Some(idxs[container]), !walked_outer) + } + }) + .collect(); + for (i, (path, (parent, outer))) in paths.into_iter().zip(links).enumerate() { + for &seg in &pieces[i] { + seg_contour[seg.idx.0] = Some(idxs[i]); + } + ret.contours[idxs[i].0] = Contour { + path, + parent, + outer, + }; } - ret.contours[contour_idx.0].path = self.segs_to_path(&segs, &positions); } - ret + Ok(ret) } /// Returns a rectangle bounding all of our segments. + /// + /// With no segments, it returns `Rect::ZERO`, as kurbo does for an empty path. pub fn bounding_box(&self) -> kurbo::Rect { + // Craft patch (input rules): an empty topology has a zero rectangle. + if self.segments.segments().next().is_none() { + return Rect::ZERO; + } let mut rect = Rect::new( f64::INFINITY, f64::INFINITY, @@ -1548,12 +2217,21 @@ impl Topology { } /// Computes paths for all the output segments. - /// - /// TODO: We should allow passing in an "inside" callback and then only do - /// positioning for the segments that are on the boundary. fn compute_positions_good_enough(&self) -> OutputSegVec { + self.compute_positions_good_enough_where(|_| true) + } + + /// Computes paths for the output segments that `wanted` accepts. The other + /// segments keep an empty path. + fn compute_positions_good_enough_where( + &self, + wanted: impl Fn(OutputSegIdx) -> bool, + ) -> OutputSegVec { let mut output = OutputSegVec::with_size(self.orig_seg.len()); for idx in self.orig_seg.indices() { + if !wanted(idx) { + continue; + } let start = self.points[self.point_idx[idx.first_half()]].to_kurbo(); let end = self.points[self.point_idx[idx.second_half()]].to_kurbo(); @@ -1620,9 +2298,25 @@ impl Topology { } // Check the continuity of contours. - let mut out_segs = SegVec::>::with_size(self.segments.len()); + // Craft patch (coincident horizontals): each piece is (creation order, start point, + // end point, orientation), from an output segment or from a fragment that got none. + // The pieces start out in the order they were created, as the output segments of + // every fragment would be. + let mut out_segs = + SegVec::>::with_size(self.segments.len()); for out_seg in self.winding.indices() { - out_segs[self.orig_seg[out_seg]].push(out_seg); + out_segs[self.orig_seg[out_seg]].push(( + 2 * out_seg.0 + 1, + self.point_idx[out_seg.first_half()], + self.point_idx[out_seg.second_half()], + self.positively_oriented[out_seg], + )); + } + for &(seg, created_before, start, end, positively_oriented) in &self.folded_pieces { + out_segs[seg].push((2 * created_before, start, end, positively_oriented)); + } + for (_, out_segs) in out_segs.iter_mut() { + out_segs.sort_by_key(|piece| piece.0); } // For each segment, figure out the first and last points of its output-segment-polyline, // in that segment's natural orientation. @@ -1642,11 +2336,11 @@ impl Topology { // where there are multiple horizontal out segments on the same sweep line, we // need to sort those segments relative to one another depending on the direction // in which the input segment traverses that sweep line. - out_segs.sort_by(|&o1, &o2| { - let p11 = self.point(o1.first_half()); - let p12 = self.point(o1.second_half()); - let p21 = self.point(o2.first_half()); - let p22 = self.point(o2.second_half()); + out_segs.sort_by(|o1, o2| { + let p11 = &self.points[o1.1]; + let p12 = &self.points[o1.2]; + let p21 = &self.points[o2.1]; + let p22 = &self.points[o2.2]; let horiz1 = p11.y == p12.y; let horiz2 = p21.y == p22.y; @@ -1658,8 +2352,8 @@ impl Topology { // We can create multiple horizontal segments for a segment in the same // sweep line, but currently we don't create any backtracking: all the // horizontal segments we create have the same orientation. - debug_assert_eq!(self.positively_oriented[o1], self.positively_oriented[o2]); - if self.positively_oriented[o1] == self.segments.positively_oriented(in_seg) { + debug_assert_eq!(o1.3, o2.3); + if o1.3 == self.segments.positively_oriented(in_seg) { cmp } else { cmp.reverse() @@ -1672,13 +2366,13 @@ impl Topology { let mut first = None; let mut last = None; - for &out_seg in &*out_segs { + for &(_, start, end, positively_oriented) in &*out_segs { let same_orientation = - self.positively_oriented[out_seg] == self.segments.positively_oriented(in_seg); + positively_oriented == self.segments.positively_oriented(in_seg); let (first_endpoint, second_endpoint) = if same_orientation { - (out_seg.first_half(), out_seg.second_half()) + (start, end) } else { - (out_seg.second_half(), out_seg.first_half()) + (end, start) }; if first.is_none() { first = Some(first_endpoint); @@ -1687,7 +2381,7 @@ impl Topology { // When walking the output segments in sweep-line order, the last endpoint of // the previous one should be the first endpoint of this one. if let Some(last) = last { - assert_eq!(self.point_idx[first_endpoint], self.point_idx[last]); + assert_eq!(first_endpoint, last); } last = Some(second_endpoint); } @@ -1699,7 +2393,7 @@ impl Topology { } else { (last, first) }; - realized_endpoints.push((self.point_idx[first], self.point_idx[last])); + realized_endpoints.push((first, last)); } for seg in self.segments.indices() { @@ -1814,7 +2508,7 @@ impl Topology { impl Topology { /// Construct a new topology from a single path. - pub fn from_path(path: &BezPath, eps: f64) -> Result { + pub fn from_path(path: &BezPath, eps: f64) -> Result { Self::from_paths(std::iter::once((path, ())), eps) } } @@ -1841,17 +2535,15 @@ impl Topology { SegVec::from_vec(shape_a), eps, Correctness::GoodEnough, + None, ) + .expect("a sweep without a work limit always finishes") } /// Creates a new `Topology` from two Bézier paths. /// /// The two Bézier paths represent two different sets for the purpose of boolean set operations. - pub fn from_paths_binary( - set_a: &BezPath, - set_b: &BezPath, - eps: f64, - ) -> Result { + pub fn from_paths_binary(set_a: &BezPath, set_b: &BezPath, eps: f64) -> Result { Self::from_paths([(set_a, OneOfTwo::A), (set_b, OneOfTwo::B)], eps) } @@ -1925,7 +2617,8 @@ impl HalfScanLineOrder { } if let Some(other_seg) = other_seg { - let order = cmp.compare_segments(segs, orig_seg[seg], orig_seg[other_seg]); + let order = + cmp.compare_non_horizontal_segments(segs, orig_seg[seg], orig_seg[other_seg]); let next_ish = order .iter() .take_while(|(order_y0, _, _)| *order_y0 < y1) @@ -2204,15 +2897,16 @@ impl Contours { } let mut ret = Vec::with_capacity(top_level.len()); + let mut stack = Vec::new(); for top in top_level { let mut tree = Vec::new(); - fn visit(idx: ContourIdx, children: &[Vec], acc: &mut Vec) { - acc.push(idx); - for &child in &children[idx.0] { - visit(child, children, acc); - } + // Walk the tree in pre-order with an explicit stack, so that deeply + // nested contours do not overflow the call stack. + stack.push(top); + while let Some(idx) = stack.pop() { + tree.push(idx); + stack.extend(children[idx.0].iter().rev()); } - visit(top, &children, &mut tree); ret.push(tree); } @@ -2259,7 +2953,7 @@ impl std::ops::Index for Contours { #[cfg(test)] mod tests { - use kurbo::BezPath; + use kurbo::{BezPath, Rect, Shape}; use proptest::prelude::*; use crate::{ @@ -2271,7 +2965,10 @@ mod tests { }, }; - use super::{OneOfTwo, Topology}; + use super::{ + Affine, Contour, ContourIdx, Contours, Correctness, HalfOutputSegVec, OneOfTwo, + OutputSegIdx, OutputSegVec, Topology, + }; fn p(x: f64, y: f64) -> Point { Point::new(x, y) @@ -2279,6 +2976,107 @@ mod tests { const EMPTY: [[Point; 0]; 0] = []; + #[test] + fn reverse_path_into_matches_reverse_subpaths() { + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((1.0, 2.0)); + open.quad_to((2.0, 3.0), (3.0, 1.0)); + open.curve_to((4.0, 0.0), (5.0, 5.0), (6.0, 2.0)); + let mut only_move = BezPath::new(); + only_move.move_to((1.0, 1.0)); + let mut closed = open.clone(); + closed.close_path(); + let mut two = open.clone(); + two.move_to((10.0, 10.0)); + two.line_to((11.0, 12.0)); + + let mut buf = Vec::new(); + for path in [open, only_move, closed, two, BezPath::new()] { + super::reverse_path_into(&path, &mut buf); + assert_eq!(buf, path.reverse_subpaths().elements()); + } + } + + #[test] + fn open_segs_pop_like_a_deque() { + use super::{OpenSegs, OutputSegIdx}; + + let mut segs = OpenSegs::default(); + let mut deque = std::collections::VecDeque::new(); + let pushes = [(1, false), (2, false), (3, true), (4, false), (5, true)]; + for (i, front) in pushes { + if front { + segs.push_front(OutputSegIdx(i)); + deque.push_front(OutputSegIdx(i)); + } else { + segs.push_back(OutputSegIdx(i)); + deque.push_back(OutputSegIdx(i)); + } + assert_eq!(segs.front(), deque.front()); + } + while let Some(idx) = deque.pop_front() { + assert!(!segs.is_empty()); + assert_eq!(segs.pop_front(), Some(idx)); + } + assert!(segs.is_empty()); + assert_eq!(segs.pop_front(), None); + } + + /// The elements of the only contour of `path` under the non-zero rule. + fn only_contour_elements(path: &BezPath) -> Vec { + let top = Topology::::from_path(path, 0.01).unwrap(); + let contours = top.contours(|w| *w != 0); + let mut contours = contours.contours(); + let contour = contours.next().unwrap(); + assert!(contours.next().is_none()); + contour.path.elements().to_vec() + } + + #[test] + fn contours_keep_their_elements_and_direction() { + use kurbo::PathEl::{ClosePath, CurveTo, LineTo, MoveTo}; + + let mut notched = BezPath::new(); + notched.move_to((0.0, 0.0)); + notched.line_to((4.0, 0.0)); + notched.line_to((4.0, 4.0)); + notched.line_to((3.0, 4.0)); + notched.line_to((2.0, 2.0)); + notched.line_to((1.0, 4.0)); + notched.line_to((0.0, 4.0)); + notched.close_path(); + assert_eq!( + only_contour_elements(¬ched), + [ + MoveTo((0.0, 4.0).into()), + LineTo((0.0, 0.0).into()), + LineTo((4.0, 0.0).into()), + LineTo((4.0, 4.0).into()), + LineTo((3.0, 4.0).into()), + LineTo((2.0, 2.0).into()), + LineTo((1.0, 4.0).into()), + LineTo((0.0, 4.0).into()), + ClosePath, + ] + ); + + let mut lens = BezPath::new(); + lens.move_to((0.0, 0.0)); + lens.curve_to((2.0, 1.0), (2.0, 2.0), (0.0, 3.0)); + lens.curve_to((-2.0, 2.0), (-2.0, 1.0), (0.0, 0.0)); + lens.close_path(); + assert_eq!( + only_contour_elements(&lens), + [ + MoveTo((0.0, 3.0).into()), + CurveTo((-2.0, 2.0).into(), (-2.0, 1.0).into(), (0.0, 0.0).into()), + CurveTo((2.0, 1.0).into(), (2.0, 2.0).into(), (0.0, 3.0).into()), + ClosePath, + ] + ); + } + #[test] fn square() { let segs = [[p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 1.0)]]; @@ -2289,6 +3087,41 @@ mod tests { insta::assert_ron_snapshot!(top); } + #[test] + fn overlapping_rectangles_near_the_float_limit() { + // Two rectangles that overlap in (5, 1.1e308)-(10, 1.2e308). Their coordinates are + // above `MAX_COORDINATE`, so `Topology::from_path` returns `Error::TooLarge` instead + // of building a topology. The curve tests `compare_near_the_float_limit` and + // `solve_for_t_near_the_float_limit` cover the comparison at these heights. + let mut path = BezPath::new(); + for (x0, y0, x1, y1) in [(0.0, 1e308, 10.0, 1.2e308), (5.0, 1.1e308, 15.0, 1.3e308)] { + path.move_to((x0, y0)); + path.line_to((x1, y0)); + path.line_to((x1, y1)); + path.line_to((x0, y1)); + path.close_path(); + } + assert_eq!( + Topology::::from_path(&path, 1e-6).err(), + Some(crate::Error::TooLarge) + ); + } + + // Craft patch (input rules) test. + #[test] + fn empty_bounding_box() { + let top = Topology::from_polylines_binary(EMPTY, EMPTY, 0.01); + assert_eq!(top.bounding_box(), kurbo::Rect::ZERO); + } + + // Craft patch (input rules) test. + #[test] + fn nonempty_bounding_box() { + let square = [[p(10.0, 20.0), p(13.0, 20.0), p(13.0, 24.0), p(10.0, 24.0)]]; + let top = Topology::from_polylines_binary(square, EMPTY, 0.01); + assert_eq!(top.bounding_box(), kurbo::Rect::new(10.0, 20.0, 13.0, 24.0)); + } + #[test] fn diamond() { let segs = [[p(0.0, 0.0), p(1.0, 1.0), p(0.0, 2.0), p(-1.0, 1.0)]]; @@ -2365,6 +3198,59 @@ mod tests { ); } + fn contours_with_parents(parents: &[Option]) -> Contours { + Contours { + contours: parents + .iter() + .map(|parent| Contour { + parent: parent.map(ContourIdx), + ..Contour::default() + }) + .collect(), + } + } + + #[test] + fn grouped_lists_each_tree_in_pre_order() { + // 0 5 + // ├─ 1 └─ 6 + // │ ├─ 3 + // │ └─ 4 + // └─ 2 + // └─ 7 + let contours = contours_with_parents(&[ + None, + Some(0), + Some(0), + Some(1), + Some(1), + None, + Some(5), + Some(2), + ]); + let grouped = contours + .grouped() + .into_iter() + .map(|tree| tree.into_iter().map(|idx| idx.0).collect::>()) + .collect::>(); + assert_eq!(grouped, vec![vec![0, 1, 3, 4, 2, 7], vec![5, 6]]); + } + + #[test] + fn grouped_handles_deep_nesting_on_a_small_stack() { + const DEPTH: usize = 30_000; + let parents = (0..DEPTH).map(|i| i.checked_sub(1)).collect::>(); + let contours = contours_with_parents(&parents); + let grouped = std::thread::Builder::new() + .stack_size(256 * 1024) + .spawn(move || contours.grouped()) + .unwrap() + .join() + .unwrap(); + assert_eq!(grouped.len(), 1); + assert!(grouped[0].iter().map(|idx| idx.0).eq(0..DEPTH)); + } + #[test] fn squares_with_gaps() { let mid = [[p(-2.0, -2.0), p(2.0, -2.0), p(2.0, 2.0), p(-2.0, 2.0)]]; @@ -2482,6 +3368,162 @@ mod tests { insta::assert_ron_snapshot!((top, contours)); } + // Checks that the contour walk finishes on a path whose winding numbers + // come out inconsistent around a point, instead of walking forever: + // `try_contours` returns an error and `contours` returns no contours. + // With `slow-asserts`, `from_path` checks the winding numbers itself and + // panics on these paths, so the tests run only without that feature. + #[cfg(not(feature = "slow-asserts"))] + fn contours_finish(svg: &str) { + let bez = BezPath::from_svg(svg).unwrap(); + let top = Topology::::from_path(&bez, 1e-6).unwrap(); + let result = top.try_contours(|w| *w != 0); + assert!(matches!( + result, + Ok(_) | Err(crate::Error::InconsistentWindingNumbers) + )); + assert_eq!(top.contours(|w| *w != 0), result.unwrap_or_default()); + } + + #[test] + #[cfg(not(feature = "slow-asserts"))] + fn contours_finish_with_no_boundary_segment_leaving_a_point() { + contours_finish("M4,-1 C8,1 -7,-2 5,8 L-4,-8 L2,1 L1,1 Z"); + } + + #[test] + #[cfg(not(feature = "slow-asserts"))] + fn contours_finish_when_the_walk_misses_its_start() { + contours_finish( + "M6,5 L3,7 L0,7 L3,6 C3,0 7,6 0,4 L4,2 C4,5 7,4 4,6 L3,3 L3,5 C6,7 2,5 3,1 L2,0 Z \ + M6,6 L4,4 C5,6 2,5 7,6 L7,6 L7,7 Z \ + M1,4 C5,2 3,3 5,7 L0,6 L0,7 L6,7 C4,5 3,7 2,1 Z \ + M3,3 C1,2 3,6 5,6 C6,4 2,7 2,0 L1,6 L6,4 L3,4 L6,7 C0,0 7,1 0,7 C0,0 1,1 1,0 Z", + ); + } + + fn rect_bez_path(x0: f64, y0: f64, x1: f64, y1: f64, reversed: bool) -> BezPath { + let mut pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]; + if reversed { + pts.reverse(); + } + let mut bez = BezPath::default(); + bez.move_to(pts[0]); + for pt in &pts[1..] { + bez.line_to(*pt); + } + bez.close_path(); + bez + } + + #[test] + fn merge_coincident_runs_longer_than_two() { + // Four copies of one square, two in each direction: the winding number is zero + // everywhere, so every edge cancels. + let mut bez = BezPath::default(); + for reversed in [false, false, true, true] { + bez.extend(rect_bez_path(0.0, 0.0, 10.0, 10.0, reversed)); + } + let top = Topology::from_path(&bez, 1e-6).unwrap(); + assert_eq!(top.segment_indices().count(), 0); + assert_eq!(top.contours(|w| *w != 0).contours().count(), 0); + + // Three copies, two in one direction and one in the other: the square remains. + let mut bez = BezPath::default(); + for reversed in [false, false, true] { + bez.extend(rect_bez_path(0.0, 0.0, 10.0, 10.0, reversed)); + } + let top = Topology::from_path(&bez, 1e-6).unwrap(); + let contours = top.contours(|w| *w != 0); + assert_eq!(contours.contours().count(), 1); + let square = contours.contours().next().unwrap(); + assert_eq!(kurbo::Shape::area(&square.path).abs(), 100.0); + } + + fn contour_area_sum(path: &str, eps: f64) -> f64 { + use kurbo::Shape as _; + + let bez = BezPath::from_svg(path).unwrap(); + let top = Topology::from_path(&bez, eps).unwrap(); + let contours = top.contours(|w| *w != 0); + contours.contours().map(|c| c.path.area().abs()).sum() + } + + #[test] + fn merge_only_pieces_of_one_input_curve() { + use kurbo::Shape as _; + + // Two arches whose right legs agree to within about 1e-6. The legs are deleted as + // coincident, and the left end of one arch meets a piece of the other at a simple point. + // The shape's area is about 0.000962; merging across the two curves gave a contour + // of area 900. + let path = "M0,100 C20,0 80,0 100,100 \ + C79.99999708333333,0 20.000011666666666,0 -0.000026249999999999998,100 Z"; + let bez = BezPath::from_svg(path).unwrap(); + let top = Topology::from_path(&bez, 1e-6).unwrap(); + let contours = top.try_contours(|w| *w != 0).unwrap(); + let area: f64 = contours.contours().map(|c| c.path.area().abs()).sum(); + assert!((0.0005..0.002).contains(&area), "area {area}"); + } + + #[test] + fn path_followed_by_its_reverse() { + // Every vertex of this contour used to look mergeable, which panicked in segs_to_path. + let path = "M0,6 Q3,4 3,4 Q5,4 3,4 C4,2 0,6 0,1 Z M0,1 C0,6 4,2 3,4 Q5,4 3,4 Q3,4 0,6 Z"; + for eps in [1e-3, 1e-6] { + let area = contour_area_sum(path, eps); + assert!(area < 1e-6, "eps {eps}: area {area}"); + } + } + + #[test] + fn merge_coincident_many_copies() { + // 64 copies in one direction leave the square once. + let mut bez = BezPath::default(); + for _ in 0..64 { + bez.extend(&BezPath::from_svg(&rect_path(0.0, 0.0, 10.0, 10.0, false)).unwrap()); + } + let top = Topology::from_path(&bez, 1e-6).unwrap(); + let contours = top.contours(|w| *w != 0); + assert_eq!(contours.contours().count(), 1); + let square = contours.contours().next().unwrap(); + assert_eq!(kurbo::Shape::area(&square.path).abs(), 100.0); + + // 32 copies in each direction cancel. + let mut bez = BezPath::default(); + for i in 0..64 { + bez.extend(&BezPath::from_svg(&rect_path(0.0, 0.0, 10.0, 10.0, i % 2 == 1)).unwrap()); + } + let top = Topology::from_path(&bez, 1e-6).unwrap(); + assert_eq!(top.segment_indices().count(), 0); + } + + #[test] + fn nearest_live_west_shortens_the_links_it_follows() { + // Segment i has segment i - 1 to its west; segments 1 to 4 are deleted. + let mut live_west = OutputSegVec::from_vec( + (0..6usize) + .map(|i| i.checked_sub(1).map(OutputSegIdx)) + .collect(), + ); + let mut deleted = OutputSegVec::from_vec(vec![false; 6]); + for i in 1..5 { + deleted[OutputSegIdx(i)] = true; + } + let west = Topology::::nearest_live_west(&mut live_west, &deleted, OutputSegIdx(5)); + assert_eq!(west, Some(OutputSegIdx(0))); + for i in 1..6 { + assert_eq!(live_west[OutputSegIdx(i)], Some(OutputSegIdx(0))); + } + + // When the result is deleted later, the next call continues past it. + deleted[OutputSegIdx(0)] = true; + let west = Topology::::nearest_live_west(&mut live_west, &deleted, OutputSegIdx(5)); + assert_eq!(west, None); + assert_eq!(live_west[OutputSegIdx(5)], None); + assert_eq!(live_west[OutputSegIdx(0)], None); + } + #[test] fn disjoint() { let s1 = [[p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 1.0)]]; @@ -2510,6 +3552,31 @@ mod tests { assert!(Topology::from_polylines_binary(s1, s2, 1e-5).is_disjoint(FillRule::EvenOdd)); } + #[test] + fn disjoint_skips_merged_segments() { + // The second set draws the same square twice, so its coincident edges are merged + // and the duplicates are deleted. + let s1 = [[p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 1.0)]]; + let s2 = [ + [p(2.0, 0.0), p(3.0, 0.0), p(3.0, 1.0), p(2.0, 1.0)], + [p(2.0, 0.0), p(3.0, 0.0), p(3.0, 1.0), p(2.0, 1.0)], + ]; + let top = Topology::from_polylines_binary(s1, s2, 1e-5); + assert!(top.is_disjoint(FillRule::NonZero)); + + // With `inside1` always false, it is called for both sides of every segment visited. + let calls = std::cell::Cell::new(0); + let disjoint = top.is_disjoint_tags( + |_| { + calls.set(calls.get() + 1); + false + }, + |w| FillRule::NonZero.is_inside(w.shape_b), + ); + assert!(disjoint); + assert_eq!(calls.get(), 2 * top.segment_indices().count()); + } + #[test] fn normal_contours() { let s = [[p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 1.0)]]; @@ -2540,6 +3607,132 @@ mod tests { assert!(!Topology::from_polylines_binary(s, EMPTY, 1e-5).has_normal_contours(OneOfTwo::A)); } + // Craft patch (coincident horizontals): n overlapping rectangles that share their top + // and bottom edges have n active horizontals at most points of those edges. Each run + // gets one output segment, so the count grows with n rather than with n * n. + #[test] + fn coincident_horizontals_get_one_output_segment_per_run() { + let n = 200; + let mut bez = BezPath::new(); + for i in 0..n { + let rect = kurbo::Rect::new(i as f64, 0.0, (i + n) as f64, 10.0); + bez.extend(kurbo::Shape::path_elements(&rect, 0.0)); + } + let top = Topology::::from_path(&bez, 1e-6).unwrap(); + assert_eq!(top.orig_seg.len(), 6 * n - 2); + assert_eq!(top.segment_indices().count(), 6 * n - 2); + + let area = |contours: &super::Contours| -> f64 { + contours + .contours() + .map(|c| kurbo::Shape::area(&c.path).abs()) + .sum() + }; + let nonzero = top.contours(|w| *w != 0); + assert_eq!(nonzero.contours().count(), 1); + assert_eq!(area(&nonzero), 10.0 * (2 * n - 1) as f64); + let even_odd = top.contours(|w| w % 2 != 0); + assert_eq!(even_odd.contours().count(), n); + assert_eq!(area(&even_odd), 10.0 * n as f64); + + // Squares that share a horizontal edge have a normal boundary: each shared piece + // has winding number 1 on both sides. + let s = [ + [p(0.0, 0.0), p(2.0, 0.0), p(2.0, 1.0), p(0.0, 1.0)], + [p(0.0, 1.0), p(2.0, 1.0), p(2.0, 2.0), p(0.0, 2.0)], + ]; + assert!(Topology::from_polylines_binary(s, EMPTY, 1e-5).has_normal_contours(OneOfTwo::A)); + + // A horizontal spur out of a square and back has winding number 0 on both sides. + let s = [[ + p(0.0, 0.0), + p(2.0, 0.0), + p(2.0, 2.0), + p(0.0, 2.0), + p(0.0, 1.0), + p(-1.0, 1.0), + p(0.0, 1.0), + ]]; + assert!(!Topology::from_polylines_binary(s, EMPTY, 1e-5).has_normal_contours(OneOfTwo::A)); + let s = [[ + p(0.0, 0.0), + p(2.0, 0.0), + p(2.0, 1.0), + p(3.0, 1.0), + p(2.0, 1.0), + p(2.0, 2.0), + p(0.0, 2.0), + ]]; + assert!(!Topology::from_polylines_binary(s, EMPTY, 1e-5).has_normal_contours(OneOfTwo::A)); + } + + fn closed_polyline(points: &[(f64, f64)]) -> BezPath { + let mut path = BezPath::default(); + path.move_to(points[0]); + for &pt in &points[1..] { + path.line_to(pt); + } + path.close_path(); + path + } + + // Overlapping rectangles with aligned tops, a square with a hole, and a + // curve that splits into monotonic pieces, so that some output segments + // are interior, some bound a hole and some can be merged. + fn contour_position_shapes() -> Vec { + let mut curve = BezPath::default(); + curve.move_to((-1., 0.)); + curve.curve_to((-1., -1.), (1., 1.), (1., 0.)); + curve.line_to((2., 4.)); + curve.line_to((-2., 4.)); + curve.close_path(); + vec![ + closed_polyline(&[(0., 0.), (4., 0.), (4., 3.), (0., 3.)]), + closed_polyline(&[(1., 0.), (5., 0.), (5., 2.), (1., 2.)]), + closed_polyline(&[(2., 0.), (3., 0.), (3., 5.), (2., 5.)]), + closed_polyline(&[(6., 0.), (10., 0.), (10., 4.), (6., 4.)]), + closed_polyline(&[(7., 1.), (7., 3.), (9., 3.), (9., 1.)]), + curve, + ] + } + + #[test] + fn contour_positions_cover_only_boundary_segments() { + let shapes = contour_position_shapes(); + let top = Topology::::from_paths(shapes.iter().map(|s| (s, ())), 1e-6).unwrap(); + let inside = |w: &i32| *w != 0; + let positions = top.contour_positions(&inside); + let mut interior = 0; + for idx in top.segment_indices() { + let on_boundary = + inside(&top.winding[idx].clockwise) != inside(&top.winding[idx].counter_clockwise); + assert_eq!( + positions[idx].path.elements().is_empty(), + !on_boundary, + "{idx:?}" + ); + if !on_boundary { + interior += 1; + } + } + assert!(interior > 0); + } + + #[test] + fn contours_match_contours_from_all_positions() { + let shapes = contour_position_shapes(); + let top = Topology::::from_paths(shapes.iter().map(|s| (s, ())), 1e-6).unwrap(); + let predicates: [fn(&i32) -> bool; 4] = + [|w| *w != 0, |w| *w >= 2, |w| *w >= 3, |w| *w % 2 != 0]; + for inside in predicates { + let expected = top + .contours_for_positions(inside, top.compute_positions()) + .unwrap(); + assert!(!expected.contours.is_empty()); + assert_eq!(top.contours(inside), expected); + } + } + #[test] fn invalid_sweep_order_repro() { let polys = [ @@ -2631,6 +3824,214 @@ mod tests { assert!(!contours[2].outer); } + // An axis-aligned rectangle, clockwise (y down) unless `hole`. + fn rect_path(x0: f64, y0: f64, x1: f64, y1: f64, hole: bool) -> String { + if hole { + format!("M{x0},{y0} L{x0},{y1} L{x1},{y1} L{x1},{y0} Z ") + } else { + format!("M{x0},{y0} L{x1},{y0} L{x1},{y1} L{x0},{y1} Z ") + } + } + + // The nonzero contours of `svg`, after checking that each one is outer + // exactly when it winds clockwise and when its parent is not outer. + fn consistent_contours(svg: &str, eps: f64) -> Contours { + let bez = BezPath::from_svg(svg).unwrap(); + let top = Topology::::from_path(&bez, eps).unwrap(); + let contours = top.contours(|w| *w != 0); + for (i, c) in contours.contours().enumerate() { + let parent_outer = c.parent.map(|p| contours[p].outer); + assert_eq!(c.outer, parent_outer != Some(true), "contour {i} of {svg}"); + let mut local = c.path.clone(); + local.apply_affine(Affine::translate(-c.path.bounding_box().origin().to_vec2())); + assert_eq!(c.outer, local.area() > 0.0, "contour {i} of {svg}"); + } + contours + } + + #[test] + fn holes_touching_at_a_point_are_siblings() { + let square = rect_path(0.0, 0.0, 100.0, 100.0, false); + for (a, b) in [ + ((10.0, 30.0, 30.0, 50.0), (30.0, 50.0, 50.0, 70.0)), + ((10.0, 50.0, 30.0, 70.0), (30.0, 30.0, 50.0, 50.0)), + ] { + // Far from the origin, a plain signed area of these squares has the wrong sign. + for (o, eps) in [(0.0, 1e-6), (1e11, 1e-3)] { + let svg = rect_path(o, o, o + 100.0, o + 100.0, false) + + &rect_path(o + a.0, o + a.1, o + a.2, o + a.3, true) + + &rect_path(o + b.0, o + b.1, o + b.2, o + b.3, true); + let contours = consistent_contours(&svg, eps); + assert_eq!(contours.len(), 3); + for i in 1..3 { + assert!(!contours[ContourIdx(i)].outer); + assert_eq!(contours[ContourIdx(i)].parent, Some(ContourIdx(0))); + } + } + } + + // Three holes in a chain, touching at (30, 50) and (50, 70). + let svg = square.clone() + + &rect_path(10.0, 30.0, 30.0, 50.0, true) + + &rect_path(30.0, 50.0, 50.0, 70.0, true) + + &rect_path(50.0, 70.0, 70.0, 90.0, true); + let contours = consistent_contours(&svg, 1e-6); + assert_eq!(contours.len(), 4); + for i in 1..4 { + assert_eq!(contours[ContourIdx(i)].parent, Some(ContourIdx(0))); + } + + // Two touching holes in an island, inside a hole of the square. + let svg = square + + &rect_path(5.0, 5.0, 95.0, 95.0, true) + + &rect_path(10.0, 10.0, 90.0, 90.0, false) + + &rect_path(20.0, 30.0, 40.0, 50.0, true) + + &rect_path(40.0, 50.0, 60.0, 70.0, true); + let contours = consistent_contours(&svg, 1e-6); + assert_eq!(contours.len(), 5); + } + + // A diamond hole 6 wide and 6 tall whose top corner is at (cx, y). + fn diamond_hole(cx: f64, y: f64) -> String { + let (l, r) = (cx - 3.0, cx + 3.0); + format!( + "M{cx},{y} L{l},{} L{cx},{} L{r},{} Z ", + y + 3.0, + y + 6.0, + y + 3.0 + ) + } + + // Craft patch (touching holes). Each of `n` diamond holes touches the top edge of the + // square at its own point, so the walk of the square splits off every hole. Only the + // rest of the walk winds like the square, so no hole needs a winding test to find its + // parent. Testing each hole against the whole square takes time growing like `n^2`. + #[test] + fn holes_touching_their_outer_contour_need_no_winding_test() { + let n = 200; + let mut svg = rect_path(0.0, 0.0, 10.0 * n as f64, 100.0, false); + for i in 0..n { + svg += &diamond_hole(10.0 * i as f64 + 5.0, 0.0); + } + super::CONTAINER_TEST_ELEMENTS.with(|c| c.set(0)); + let contours = consistent_contours(&svg, 1e-6); + assert_eq!(super::CONTAINER_TEST_ELEMENTS.with(|c| c.get()), 0); + assert_eq!(contours.len(), n + 1); + let outer: Vec = (0..contours.len()) + .map(ContourIdx) + .filter(|&i| contours[i].outer) + .collect(); + assert_eq!(outer.len(), 1); + assert_eq!(contours[outer[0]].parent, None); + for i in (0..contours.len()) + .map(ContourIdx) + .filter(|&i| i != outer[0]) + { + assert_eq!(contours[i].parent, Some(outer[0])); + } + } + + // The contour of `contours` whose bounding box is `bbox`. + fn contour_with_box(contours: &Contours, bbox: Rect) -> ContourIdx { + let found: Vec = contours + .contours() + .enumerate() + .filter(|(_, c)| c.path.bounding_box() == bbox) + .map(|(i, _)| i) + .collect(); + assert_eq!(found.len(), 1, "contours with box {bbox:?}"); + ContourIdx(found[0]) + } + + // The bounding box of the path `svg`. + fn svg_box(svg: &str) -> Rect { + BezPath::from_svg(svg).unwrap().bounding_box() + } + + #[test] + fn touching_child_attaches_to_the_sibling_that_contains_it() { + // Two outer squares touching at (100, 100), with a hole that touches the + // edge of one of them. Each case puts the hole in a different square, and + // the hole attaches to that square. + let a = Rect::new(0.0, 0.0, 100.0, 100.0); + let b = Rect::new(100.0, 100.0, 200.0, 200.0); + let squares = + rect_path(a.x0, a.y0, a.x1, a.y1, false) + &rect_path(b.x0, b.y0, b.x1, b.y1, false); + for (hole, container) in [ + ("M150,100 L140,120 L150,140 L160,120 Z", b), + ("M50,100 L60,80 L50,60 L40,80 Z", a), + ] { + let svg = squares.clone() + hole; + let contours = consistent_contours(&svg, 1e-6); + assert_eq!(contours.len(), 3, "{svg}"); + let hole = &contours[contour_with_box(&contours, svg_box(hole))]; + assert!(!hole.outer, "{svg}"); + let container = contour_with_box(&contours, container); + assert_eq!(hole.parent, Some(container), "{svg}"); + for square in [a, b] { + let square = &contours[contour_with_box(&contours, square)]; + assert_eq!(square.parent, None, "{svg}"); + } + } + + // Two holes of a square touching at (150, 150), with an island that touches + // the edge of one of them. + let outer = Rect::new(0.0, 0.0, 300.0, 300.0); + let h1 = Rect::new(50.0, 50.0, 150.0, 150.0); + let h2 = Rect::new(150.0, 150.0, 250.0, 250.0); + let holes = rect_path(outer.x0, outer.y0, outer.x1, outer.y1, false) + + &rect_path(h1.x0, h1.y0, h1.x1, h1.y1, true) + + &rect_path(h2.x0, h2.y0, h2.x1, h2.y1, true); + for (island, container) in [ + ("M200,150 L210,170 L200,190 L190,170 Z", h2), + ("M100,150 L90,130 L100,110 L110,130 Z", h1), + ] { + let svg = holes.clone() + island; + let contours = consistent_contours(&svg, 1e-6); + assert_eq!(contours.len(), 4, "{svg}"); + let island = &contours[contour_with_box(&contours, svg_box(island))]; + assert!(island.outer, "{svg}"); + let container = contour_with_box(&contours, container); + assert_eq!(island.parent, Some(container), "{svg}"); + let square = contour_with_box(&contours, outer); + for hole in [h1, h2] { + let hole = &contours[contour_with_box(&contours, hole)]; + assert_eq!(hole.parent, Some(square), "{svg}"); + } + } + + // The same two holes, with an island that touches the edge of the second hole + // and a second island that touches only the first island. Both islands + // attach to the second hole. + let near = "M200,150 L210,170 L200,190 L190,170 Z"; + let far = "M200,190 L210,210 L200,230 L190,210 Z"; + let svg = holes.clone() + near + " " + far; + let contours = consistent_contours(&svg, 1e-6); + assert_eq!(contours.len(), 5, "{svg}"); + let container = contour_with_box(&contours, h2); + for island in [near, far] { + let island = &contours[contour_with_box(&contours, svg_box(island))]; + assert!(island.outer, "{svg}"); + assert_eq!(island.parent, Some(container), "{svg}"); + } + + // A square with a hole that touches its top edge at (150, 0), and a second + // hole that touches the first at (200, 50). One walk splits into the square + // and both holes, and each hole attaches to the square. + let first = "M150,0 L100,50 L150,100 L200,50 Z"; + let second = "M200,50 L200,150 L250,150 L250,50 Z"; + let svg = rect_path(outer.x0, outer.y0, outer.x1, outer.y1, false) + first + " " + second; + let contours = consistent_contours(&svg, 1e-6); + assert_eq!(contours.len(), 3, "{svg}"); + let square = contour_with_box(&contours, outer); + assert_eq!(contours[square].parent, None); + for hole in [first, second] { + let hole = &contours[contour_with_box(&contours, svg_box(hole))]; + assert!(!hole.outer, "{svg}"); + assert_eq!(hole.parent, Some(square), "{svg}"); + } + } + // Checks that all output segments intersect one another only at endpoints. // fn check_intersections(top: &Topology) { // for i in 0..top.winding.inner.len() { @@ -2662,6 +4063,310 @@ mod tests { // } // } + // Craft patch (work limit). Stacked copies of a circle make every segment + // overlap every other, and the sweep compares each segment with all of them. + #[test] + fn work_limit() { + use kurbo::{Circle, Shape}; + + let circle = Circle::new((100.0, 100.0), 50.0).to_path(1e-3); + let paths = vec![circle; 20]; + let tagged = || paths.iter().map(|p| (p, ())); + + let result = Topology::::from_paths_with_work_limit(tagged(), 1e-6, 1_000); + assert_eq!(result.err(), Some(crate::Error::WorkLimitExceeded)); + + let expected = Topology::::from_paths(tagged(), 1e-6) + .unwrap() + .contours(|w| *w != 0); + let actual = Topology::::from_paths_with_work_limit(tagged(), 1e-6, u64::MAX) + .unwrap() + .contours(|w| *w != 0); + let paths = |c: &super::Contours| c.contours().map(|c| c.path.clone()).collect::>(); + assert_eq!(paths(&actual), paths(&expected)); + assert!(!paths(&actual).is_empty()); + } + + #[test] + fn work_limit_constructor_rejects_coordinates_that_are_too_large() { + let huge = f64::MAX / 8.0; + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((huge, 0.0)); + path.line_to((0.0, huge)); + path.close_path(); + let result = Topology::::from_paths_with_work_limit([(&path, ())], 1e-6, 1_000_000); + assert_eq!(result.err(), Some(crate::Error::TooLarge)); + } + + // `n` tall bars (the second set) west of a column of `m` small squares (the first set). + fn bars_and_squares(n: usize, m: usize) -> (Vec<[Point; 4]>, Vec<[Point; 4]>) { + let rect = + |x0: f64, y0: f64, x1: f64, y1: f64| [p(x0, y0), p(x1, y0), p(x1, y1), p(x0, y1)]; + let height = 3.0 * m as f64 + 3.0; + let bars = (0..n) + .map(|i| { + let x = 3.0 * i as f64; + rect(x, 0.0, x + 1.0, height) + }) + .collect(); + let x = 3.0 * n as f64 + 10.0; + let squares = (0..m) + .map(|j| { + let y = 3.0 * j as f64 + 1.0; + rect(x, y, x + 1.0, y + 1.0) + }) + .collect(); + (squares, bars) + } + + #[test] + fn contour_starts_follow_each_west_chain_once() { + let (squares, bars) = bars_and_squares(200, 200); + let top = Topology::from_polylines_binary(squares, bars, 1e-6); + super::WEST_STEPS.with(|n| n.set(0)); + let contours = top.contours(|w| w.shape_a != 0 && w.shape_b == 0); + // No bar edge is on the boundary of the squares minus the bars, so the west chain of + // every square passes all 400 bar edges. Each link is followed at most once; walking + // the chain again for each square follows about 400 * 200 links. + let steps = super::WEST_STEPS.with(|n| n.get()); + let segs = top.segment_indices().count(); + assert!(steps <= segs, "{steps} scan-west links followed for {segs} segments"); + assert_eq!(contours.contours().count(), 200); + assert!(contours.contours().all(|c| c.outer && c.parent.is_none())); + } + + #[test] + fn contours_of_one_polygon_test_the_boundary_only_where_needed() { + // One convex polygon with `k` edges: the walk from its first edge visits every other + // edge, so no edge past the first needs its own boundary test. + let k = 1000; + let poly: Vec = (0..k) + .map(|i| { + let a = std::f64::consts::TAU * i as f64 / k as f64; + p(100.0 * a.cos(), 100.0 * a.sin()) + }) + .collect(); + let top = Topology::from_polylines_binary([poly], std::iter::empty::>(), 1e-6); + let segs = top.segment_indices().count(); + let calls = std::cell::Cell::new(0usize); + let contours = top.contours(|w| { + calls.set(calls.get() + 1); + w.shape_a != 0 + }); + assert_eq!(contours.contours().count(), 1); + // The walk calls `inside` four times per edge: once to find the next boundary edge + // and three times to check the winding numbers, which it does in release builds too. + // `contour_positions` tests each edge for the boundary with two more. + let per_seg = 6; + assert!( + calls.get() <= per_seg * segs + 16, + "{} calls to inside for {segs} segments", + calls.get() + ); + } + + #[test] + fn contour_starts_find_the_boundary_past_non_boundary_segments() { + let (mut set_a, bars) = bars_and_squares(20, 20); + // A frame around everything: the squares are holes in it, and the bars do not + // change the set, so every square's west chain passes the bar edges and ends at the + // frame's left edge. + set_a.push([ + p(-5.0, -5.0), + p(200.0, -5.0), + p(200.0, 200.0), + p(-5.0, 200.0), + ]); + let top = Topology::from_polylines_binary(set_a, bars, 1e-6); + let contours = top.contours(|w| w.shape_a % 2 != 0); + let count = contours.contours().count(); + assert_eq!(count, 21); + let roots: Vec = (0..count) + .map(ContourIdx) + .filter(|&i| contours[i].parent.is_none()) + .collect(); + assert_eq!(roots.len(), 1); + let frame = roots[0]; + assert!(contours[frame].outer); + for i in (0..count).map(ContourIdx).filter(|&i| i != frame) { + assert_eq!(contours[i].parent, Some(frame)); + assert!(!contours[i].outer); + } + } + + // Craft patch (work limit). Closed paths made only of horizontal segments + // at one height take little sweep work, but each step of a sweep line + // range visits every active horizontal segment, so the topology visits + // about n^2 of them. Those visits count toward the limit. Every run of + // these coincident segments cancels, so they make no output segments. + #[test] + fn work_limit_counts_the_horizontal_splits() { + let n = 300; + let paths: Vec = (0..n) + .map(|i| { + let i = f64::from(i); + let mut path = BezPath::new(); + path.move_to((i, 0.0)); + path.line_to((2.0 * f64::from(n) + i, 0.0)); + path.close_path(); + path + }) + .collect(); + let tagged = || paths.iter().map(|p| (p, ())); + + let result = Topology::::from_paths_with_work_limit(tagged(), 1e-6, 100_000); + assert_eq!(result.err(), Some(crate::Error::WorkLimitExceeded)); + + let expected = Topology::::from_paths(tagged(), 1e-6).unwrap(); + let actual = Topology::::from_paths_with_work_limit(tagged(), 1e-6, u64::MAX).unwrap(); + assert_eq!(actual.winding.inner.len(), expected.winding.inner.len()); + } + + // With default features, 1,200 separate squares make 4,800 output + // segments, each holding points, neighbors and winding numbers. The output + // limit stops the topology before it allocates them all. An `i32` winding + // number takes one storage unit, so each output segment takes three. + #[test] + fn output_limit() { + // slow-asserts checks every pair on the sweep line after each insertion. + let (count, output_budget) = if cfg!(feature = "slow-asserts") { (100, 1000) } else { (1200, 10_000) }; + let paths: Vec = (0..count) + .map(|i| { + let x = 3.0 * f64::from(i); + let mut path = BezPath::new(); + path.move_to((x, 0.0)); + path.line_to((x + 1.0, 0.0)); + path.line_to((x + 1.0, 1.0)); + path.line_to((x, 1.0)); + path.close_path(); + path + }) + .collect(); + let tagged = || paths.iter().map(|p| (p, ())); + + let result = Topology::::from_paths_with_limits(tagged(), 1e-6, u64::MAX, output_budget); + assert_eq!(result.err(), Some(crate::Error::WorkLimitExceeded)); + + let all = Topology::::from_paths(tagged(), 1e-6).unwrap().winding.inner.len(); + let exact = Topology::::from_paths_with_limits(tagged(), 1e-6, u64::MAX, 3 * all).unwrap(); + assert_eq!(exact.winding.inner.len(), all); + let result = Topology::::from_paths_with_limits(tagged(), 1e-6, u64::MAX, 3 * all - 1); + assert_eq!(result.err(), Some(crate::Error::WorkLimitExceeded)); + } + + // Craft patch (work limit). A winding number may report any storage size; + // constructors without an output limit do not count it. + #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] + struct HugeWinding(i32); + + impl std::ops::Add for HugeWinding { + type Output = Self; + fn add(self, rhs: Self) -> Self { + HugeWinding(self.0 + rhs.0) + } + } + + impl std::ops::AddAssign for HugeWinding { + fn add_assign(&mut self, rhs: Self) { + self.0 += rhs.0; + } + } + + impl super::WindingNumber for HugeWinding { + type Tag = (); + fn single((): (), positive: bool) -> Self { + HugeWinding(if positive { 1 } else { -1 }) + } + fn of_tag(&self, (): ()) -> Self { + self.clone() + } + fn storage_units(&self) -> usize { + usize::MAX + } + } + + #[test] + fn unlimited_constructors_ignore_storage_units() { + let mut square = BezPath::new(); + square.move_to((0.0, 0.0)); + square.line_to((1.0, 0.0)); + square.line_to((1.0, 1.0)); + square.line_to((0.0, 1.0)); + square.close_path(); + let paths = [(&square, ())]; + + assert!(Topology::::from_paths(paths, 1e-6).is_ok()); + assert!(Topology::::from_paths_with_work_limit(paths, 1e-6, u64::MAX).is_ok()); + let result = Topology::::from_paths_with_limits(paths, 1e-6, u64::MAX, usize::MAX); + assert_eq!(result.err(), Some(crate::Error::WorkLimitExceeded)); + } + + #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] + struct StoredTags(std::collections::BTreeMap); + + impl std::ops::Add for StoredTags { + type Output = Self; + + fn add(mut self, rhs: Self) -> Self { + self += rhs; + self + } + } + + impl std::ops::AddAssign for StoredTags { + fn add_assign(&mut self, rhs: Self) { + for (tag, value) in rhs.0 { + *self.0.entry(tag).or_default() += value; + } + self.0.retain(|_, value| *value != 0); + } + } + + impl super::WindingNumber for StoredTags { + type Tag = usize; + + fn single(tag: usize, positive: bool) -> Self { + Self([(tag, if positive { 1 } else { -1 })].into_iter().collect()) + } + + fn of_tag(&self, tag: usize) -> Self { + Self(self.0.get(&tag).map(|value| (tag, *value)).into_iter().collect()) + } + + fn storage_units(&self) -> usize { + self.0.len() + } + } + + #[test] + fn output_accounting_includes_winding_growth_when_coincident_edges_merge() { + let mut exercised_growth = false; + for reversed in [false, true] { + let paths: Vec<_> = [10.0, 20.0, 30.0].into_iter() + .map(|width| rect_bez_path(0.0, 0.0, width, 10.0, reversed)).collect(); + let tagged = || paths.iter().enumerate().map(|(tag, path)| (path, tag)); + let topology = Topology::::from_paths_with_limits(tagged(), 1e-6, u64::MAX, usize::MAX).unwrap(); + let before = super::OUTPUT_UNITS_BEFORE_MERGE.with(std::cell::Cell::get); + let stored: usize = topology.winding.inner.iter() + .map(|winding| 1 + winding.clockwise.0.len() + winding.counter_clockwise.0.len()).sum(); + if stored > before { + exercised_growth = true; + let limited = Topology::::from_paths_with_limits(tagged(), 1e-6, u64::MAX, before); + assert_eq!(limited.err(), Some(crate::Error::WorkLimitExceeded), "stored {stored}, budget {before}"); + } + } + assert!(exercised_growth); + } + + #[test] + fn output_accounting_rejects_an_overflowing_winding_storage_sum() { + let mut output = super::OutputLimit { used: 0, limit: Some(usize::MAX) }; + let winding = super::HalfSegmentWindingNumbers { clockwise: HugeWinding(1), counter_clockwise: HugeWinding(0) }; + assert!(!output.take(&winding)); + assert_eq!(output.used, 0); + } + fn run_perturbation(ps: Vec>) { let base = vec![vec![ p(0.0, 0.0), @@ -2680,6 +4385,72 @@ mod tests { //check_intersections(&top); } + // A column of shapes, each made of two closed paths whose wavy cubic sides + // cross each other twice. + fn wavy_column(rows: usize) -> BezPath { + let mut path = BezPath::new(); + for k in 0..rows { + let y = 10.0 * k as f64; + for offset in [0.0, 0.7] { + path.move_to((offset, y)); + path.curve_to( + (offset + 3.0, y + 2.0), + (offset - 3.0, y + 6.0), + (offset, y + 8.0), + ); + path.line_to((offset + 2.0, y + 8.0)); + path.line_to((offset + 2.0, y)); + path.close_path(); + } + } + path + } + + // The positions that `compute_positions_correct` computes, with a cache + // that drops ended pairs or one that keeps every pair. + fn correct_positions(top: &Topology, evict: bool) -> (String, usize) { + let mut cmp = ComparisonCache::new(top.eps, top.eps / 2.0); + if !evict { + cmp.never_evict(); + } + let mut endpoints = HalfOutputSegVec::with_size(top.orig_seg.len()); + for idx in top.orig_seg.indices() { + endpoints[idx.first_half()] = top.points[top.point_idx[idx.first_half()]].to_kurbo(); + endpoints[idx.second_half()] = top.points[top.point_idx[idx.second_half()]].to_kurbo(); + } + let out = crate::position::compute_positions( + &top.segments, + &top.orig_seg, + &mut cmp, + &endpoints, + &top.build_scan_line_orders(), + top.eps / 4.0, + ); + (format!("{out:?}"), cmp.cached_pairs()) + } + + #[test] + fn evicting_comparisons_keeps_the_correct_positions() { + let path = wavy_column(200); + for eps in [0.01, 0.25] { + let top = Topology::::from_paths_with_correctness( + [(&path, ())], + eps, + Correctness::ReallyCorrect, + ) + .unwrap(); + let (kept, kept_pairs) = correct_positions(&top, false); + let (evicted, evicted_pairs) = correct_positions(&top, true); + assert!(kept == evicted); + assert_eq!(format!("{:?}", top.compute_positions()), evicted); + assert!(kept_pairs >= 400, "{kept_pairs}"); + assert!( + evicted_pairs * 10 < kept_pairs, + "{evicted_pairs} {kept_pairs}" + ); + } + } + proptest! { #[test] fn perturbation_test_f64(perturbations in prop::collection::vec(perturbation(f64_perturbation(0.1)), 1..5)) { diff --git a/vendor/linesweeper/src/treevec.rs b/vendor/linesweeper/src/treevec.rs index ff17270bb5..ca2d8913a8 100644 --- a/vendor/linesweeper/src/treevec.rs +++ b/vendor/linesweeper/src/treevec.rs @@ -541,7 +541,7 @@ impl TreeVec { Node::Leaf { data } => IterInner::Simple(data.iter()), Node::Internal { .. } => { let mut ret = TreeIter { - stack: Vec::new(), + stack: Stack::new(), leaf: [].iter(), remaining: self.len(), }; @@ -560,7 +560,7 @@ impl TreeVec { Node::Leaf { data } => IterMutInner::Simple(data.iter_mut()), root @ Node::Internal { .. } => { let mut ret = TreeIterMut { - stack: Vec::new(), + stack: Stack::new(), leaf: [].iter_mut(), remaining: len, }; @@ -587,22 +587,34 @@ impl TreeVec { /// Turns a generic range bounds into an inclusive start and an exclusive end. /// - /// This won't work if the range end is inclusive of `usize::MAX`, so don't do that. + /// Panics if a bound is past `usize::MAX` or if the start is after the end. + // Craft patch (range bounds): checked bounds and a start-after-end check. fn normalize_bounds(&self, range: impl std::ops::RangeBounds) -> (usize, usize) { let start = match range.start_bound() { std::ops::Bound::Included(x) => *x, - std::ops::Bound::Excluded(x) => *x + 1, + std::ops::Bound::Excluded(x) => { + x.checked_add(1).expect("range start is past usize::MAX") + } std::ops::Bound::Unbounded => 0, }; let end = match range.end_bound() { - std::ops::Bound::Included(x) => *x + 1, + std::ops::Bound::Included(x) => x.checked_add(1).expect("range end is past usize::MAX"), std::ops::Bound::Excluded(x) => *x, std::ops::Bound::Unbounded => self.len(), }; + if start > end { + panic!("range starts at {start} but ends at {end}"); + } (start, end) } /// Returns an iterator over a sub-range of this container. + /// + /// # Panics + /// + /// Panics if a bound is past `usize::MAX`, if the start is after the end, or if the end is + /// past the length of this container. + // Craft patch (range bounds): the panics are documented. pub fn range(&self, range: impl std::ops::RangeBounds) -> Iter<'_, T, B> { let (start, end) = self.normalize_bounds(range); let inner = match &*self.root { @@ -612,7 +624,7 @@ impl TreeVec { panic!("out of bounds"); } let mut ret = TreeIter { - stack: Vec::new(), + stack: Stack::new(), leaf: [].iter(), remaining: end - start, }; @@ -624,6 +636,12 @@ impl TreeVec { } /// Returns an iterator over mutable references to a sub-range of this container. + /// + /// # Panics + /// + /// Panics if a bound is past `usize::MAX`, if the start is after the end, or if the end is + /// past the length of this container. + // Craft patch (range bounds): the panics are documented. pub fn range_mut(&mut self, range: impl std::ops::RangeBounds) -> IterMut<'_, T, B> { let (start, end) = self.normalize_bounds(range); let len = self.len(); @@ -635,7 +653,7 @@ impl TreeVec { panic!("out of bounds"); } let mut ret = TreeIterMut { - stack: Vec::new(), + stack: Stack::new(), leaf: [].iter_mut(), remaining: end - start, }; @@ -645,6 +663,28 @@ impl TreeVec { }; IterMut { inner } } + + // Craft patch (scan runs): reverse iteration for `intersection_scan_left`. + /// Returns an iterator over the elements before index `end`, from the + /// last one to the first. An `end` past the length means the length. + pub(crate) fn range_rev_to(&self, end: usize) -> RevIter<'_, T, B> { + let end = end.min(self.len()); + let inner = match &*self.root { + Node::Leaf { data } => RevIterInner::Simple(data[..end].iter()), + Node::Internal { .. } => { + let mut ret = RevTreeIter { + stack: Stack::new(), + leaf: [].iter(), + remaining: end, + }; + if end > 0 { + ret.descend_to(&*self.root, end); + } + RevIterInner::Tree(ret) + } + }; + RevIter { inner } + } } impl FromIterator for TreeVec { @@ -687,12 +727,53 @@ enum IterInner<'a, T, const B: usize> { Tree(TreeIter<'a, T, B>), } +// Craft patch (iterator stack): the tree iterators keep their stack in place. +/// The number of tree levels whose iterators a [`Stack`] holds without +/// allocating. Every node but the root has at least `B/2` children, so a tree +/// with `B = 128` needs at least `2 * 64^9` elements to be taller than this. +const INLINE_HEIGHT: usize = 8; + +/// The stack of child iterators in [`TreeIter`] and [`TreeIterMut`]. The first +/// [`INLINE_HEIGHT`] entries are stored in place and the rest go in `spill`, +/// which allocates only for a tree taller than that. +struct Stack { + inline: ArrayVec, + spill: Vec, +} + +impl Stack { + fn new() -> Self { + Stack { + inline: ArrayVec::new(), + spill: Vec::new(), + } + } + + fn push(&mut self, item: I) { + if let Err(full) = self.inline.try_push(item) { + self.spill.push(full.element()); + } + } + + fn last_mut(&mut self) -> Option<&mut I> { + if self.spill.is_empty() { + self.inline.last_mut() + } else { + self.spill.last_mut() + } + } + + fn pop(&mut self) -> Option { + self.spill.pop().or_else(|| self.inline.pop()) + } +} + struct TreeIter<'a, T, const B: usize> { // If you imagine how the recursive implementation of a tree iteration // works, the local state at each intermediate call consists of a // partially-finished iteration over the children of that internal node. // This stores the stack of that imaginary recursive implementation. - stack: Vec>>>, + stack: Stack>>>, leaf: std::slice::Iter<'a, T>, // The number of remaining elements; used for iteration over ranges. The // full-iteration implementation doesn't need it, but it isn't worth having @@ -781,6 +862,107 @@ impl<'a, T, const B: usize> Iterator for Iter<'a, T, B> { } } +// Craft patch (scan runs): reverse iteration for `intersection_scan_left`. +/// An iterator over elements of a [`TreeVec`], from back to front. +pub(crate) struct RevIter<'a, T, const B: usize> { + inner: RevIterInner<'a, T, B>, +} + +enum RevIterInner<'a, T, const B: usize> { + Simple(std::slice::Iter<'a, T>), + Tree(RevTreeIter<'a, T, B>), +} + +// The mirror image of `TreeIter`: the stack holds the children still to visit +// on the left, and elements come off the back of each slice. +struct RevTreeIter<'a, T, const B: usize> { + stack: Stack>>>, + leaf: std::slice::Iter<'a, T>, + remaining: usize, +} + +impl<'a, T, const B: usize> RevTreeIter<'a, T, B> { + // Fill out the rest of the stack and the leaf, by descending + // to the last descendent of `node`. + fn descend(&mut self, mut node: &'a Node) { + loop { + match node { + Node::Leaf { data } => { + self.leaf = data.iter(); + return; + } + Node::Internal { children, .. } => { + let mut children = children.iter(); + // unwrap: internal nodes are always non-empty + node = children.next_back().unwrap(); + self.stack.push(children); + } + } + } + } + + // Fill out the rest of the stack and the leaf, so that the next element is + // the one at offset `end - 1` in the subtree rooted at `node`. `end` must + // be positive. + fn descend_to(&mut self, mut node: &'a Node, mut end: usize) { + loop { + match node { + Node::Leaf { data } => { + self.leaf = data[..end].iter(); + return; + } + Node::Internal { children, size } => { + let Some((idx, child_offset)) = child_idx(size, end - 1) else { + return; + }; + end = child_offset + 1; + let mut children = children[..=idx].iter(); + // unwrap: child_idx always returns a valid index into children + node = children.next_back().unwrap(); + self.stack.push(children); + } + } + } + } + + fn next(&mut self) -> Option<&'a T> { + if self.remaining == 0 { + None + } else { + self.remaining -= 1; + if let Some(ret) = self.leaf.next_back() { + Some(ret) + } else { + // The current leaf is exhausted. Unwind the stack until we find + // a non-exhausted internal node, then descend again. + loop { + let stack_top = self.stack.last_mut()?; + + let Some(next_node) = stack_top.next_back() else { + self.stack.pop(); + continue; + }; + + self.descend(next_node); + return self.leaf.next_back(); + } + } + } + } +} + +impl<'a, T, const B: usize> Iterator for RevIter<'a, T, B> { + type Item = &'a T; + + #[inline(always)] + fn next(&mut self) -> Option { + match &mut self.inner { + RevIterInner::Simple(it) => it.next_back(), + RevIterInner::Tree(it) => it.next(), + } + } +} + /// An iterator over mutable references elements of a [`TreeVec`]. pub struct IterMut<'a, T, const B: usize> { inner: IterMutInner<'a, T, B>, @@ -795,7 +977,7 @@ enum IterMutInner<'a, T, const B: usize> { // turned into mut things. Right now there's only the one duplication so // is isn't worth trying to build an abstraction. struct TreeIterMut<'a, T, const B: usize> { - stack: Vec>>>, + stack: Stack>>>, leaf: std::slice::IterMut<'a, T>, remaining: usize, } @@ -907,6 +1089,64 @@ mod tests { assert_eq!(*vec.get(7).unwrap(), 1); } + // Craft patch (iterator stack). + fn internal_levels(vec: &TreeVec) -> usize { + let mut node = &*vec.root; + let mut levels = 0; + while let Node::Internal { children, .. } = node { + node = &children[0]; + levels += 1; + } + levels + } + + // Craft patch (iterator stack). + #[test] + fn iterators_on_short_and_tall_trees() { + for len in [100, 3_000] { + let mut vec: TreeVec = (0..len).collect(); + let mut expected: Vec = (0..len).collect(); + let levels = internal_levels(&vec); + if len == 100 { + assert!(levels > 2 && levels <= INLINE_HEIGHT, "{levels} levels"); + } else { + assert!(levels > INLINE_HEIGHT, "{levels} levels"); + } + + assert!(vec.iter().eq(expected.iter()), "iter, len {len}"); + let ranges = [ + (0, len), + (1, len - 1), + (len / 2, len / 2 + 4), + (len - 1, len), + (len, len), + ]; + for (start, end) in ranges { + assert!( + vec.range(start..end).eq(expected[start..end].iter()), + "range {start}..{end}, len {len}" + ); + } + + for x in vec.iter_mut() { + *x += 1; + } + for x in &mut expected { + *x += 1; + } + for (start, end) in ranges { + for x in vec.range_mut(start..end) { + *x *= 3; + } + for x in &mut expected[start..end] { + *x *= 3; + } + } + assert!(vec.iter().eq(expected.iter()), "after edits, len {len}"); + vec.check_invariants(); + } + } + #[test] fn insert_remove() { let mut vec = TreeVec::::default(); @@ -934,6 +1174,22 @@ mod tests { assert_eq!(*vec.get(5).unwrap(), 1); } + // Craft patch (scan runs). + #[test] + fn range_rev_to() { + for len in [0, 1, 4, 5, 17, 70] { + let vec: TreeVec = (0..len).collect(); + for end in 0..=len + 2 { + let got: Vec = vec.range_rev_to(end).copied().collect(); + let expected: Vec = (0..end.min(len)).rev().collect(); + assert_eq!(got, expected, "len {len}, end {end}"); + } + let take: Vec = vec.range_rev_to(len).take(3).copied().collect(); + let expected: Vec = (0..len).rev().take(3).collect(); + assert_eq!(take, expected, "len {len}"); + } + } + #[test] fn iter() { let mut vec = TreeVec::::default(); @@ -952,4 +1208,44 @@ mod tests { vec![1, 1, 1, 1, 1, 1, 2] ); } + + // Craft patch (range bounds). + fn internal_node_vec() -> TreeVec { + let vec: TreeVec = (0..20).collect(); + assert!(matches!(&*vec.root, Node::Internal { .. })); + vec + } + + #[test] + #[should_panic(expected = "range starts at 10 but ends at 5")] + fn range_reversed() { + let vec = internal_node_vec(); + #[allow(clippy::reversed_empty_ranges)] + let _ = vec.range(10..5); + } + + #[test] + #[should_panic(expected = "range starts at 10 but ends at 5")] + fn range_mut_reversed() { + let mut vec = internal_node_vec(); + #[allow(clippy::reversed_empty_ranges)] + let _ = vec.range_mut(10..5); + } + + #[test] + #[should_panic(expected = "range start is past usize::MAX")] + fn range_start_past_max() { + let vec = internal_node_vec(); + let _ = vec.range(( + std::ops::Bound::Excluded(usize::MAX), + std::ops::Bound::Unbounded, + )); + } + + #[test] + #[should_panic(expected = "range end is past usize::MAX")] + fn range_end_past_max() { + let vec = internal_node_vec(); + let _ = vec.range(0..=usize::MAX); + } } diff --git a/vendor/linesweeper/tests/paperjs.rs b/vendor/linesweeper/tests/paperjs.rs index a7ad9c5a60..5dcc90052d 100644 --- a/vendor/linesweeper/tests/paperjs.rs +++ b/vendor/linesweeper/tests/paperjs.rs @@ -11,8 +11,6 @@ fn main() { } fn paperjs_tests() -> Vec { - let mut tests = Vec::new(); - // Load all test files let test_files = vec![ ("boolean-test/data/intersection.json", "intersection"), @@ -20,15 +18,56 @@ fn paperjs_tests() -> Vec { ("boolean-test/data/subtraction.json", "subtraction"), ]; - for (file_path, op_name) in test_files { - if let Ok(file_tests) = load_test_file(file_path, op_name) { - tests.extend(file_tests); + let mut tests = trials_for(&test_files); + tests.push(Trial::test("load_errors_are_reported", || { + let trials = trials_for(&[("boolean-test/data/missing.json", "missing")]); + let names: Vec<&str> = trials.iter().map(Trial::name).collect(); + if names == ["missing/load"] { + Ok(()) + } else { + Err(format!("expected one failing load trial, got {names:?}").into()) } - } + })); + + // Craft patch (image distance alpha) + tests.push(Trial::test( + "pixmap_distance_counts_coverage", + pixmap_distance_counts_coverage, + )); tests } +fn trials_for(test_files: &[(&str, &str)]) -> Vec { + let mut tests = Vec::new(); + for &(file_path, op_name) in test_files { + match load_test_file(file_path, op_name) { + Ok(file_tests) => tests.extend(file_tests), + Err(e) => { + let message = format!("cannot load {file_path}: {e}"); + tests.push(Trial::test(format!("{op_name}/load"), move || { + Err(message.into()) + })); + } + } + } + tests +} + +// Craft patch (image distance alpha) +/// A filled pixmap and an empty one differ only in alpha: the fill is +/// opaque black and the empty pixmap is transparent black. +fn pixmap_distance_counts_coverage() -> Result<(), Failed> { + let empty = tiny_skia::Pixmap::new(4, 4).ok_or("Failed to create pixmap")?; + let mut filled = empty.clone(); + filled.fill(tiny_skia::Color::BLACK); + let diff = pixmap_distance(&filled, &empty); + if diff != 1.0 { + return Err(format!("pixmap distance {diff}, expected 1").into()); + } + Ok(()) +} + fn load_test_file( file_path: &str, op_name: &str, @@ -151,7 +190,10 @@ fn pixmap_distance(a: &tiny_skia::Pixmap, b: &tiny_skia::Pixmap) -> f32 { let rdiff = ac.red().abs_diff(bc.red()); let gdiff = ac.green().abs_diff(bc.green()); let bdiff = ac.blue().abs_diff(bc.blue()); - diff += rdiff.max(gdiff).max(bdiff) as f32 / 255.0; + // Craft patch (image distance alpha): the shapes are filled black, so a + // covered pixel and an empty one differ only in alpha. + let adiff = ac.alpha().abs_diff(bc.alpha()); + diff += rdiff.max(gdiff).max(bdiff).max(adiff) as f32 / 255.0; } } diff --git a/vendor/linesweeper/tests/regression.rs b/vendor/linesweeper/tests/regression.rs index 4c55b8edaa..461262084a 100644 --- a/vendor/linesweeper/tests/regression.rs +++ b/vendor/linesweeper/tests/regression.rs @@ -12,15 +12,19 @@ fn main() { fn regression_tests() -> Vec { let ws = std::env::var("CARGO_MANIFEST_DIR").unwrap(); - let paths = glob::glob(&format!("{ws}/tests/regression/**/*.txt")).unwrap(); - paths - .into_iter() + // Craft patch (regression glob): a checkout path can hold glob + // metacharacters such as `[`, and a run that finds no inputs is a failure. + let pattern = format!("{}/tests/regression/**/*.txt", glob::Pattern::escape(&ws)); + let trials: Vec = glob::glob(&pattern) + .unwrap() .map(|p| { let p = p.unwrap(); let name = input_path_base(&p).display().to_string(); Trial::test(name, || generate_regression_test(p)) }) - .collect() + .collect(); + assert!(!trials.is_empty(), "no regression inputs under {ws}"); + trials } fn input_path_base(input_path: &Path) -> &Path {