From 604c29bc2d00e4cb3227b0b2a54f893a9ac33a54 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 23 Nov 2026 08:02:54 -0500 Subject: [PATCH] Use horizontal font metrics and measured text coverage --- Cargo.lock | 1 + Cargo.toml | 1 + crates/eval/src/tests/font_resource.rs | 65 ++++++++++++++++++++-- crates/nodes/Cargo.toml | 1 + crates/nodes/src/atomic/font.rs | 20 ++++--- crates/nodes/src/atomic/text.rs | 4 +- crates/nodes/src/raster/composite.rs | 36 +++++++++--- crates/nodes/src/raster/mod.rs | 2 +- crates/nodes/tests/atomic_filter_parity.rs | 4 ++ docs/parity-fixes.md | 24 ++++++++ docs/sbs-root-nodes.md | 2 +- 11 files changed, 136 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 18b34d00..e2819ef5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2952,6 +2952,7 @@ dependencies = [ "harfrust 0.13.3", "materialcraft-core", "rayon", + "read-fonts 0.43.3", "unicode-bidi", "vello_cpu", ] diff --git a/Cargo.toml b/Cargo.toml index e663ed63..22e662f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -90,6 +90,7 @@ craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "453b0da7 craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["serde"] } craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", default-features = false } harfrust = "0.13" +read-fonts = { version = "0.43", default-features = false } unicode-bidi = "0.3.18" vello_cpu = { version = "0.2", default-features = false, features = ["std", "u8_pipeline"] } # Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0 diff --git a/crates/eval/src/tests/font_resource.rs b/crates/eval/src/tests/font_resource.rs index 4c7db3fe..ba2061e8 100644 --- a/crates/eval/src/tests/font_resource.rs +++ b/crates/eval/src/tests/font_resource.rs @@ -2,7 +2,7 @@ use super::*; use materialcraft_core::{OutputFormat, Resource, ResourceBytes}; /// A two-glyph TrueType face. U+0041 is a rectangle with a variable cap height. -fn rectangle_font(height: i16) -> Vec { +fn rectangle_font(height: i16, metrics: [i16; 3]) -> Vec { fn words(values: &[i16]) -> Vec { values.iter().flat_map(|value| value.to_be_bytes()).collect() } @@ -21,7 +21,7 @@ fn rectangle_font(height: i16) -> Vec { head[40..44].copy_from_slice(&words(&[512, height])); let mut hhea = vec![0; 36]; hhea[..4].copy_from_slice(&0x10000u32.to_be_bytes()); - hhea[4..12].copy_from_slice(&words(&[768, -256, 0, 640])); + hhea[4..12].copy_from_slice(&words(&[metrics[0], metrics[1], metrics[2], 640])); hhea[34..].copy_from_slice(&2i16.to_be_bytes()); let mut maxp = vec![0; 32]; maxp[..4].copy_from_slice(&0x10000u32.to_be_bytes()); @@ -71,11 +71,11 @@ fn package_font_outlines_render_and_invalidate_the_parent_instance() { child.connect(text, "output", output, "input").unwrap(); let mut package = Package::new("Original lettering"); package.graphs = vec![parent, child]; - package.resources.push(Resource::new("Ink", "Ink.ttf", ResourceBytes::new(rectangle_font(512)))); + package.resources.push(Resource::new("Ink", "Ink.ttf", ResourceBytes::new(rectangle_font(512, [768, -256, 0])))); let cache = Mutex::new(Cache::default()); let options = Options::new(&no_res); for (height, first_row) in [(512, 8), (256, 12)] { - package.resources[0].bytes = ResourceBytes::new(rectangle_font(height)); + package.resources[0].bytes = ResourceBytes::new(rectangle_font(height, [768, -256, 0])); let direct = cook(&package, 1, &options, &cache); assert!(direct.nodes[&text].error.is_none(), "{:?}", direct.nodes[&text].error); let nested = cook(&package, 0, &options, &cache); @@ -91,3 +91,60 @@ fn package_font_outlines_render_and_invalidate_the_parent_instance() { assert!(cook(&package, 0, &options, &cache).nodes[&instance].cached); } } + +fn text_sample(size: [u32; 2], metrics: [i16; 3], params: &[(&str, Value)]) -> (Package, NodeId) { + let mut graph = Graph::new("Print"); + graph.size = size; + graph.format = OutputFormat::F32; + let id = graph.add_node("text", [0.0; 2]); + let node = graph.node_mut(id).unwrap(); + node.params.insert("fontdata".into(), Value::Text("Ink".into())); + node.params.extend(params.iter().map(|(name, value)| (name.to_string(), value.clone()))); + let mut package = Package::new("Original type"); + package.resources.push(Resource::new("Ink", "Ink.ttf", ResourceBytes::new(rectangle_font(512, metrics)))); + package.graphs.push(graph); + (package, id) +} + +#[test] +fn package_font_uses_horizontal_height_and_line_gap() { + let (package, id) = text_sample([6, 6], [1536, -512, 512], &[("text", Value::Text("A\nA".into())), ("fontsize", Value::Float(0.25))]); + let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default())); + assert_eq!(cooked.nodes[&id].error, None); + let image = cooked.image(id, 0).unwrap(); + for y in 0..64 { + for x in 0..64 { + let ink = (30..34).contains(&x) && ((28..32).contains(&y) || (48..52).contains(&y)); + assert_eq!(image.get_gray(x, y, false), f32::from(ink), "({x}, {y})"); + } + } +} + +#[test] +fn package_font_coverage_interpolates_the_background_channels() { + let (mut package, id) = text_sample( + [5, 4], + [768, -256, 0], + &[ + ("text", Value::Text("A".into())), + ("fontsize", Value::Float(0.5)), + ("position", Value::Float2([1.0 / 128.0, 0.0])), + ("background", Value::Color([1.0, 0.0, 0.0, 0.25])), + ], + ); + let cache = Mutex::new(Cache::default()); + for color in [false, true] { + package.graphs[0].node_mut(id).unwrap().params.insert("color_mode".into(), Value::Bool(color)); + let cooked = cook(&package, 0, &Options::new(&no_res), &cache); + assert_eq!(cooked.nodes[&id].error, None); + let image = cooked.image(id, 0).unwrap(); + for (x, code) in [(0, 0), (12, 191), (18, 255), (20, 64)] { + let alpha = f32::from(code as u8) / 255.0; + if color { + assert_eq!(image.get(x, 6, false), [1.0, alpha, alpha, (1.0 - alpha).mul_add(0.25, alpha)]); + } else { + assert_eq!(image.get_gray(x, 6, false), (1.0 - alpha).mul_add(1.0 / 3.0, alpha)); + } + } + } +} diff --git a/crates/nodes/Cargo.toml b/crates/nodes/Cargo.toml index d42d38ce..a00743f7 100644 --- a/crates/nodes/Cargo.toml +++ b/crates/nodes/Cargo.toml @@ -13,6 +13,7 @@ materialcraft-core = { workspace = true } craft-font-catalog = { workspace = true } craft-texture = { workspace = true } harfrust = { workspace = true } +read-fonts = { workspace = true } unicode-bidi = { workspace = true } vello_cpu = { workspace = true } half = { workspace = true } diff --git a/crates/nodes/src/atomic/font.rs b/crates/nodes/src/atomic/font.rs index 47c22686..e53af57a 100644 --- a/crates/nodes/src/atomic/font.rs +++ b/crates/nodes/src/atomic/font.rs @@ -3,13 +3,14 @@ use std::collections::BTreeMap; use craft_font_catalog::{FontOutline, RunGlyph, RunInput, ShapePlanCache, shape_run}; use harfrust::{Direction, Shaper}; +use read_fonts::TableProvider; use vello_cpu::{ Pixmap, RenderContext, Resources, color::palette::css::WHITE, kurbo::{Affine, BezPath, Rect, Shape}, }; -use crate::{CookContext, CookResult, raster::composite}; +use crate::{CookContext, CookResult, raster::composite_text}; // A short string can repeat a complex glyph across many wrapping tiles. Bound the // outline storage and submitted path elements independently of the character count. @@ -99,11 +100,16 @@ impl Drawing { /// Draw a Text node with the bytes of its resolved package font. pub fn text_with_font(context: &CookContext<'_>, bytes: &[u8]) -> CookResult { let face = FontOutline::from_bytes(bytes, 0, &[]).map_err(|e| e.to_string())?; - let metrics = face.metrics(); - if metrics.units_per_em == 0 { + if face.metrics().units_per_em == 0 { return Err("font has no design units per em".into()); } let font = harfrust::FontRef::from_index(bytes, 0).map_err(|e| e.to_string())?; + let header = font.hhea().map_err(|e| e.to_string())?; + let height_units = f64::from(header.ascender().to_i16()) - f64::from(header.descender().to_i16()); + if height_units <= 0.0 { + return Err("font has no positive horizontal line height".into()); + } + let pitch = height_units + f64::from(header.line_gap().to_i16()); let data = harfrust::ShaperData::new(&font); let shaper = data.shaper(&font).build(); let plans = ShapePlanCache::default(); @@ -116,7 +122,7 @@ pub fn text_with_font(context: &CookContext<'_>, bytes: &[u8]) -> CookResult { let [a, b, c, d] = context.v4("matrix").map(f64::from); let inverse = if a * d == b * c { Affine::IDENTITY } else { Affine::new([a, b, c, d, 0.0, 0.0]).inverse() }; let [x, y] = context.v2("position").map(f64::from); - let scale = f64::from(context.f("fontsize").max(0.0)) / f64::from(metrics.units_per_em); + let scale = f64::from(context.f("fontsize").max(0.0)) / height_units; let frame = Affine::scale_non_uniform(f64::from(width), f64::from(height)) * Affine::translate((0.5 + x, 0.5 + y)) * inverse @@ -124,7 +130,6 @@ pub fn text_with_font(context: &CookContext<'_>, bytes: &[u8]) -> CookResult { if !frame.as_coeffs().into_iter().all(f64::is_finite) { return Err("non-finite text transform".into()); } - let pitch = f64::from(metrics.ascent - metrics.descent + metrics.leading); let text = context.text("text").chars().take(super::text::MAX_CHARS).collect::().replace("\\n", "\n"); let mut cache = BTreeMap::new(); let mut outline_budget = MAX_ELEMENTS; @@ -164,9 +169,8 @@ pub fn text_with_font(context: &CookContext<'_>, bytes: &[u8]) -> CookResult { let mut target = Pixmap::new(width, height); drawing.context.flush(); drawing.context.render(&mut target, &mut Resources::new()); - Ok(vec![composite(context, |x, y| { + Ok(vec![composite_text(context, |x, y| { let index = y as usize * usize::from(width) + x as usize; - let alpha = target.data().get(index).map_or(0.0, |pixel| f32::from(pixel.a) / 255.0); - [1.0, 1.0, 1.0, alpha] + target.data().get(index).map_or(0.0, |pixel| f32::from(pixel.a) / 255.0) })]) } diff --git a/crates/nodes/src/atomic/text.rs b/crates/nodes/src/atomic/text.rs index 2563e3a7..3ea580d4 100644 --- a/crates/nodes/src/atomic/text.rs +++ b/crates/nodes/src/atomic/text.rs @@ -1,7 +1,7 @@ //! Original single-stroke font rendered as anti-aliased capsules use crate::atomic::ATOMIC; -use crate::raster::{CapsuleRaster, CapsuleSegment, composite}; +use crate::raster::{CapsuleRaster, CapsuleSegment, composite_text}; use crate::{CookContext, CookResult, NodeDefinition, node}; /// The font: each glyph is strokes separated by spaces, each stroke a polyline of `xy` digit pairs on a grid 4 wide where y = 0 is the cap height, 2 the x-height, 6 the baseline and 8 the descender @@ -179,7 +179,7 @@ fn text(context: &CookContext) -> CookResult { let text: String = context.text("text").replace("\\n", "\n").chars().take(MAX_CHARS).collect(); let radius = 0.7 * context.f("fontsize").max(0.0) * context.h as f32 / 16.0; let raster = CapsuleRaster::new(layout(context, &text), radius, context.w, context.h, context.tile); - Ok(vec![composite(context, |x, y| [1.0, 1.0, 1.0, raster.coverage(x as f32 + 0.5, y as f32 + 0.5)])]) + Ok(vec![composite_text(context, |x, y| raster.coverage(x as f32 + 0.5, y as f32 + 0.5))]) } #[cfg(test)] diff --git a/crates/nodes/src/raster/composite.rs b/crates/nodes/src/raster/composite.rs index 0e1f0ee1..4e829b5f 100644 --- a/crates/nodes/src/raster/composite.rs +++ b/crates/nodes/src/raster/composite.rs @@ -1,17 +1,37 @@ -use craft_texture::{Image, Kind, luminance}; +use craft_texture::{Image, Kind}; use crate::CookContext; -pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { +fn mean_rgb([r, g, b, _]: [f32; 4]) -> f32 { + (r + g + b) / 3.0 +} + +fn background(context: &CookContext) -> Image { let kind = if context.b("color_mode") { Kind::Color } else { Kind::Gray }; - let background = match context.input(0) { + match context.input(0) { Some(image) if image.kind() == kind => image.resize(context.w, context.h, context.tile), // An incompatible connection replaces the constant background with empty pixels Some(_) => Image::filled(1, 1, kind, [0.0; 4]), - None => Image::filled(1, 1, Kind::Color, context.v4("background")), - }; - let gray_background = background.is_gray(); + None => { + let color = context.v4("background"); + Image::filled(1, 1, kind, if kind == Kind::Gray { [mean_rgb(color); 4] } else { color }) + } + } +} + +pub(crate) fn composite_text(context: &CookContext, coverage: impl Fn(u32, u32) -> f32 + Sync) -> Image { + let background = background(context); + Image::generate(context.w, context.h, background.kind(), |x, y| { + let ink = coverage(x, y).clamp(0.0, 1.0); + let pixel = background.get(i64::from(x), i64::from(y), false); + pixel.map(|channel| (1.0 - ink).mul_add(channel, ink)) + }) +} + +pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Image { + let background = background(context); + let kind = background.kind(); // Clamped sampling broadcasts constant backgrounds from one pixel Image::generate(context.w, context.h, kind, |x, y| { @@ -20,7 +40,7 @@ pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> let foreground_alpha = foreground[3].clamp(0.0, 1.0); if foreground_alpha == 0.0 { // Empty content must preserve hidden RGB in a transparent background - return if kind == Kind::Gray && !gray_background { [luminance(background), 0.0, 0.0, 0.0] } else { background }; + return background; } let background_alpha = background[3].clamp(0.0, 1.0) * (1.0 - foreground_alpha); @@ -31,6 +51,6 @@ pub(crate) fn composite(context: &CookContext, foreground: impl Fn(u32, u32) -> let channel = |index: usize| (foreground[index] * foreground_alpha + background[index] * background_alpha) / alpha; let pixel = [channel(0), channel(1), channel(2), alpha]; - if kind == Kind::Gray { [luminance(pixel), 0.0, 0.0, 0.0] } else { pixel } + if kind == Kind::Gray { [mean_rgb(pixel), 0.0, 0.0, 0.0] } else { pixel } }) } diff --git a/crates/nodes/src/raster/mod.rs b/crates/nodes/src/raster/mod.rs index f33956be..e13b80e4 100644 --- a/crates/nodes/src/raster/mod.rs +++ b/crates/nodes/src/raster/mod.rs @@ -4,4 +4,4 @@ mod composite; pub(crate) use capsule_raster::CapsuleRaster; pub(crate) use capsule_segment::CapsuleSegment; -pub(crate) use composite::composite; +pub(crate) use composite::{composite, composite_text}; diff --git a/crates/nodes/tests/atomic_filter_parity.rs b/crates/nodes/tests/atomic_filter_parity.rs index dfe4ed53..ae6de406 100644 --- a/crates/nodes/tests/atomic_filter_parity.rs +++ b/crates/nodes/tests/atomic_filter_parity.rs @@ -854,6 +854,10 @@ fn reduced_sharpen_reads_neighbors_one_source_texel_apart() { #[test] fn empty_raster_preserves_transparent_rgb_and_rejects_mismatched_background_kind() { for id in ["text", "svg"] { + let constant = [("color_mode", Value::Bool(false)), ("background", Value::Color([0.0, 1.0, 0.0, 0.25]))]; + let output = cook(id, &[], &constant, [16, 16], false); + assert_eq!(output.get_gray(0, 0, false), 1.0 / 3.0, "{id} grayscale background"); + let pixel = [0.25, 0.5, 0.75, 0.0]; let color = Some(Image::filled(16, 16, Kind::Color, pixel)); let gray = Some(Image::filled(16, 16, Kind::Gray, [0.25; 4])); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 4f0608b3..8860c58f 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -59,6 +59,30 @@ The first pass classifies all 546 roots: 166 Parity and 380 Too hard. These meas ## 2026-11-23 root comparisons +### Font line height and coverage over a constant background + +Give a generated TrueType A a 512 × 512 rectangular outline, an advance of 640 and 1,024 units per em. Render two lines of A at size .25, centered at offset (0,−.125) on a 64² F32 output. Start at horizontal ascent 768, descent −256 and gap 0. Independently change the horizontal header, the typographic and Windows metrics in the OS/2 table, and the typographic-metrics selection bit. Include two version-4 OS/2 tables with the bit enabled. Across the twelve fonts, the vertical scale is `pixel_height / (ascender - descender)`. The baseline interval is `scale * (ascender - descender + line_gap)`. For example, horizontal metrics (896,−256,128) use a scale denominator of 1,152 and a baseline interval of 1,280 design units. The twelve MaterialCraft renders match **49,152/49,152 pixels**, maximum error 0. Three of these graphs saved and reopened in both applications match **12,288/12,288**, maximum error 0. [OpenType horizontal header fields](https://learn.microsoft.com/en-us/typography/opentype/spec/hhea) + +Render the rectangular A at 32 × 16, size .5, offset (1/128,0). Use grayscale and RGBA outputs. Set the background to red with alpha .25, green with .5, blue with 0 or (.1875,.4375,.625,.375). The measured grayscale background is the arithmetic mean of RGB. Coverage interpolates each output channel from its background value to white, including alpha. All counts below require every channel of a pixel to match the one-worker F32 readback. + +| Original graph | Previous exact / total · max | Current exact / total · max | +|---|---:|---:| +| Text, four backgrounds and two output types | 2,128/4,096 · 0.749019593 | 4,096/4,096 · 0 | +| SVG, opaque red and half-opacity white rectangles on the same backgrounds | 1,664/4,096 · 0.498039186 | 3,072/4,096 · 0.498039186 | +| Six settings with the licensed monospace face, seven dimensions each | 73,641/83,328 · 1 | 81,267/83,328 · 0.631372556 | + +For the monospace controls, use 0, 0123, 01 and 23 on successive lines, A, a period, and the Points Preview label sheet. Use the same linked font bytes in each application, with the sizes, transforms and alignments stored in the graph. Render 8², 16², 16 × 8, 8 × 16, 32², 64² and 128 × 64. Across six ordinary package saves (three line-metric graphs, the label sheet at four sizes, tinted RGBA Text and grayscale SVG), the reference output before and after saving agrees for **21,952/21,952 · 0**. MaterialCraft against the reopened reference gives **21,101/21,952 · 0.631372556**. The remaining SVG differences include the authored half-opacity rectangle. Independent diagonal SVG edges at 32 × 16 give **3,664/4,096 · 0.623529404**. The original square and triangular font controls across transforms give **261,700/262,144 · 0.584313743** in 96 renders and **48,994/49,152 · 0.584313743** in 18 renders of prior saves. [Outline shapes and transform settings](#package-font-outlines-and-point-preview) + +Repeat the whole Points Preview comparison using the same two-row procedural field, counts, offsets, settings and seeds. Each saved-library comparison resolves the same licensed font on both sides. The reference catalog chooses a different font file. [Root settings and inputs](#stored-and-wired-values-at-graph-instance-inputs) + +| View | Previous, full save · max | Current, full save · max | Current, original catalog · max | +|---|---:|---:|---:| +| Points only | 5,376/5,376 · 0 | 5,376/5,376 · 0 | 5,376/5,376 · 0 | +| Labels only | 5,087/5,376 · 0.494117673 | 5,338/5,376 · 0.164705887 | 5,103/5,376 · 0.380392157 | +| Both, including empty input | 7,063/7,168 · 0.419607846 | 7,155/7,168 · 0.113725491 | 7,066/7,168 · 0.356862746 | + +Point-only controls remain exact. Visible labels keep this root in progress. + ### Stored and wired values at graph instance inputs Connect a typed graph input directly to an output. In the caller place an instance with an open input, an explicit argument, a wire from a Value Processor, or both an argument and a wire. The reference uses the declared default when the port is open. A wire supplies the value when the argument is absent. An explicit constant or parameter function supplies the value even with a wire present. MaterialCraft now resolves the argument using the bridge's declared type. The same-package and linked-package paths use the same port information. diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 0d1a1840..1137b644 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -652,7 +652,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [spline_tools.sbs/internal_tools/get_spline_point_data](../assets/sbs/spline_tools.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) | | [spline_tools.sbs/internal_tools/modify_spline_property_sub](../assets/sbs/spline_tools.sbs) | 4 | Yes | [Parity · 28,928 exact pixels in 19 renders](parity-fixes.md#clamped-texture-reads-in-spline-graphs) | | [spline_tools.sbs/internal_tools/normalize_spline_distance](../assets/sbs/spline_tools.sbs) | 1 | Yes | [Parity · 16 cases, 52,480 exact pixels](parity-fixes.md#tile-edge-masks-and-normalized-spline-distances) | -| [spline_tools.sbs/internal_tools/points_preview](../assets/sbs/spline_tools.sbs) | 3 | Yes | [In progress · all 25,088 empty and point-only pixels exact, visible labels differ](parity-fixes.md#stored-and-wired-values-at-graph-instance-inputs) | +| [spline_tools.sbs/internal_tools/points_preview](../assets/sbs/spline_tools.sbs) | 3 | Yes | [In progress · all 25,088 empty and point-only pixels exact, 5,338/5,376 saved label-only pixels](parity-fixes.md#font-line-height-and-coverage-over-a-constant-background) | | [spline_tools.sbs/internal_tools/resample_spline_data](../assets/sbs/spline_tools.sbs) | 3 | Yes | [Parity · 29,952 exact pixels in 19 renders](parity-fixes.md#clamped-texture-reads-in-spline-graphs) | | [spline_tools.sbs/internal_tools/scatter_splines_on_splines_preprocess](../assets/sbs/spline_tools.sbs) | 5 | Yes | [Parity · 622,592/622,592 pixels and 16/16 counts, both full-library saves exact](parity-fixes.md#spline-preprocessing-with-empty-inputs-and-complete-library-saves) · [Four output formats](parity-fixes.md#spline-preprocessing-with-wired-counts) | | [spline_tools.sbs/internal_tools/select_spline_sub](../assets/sbs/spline_tools.sbs) | 3 | Yes | [Parity · 622,592 exact pixels in 19 renders](parity-fixes.md#clamped-texture-reads-in-spline-graphs) |