From 508cc39fd04e38f5236a1e6f5be3bef5c2ff71d9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:10:21 -0800 Subject: [PATCH] Preserve PDF sweep limits and narrow geometry --- crates/prepress/src/flatten/compose.rs | 63 +++++++++++++++-------- crates/prepress/src/flatten/document.rs | 25 +++++++-- crates/prepress/src/flatten/mod.rs | 10 ++-- crates/prepress/src/flatten/pdf.rs | 34 ++++++------ crates/prepress/src/flatten/raster.rs | 16 ++++-- crates/prepress/tests/flatten_document.rs | 35 +++++++++++++ vendor/linesweeper/README.craft.md | 7 ++- vendor/linesweeper/SOURCE.json | 9 ++-- vendor/linesweeper/src/curve/line.rs | 17 ++++++ vendor/linesweeper/src/lib.rs | 29 ++++++++++- 10 files changed, 190 insertions(+), 55 deletions(-) diff --git a/crates/prepress/src/flatten/compose.rs b/crates/prepress/src/flatten/compose.rs index 168fa4113a..7ba7b8fdf4 100644 --- a/crates/prepress/src/flatten/compose.rs +++ b/crates/prepress/src/flatten/compose.rs @@ -30,6 +30,13 @@ use super::{BlendMode, DisplayList, FillItem, FillRule, GroupItem, Item, Paint}; use crate::ink::{InkColor, InkId, InkSet, Overprint, Process}; /// How [`flatten`] cuts transparent art. +/// +/// `FlattenOptions` can be initialized with its three fields: +/// +/// ``` +/// use craft_prepress::flatten::FlattenOptions; +/// let options = FlattenOptions { sliver: 0.01, max_regions: 5000, raster_dpi: 300.0 }; +/// ``` #[derive(Clone, Copy, Debug, PartialEq)] pub struct FlattenOptions { /// Regions narrower than this (in points) are dropped ([`geom::regions_with`]). @@ -39,26 +46,31 @@ pub struct FlattenOptions { pub max_regions: usize, /// The resolution complex regions are rasterized at ([`raster`](super::raster)). pub raster_dpi: f32, - /// The most work the region sweep of one group may do before the group goes to - /// [`Flattened::complex`] whole as [`ComplexReason::Degenerate`] - /// ([`geom::DEFAULT_MAX_SWEEP_WORK`]). - pub max_sweep_work: u64, - /// The most output the region sweep of one group may hold before the group goes to - /// [`Flattened::complex`] whole as [`ComplexReason::Degenerate`] - /// ([`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]). - pub max_sweep_units: usize, } impl Default for FlattenOptions { fn default() -> Self { // VectorCraft's medium preset (balance 75) allows 10^(75/20), about 5600 regions. - Self { - sliver: geom::DEFAULT_SLIVER, - max_regions: 5000, - raster_dpi: 300.0, - max_sweep_work: geom::DEFAULT_MAX_SWEEP_WORK, - max_sweep_units: geom::DEFAULT_MAX_TOPOLOGY_UNITS, - } + Self { sliver: geom::DEFAULT_SLIVER, max_regions: 5000, raster_dpi: 300.0 } + } +} + +/// These limits bound the region sweep used by [`flatten_with_limits`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FlattenSweepLimits { + /// The region sweep of one group stops after this many work units. The group then goes to + /// [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. The default is + /// [`geom::DEFAULT_MAX_SWEEP_WORK`]. + pub max_sweep_work: u64, + /// The region sweep of one group stops before holding more than this many output units. + /// The group then goes to [`Flattened::complex`] whole as [`ComplexReason::Degenerate`]. + /// The default is [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]. + pub max_sweep_units: usize, +} + +impl Default for FlattenSweepLimits { + fn default() -> Self { + Self { max_sweep_work: geom::DEFAULT_MAX_SWEEP_WORK, max_sweep_units: geom::DEFAULT_MAX_TOPOLOGY_UNITS } } } @@ -146,6 +158,11 @@ pub enum FlattenError { /// an item that does come back unchanged, and so do opaque items with no transparency painted /// above them where they paint. pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result { + flatten_with_limits(list, opts, &FlattenSweepLimits::default()) +} + +/// `flatten_with_limits` flattens `list` using `opts` and the region sweep `limits`. +pub fn flatten_with_limits(list: &DisplayList, opts: &FlattenOptions, limits: &FlattenSweepLimits) -> Result { let nan = Rect::new(f64::NAN, f64::NAN, f64::NAN, f64::NAN); let bounds: Vec = list.items.iter().map(|i| bounds(i).unwrap_or(nan)).collect(); let transparent: Vec = list.items.iter().map(is_transparent).collect(); @@ -179,7 +196,7 @@ pub fn flatten(list: &DisplayList, opts: &FlattenOptions) -> Result {} - Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, &mut out)?, + Plan::Emit(g) => flatten_group(list, &members[g], &bounds, &transparent, opts, limits, &mut out)?, } } out.report.complex_regions = out.complex.len(); @@ -192,6 +209,7 @@ fn flatten_group( bounds: &[Rect], transparent: &[bool], opts: &FlattenOptions, + limits: &FlattenSweepLimits, out: &mut Flattened, ) -> Result<(), FlattenError> { let mut b = Builder::new(&list.inks); @@ -220,7 +238,7 @@ fn flatten_group( out.report.flattened += members.len(); return Ok(()); } - let regions = match geom::regions_with_limits(&b.shapes, &b.clips, opts.sliver, opts.max_sweep_work, opts.max_sweep_units) { + let regions = match geom::regions_with_limits(&b.shapes, &b.clips, opts.sliver, limits.max_sweep_work, limits.max_sweep_units) { Ok(r) => r, Err(GeomError::Degenerate) => { // Each member's box is clear of every other group's items. @@ -1072,11 +1090,12 @@ mod tests { ); assert!(flat(&l).report.complex_groups.is_empty()); - for opts in - [FlattenOptions { max_sweep_work: 1, ..FlattenOptions::default() }, FlattenOptions { max_sweep_units: 1, ..FlattenOptions::default() }] - { - let f = flatten(&l, &opts).unwrap(); - assert_eq!(f.report.complex_groups, [ComplexGroup { items: vec![0, 1], reason: ComplexReason::Degenerate }], "{opts:?}"); + for limits in [ + FlattenSweepLimits { max_sweep_work: 1, ..FlattenSweepLimits::default() }, + FlattenSweepLimits { max_sweep_units: 1, ..FlattenSweepLimits::default() }, + ] { + let f = flatten_with_limits(&l, &FlattenOptions::default(), &limits).unwrap(); + assert_eq!(f.report.complex_groups, [ComplexGroup { items: vec![0, 1], reason: ComplexReason::Degenerate }], "{limits:?}"); } } } diff --git a/crates/prepress/src/flatten/document.rs b/crates/prepress/src/flatten/document.rs index 95ef200604..a09f75f9bb 100644 --- a/crates/prepress/src/flatten/document.rs +++ b/crates/prepress/src/flatten/document.rs @@ -42,7 +42,7 @@ use kurbo::Rect; use super::pdf::{ReadColor, ReadError, ReadOptions, read_color, read_page_in}; use super::raster::{FlattenPageReport, Rasterizer}; use super::write::{FontMap, WriteError, write_flattened_with_fonts}; -use super::{DisplayList, FlattenError, FlattenOptions, flatten}; +use super::{DisplayList, FlattenError, FlattenOptions, FlattenSweepLimits, flatten_with_limits}; use crate::cms::CmsConversion; use crate::plates::{self, Fallback, pdf_text}; @@ -175,7 +175,16 @@ pub enum FlattenDocumentError { /// `pdf` with the transparency of every page in [`FlattenDocumentOptions::pages`] flattened, as /// one PDF. See the module docs for what carries over. pub fn flatten_document(pdf: &[u8], opts: &FlattenDocumentOptions) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { - flatten_document_with_progress(pdf, opts, &mut |_, _| {}) + flatten_document_with_limits(pdf, opts, &FlattenSweepLimits::default()) +} + +/// [`flatten_document`] with explicit sweep work and output limits. +pub fn flatten_document_with_limits( + pdf: &[u8], + opts: &FlattenDocumentOptions, + limits: &FlattenSweepLimits, +) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { + flatten_document_with_limits_and_progress(pdf, opts, limits, &mut |_, _| {}) } /// [`flatten_document`], calling `progress(done, total)` after each page. @@ -183,6 +192,16 @@ pub fn flatten_document_with_progress( pdf: &[u8], opts: &FlattenDocumentOptions, progress: &mut dyn FnMut(usize, usize), +) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { + flatten_document_with_limits_and_progress(pdf, opts, &FlattenSweepLimits::default(), progress) +} + +/// [`flatten_document_with_limits`], calling `progress(done, total)` after each page. +pub fn flatten_document_with_limits_and_progress( + pdf: &[u8], + opts: &FlattenDocumentOptions, + limits: &FlattenSweepLimits, + progress: &mut dyn FnMut(usize, usize), ) -> Result<(Vec, FlattenDocumentReport), FlattenDocumentError> { let doc = Arc::new(open_slice(pdf, None)?); let count = doc.pages().len(); @@ -215,7 +234,7 @@ pub fn flatten_document_with_progress( let p = doc.pages().get(page).ok_or(FlattenDocumentError::Read { page, source: ReadError::NoPage(page) })?; match read_page_in(&doc, page, &opts.read, color.read.clone()) { Ok((list, read)) => { - let flat = flatten(&list, &opts.flatten).map_err(|source| FlattenDocumentError::Flatten { page, source })?; + let flat = flatten_with_limits(&list, &opts.flatten, limits).map_err(|source| FlattenDocumentError::Flatten { page, source })?; let mut raster = Rasterizer::new(&list, color.settings.clone(), color.condition.clone(), &color.cms, opts.flatten.raster_dpi); let at = |source| FlattenDocumentError::Write { page, source }; let settings = page_settings(p, list.page).ok_or(at(WriteError::Page))?; diff --git a/crates/prepress/src/flatten/mod.rs b/crates/prepress/src/flatten/mod.rs index 2a657a6701..7755eb0fe9 100644 --- a/crates/prepress/src/flatten/mod.rs +++ b/crates/prepress/src/flatten/mod.rs @@ -14,12 +14,16 @@ use kurbo::{Affine, BezPath, Point, Rect}; use crate::ink::{InkColor, InkId, InkSet, Overprint}; -pub use compose::{ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, Flattened, flatten}; +pub use compose::{ + ComplexGroup, ComplexReason, ComplexRegion, FlattenError, FlattenOptions, FlattenReport, FlattenSweepLimits, Flattened, flatten, + flatten_with_limits, +}; pub use document::{ - FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_progress, + FlattenDocumentError, FlattenDocumentOptions, FlattenDocumentReport, FlattenTotals, Unreadable, flatten_document, flatten_document_with_limits, + flatten_document_with_limits_and_progress, flatten_document_with_progress, }; pub use geom::FillRule; -pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page}; +pub use raster::{FlattenPageError, FlattenPageOptions, FlattenPageReport, flatten_page, flatten_page_with_limits}; mod compose; mod document; diff --git a/crates/prepress/src/flatten/pdf.rs b/crates/prepress/src/flatten/pdf.rs index f1a69803a8..61cac2960b 100644 --- a/crates/prepress/src/flatten/pdf.rs +++ b/crates/prepress/src/flatten/pdf.rs @@ -1320,9 +1320,8 @@ fn dash_pattern(path: &BezPath, dashes: &[f32]) -> Option> { /// `path` filled by `rule`, as a path and the rule it is filled by. An even-odd path is /// rebuilt from its boundary as a path filled nonzero; if that fails, panics, or passes the /// flattener's default sweep work or output limit ([`geom::DEFAULT_MAX_SWEEP_WORK`], -/// [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]), it is kept closed and filled even-odd. A subpath too -/// small for the tolerance that the path's largest coordinate needs is rebuilt at that tolerance, -/// and may be dropped. +/// [`geom::DEFAULT_MAX_TOPOLOGY_UNITS`]), it is kept closed and filled even-odd. The same fallback +/// applies when an input subpath fails [`linesweeper::binary_op`]'s automatic-accuracy check. fn nonzero(path: &BezPath, rule: FillRule) -> (BezPath, FillRule) { nonzero_within(path, rule, geom::DEFAULT_MAX_SWEEP_WORK, geom::DEFAULT_MAX_TOPOLOGY_UNITS) } @@ -1335,7 +1334,8 @@ fn nonzero_within(path: &BezPath, rule: FillRule, work_limit: u64, output_limit: } let closed = closed(path); let op = catch_unwind(AssertUnwindSafe(|| { - let top = linesweeper::topology::Topology::::from_paths_with_limits([(&closed, ())], sweep_eps(&closed), work_limit, output_limit)?; + let eps = linesweeper::binary_op_accuracy(&closed, &BezPath::new())?; + let top = linesweeper::topology::Topology::::from_paths_with_limits([(&closed, ())], eps, work_limit, output_limit)?; top.try_contours(|winding| winding % 2 != 0) })); match op { @@ -1350,15 +1350,6 @@ fn nonzero_within(path: &BezPath, rule: FillRule, work_limit: u64, output_limit: } } -/// The sweep tolerance [`linesweeper::binary_op`] picks for `path`: 64 times `f64::EPSILON` -/// times its largest coordinate magnitude, and at least [`linesweeper::MIN_AUTO_EPS`]. -fn sweep_eps(path: &BezPath) -> f64 { - let largest = kurbo::segments(path.iter().skip_while(|el| matches!(el, PathEl::ClosePath))) - .map(|seg| kurbo::ParamCurveExtrema::bounding_box(&seg)) - .fold(0.0_f64, |m, r| m.max(r.x0.abs()).max(r.y0.abs()).max(r.x1.abs()).max(r.y1.abs())); - (largest * f64::EPSILON * 64.0).max(linesweeper::MIN_AUTO_EPS) -} - /// `path` with every subpath closed, as a fill closes them. fn closed(path: &BezPath) -> BezPath { let mut out = BezPath::new(); @@ -1405,13 +1396,22 @@ mod tests { path.line_to((3.0e13 + 1.0e3, 3.0e13)); path.line_to((3.0e13, 3.0e13 + 1.0e3)); path.close_path(); - // linesweeper reports the sliver, and the rebuild runs again at its tolerance. + // The automatic-accuracy check rejects rebuilding the narrow subpath. let swept = linesweeper::binary_op(&path, &BezPath::new(), linesweeper::FillRule::EvenOdd, linesweeper::BinaryOp::Union); assert!(matches!(swept, Err(linesweeper::Error::FeatureBelowTolerance { .. }))); let (out, rule) = nonzero(&path, FillRule::EvenOdd); - assert_eq!(rule, FillRule::NonZero); - assert_ne!(out.winding((10.0, 10.0).into()), 0); - assert_eq!(out.winding((50.0, 50.0).into()), 0); + let contains = |point| { + let winding = out.winding(point); + match rule { + FillRule::EvenOdd => winding % 2 != 0, + FillRule::NonZero => winding != 0, + } + }; + assert!(contains((200.15, 5.0).into()), "the narrow subpath remains filled"); + assert!(contains((10.0, 10.0).into())); + assert!(!contains((50.0, 50.0).into())); + assert_eq!(rule, FillRule::EvenOdd); + assert_eq!(out, path); } #[test] diff --git a/crates/prepress/src/flatten/raster.rs b/crates/prepress/src/flatten/raster.rs index 6ca926d81c..72e9d2075e 100644 --- a/crates/prepress/src/flatten/raster.rs +++ b/crates/prepress/src/flatten/raster.rs @@ -41,7 +41,7 @@ use craft_pdf::interpret::color::CmykConversion; use craft_pdf::write::backend::SerializeSettings; use kurbo::{Affine, Rect, Shape as _}; -use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document}; +use super::document::{FlattenDocumentError, FlattenDocumentOptions, flatten_document_with_limits}; use super::pdf::{ReadError, ReadOptions, ReadReport}; use super::write::{WriteError, page_pdf}; use super::{ @@ -409,11 +409,21 @@ pub enum FlattenPageError { } /// Page `page` (from 0) of `pdf` with its transparency flattened, as a one-page PDF: the -/// one-page case of [`flatten_document`]. +/// one-page case of [`super::flatten_document`]. pub fn flatten_page(pdf: &[u8], page: usize, opts: &FlattenPageOptions) -> Result<(Vec, FlattenPageReport), FlattenPageError> { + flatten_page_with_limits(pdf, page, opts, &super::FlattenSweepLimits::default()) +} + +/// [`flatten_page`] with explicit sweep work and output limits. +pub fn flatten_page_with_limits( + pdf: &[u8], + page: usize, + opts: &FlattenPageOptions, + limits: &super::FlattenSweepLimits, +) -> Result<(Vec, FlattenPageReport), FlattenPageError> { let doc = FlattenDocumentOptions { read: opts.read.clone(), flatten: opts.flatten, pages: Some(page..page.saturating_add(1)), ..Default::default() }; - let (bytes, mut report) = flatten_document(pdf, &doc).map_err(|e| match e { + let (bytes, mut report) = flatten_document_with_limits(pdf, &doc, limits).map_err(|e| match e { FlattenDocumentError::Open(e) => FlattenPageError::Open(e), FlattenDocumentError::PageRange { .. } => FlattenPageError::Read(ReadError::NoPage(page)), FlattenDocumentError::Read { source, .. } => FlattenPageError::Read(source), diff --git a/crates/prepress/tests/flatten_document.rs b/crates/prepress/tests/flatten_document.rs index cd9d14c8df..8cb685f227 100644 --- a/crates/prepress/tests/flatten_document.rs +++ b/crates/prepress/tests/flatten_document.rs @@ -117,6 +117,41 @@ fn opts() -> FlattenDocumentOptions { FlattenDocumentOptions { flatten: FlattenOptions { raster_dpi: 72.0, ..FlattenOptions::default() }, ..FlattenDocumentOptions::default() } } +#[test] +fn pdf_entry_points_keep_explicit_sweep_limits() { + use craft_prepress::flatten::{ + FlattenSweepLimits, flatten_document_with_limits, flatten_document_with_limits_and_progress, flatten_page_with_limits, + }; + let settings = SerializeSettings { no_device_cs: false, group_color_space: GroupColorSpace::Cmyk, ..Default::default() }; + let mut writer = Writer::new(settings, Metadata::default()); + let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(200.0, 160.0).unwrap()); + let mut surface = page.surface(); + rect(&mut surface, 20.0, 20.0, 120.0, 100.0, fill(255, 0, 0, 0)); + surface.push_opacity(NormalizedF32::new(0.5).unwrap()); + rect(&mut surface, 70.0, 60.0, 170.0, 130.0, fill(0, 255, 0, 0)); + surface.pop(); + surface.finish(); + page.finish(); + let source = writer.finish().unwrap(); + let options = opts(); + let (_, ordinary) = flatten_document(&source, &options).unwrap(); + assert_eq!(ordinary.totals.complex_groups, 0); + for limits in [FlattenSweepLimits { max_sweep_work: 1, ..Default::default() }, FlattenSweepLimits { max_sweep_units: 1, ..Default::default() }] { + let (_, document) = flatten_document_with_limits(&source, &options, &limits).unwrap(); + assert_eq!(document.totals.complex_groups, 1); + let mut progress = Vec::new(); + let (_, observed) = flatten_document_with_limits_and_progress(&source, &options, &limits, &mut |done, total| { + progress.push((done, total)); + }) + .unwrap(); + assert_eq!(observed, document); + assert_eq!(progress, [(1, 1)]); + let page_options = FlattenPageOptions { flatten: options.flatten, ..Default::default() }; + let (_, page) = flatten_page_with_limits(&source, 0, &page_options, &limits).unwrap(); + assert_eq!(page.flatten.complex_groups.len(), 1); + } +} + fn separate(pdf: &[u8], page: usize) -> Plates { plates(pdf, page, DPI, &Options::default()).unwrap() } diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index 9c9a0c4006..71500847da 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -15,6 +15,8 @@ holds `upstream_revision`. `local_patches` describes each local change. | File | Change | |---|---| +| `src/lib.rs` | `binary_op_accuracy` returns the automatic accuracy and applies `binary_op`'s coordinate and subpath-size checks before a bounded caller constructs its topology. | +| `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`. | @@ -102,7 +104,7 @@ holds `upstream_revision`. `local_patches` describes each local change. | `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 stay unchanged. | +| `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. To take a new linesweeper release, unpack the crates.io package, carry these changes over, regenerate `SOURCE.json`, and run the @@ -157,7 +159,8 @@ cargo clippy --locked --all-targets --all-features -- -D warnings `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 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, and their source files are kept unchanged. The +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. diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index b95fcf19f4..f5d45bfc93 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,6 +8,7 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ + "`binary_op_accuracy` in `src/lib.rs` returns the automatic accuracy and applies the same coordinate and subpath-size checks as `binary_op`. Bounded callers can use the checked accuracy before constructing a topology with work and output limits.", "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.", @@ -15,11 +16,11 @@ "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`.", + "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 stay unchanged.", + "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`.", @@ -112,13 +113,13 @@ { "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": "e7e8b418663092423f41d17d60607eaddf7834cbc4ae1ea7cd7541c603215303" }, - { "path": "src/curve/line.rs", "source_sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e", "source_git_blob": null, "sha256": "27857a923dcaaa1d4f7bf920817b4fea8261c85ba13b03f27494938cd8de53e9" }, + { "path": "src/curve/line.rs", "source_sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e", "source_git_blob": null, "sha256": "01f8d679628c4400dcee1528d426ef371213843a28745fa9e74784d1ff336e5a" }, { "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "16189bba88d1f8c83133a2abfd231d257c73b2d43404d84d45f7bce5bdf56ba6" }, { "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": "24b25da4c07a9361b72b324564e2aaa4c2dd9f7d9a6e27dfb1cb1b3d08104edf" }, { "path": "src/geom.rs", "source_sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08", "source_git_blob": null, "sha256": "67437cea1121c132ec5edd0fe3d1a8384d570a0d5a28e62bc41c5150fccf4961" }, - { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "40541a506b52da3cb17c025b6d7bf2df5152bef5f1c0877b508b7f6a260f0bbd" }, + { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "d4172f01985372bc9bfd2d28946c1567f154f2881354b192303049bd18cc272e" }, { "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": "9f852574f5f5d663962129f492731b119d9feb9dba6887bf2dd6b4bc20c75343" }, { "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "5030efede9c94b5837f70f2eb3e5447dec772ea1aac3800d162d2fb26da0b929" }, diff --git a/vendor/linesweeper/src/curve/line.rs b/vendor/linesweeper/src/curve/line.rs index fd8ad2a30b..36d0e056dd 100644 --- a/vendor/linesweeper/src/curve/line.rs +++ b/vendor/linesweeper/src/curve/line.rs @@ -21,6 +21,9 @@ fn line_at_ys(line: Line, y0: f64, y1: f64) -> (f64, f64) { /// 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 @@ -194,6 +197,20 @@ 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] { diff --git a/vendor/linesweeper/src/lib.rs b/vendor/linesweeper/src/lib.rs index dac08efad0..ee32546b16 100644 --- a/vendor/linesweeper/src/lib.rs +++ b/vendor/linesweeper/src/lib.rs @@ -183,6 +183,15 @@ pub fn binary_op( fill_rule: FillRule, op: BinaryOp, ) -> Result { + let eps = binary_op_accuracy(set_a, set_b)?; + binary_op_with_eps(set_a, set_b, fill_rule, op, eps) +} + +/// Returns the automatic accuracy for [`binary_op`]. Nonfinite coordinates and +/// subpaths that fail that function's feature-size check return its errors. +pub fn binary_op_accuracy(set_a: &kurbo::BezPath, set_b: &kurbo::BezPath) -> Result { + check_coordinates(set_a)?; + check_coordinates(set_b)?; // Find the extremal values, to figure out how much precision we can support. // Craft patch (leading ClosePath): `BezPath::bounding_box` panics on a leading ClosePath. let bounding_box = |path: &kurbo::BezPath| { @@ -226,7 +235,7 @@ pub fn binary_op( return Err(Error::FeatureBelowTolerance { eps }); } } - binary_op_with_eps(set_a, set_b, fill_rule, op, eps) + Ok(eps) } /// The smallest accuracy parameter that [`binary_op`] chooses. @@ -336,6 +345,24 @@ pub fn binary_op_with_eps( #[cfg(test)] mod tests { + #[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;