diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index df0d88a489..2ce951f812 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -164,6 +164,9 @@ struct Line { pieces: Vec, /// What each piece matched, as `pieces`. matches: Vec, + /// Every glyph the first piece fits, while the line holds only it: the next glyph may tell + /// which one it is (see [`join`]). + first_cands: Vec, text: String, face: Arc, scale: f64, @@ -224,6 +227,7 @@ impl Line { let mut l = Line { pieces: vec![*first], matches: vec![m.clone()], + first_cands: vec![], text: m.ch.to_string(), face: m.face.clone(), scale: m.scale, @@ -331,11 +335,64 @@ fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0) } -fn new_line(pc: &Piece, m: &GlyphMatch) -> Line { +/// Add shape `pc` to line `l` when one of its candidate glyphs `cands`, in one of its poses, +/// continues it (one shape can be several glyphs, and a glyph that looks the same turned fits in +/// more than one pose). A line of one shape may turn to another of that shape's candidates to take +/// the next one: an L or a turned L half round, an I upright or upside down, and the glyph after it +/// tells which. Whether it was added. +fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool { + let fits = |l: &Line| cands.iter().flat_map(|c| c.poses()).find(|mp| l.continues(pc, mp)); + if let Some(mp) = fits(l) { + l.push(pc.id, &mp); + return true; + } + let (Some(id), [current]) = (l.pieces.first().copied(), l.matches.as_slice()) else { return false }; + let current = current.clone(); + let others: Vec = l + .first_cands + .iter() + .flat_map(|c| c.poses()) + .filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle)) + .collect(); + for fp in others { + let mut turned = reposed(l, id, &fp); + if let Some(mp) = fits(&turned) { + turned.push(pc.id, &mp); + *l = turned; + return true; + } + } + false +} + +/// Line `l`'s group, paint and transparency with glyph `m` (shape `id`) alone on it. +fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Line { + pieces: vec![id], + matches: vec![m.clone()], + first_cands: l.first_cands.clone(), + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: l.appearance.clone(), + parent: l.parent, + opacity: l.opacity, + blend: l.blend, + } +} + +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). +fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { + let m = cands.first()?; + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + Some(Line { pieces: vec![pc.id], matches: vec![m.clone()], + first_cands: cands.to_vec(), text: m.ch.to_string(), face: m.face.clone(), scale: m.scale, @@ -346,7 +403,7 @@ fn new_line(pc: &Piece, m: &GlyphMatch) -> Line { parent: pc.parent, opacity: pc.opacity, blend: pc.blend, - } + }) } fn retype(s: &mut Session, p: &Value) -> Result { @@ -394,10 +451,16 @@ fn retype(s: &mut Session, p: &Value) -> Result { // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; - for m in found.iter().flatten() { - match votes.iter_mut().find(|(f, _)| *f == m.face.id()) { - Some(v) => v.1 += 1, - None => votes.push((m.face.id(), 1)), + for ms in &found { + // Each shape votes once for each face it fits. + let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); + faces.sort_unstable(); + faces.dedup(); + for f in faces { + match votes.iter_mut().find(|(v, _)| *v == f) { + Some(v) => v.1 += 1, + None => votes.push((f, 1)), + } } } let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); @@ -409,26 +472,34 @@ fn retype(s: &mut Session, p: &Value) -> Result { if pc.after_barrier { open = false; } - // Earlier matches win ties: they are the closer fits. - let best = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m); - let Some(m) = best else { + // The shape's candidates in the face most shapes fit (the first such face, as the + // matches come upright and closest first). + let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + if cands.is_empty() { unmatched.push(pc.id); open = false; continue; + } + let joined = match lines.last_mut() { + Some(l) if open => join(l, pc, &cands), + _ => false, }; - match lines.last_mut() { - Some(l) if open && l.continues(pc, m) => l.push(pc.id, m), - _ => lines.push(new_line(pc, m)), + if !joined { + lines.extend(new_line(pc, &cands)); } open = true; } - let mut lines = verified(lines, system_layout, &mut unmatched); // A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is - // what was asked for. + // what was asked for. Lone means alone on its baseline as the outlines lie, before the + // layout check splits lines (tracking and manual kerning split them glyph by glyph). + let lone_pieces: std::collections::HashSet = + lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect(); + let mut lines = verified(lines, system_layout, &mut unmatched); if pieces.len() > 1 { lines.retain(|l| { - let lone = matches!(l.matches.as_slice(), [m] if m.contours == 1); + let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); if lone { unmatched.extend(l.pieces.iter().copied()); } diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 1c8cf5c2f2..98736c5a4f 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -349,15 +349,15 @@ fn a_hidden_or_locked_glyph_stays_an_outline() { #[test] fn an_isolated_or_knockout_group_keeps_its_type_inside() { - for knock in [false, true] { + for case in ["isolate", "knockout", "knockout_shape"] { let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); s.edit("test", |d, _| { let n = d.node_mut(NodeId(g)).unwrap(); - if knock { - n.knockout = vectorcraft_doc::Knockout::On; - } else { - n.isolate = true; + match case { + "isolate" => n.isolate = true, + "knockout" => n.knockout = vectorcraft_doc::Knockout::On, + _ => n.knockout_shape = true, } Ok(()) }) @@ -365,7 +365,7 @@ fn an_isolated_or_knockout_group_keeps_its_type_inside() { s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); let id = r["ids"][0].as_u64().unwrap(); - assert_eq!(children_of(&s, g), vec![id], "knockout {knock}: the group stays, holding the type"); + assert_eq!(children_of(&s, g), vec![id], "{case}: the group stays, holding the type"); } } @@ -465,3 +465,56 @@ fn nothing_retypable_reads_no_font() { let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); assert!(e.contains("(1 checked)"), "the masked shape is reported, and no font was indexed: {e}"); } + +#[test] +fn tracked_one_contour_letters_still_become_type() { + for text in ["LIT", "HELLO", "LIST"] { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30})).unwrap()["id"].as_u64().unwrap(); + let n = text.len() as u64; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": n, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}"); + assert!(texts.len() > 1, "the tracking splits the line: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + +/// How long Retype takes on a few hundred CJK outlines at once (run with `--ignored --nocapture`; +/// skips when no large CJK font is installed). Not a pass/fail budget: it prints. +#[test] +#[ignore = "timing: needs an installed CJK font"] +fn timing_with_hundreds_of_cjk_outlines() { + let db = vectorcraft_text::FontDb::global(); + let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f)) + else { + eprintln!("skipped: no large CJK font installed"); + return; + }; + let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap(); + // 300 common ideographs, ten lines of thirty. + let chars: Vec = (0x4E00u32..).filter_map(char::from_u32).filter(|c| face.covers(*c)).take(300).collect(); + let mut s = session(); + let mut groups = vec![]; + for (i, line) in chars.chunks(30).enumerate() { + let text: String = line.iter().collect(); + groups.push(outlined(&mut s, json!({"x": 20, "y": 40 + 30 * i, "text": text, "size": 20, "font": family, "style": face.style}))); + } + for run in ["cold", "warm"] { + s.execute("select.set", &json!({"ids": groups})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap(); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + let typed: usize = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().chars().count()).sum(); + eprintln!( + "{run}: Retype of {} {family} outlines: {ms:.0} ms → {typed} characters typed, {} unmatched", + chars.len(), + r["unmatched"].as_array().unwrap().len() + ); + s.execute("edit.undo", &json!({})).unwrap(); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 99844220f5..3c2a613b56 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -660,13 +660,7 @@ impl FontDb { if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { return p.clone(); } - let mut pen = FlipPen(BezPath::new()); - if let Some(f) = face.skrifa() - && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) - { - let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); - } - let p = Arc::new(pen.0); + let p = Arc::new(self.outline_uncached(face, gid)); let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner()); if cache.len() >= OUTLINE_CACHE_MAX { cache.clear(); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 5ef5073909..b778ce47dd 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -42,6 +42,8 @@ const OUTLINE_TOLERANCE: f64 = 5e-3; const MAX_OUTLINE_POINTS: usize = 8192; /// Points along an outline past which the whole-outline check gives up (and so rejects). const MAX_CHECKED_POINTS: usize = 65_536; +/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]). +pub const MAX_CANDIDATES: usize = 16; /// How far apart two shapes' spread-to-length ratios may be and still be compared. const INVARIANT_SLACK: f64 = 0.02; @@ -62,6 +64,32 @@ pub struct GlyphMatch { pub residual: f64, /// How many contours the glyph has. pub contours: usize, + /// Other poses the glyph fits the shape in equally (a glyph that looks the same turned). + pub alts: Vec, +} + +/// Where and how a glyph lies: its size, turn and origin. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + /// Document units per font unit. + pub scale: f64, + /// Radians, as [`kurbo::Affine::rotate`] turns. + pub angle: f64, + /// Where the glyph's origin lies. + pub origin: Point, +} + +impl GlyphMatch { + /// This match in each pose it fits: its own first, then [`Self::alts`]. + pub fn poses(&self) -> impl Iterator + '_ { + let own = Pose { scale: self.scale, angle: self.angle, origin: self.origin }; + std::iter::once(own).chain(self.alts.iter().copied()).map(move |p| GlyphMatch { + scale: p.scale, + angle: p.angle, + origin: p.origin, + ..self.clone() + }) + } } /// A shape reduced for matching: points along each contour, centred. @@ -152,8 +180,12 @@ impl RetypeIndex { self.entries.is_empty() } - /// The glyphs `shape` (in document space) is, the closest one per face, closest first; empty - /// when it is no glyph of the indexed faces. + /// The glyphs `shape` (in document space) is: every glyph that fits it exactly, upright ones + /// first, then the closest; empty when it is no glyph of the indexed faces. One shape can be + /// several glyphs: an L, and a turned L (U+A780) turned half round; a u, and an n upside down. + /// A glyph that looks the same turned (an I, an O, a hyphen) also fits in more than one pose: + /// the upright-most comes first and the others are kept in [`GlyphMatch::alts`]. The line + /// around the shape chooses among them. At most [`MAX_CANDIDATES`]. pub fn matches(&self, shape: &BezPath) -> Vec { let variants = signatures(shape, true); let Some(first) = variants.first() else { return vec![] }; @@ -161,53 +193,70 @@ impl RetypeIndex { let lo = first.invariant * (1.0 - INVARIANT_SLACK); let hi = first.invariant * (1.0 + INVARIANT_SLACK); let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); - let mut best: HashMap = HashMap::new(); + let tol = first.spread * OUTLINE_TOLERANCE; + // The shape flattened for the whole-outline check, once, when a glyph first gets that far. + let mut shape_flat: Option> = None; + let mut out: Vec<(usize, GlyphMatch)> = vec![]; for i in list.iter().skip(start) { let Some(e) = self.entries.get(*i) else { continue }; if e.sig.invariant > hi { break; } - // The reading of the shape (its tied starting corners) that fits the glyph best. - let Some((sig, z, residual)) = variants.iter().filter_map(|s| fit(&e.sig, s).map(|(z, r)| (s, z, r))).min_by(|a, b| a.2.total_cmp(&b.2)) - else { - continue; - }; - if residual > TOLERANCE { - continue; - } let Some(face) = self.faces.get(e.face) else { continue }; - // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. - let gc = mul(z, e.sig.centre); - let origin = Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y); - // The samples can step over a detail (a notch between two of them): the whole outline, - // turned onto the shape, must lie on it. - let onto = Affine::new([z.0, z.1, -z.1, z.0, origin.x, origin.y]); - if !outlines_agree(&(onto * e.outline.clone()), shape, sig.spread * OUTLINE_TOLERANCE) { - continue; + // Each reading of the shape (its tied starting corners) that fits the glyph is a pose. + let mut poses: Vec<(Pose, f64)> = vec![]; + for sig in &variants { + let Some((z, residual)) = fit(&e.sig, sig) else { continue }; + if residual > TOLERANCE { + continue; + } + // The glyph's origin is (0, 0) in font units: it lands at centre − z·glyph centre. + let gc = mul(z, e.sig.centre); + let pose = Pose { scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin: Point::new(sig.centre.x - gc.x, sig.centre.y - gc.y) }; + if poses.iter().any(|(p, _)| wrapped(p.angle - pose.angle).abs() < 1e-6) { + continue; + } + // The samples can step over a detail (a notch between two of them): the whole + // outline, turned onto the shape, must lie on it. + let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); + let Some(flat) = flat.as_ref() else { break }; + let onto = Affine::new([z.0, z.1, -z.1, z.0, pose.origin.x, pose.origin.y]); + if !Flat::new(&(onto * e.outline.clone()), tol).is_some_and(|g| g.agrees(flat)) { + continue; + } + poses.push((pose, residual)); } + // The upright-most pose first. + poses.sort_by(|a, b| wrapped(a.0.angle).abs().total_cmp(&wrapped(b.0.angle).abs())); + let Some(((pose, _), rest)) = poses.split_first() else { continue }; + let residual = poses.iter().map(|(_, r)| *r).fold(f64::INFINITY, f64::min); let m = GlyphMatch { face: face.clone(), gid: e.gid, ch: e.ch, - scale: z.0.hypot(z.1), - angle: z.1.atan2(z.0), - origin, + scale: pose.scale, + angle: pose.angle, + origin: pose.origin, residual, contours: e.sig.contours, + alts: rest.iter().map(|(p, _)| *p).collect(), }; - match best.get(&e.face) { - Some(b) if b.residual < m.residual || (b.residual == m.residual && b.ch <= m.ch) => {} - _ => { - best.insert(e.face, m); - } - } + out.push((e.face, m)); } - let mut out: Vec<(usize, GlyphMatch)> = best.into_iter().collect(); - out.sort_by(|a, b| a.1.residual.total_cmp(&b.1.residual).then(a.0.cmp(&b.0))); + let upright = |m: &GlyphMatch| wrapped(m.angle).abs() >= 1e-3; + out.sort_by(|a, b| { + upright(&a.1).cmp(&upright(&b.1)).then(a.1.residual.total_cmp(&b.1.residual)).then(a.0.cmp(&b.0)).then(a.1.ch.cmp(&b.1.ch)) + }); + out.truncate(MAX_CANDIDATES); out.into_iter().map(|(_, m)| m).collect() } } +/// `a` wrapped into −π..π. +fn wrapped(a: f64) -> f64 { + (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI +} + /// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph /// under the lowest character that maps to it. type FaceKeys = Arc>; @@ -308,17 +357,38 @@ fn fit(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> { rel.is_finite().then_some((z, rel)) } -/// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within -/// `tol` of the other? `false` when either is too large to check. -fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { - if !tol.is_finite() || tol <= 0.0 { - return false; - } - let flat = |p: &BezPath| -> Option> { +/// An outline flattened for the whole-outline check: its segments, points along them (every +/// corner, and points twice `tol` apart between corners: a detail narrower than that has corners +/// of its own), and a uniform grid listing each segment under every cell its box, grown by `tol`, +/// touches, so whether a point lies within `tol` of the outline is asked of the few segments +/// around it. +struct Flat { + segs: Vec<(Point, Point)>, + pts: Vec, + origin: Point, + cell: f64, + cols: usize, + rows: usize, + /// Segment indices per cell, row by row. + cells: Vec>, + tol: f64, +} + +impl Flat { + /// Cells along the longer side, at most. + const MAX_SIDE: f64 = 48.0; + /// Segment listings in all, at most: past it (or past [`MAX_OUTLINE_POINTS`] segments or + /// [`MAX_CHECKED_POINTS`] points), `None`, and so no match. + const MAX_LISTINGS: usize = 1 << 18; + + fn new(path: &BezPath, tol: f64) -> Option { + if !tol.is_finite() || tol <= 0.0 { + return None; + } let mut segs = vec![]; let (mut start, mut last) = (Point::ZERO, Point::ZERO); let mut too_many = false; - kurbo::flatten(p.iter(), tol / 4.0, |el| { + kurbo::flatten(path.iter(), tol / 2.0, |el| { if segs.len() > MAX_OUTLINE_POINTS { too_many = true; return; @@ -336,26 +406,73 @@ fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { _ => {} } }); - (!too_many).then_some(segs) - }; - let (Some(sa), Some(sb)) = (flat(a), flat(b)) else { return false }; - let near = |p: Point, segs: &[(Point, Point)]| segs.iter().any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol * tol); - // Points along every edge, not only its ends: two outlines with the same corners joined in - // another order differ between them. Spaced `tol` apart; past the work limit, not a match. - let along = |segs: &[(Point, Point)]| -> Option> { + if too_many { + return None; + } let mut pts = vec![]; - for (s, e) in segs { - let steps = (s.distance(*e) / tol).ceil(); + for (s, e) in &segs { + let steps = (s.distance(*e) / (2.0 * tol)).ceil(); if !steps.is_finite() || pts.len() as f64 + steps > MAX_CHECKED_POINTS as f64 { return None; } let steps = (steps as usize).max(1); pts.extend((0..steps).map(|i| s.lerp(*e, i as f64 / steps as f64))); } - Some(pts) - }; - let (Some(pa), Some(pb)) = (along(&sa), along(&sb)) else { return false }; - pa.iter().all(|p| near(*p, &sb)) && pb.iter().all(|p| near(*p, &sa)) + let (first, _) = segs.first()?; + let mut bb = kurbo::Rect::from_points(*first, *first); + for (s, e) in &segs { + bb = bb.union_pt(*s).union_pt(*e); + } + let bb = bb.inflate(tol, tol); + let cell = (bb.width().max(bb.height()) / Self::MAX_SIDE).max(2.0 * tol); + if !cell.is_finite() || cell <= 0.0 { + return None; + } + let at = |v: f64, o: f64| (((v - o) / cell).floor().max(0.0) as usize).min(Self::MAX_SIDE as usize); + let (cols, rows) = (at(bb.x1, bb.x0) + 1, at(bb.y1, bb.y0) + 1); + let mut cells: Vec> = vec![vec![]; cols * rows]; + let mut listings = 0usize; + for (i, (s, e)) in segs.iter().enumerate() { + let r = kurbo::Rect::from_points(*s, *e).inflate(tol, tol); + for cy in at(r.y0, bb.y0)..=at(r.y1, bb.y0).min(rows - 1) { + for cx in at(r.x0, bb.x0)..=at(r.x1, bb.x0).min(cols - 1) { + listings += 1; + if listings > Self::MAX_LISTINGS { + return None; + } + if let Some(c) = cells.get_mut(cy * cols + cx) { + c.push(u32::try_from(i).ok()?); + } + } + } + } + Some(Flat { segs, pts, origin: Point::new(bb.x0, bb.y0), cell, cols, rows, cells, tol }) + } + + /// Does `p` lie within `tol` of a segment? + fn near(&self, p: Point) -> bool { + let (fx, fy) = ((p.x - self.origin.x) / self.cell, (p.y - self.origin.y) / self.cell); + if !(fx >= 0.0 && fy >= 0.0) || fx >= self.cols as f64 || fy >= self.rows as f64 { + return false; + } + let (cx, cy) = (fx as usize, fy as usize); + let tol2 = self.tol * self.tol; + self.cells.get(cy * self.cols + cx).is_some_and(|list| { + list.iter().filter_map(|i| self.segs.get(*i as usize)).any(|(s, e)| Line::new(*s, *e).nearest(p, 1e-9).distance_sq <= tol2) + }) + } + + /// Do the two outlines lie on each other: every point of each within `tol` of the other? + fn agrees(&self, other: &Flat) -> bool { + self.pts.iter().all(|p| other.near(*p)) && other.pts.iter().all(|p| self.near(*p)) + } +} + +/// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within +/// `tol` of the other? `false` when either is too large to check. +#[cfg(test)] +fn outlines_agree(a: &BezPath, b: &BezPath, tol: f64) -> bool { + matches!((Flat::new(a, tol), Flat::new(b, tol)), (Some(fa), Some(fb)) if fa.agrees(&fb)) } /// `seg` as a line when it is one (a curve with its handles on its ends or on its line), else as it is.