From bcbabf0938e843bf8001cda405331d6937862be9 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 20 Nov 2026 14:11:17 -0700 Subject: [PATCH] feat(text): several lines on a path and editing a text's path with the point commands (M5) --- crates/engine/src/cmds_path.rs | 17 ++- crates/engine/src/cmds_text.rs | 7 +- crates/text/src/lib.rs | 248 ++++++++++++++++++++++++++++++--- src/pathtools.rs | 8 +- 4 files changed, 250 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs index 24a01c68..550e9648 100644 --- a/crates/engine/src/cmds_path.rs +++ b/crates/engine/src/cmds_path.rs @@ -126,7 +126,7 @@ fn draw_freehand(s: &mut Session, p: &Value) -> Result { // ----- point editing ---------------------------------------------------------------------- /// Runs `edit` on shape element `id` (param `id`) in the editable keyframe (copy-on-write), with -/// its transform. The shape of a shape armature is reshaped at rest instead, keeping its binding +/// its transform; on text on a path, on the path the text follows (ADR 0107). The shape of a shape armature is reshaped at rest instead, keeping its binding /// (ADR 0090). fn edit_shape(s: &mut Session, p: &Value, edit: impl FnOnce(&mut Shape, Affine) -> Result) -> Result { let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?); @@ -139,10 +139,23 @@ fn edit_shape(s: &mut Session, p: &Value, edit: impl FnOnce(&mut Shape, Affin let kf = s.editable_keyframe()?; let el: &mut Element = kf.elements_mut_where(|e| e == id).into_iter().next().ok_or_else(|| EngineError::State(format!("no element {}", id.0)))?; let m = el.transform; + // Text on a path: the points of the path it follows (its own copy, ADR 0107). The glyphs + // are set along the edited path, and the block's box moves so nothing else does. + if let ElementKind::Text(t) = &el.kind + && let Some(on) = &t.on_path + { + let mut sh = Shape { path: Arc::new(on.path.clone()), fill: None, stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None }; + let out = edit(&mut sh, m)?; + let block = anicraft_doc::TextBlock { on_path: Some(anicraft_doc::TextPath { path: Path::clone(&sh.path), ..on.clone() }), ..(**t).clone() }; + let (block, _, shift) = crate::cmds_text::lay_out_block(&block)?; + el.transform = m.mul(&Affine::translate(shift.x, shift.y)); + el.kind = ElementKind::Text(Arc::new(block)); + return Ok(out); + } match &mut el.kind { ElementKind::Shape(sh) => edit(sh, m), ElementKind::Symbol { .. } => Err(EngineError::State("symbol instances have no points to edit (double-click to edit the symbol)".into())), - ElementKind::Text(_) => Err(EngineError::State("text has no points to edit; break it apart (Ctrl+B) to edit its outlines".into())), + ElementKind::Text(_) => Err(EngineError::State("text has no points to edit; break it apart (Ctrl+B) to edit its outlines, or attach it to a path and edit the path".into())), ElementKind::Camera => Err(EngineError::State("the camera has no points to edit".into())), ElementKind::Group { .. } => Err(EngineError::State("a group has no points of its own (double-click it to edit what is inside)".into())), } diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index b1b0bc67..a96a7def 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -334,9 +334,10 @@ pub(crate) fn lay_out_block(d: &TextBlock) -> Result<(TextBlock, Option, let (runs, paras, paints) = rich_parts(&d); match (d.field.clone(), d.on_path.clone()) { (_, Some(on)) => { - // One line along the path (line breaks become spaces), anchored by the alignment. - let line: String = d.text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect(); - let l = fonts.layout_rich(&anicraft_text::RichText { text: &line, runs: &runs, paragraphs: &[anicraft_text::ParaStyle::default()], width: None }, true).map_err(layout_err)?; + // Lines along the path (ADR 0107): laid out left-aligned with each paragraph's + // line spacing; the block's alignment anchors every line along the path. + let lines: Vec = paras.iter().map(|q| anicraft_text::ParaStyle { line_spacing: q.line_spacing, ..anicraft_text::ParaStyle::default() }).collect(); + let l = fonts.layout_rich(&anicraft_text::RichText { text: &d.text, runs: &runs, paragraphs: &lines, width: None }, true).map_err(layout_err)?; let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 }; let set = anicraft_text::on_path_boxed(&l.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align: align_text(d.align) }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?; d.width = None; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index d51a7e63..7db09553 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -129,49 +129,170 @@ pub struct PathText { pub pieces: Vec<(u32, Path)>, /// The path's length. pub length: f32, - /// Each shown glyph's character, the point on the path under its middle and its angle + /// Each shown glyph's character, the point of its line's baseline under its middle (on the + /// path for the first line, on the curve parallel to it for further lines) and its angle /// (radians, the direction of travel). pub placed: Vec<(u32, Vec2, f32)>, /// Glyphs whose middle falls past an open path's ends (not drawn, as SVG leaves them). pub hidden: usize, } -/// The glyphs of a one-line layout set along `path`'s first subpath (ADR 0070): each glyph's -/// middle at its distance along the path (measured on the curve itself), the glyph turned to -/// the path's direction there, its baseline on the path, standing on the path's left (above a -/// path drawn left to right; `flip` walks it backwards, onto the other side). On a closed path -/// glyphs wrap round; on an open one those past its ends are left out. `None` when the path has -/// no length. +/// Most lines set along one path; glyphs on lines past it are left out (and counted as hidden). +pub const MAX_PATH_LINES: usize = 64; + +/// Most samples of a path taken to measure a line parallel to it. +const PARALLEL_SAMPLES: usize = 2048; + +/// The curve parallel to a walked path at a distance (ADR 0107): distances along the path +/// against distances along the parallel curve, sampled, so a further line of text is spaced by +/// its own length (tighter inside a bend, wider outside it) and not by the path's. +struct Parallel { + /// The path's length, and the parallel curve's length up to each of `n + 1` even samples. + length: f32, + along: Vec, +} + +impl Parallel { + fn new(length: f32, point: &dyn Fn(f32) -> Vec2) -> Parallel { + let n = ((length * 0.5).ceil() as usize).clamp(16, PARALLEL_SAMPLES); + let mut along = Vec::with_capacity(n + 1); + let (mut sum, mut prev) = (0.0f32, point(0.0)); + along.push(0.0); + for i in 1..=n { + let q = point(length * i as f32 / n as f32); + let d = (q - prev).length(); + if d.is_finite() { + sum += d; + } + along.push(sum); + prev = q; + } + Parallel { length, along } + } + + fn total(&self) -> f32 { + self.along.last().copied().unwrap_or(0.0) + } + + /// The distance along the parallel curve under distance `s` along the path (past the + /// path's ends it carries on at the path's own pace). + fn from_path(&self, s: f32) -> f32 { + let n = self.along.len().saturating_sub(1).max(1); + if s <= 0.0 { + return s; + } + if s >= self.length { + return self.total() + (s - self.length); + } + let f = s / self.length * n as f32; + let i = (f.floor() as usize).min(n - 1); + let (a, b) = (self.along.get(i).copied().unwrap_or(0.0), self.along.get(i + 1).copied().unwrap_or(0.0)); + a + (b - a) * (f - i as f32) + } + + /// The distance along the path over distance `t` along the parallel curve (in range). + fn to_path(&self, t: f32) -> f32 { + let n = self.along.len().saturating_sub(1).max(1); + let i = self.along.partition_point(|l| *l <= t).clamp(1, n); + let (a, b) = (self.along.get(i - 1).copied().unwrap_or(0.0), self.along.get(i).copied().unwrap_or(0.0)); + let f = if b > a { ((t - a) / (b - a)).clamp(0.0, 1.0) } else { 0.0 }; + self.length * ((i - 1) as f32 + f) / n as f32 + } +} + +/// The glyphs of a layout set along `path`'s first subpath (ADR 0070): each glyph's middle at +/// its distance along the path (measured on the curve itself), the glyph turned to the path's +/// direction there, its baseline on the path, standing on the path's left (above a path drawn +/// left to right; `flip` walks it backwards, onto the other side). On a closed path glyphs wrap +/// round; on an open one those past its ends are left out. `None` when the path has no length. +/// +/// Several lines (ADR 0107): glyphs with another baseline are a further line. The first line +/// with glyphs sits on the path; each further line runs parallel to it, its baseline as far +/// from the path as it is from the first line's in the layout, on the side away from the +/// glyphs' tops (below the first line, as lines of text are), and is spaced along that parallel +/// curve. Every line is anchored on its own width at the same place on the path. Lay the text +/// out left-aligned: the placement's alignment anchors the lines. At most [`MAX_PATH_LINES`]. pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Option { let walk = anicraft_geom::walk::CurveWalk::new(path)?; let length = walk.length(); + if !(length.is_finite() && length > 0.0) { + return None; + } let closed = first_subpath_closed(path); - // The run's width: from its pen start (0) to the end of its last glyph. - let width = glyphs.iter().map(|g| g.x + g.advance).filter(|w| w.is_finite()).fold(0.0f32, f32::max); let offset = if how.offset.is_finite() { how.offset.clamp(-1e6, 1e6) } else { 0.0 }; - let start = offset - - match how.align { - Align::Left => 0.0, - Align::Center => width * 0.5, - Align::Right => width, - }; - let mut out = PathText { outline: Path::new(), pieces: Vec::new(), length, placed: Vec::with_capacity(glyphs.len()), hidden: 0 }; + // A point of the path as the text walks it, and its direction there. + let at = |s: f32| -> (Vec2, Vec2) { if how.flip { (walk.at(length - s), walk.tangent(length - s) * -1.0) } else { (walk.at(s), walk.tangent(s)) } }; + // The lines: glyphs come line by line, each line's with one baseline. + let mut lines: Vec<(f32, f32)> = Vec::new(); + let mut line_of: Vec = Vec::with_capacity(glyphs.len()); for g in glyphs { - let mid = start + g.x + g.advance * 0.5; - if !mid.is_finite() { + if lines.last().is_none_or(|l| l.0.to_bits() != g.baseline.to_bits()) { + lines.push((g.baseline, 0.0)); + } + let w = g.x + g.advance; + if let Some(l) = lines.last_mut() + && w.is_finite() + { + l.1 = l.1.max(w); + } + line_of.push(lines.len() - 1); + } + let first = lines.first().map_or(0.0, |l| l.0); + // Each further line's parallel curve (the first line is the path itself). + let parallels: Vec> = lines + .iter() + .take(MAX_PATH_LINES) + .map(|(baseline, _)| { + let d = baseline - first; + (d.is_finite() && d != 0.0).then(|| { + ( + d, + Parallel::new(length, &|s| { + let (p, t) = at(s); + p + Vec2::new(-t.y, t.x) * d + }), + ) + }) + }) + .collect(); + let mut out = PathText { outline: Path::new(), pieces: Vec::new(), length, placed: Vec::with_capacity(glyphs.len()), hidden: 0 }; + for (g, &row) in glyphs.iter().zip(&line_of) { + let (Some(line), Some(parallel)) = (lines.get(row), parallels.get(row)) else { + out.hidden += 1; + continue; + }; + let back = match how.align { + Align::Left => 0.0, + Align::Center => line.1 * 0.5, + Align::Right => line.1, + }; + // Where the glyph's middle is along its line, and how long that line is. + let (anchor, total) = match parallel { + None => (offset, length), + Some((_, par)) => (par.from_path(if closed { offset.rem_euclid(length) } else { offset }), par.total()), + }; + let mid = anchor - back + g.x + g.advance * 0.5; + // A parallel curve squeezed to (almost) nothing, as at a circle's centre, holds no text. + if !mid.is_finite() || !(total.is_finite() && total > length * 0.01) { out.hidden += 1; continue; } - let s = if closed { - mid.rem_euclid(length) - } else if (0.0..=length).contains(&mid) { + let t = if closed { + mid.rem_euclid(total) + } else if (0.0..=total).contains(&mid) { mid } else { out.hidden += 1; continue; }; - let (p, t) = if how.flip { (walk.at(length - s), walk.tangent(length - s) * -1.0) } else { (walk.at(s), walk.tangent(s)) }; - let angle = t.y.atan2(t.x); + let (p, dir) = match parallel { + None => at(t), + Some((d, par)) => { + let (p, dir) = at(par.to_path(t)); + (p + Vec2::new(-dir.y, dir.x) * *d, dir) + } + }; + let angle = dir.y.atan2(dir.x); let m = anicraft_geom::Affine::translate(p.x, p.y).mul(&anicraft_geom::Affine::rotate(angle)).mul(&anicraft_geom::Affine::translate(-g.advance * 0.5, 0.0)); let k = match out.pieces.iter().position(|(paint, _)| *paint == g.paint) { Some(k) => k, @@ -765,6 +886,87 @@ mod tests { assert!(on_path(&boxes(1), &dot, PathPlacement { offset: 0.0, flip: false, align: Align::Left }).is_none()); } + /// Two lines of synthetic glyphs: `n` on the first line and `m` on the second, 30 below. + fn two_lines(n: u32, m: u32) -> Vec { + let mut g = boxes(n); + g.extend((0..m).map(|i| PlacedGlyph { outline: Path::rect(0.0, -20.0, 10.0, 20.0), x: i as f32 * 10.0, baseline: 50.0, advance: 10.0, index: n + 1 + i, paint: 0 })); + g + } + + #[test] + fn further_lines_run_parallel_to_the_path() { + // A straight line: the second line is 30 below the path, spaced as the first. + let mut line = Path::new(); + line.cmds = vec![PathCmd::MoveTo(Vec2::new(0.0, 100.0)), PathCmd::LineTo(Vec2::new(200.0, 100.0))]; + let t = on_path(&two_lines(3, 2), &line, PathPlacement { offset: 20.0, flip: false, align: Align::Left }).unwrap(); + assert_eq!((t.placed.len(), t.hidden), (5, 0)); + let want = [(25.0, 100.0), (35.0, 100.0), (45.0, 100.0), (25.0, 130.0), (35.0, 130.0)]; + for ((i, p, a), (x, y)) in t.placed.iter().zip(want) { + assert!((p.x - x).abs() < 1e-2 && (p.y - y).abs() < 1e-2 && a.abs() < 1e-4, "glyph {i}: {p:?}"); + } + assert_eq!(t.placed.iter().map(|p| p.0).collect::>(), vec![0, 1, 2, 4, 5], "glyph order kept"); + // Each line is anchored on its own width: centred, the shorter line is centred too. + let c = on_path(&two_lines(3, 1), &line, PathPlacement { offset: 100.0, flip: false, align: Align::Center }).unwrap(); + assert!((c.placed[0].1.x - 90.0).abs() < 1e-2 && (c.placed[3].1.x - 100.0).abs() < 1e-2, "{:?}", c.placed); + let r = on_path(&two_lines(3, 1), &line, PathPlacement { offset: 200.0, flip: false, align: Align::Right }).unwrap(); + assert!((r.placed[2].1.x - 195.0).abs() < 1e-2 && (r.placed[3].1.x - 195.0).abs() < 1e-2, "{:?}", r.placed); + // Flipped, the text hangs below the path and its second line is above it. + let f = on_path(&two_lines(1, 1), &line, PathPlacement { offset: 0.0, flip: true, align: Align::Left }).unwrap(); + assert!((f.placed[0].1 - Vec2::new(195.0, 100.0)).length() < 1e-2 && (f.placed[1].1 - Vec2::new(195.0, 70.0)).length() < 1e-2, "{:?}", f.placed); + } + + #[test] + fn a_line_inside_a_circle_is_spaced_on_its_own_circle() { + // Radius 100, drawn clockwise on screen: glyphs stand outside, further lines go inside. + // The second line's baseline is the circle of radius 70, and its glyphs' middles are an + // advance (10) apart along that circle: 10 / 70 of a radian, not 10 / 100. + let circle = Path::ellipse(0.0, 0.0, 100.0, 100.0); + let t = on_path(&two_lines(2, 3), &circle, PathPlacement { offset: 50.0, flip: false, align: Align::Left }).unwrap(); + assert_eq!((t.placed.len(), t.hidden), (5, 0)); + let ang = |p: Vec2| p.y.atan2(p.x); + for (_, p, _) in &t.placed[..2] { + assert!((p.length() - 100.0).abs() < 0.05, "{p:?}"); + } + for (_, p, a) in &t.placed[2..] { + assert!((p.length() - 70.0).abs() < 0.1, "on the inner circle: {p:?}"); + assert!(Vec2::new(a.cos(), a.sin()).dot(*p).abs() < 0.5, "turned along it"); + } + let step = ang(t.placed[3].1) - ang(t.placed[2].1); + assert!((step - 10.0 / 70.0).abs() < 2e-3, "{step}"); + assert!(((ang(t.placed[1].1) - ang(t.placed[0].1)) - 0.1).abs() < 1e-3); + // Both lines start at the same place round the circle: the anchor's radius. + let first_start = ang(t.placed[0].1) - 0.05; + let second_start = ang(t.placed[2].1) - 5.0 / 70.0; + assert!((first_start - second_start).abs() < 2e-3, "{first_start} vs {second_start}"); + // It wraps round its own length. + let w = on_path(&two_lines(1, 60), &circle, PathPlacement { offset: 0.0, flip: false, align: Align::Left }).unwrap(); + assert_eq!(w.hidden, 0, "60 glyphs of 10 wrap round 440"); + // A line whose parallel curve has no length (through the centre) is left out. + let mut g = boxes(1); + g.push(PlacedGlyph { outline: Path::rect(0.0, -20.0, 10.0, 20.0), x: 0.0, baseline: 120.0, advance: 10.0, index: 2, paint: 0 }); + let z = on_path(&g, &circle, PathPlacement { offset: 0.0, flip: false, align: Align::Left }).unwrap(); + assert_eq!((z.placed.len(), z.hidden), (1, 1)); + } + + #[test] + fn lines_past_the_limit_and_hostile_baselines_are_left_out() { + let mut line = Path::new(); + line.cmds = vec![PathCmd::MoveTo(Vec2::new(0.0, 0.0)), PathCmd::LineTo(Vec2::new(500.0, 0.0))]; + let many: Vec = (0..MAX_PATH_LINES as u32 + 5).map(|i| PlacedGlyph { outline: Path::rect(0.0, -2.0, 1.0, 2.0), x: 0.0, baseline: i as f32 * 3.0, advance: 1.0, index: i, paint: 0 }).collect(); + let t = on_path(&many, &line, PathPlacement { offset: 0.0, flip: false, align: Align::Left }).unwrap(); + assert_eq!((t.placed.len(), t.hidden), (MAX_PATH_LINES, 5)); + let bad = vec![ + PlacedGlyph { outline: Path::new(), x: 0.0, baseline: 0.0, advance: 1.0, index: 0, paint: 0 }, + PlacedGlyph { outline: Path::new(), x: 0.0, baseline: f32::NAN, advance: 1.0, index: 1, paint: 0 }, + PlacedGlyph { outline: Path::new(), x: f32::INFINITY, baseline: 1e30, advance: 1.0, index: 2, paint: 0 }, + ]; + let t = on_path(&bad, &line, PathPlacement { offset: f32::NAN, flip: true, align: Align::Right }).unwrap(); + assert!(t.outline.cmds.iter().all(|c| match c { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => p.is_finite(), + _ => true, + })); + } + #[test] fn carets_stand_at_every_boundary_line_by_line() { let Some(fonts) = fonts() else { return }; diff --git a/src/pathtools.rs b/src/pathtools.rs index 95e9c89f..94928082 100644 --- a/src/pathtools.rs +++ b/src/pathtools.rs @@ -515,7 +515,8 @@ pub fn commit_pencil(app: &mut App, xf: Xf) { /// A selected point: element, command, slot. pub type PointRef = (ElementId, usize, u8); -/// Selected shapes on the active layer with their path and transform. +/// Selected shapes on the active layer with their path and transform, and selected text on a +/// path with the path it follows. fn selected_shapes(app: &App) -> Vec<(ElementId, Arc, Affine)> { app.s .visible_elements() @@ -525,7 +526,10 @@ fn selected_shapes(app: &App) -> Vec<(ElementId, Arc, Affine)> { // Raw shapes show their shared points instead (ADR 0042, below). ElementKind::Shape(sh) if sh.merge => None, ElementKind::Shape(sh) => Some((e.id, sh.path.clone(), e.transform)), - ElementKind::Symbol { .. } | ElementKind::Text(_) | ElementKind::Camera | ElementKind::Group { .. } => None, + // Text on a path shows the points of the path it follows (ADR 0107): the same + // point commands edit them, and the glyphs follow. + ElementKind::Text(t) => t.on_path.as_ref().map(|on| (e.id, Arc::new(on.path.clone()), e.transform)), + ElementKind::Symbol { .. } | ElementKind::Camera | ElementKind::Group { .. } => None, }) .take(64) .collect()