M7/G4: retype review: tracked letters, outline check cost, poses (#4934)

The lone-glyph rule looks at lines as the outlines lie, before the layout
check splits them, so tracked one-contour letters (L, I, T, H, E) become
type. A shape keeps every glyph and pose it fits exactly, upright first
(an L, and a turned L half round; an I upright or upside down), and the
line around it chooses; a one-glyph line may turn to another candidate
to take the next glyph.

The whole-outline check flattens the shape once per shape, samples every
corner and points twice the tolerance apart, and asks a flat uniform grid
of segments. With Microsoft YaHei loaded: 300 CJK outlines in 350 ms
(1.9 s before), one line in 25 ms. FontDb::outline reuses
outline_uncached, and the compositing test covers knockout_shape.
This commit is contained in:
ruchirguitar
2026-11-18 18:58:52 +05:30
parent 9c9410e3cc
commit 1cffa0b862
4 changed files with 314 additions and 79 deletions
+86 -15
View File
@@ -164,6 +164,9 @@ struct Line {
pieces: Vec<NodeId>,
/// What each piece matched, as `pieces`.
matches: Vec<GlyphMatch>,
/// 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<GlyphMatch>,
text: String,
face: Arc<vectorcraft_text::FontFace>,
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<GlyphMatch> = 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<Line> {
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<Value> {
@@ -394,10 +451,16 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
// 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<u32> = 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<Value> {
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<GlyphMatch> = 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<NodeId> =
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());
}
+59 -6
View File
@@ -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<String> = 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<char> = (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();
}
}