Retype: near matching reuses poses by outline group without comparing again

ranked_near now returns each glyph's outline group with it, and
near_matches reuses the last fitted poses when the group matches instead
of comparing the two outlines again. The outline comparisons all happen
in ranked_near, where each one is charged to the shape's allowance, so
the 50 million and 2 billion limits cover them. A new test counts the
outline comparisons near_matches makes beyond ranking.
This commit is contained in:
dotCooCoo committed 2026-11-30 05:27:38 -08:00
1 parent 3e0a3f6cc7
commit bf562e3717
1 file changed
+46 -11
+46 -11
View File
@@ -537,11 +537,12 @@ impl RetypeIndex {
}
};
let near = self.ranked_near(&s, &mut work);
// The glyph fitted last and its poses: the glyphs drawn alike after it take them.
let mut last: Option<(&Entry, Option<NearPoses>)> = None;
for (_, e) in near {
// The outline fitted last and its poses: the glyphs drawn alike after it take them, with no
// second comparison of their outlines.
let mut last: Option<(usize, Option<NearPoses>)> = None;
for (_, outline, e) in near {
let Some(face) = self.faces.get(e.face) else { continue };
let alike = last.as_ref().filter(|(l, _)| drawn_alike(l, e)).map(|(_, p)| p.clone());
let alike = last.as_ref().filter(|(l, _)| *l == outline).map(|(_, p)| p.clone());
let posed = match alike {
Some(p) => p,
None => {
@@ -559,7 +560,7 @@ impl RetypeIndex {
.filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r)))
.take(MAX_NEAR_POSES);
let p = poses.next().map(|(pose, residual)| (pose, residual, poses.collect()));
last = Some((e, p.clone()));
last = Some((outline, p.clone()));
p
}
};
@@ -597,8 +598,9 @@ impl RetypeIndex {
/// copy; outlines as close come in index order. Ranking a glyph takes one comparison per
/// contour, and one more, from `work`, and comparing its outline with one that hashes alike (at
/// most [`MAX_HASH_CLASHES`] of them) one per element of its outline; once it is spent, the
/// glyphs not yet ranked are left out.
fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> {
/// glyphs not yet ranked are left out. Each glyph comes with its distance and the number of
/// its outline in the list, the same for every glyph drawn alike.
fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, usize, &Entry)> {
let Some(list) = self.buckets.get(&s.contours) else { return vec![] };
let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK);
let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK);
@@ -665,7 +667,7 @@ impl RetypeIndex {
outlines.truncate(NEAR_FITS);
}
outlines.sort_by(order);
outlines.into_iter().flat_map(|(d, glyphs)| glyphs.into_iter().map(move |(_, e)| (d, e))).collect()
outlines.into_iter().enumerate().flat_map(|(k, (d, glyphs))| glyphs.into_iter().map(move |(_, e)| (d, k, e))).collect()
}
}
@@ -689,6 +691,8 @@ fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) {
/// Whether glyphs `a` and `b` are drawn alike: the same outline in font units.
fn drawn_alike(a: &Entry, b: &Entry) -> bool {
#[cfg(test)]
OUTLINES_COMPARED.set(OUTLINES_COMPARED.get() + 1);
a.drawn == b.drawn && a.outline == b.outline
}
@@ -1818,6 +1822,8 @@ fn sample(cs: &[(Vec<PathSeg>, Vec<f64>)], starts: &[Vec<usize>], pick: &[usize]
thread_local! {
/// How many readings [`signatures`] tried on this thread, kept or not.
static READINGS_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many outline comparisons [`drawn_alike`] made on this thread.
static OUTLINES_COMPARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The first reading of `path` (for tests).
@@ -2231,11 +2237,39 @@ mod tests {
assert_eq!(found.len(), alone_found.len() * faces.len());
let mut all = u64::MAX;
let ranked: u64 =
alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, e)| 2 + e.outline.elements().len() as u64).sum();
alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, _, e)| 2 + e.outline.elements().len() as u64).sum();
let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire);
assert_eq!(spent(&index), spent(&alone) + 40 * ranked);
}
#[test]
fn glyphs_drawn_alike_are_not_compared_again_after_ranking() {
// Source Sans 3 Regular and 30 copies of it: ranking compares each copy's outlines with
// the first face's and charges every comparison; fitting reuses the poses by outline and
// compares no outline again.
let db = FontDb::with_font_dirs(vec![]);
let source = db.face("Source Sans 3", "Regular").unwrap();
let mut faces = vec![source.clone()];
for i in 0..30 {
let family = format!("Again {i} Sans");
db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Again{i}Sans-Regular"))).unwrap());
faces.push(db.face(&family, "Regular").unwrap());
}
let gid = source.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap();
let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&source, gid);
let simple = simplified(&shape, 0.05);
let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]);
OUTLINES_COMPARED.set(0);
let mut all = u64::MAX;
let ranked = index.ranked_near(&near_signature(&simple).unwrap(), &mut all);
let in_ranking = OUTLINES_COMPARED.get();
assert!(ranked.len() > faces.len(), "{} ranked", ranked.len());
OUTLINES_COMPARED.set(0);
let found = index.near_matches(&simple, 0.02);
assert!(found.iter().any(|m| m.ch == 'o'), "no o among {} matches", found.len());
assert_eq!(OUTLINES_COMPARED.get(), in_ranking, "outlines compared outside the charged ranking");
}
#[test]
fn outlines_whose_hashes_clash_are_compared_within_the_work_budget() {
// 5,000 glyphs of one square each, moved apart, all given the same outline hash: each is
@@ -2540,8 +2574,9 @@ mod tests {
let ranked = index.ranked_near(&s, &mut all);
assert!(!ranked.is_empty(), "the o is ranked");
// The Greek omicron is drawn as the o: it is also compared with the o's outline.
let compared = |i: usize, e: &Entry| if ranked[..i].iter().any(|(_, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 };
let spent: u64 = ranked.iter().enumerate().map(|(i, (_, e))| 3 + compared(i, e)).sum();
let compared =
|i: usize, e: &Entry| if ranked[..i].iter().any(|(_, _, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 };
let spent: u64 = ranked.iter().enumerate().map(|(i, (_, _, e))| 3 + compared(i, e)).sum();
assert_eq!(u64::MAX - all, spent, "each glyph of two contours takes three, and one per element for each comparison");
// Enough to rank one glyph of two contours and nothing more.
let mut work = 4;