diff --git a/Cargo.lock b/Cargo.lock index bd99b2f64..98c2edccf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4357,6 +4357,7 @@ dependencies = [ "solidcraft-doc", "solidcraft-geom", "solidcraft-kernel", + "solidcraft-sketch", "thiserror 2.0.21", "tiny-skia", "zip", diff --git a/crates/geom/src/paper.rs b/crates/geom/src/paper.rs index 1bd0848cc..119b7dc84 100644 --- a/crates/geom/src/paper.rs +++ b/crates/geom/src/paper.rs @@ -55,7 +55,7 @@ pub mod grid; pub mod text; pub use flatten::flatten; -pub use grid::{Grid, GridGroup, GridItem, GridPath, GridPoint, GridReport, OnGrid, Piece}; +pub use grid::{FillRule, Grid, GridGroup, GridItem, GridPath, GridPoint, GridReport, OnGrid, Paint, Piece}; use text::{Font, TextRun}; /// The widest line a scene may draw, in millimetres. diff --git a/crates/geom/src/paper/grid.rs b/crates/geom/src/paper/grid.rs index cac72a763..94d7eaf17 100644 --- a/crates/geom/src/paper/grid.rs +++ b/crates/geom/src/paper/grid.rs @@ -10,6 +10,10 @@ //! - A width under half a step is one step, and is counted. //! - Circular arcs come in pieces of at most a quarter turn ([`arc_pieces`]). Ellipses, hyperbolas //! and Béziers above degree 3 aren't walked yet (A3b): a scene with one is refused. +//! - A text run is its glyphs' outlines as the run places them +//! ([`super::text::TextRun::outlines`]), each loop walked as a fill's, filled nonzero (B2). It +//! keeps its item's place in the group, so a writer that sets real text (PDF) finds the run in +//! paint order. use super::{Invalid, Item, ObjectKind, Picture, Prepared, Result, arc_pieces}; use crate::{Seg2, Vec2}; @@ -108,6 +112,42 @@ pub enum GridItem { Fill { loops: Vec }, /// A picture as the scene has it: its pixels are placed by [`crate::pixel_grid`], not this grid. Picture(Picture), + /// A text run's glyph outlines, each loop closed, filled nonzero; `item` is the run's index + /// among its group's items. + Text { item: usize, loops: Vec }, +} + +/// How a writer paints an item on the grid ([`GridItem::paint`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Paint<'a> { + /// A line `width` steps wide along `path`. + Stroke { width: i64, path: &'a GridPath }, + /// Closed loops filled solid, by `rule`. + Fill { loops: &'a [GridPath], rule: FillRule }, + /// A picture, placed by [`crate::pixel_grid`]. + Picture(&'a Picture), +} + +/// Which parts of a fill's loops are inside. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FillRule { + /// Where the loops are crossed an odd number of times: the scene's fills, whose holes are loops. + EvenOdd, + /// Where they wind round at all: glyph outlines, whose contours may overlap. + NonZero, +} + +impl GridItem { + /// How a writer paints it: a text run fills its loops as a fill does, by another rule, so no + /// writer tells the two apart but one that sets real text (PDF). + pub fn paint(&self) -> Paint<'_> { + match self { + GridItem::Stroke { width, path } => Paint::Stroke { width: *width, path }, + GridItem::Fill { loops } => Paint::Fill { loops, rule: FillRule::EvenOdd }, + GridItem::Text { loops, .. } => Paint::Fill { loops, rule: FillRule::NonZero }, + GridItem::Picture(picture) => Paint::Picture(picture), + } + } } /// A group's items on the grid, in paint order. @@ -142,7 +182,7 @@ impl Prepared<'_> { let mut groups = Vec::with_capacity(self.groups().len()); for group in self.groups() { let mut items = Vec::with_capacity(group.items.len()); - for item in &group.items { + for (at, item) in group.items.iter().enumerate() { match item { Item::Stroke { path, closed, width_mm } => { let Some(path) = walk(grid, path, *closed, &mut report)? else { continue }; @@ -160,8 +200,16 @@ impl Prepared<'_> { } items.push(GridItem::Fill { loops }); } - Item::Text(_) => return Err(Invalid("not supported yet: text in an SVG or a sheet PNG (#4890 B2)")), Item::Picture(picture) => items.push(GridItem::Picture(*picture)), + Item::Text(run) => { + // `validate` holds every run's font in the scene. + let font = self.font(run).ok_or(Invalid("a run's font is in the scene's table"))?; + let mut loops = Vec::new(); + for l in run.outlines(font) { + loops.extend(walk(grid, &l.segs, true, &mut report)?); + } + items.push(GridItem::Text { item: at, loops }); + } } } groups.push(GridGroup { object: group.object, kind: group.kind, items }); diff --git a/crates/geom/src/paper_tests.rs b/crates/geom/src/paper_tests.rs index 27c1421b1..72068f1d4 100644 --- a/crates/geom/src/paper_tests.rs +++ b/crates/geom/src/paper_tests.rs @@ -345,6 +345,77 @@ fn a_scene_on_the_grid_keeps_y_up_and_leaves_the_closing_line_to_the_writer() { assert_eq!(on.report, GridReport::default()); } +/// "AA" in a made-up font whose glyph is a 500 x 700 unit box: 3.5 mm capitals from (20, 30), +/// turned a quarter and leaning 0.2. +fn boxed_text() -> (text::TextRun, text::Font) { + let metrics = text::FontMetrics { + ascent: 900, + descent: -200, + cap_height: 700, + bbox: [0, 0, 500, 700], + italic_angle: 0.0, + flags: text::FontFlags::default(), + stem_v: 80, + }; + let glyph = text::FontGlyph { advance: 600, outline: vec![rectangle(p(0.0, 0.0), p(500.0, 700.0))] }; + let font = text::Font { + id: [1; 32], + bytes: std::sync::Arc::from(vec![1u8]), + face: 0, + postscript_name: "MadeUp".into(), + family: "Made Up".into(), + embed: text::Embed::Subset, + num_glyphs: 2, + units_per_em: 1000, + metrics, + glyphs: [(1, glyph)].into(), + }; + let placed = |x: f64| text::PlacedGlyph { id: 1, x, rise: 0.0, advance: 3.0 }; + let run = text::TextRun { + font: [1; 32], + scale: 0.005, + origin: p(20.0, 30.0), + angle: FRAC_PI_2, + slant: 0.2, + glyphs: vec![placed(0.0), placed(3.0)], + text: "AA".into(), + clusters: vec![text::Cluster { glyphs: 0..1, text: 0..1 }, text::Cluster { glyphs: 1..2, text: 1..2 }], + rtl: false, + }; + (run, font) +} + +/// A text run on the grid is its glyphs' outlines as the run places them, each loop walked as a +/// fill's, and keeps its place among its group's items; a writer paints it as a fill, nonzero. +#[test] +fn text_on_the_grid_is_its_placed_outlines() { + let (run, font) = boxed_text(); + let outlines: Vec = run.outlines(&font).collect(); + let scene = Scene { fonts: vec![font], ..sheet(vec![stroke(vec![line(p(0.0, 0.0), p(5.0, 0.0))], false, 0.35), Item::Text(run)]) }; + let on = scene.prepare().unwrap().on_grid(Grid::NANOMETRE).unwrap(); + let GridItem::Text { item, loops } = &on.groups[0].items[1] else { panic!("{:?}", on.groups[0].items[1]) }; + assert_eq!(*item, 1); + // By hand, the first glyph's box: (0, 0) at the origin; along the baseline (x + 0.2 y) * 0.005 mm + // and up y * 0.005 mm, turned a quarter, so along is up the page and up is to the left. + let g = |x: f64, y: f64| Grid::NANOMETRE.point(p(x, y)).unwrap(); + let lines = |points: &[GridPoint]| points.iter().map(|&to| Piece::Line { to }).collect::>(); + let first = GridPath { start: g(20.0, 30.0), pieces: lines(&[g(20.0, 32.5), g(16.5, 33.2), g(16.5, 30.7)]), closed: true }; + assert_eq!((loops.len(), &loops[0]), (2, &first)); + // The same loops a fill of the placed outlines gives. + let filled = sheet(outlines.into_iter().map(|l| fill(l, vec![])).collect()).prepare().unwrap().on_grid(Grid::NANOMETRE).unwrap(); + let walked: Vec = filled.groups[0] + .items + .iter() + .flat_map(|i| match i { + GridItem::Fill { loops } => loops.clone(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(*loops, walked); + assert_eq!(on.groups[0].items[1].paint(), Paint::Fill { loops, rule: FillRule::NonZero }); + assert_eq!(filled.groups[0].items[0].paint(), Paint::Fill { loops: &walked[..1], rule: FillRule::EvenOdd }); +} + /// Slivers are measured in the grid's own steps: a 5 mm piece goes straight on to the next on a /// 1 mm grid, and stays on the nanometre grid. An arc's quarters keep its radius and turn, in /// steps; a width under half a step is one step. A curve the walk can't take yet is refused. diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index e44b1c615..5ba521aca 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -42,3 +42,6 @@ rustix = { version = "1", default-features = false, features = ["std", "fs"] } # The computer's name for a design's lock file (src/design_lock.rs; the browser keeps no lock files). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] gethostname = { workspace = true } + +[dev-dependencies] +solidcraft-sketch = { workspace = true } diff --git a/crates/io/src/paper/png.rs b/crates/io/src/paper/png.rs index 4f24e71c7..c161c3784 100644 --- a/crates/io/src/paper/png.rs +++ b/crates/io/src/paper/png.rs @@ -127,6 +127,7 @@ fn write(scene: &Prepared, options: PngOptions, pictures: &dyn Pictures, out: im shapes.extend(builder.finish().map(Shape::EvenOdd)); } GridItem::Picture(picture) => shapes.extend(grid.window(picture.rect).map(|window| Shape::Picture(*picture, window))), + GridItem::Text { .. } => return Err(IoError::Invalid("not supported yet: text in a sheet PNG (#4890 B2)".into())), } } let png_error = |e: png::EncodingError| IoError::Invalid(format!("the sheet PNG: {e}")); diff --git a/crates/io/src/paper/png_tests.rs b/crates/io/src/paper/png_tests.rs index 61a78d3af..db5a3e84d 100644 --- a/crates/io/src/paper/png_tests.rs +++ b/crates/io/src/paper/png_tests.rs @@ -242,8 +242,8 @@ fn bands_change_nothing_and_the_bytes_repeat() { } } -/// Out of range resolutions, a curve the walk can't take yet, and more points than the cap are -/// refused, never drawn some other way. +/// Out of range resolutions, a curve the walk can't take yet, text (B2b) and more points than the +/// cap are refused, never drawn some other way. #[test] fn what_cannot_be_drawn_is_refused() { let prepared_small = small(); @@ -261,6 +261,11 @@ fn what_cannot_be_drawn_is_refused() { ); let e = paper_png(&ellipse.prepare().unwrap(), PngOptions::default(), &NoPictures, Vec::new()).unwrap_err(); assert!(e.to_string().contains("not supported yet"), "{e}"); + let style = solidcraft_sketch::TextStyle::default(); + let (runs, fonts) = solidcraft_sketch::paper_text("A", None, "", p(2.0, 2.0), 3.5, 0.0, &style).unwrap().unwrap(); + let text = Scene { fonts, ..scene(p(20.0, 10.0), runs.into_iter().map(Item::Text).collect()) }; + let e = paper_png(&text.prepare().unwrap(), PngOptions::default(), &NoPictures, Vec::new()).unwrap_err(); + assert!(e.to_string().contains("not supported yet: text in a sheet PNG"), "{e}"); // 1,000 circles of 100 m at 2400 dpi, each about 19,000 points: over 2^24 in all. A small sheet, // so a cap that failed would cost seconds, not hours. let big = Loop2::circle(p(0.0, 0.0), 1e5); diff --git a/crates/io/src/paper/svg.rs b/crates/io/src/paper/svg.rs index c3b5b08d1..9469b0dae 100644 --- a/crates/io/src/paper/svg.rs +++ b/crates/io/src/paper/svg.rs @@ -10,7 +10,9 @@ //! - **Curves:** lines `L`, circular arcs `A` in the grid's pieces of at most a quarter turn (a half //! turn's centre is ill-conditioned once its ends are rounded), cubics `C`, parabolas `Q`. //! - **Paint:** strokes `stroke-width`, with butt caps, miter joins and a miter limit of 4 on the -//! root; fills black, even-odd. One `` per item, so each stays one object in an editor. +//! root; fills black, even-odd. Text is its glyph outlines, one `` a run, filled black +//! nonzero (SVG's default), so it looks the same without the font and never reflows. One `` +//! per item, so each stays one object in an editor. //! - **Groups** are ``: object ids repeat and start with a digit, //! so they can't be XML ids. No background: the page stays transparent, as cutters want. //! - **Pictures** (#5624 S5) are ``s holding a PNG as a data URI, on their own pixel grid @@ -19,7 +21,7 @@ use std::fmt::Write; -use solidcraft_geom::paper::{Grid, GridItem, GridPath, GridPoint, GridReport, Picture, Pictures, Piece, Prepared}; +use solidcraft_geom::paper::{FillRule, Grid, GridPath, GridPoint, GridReport, Paint, Picture, Pictures, Piece, Prepared}; use solidcraft_geom::{Aabb2, Vec2}; use super::png::{PICTURE_DPI, picture_png}; @@ -47,18 +49,20 @@ pub fn paper_svg(scene: &Prepared, pictures: &dyn Pictures, picture_dpi: f64) -> let kind = serde_json::to_value(group.kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); let _ = writeln!(w.out, "", group.object); for item in &group.items { - match item { - GridItem::Stroke { width, path } => { + match item.paint() { + Paint::Stroke { width, path } => { w.out.push_str(" { - w.out.push_str(" { + // Nonzero is SVG's default. + let rule = if rule == FillRule::EvenOdd { " fill-rule=\"evenodd\"" } else { "" }; + let _ = write!(w.out, " { + Paint::Picture(picture) => { let sheet = Aabb2 { min: Vec2::new(0.0, 0.0), max: scene.size_mm() }; if !w.picture(picture, sheet, picture_dpi, pictures)? { continue; diff --git a/crates/io/src/paper/svg_tests.rs b/crates/io/src/paper/svg_tests.rs index 6cd19a82c..811f945ad 100644 --- a/crates/io/src/paper/svg_tests.rs +++ b/crates/io/src/paper/svg_tests.rs @@ -165,9 +165,9 @@ fn the_svg_reader_reads_it_back() { assert!(c.dist(p(50.0, 50.0)) < 3e-6 && a.dist(p(60.0, 50.0)) < 3e-6 && b.dist(p(50.0, 60.0)) < 3e-6, "{:?}", arcs[0]); } -/// Text isn't written yet (B2): a scene with a run is refused by name, never written without it. +/// Text is its glyph outlines, one path a run, filled black with SVG's default nonzero rule. #[test] -fn text_is_refused_by_name_until_the_writer_learns_it() { +fn text_is_its_outlines_filled_black_nonzero() { use solidcraft_geom::paper::text::{Cluster, Embed, Font, FontFlags, FontGlyph, FontMetrics, PlacedGlyph, TextRun}; let metrics = FontMetrics { ascent: 900, @@ -202,9 +202,30 @@ fn text_is_refused_by_name_until_the_writer_learns_it() { clusters: vec![Cluster { glyphs: 0..1, text: 0..1 }], rtl: false, }; + let outlines: Vec = run.outlines(&font).collect(); let scene = Scene { fonts: vec![font], ..sheet(vec![Item::Text(run)]) }; - let refusal = paper_svg(&scene.prepare().unwrap(), &NoPictures, 300.0).unwrap_err().to_string(); - assert!(refusal.contains("not supported yet: text in an SVG"), "{refusal}"); + let (text, _) = svg(&scene); + assert_eq!(text.matches(" 0 && text.matches('M').count() == loops && text.matches('Z').count() == loops, "{line}: {text}"); + } } fn picture(source: u64, min: Vec2, max: Vec2, opacity: f64) -> Item {