diff --git a/crates/eval/src/tests/font_resource.rs b/crates/eval/src/tests/font_resource.rs index 038c1db0..ddfbb74d 100644 --- a/crates/eval/src/tests/font_resource.rs +++ b/crates/eval/src/tests/font_resource.rs @@ -1,8 +1,12 @@ 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, metrics: [i16; 3]) -> Vec { + outline_font(metrics, &[(0, 0, true), (0, height, true), (512, height, true), (512, 0, true)]) +} + +/// A two-glyph TrueType face with one contour for A. A false flag denotes a quadratic control point. +fn outline_font(metrics: [i16; 3], contour: &[(i16, i16, bool)]) -> Vec { fn words(values: &[i16]) -> Vec { values.iter().flat_map(|value| value.to_be_bytes()).collect() } @@ -18,19 +22,30 @@ fn rectangle_font(height: i16, metrics: [i16; 3]) -> Vec { head[..4].copy_from_slice(&0x10000u32.to_be_bytes()); head[12..16].copy_from_slice(&0x5f0f3cf5u32.to_be_bytes()); head[18..20].copy_from_slice(&1024i16.to_be_bytes()); - head[40..44].copy_from_slice(&words(&[512, height])); + let width = contour.iter().map(|p| p.0).max().unwrap(); + let height = contour.iter().map(|p| p.1).max().unwrap(); + head[40..44].copy_from_slice(&words(&[width, height])); let mut hhea = vec![0; 36]; hhea[..4].copy_from_slice(&0x10000u32.to_be_bytes()); 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()); - maxp[4..10].copy_from_slice(&words(&[2, 4, 1])); + let count = i16::try_from(contour.len()).unwrap(); + maxp[4..10].copy_from_slice(&words(&[2, count, 1])); let mut cmap = words(&[0, 1, 3, 1, 0, 12]); cmap.extend(words(&[4, 32, 0, 4, 4, 1, 0, 65, -1, 0, 65, -1, -64, 1, 0, 0])); - let mut glyf = words(&[1, 0, 0, 512, height, 3, 0]); - glyf.extend([1; 4]); - glyf.extend(words(&[0, 0, 512, 0, 0, height, 0, -height])); + let mut glyf = words(&[1, 0, 0, width, height, count - 1, 0]); + glyf.extend(contour.iter().map(|p| u8::from(p.2))); + for axis in 0..2 { + let mut previous = 0; + for &(x, y, _) in contour { + let coordinate = [x, y][axis]; + glyf.extend((coordinate - previous).to_be_bytes()); + previous = coordinate; + } + } + glyf.resize(glyf.len().next_multiple_of(2), 0); let loca = words(&[0, 0, (glyf.len() / 2) as i16]); let tables = [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", words(&[640, 0, 640, 0])), (b"loca", loca), (b"maxp", maxp)]; let mut font = words(&[1, 0, 7, 64, 2, 48]); @@ -139,6 +154,31 @@ fn package_font_clips_overhang_at_the_outside_of_the_text_block() { } } +#[test] +fn package_font_quadratic_detail_tracks_the_text_scale() { + let metrics = [768, -256, 0]; + let (mut package, id) = text_sample([5, 5], metrics, &[("text", Value::Text("A".into())), ("position", Value::Float2([-0.0625, 1.0 / 256.0]))]); + let curve = [(0, 0, true), (512, 1024, false), (1024, 0, true)]; + let options = Options::new(&no_res); + let cache = Mutex::new(Cache::default()); + for (size, segments) in [(0.35, 4), (0.35001, 8)] { + package.graphs[0].node_mut(id).unwrap().params.insert("fontsize".into(), Value::Float(size)); + let chords: Vec<_> = (0..=segments).map(|i| ((1024 * i / segments) as i16, (2048 * i * (segments - i) / (segments * segments)) as i16, true)).collect(); + let mut render = |contour: &[(i16, i16, bool)]| { + package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, contour)); + let result = cook(&package, 0, &options, &cache); + assert_eq!(result.nodes[&id].error, None); + result.image(id, 0).unwrap().clone() + }; + let expected = render(&chords); + assert!(expected.data().contains(&1.0)); + let ink = render(&curve); + for (pixel, (a, b)) in ink.data().iter().zip(expected.data()).enumerate() { + assert_eq!(a, b, "pixel {pixel} at size {size}"); + } + } +} + #[test] fn package_font_coverage_interpolates_the_background_channels() { let (mut package, id) = text_sample( diff --git a/crates/nodes/src/atomic/font.rs b/crates/nodes/src/atomic/font.rs index 7c535698..cd5ab76f 100644 --- a/crates/nodes/src/atomic/font.rs +++ b/crates/nodes/src/atomic/font.rs @@ -7,7 +7,7 @@ use read_fonts::TableProvider; use vello_cpu::{ Pixmap, RenderContext, Resources, color::palette::css::WHITE, - kurbo::{Affine, BezPath, Rect, Shape}, + kurbo::{Affine, BezPath, ParamCurve, PathEl, Point, QuadBez, Rect, Shape}, }; use crate::{CookContext, CookResult, raster::composite_text}; @@ -21,6 +21,49 @@ struct Glyph { bounds: Rect, } +impl Glyph { + fn new(path: BezPath, pixels_per_unit: f64, remaining: &mut usize) -> Result { + let budget_error = "font exceeds the outline storage budget"; + *remaining = remaining.checked_sub(path.elements().len()).ok_or(budget_error)?; + let bounds = path.bounding_box(); + if !path.elements().iter().any(|element| matches!(element, PathEl::QuadTo(..))) { + return Ok(Self { path, bounds }); + } + + let mut raster = BezPath::new(); + let mut current = Point::ORIGIN; + let mut start = Point::ORIGIN; + for &element in path.elements() { + match element { + PathEl::MoveTo(point) => { + start = point; + current = point; + } + PathEl::LineTo(point) | PathEl::CurveTo(_, _, point) => current = point, + PathEl::ClosePath => current = start, + PathEl::QuadTo(control, end) => { + // Each bisection quarters the distance between the curve midpoint and the chord. + let mut deviation = control.distance(current.midpoint(end)) * 0.5 * pixels_per_unit; + let mut segments = 1; + while deviation > 0.35 { + *remaining = remaining.checked_sub(segments).ok_or(budget_error)?; + segments *= 2; + deviation *= 0.25; + } + let curve = QuadBez { p0: current, p1: control, p2: end }; + for step in 1..=segments { + raster.line_to(curve.eval(step as f64 / segments as f64)); + } + current = end; + continue; + } + } + raster.push(element); + } + Ok(Self { path: raster, bounds }) + } +} + fn shape_line(line: &str, shaper: &Shaper<'_>, plans: &ShapePlanCache) -> Result, String> { let bidi = unicode_bidi::BidiInfo::new(line, None); let mut glyphs = Vec::new(); @@ -145,6 +188,8 @@ 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 [xx, yx, xy, yy, _, _] = frame.as_coeffs(); + let pixels_per_unit = xx.hypot(xy).min(yx.hypot(yy)); 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; @@ -160,8 +205,7 @@ pub fn text_with_font(context: &CookContext<'_>, bytes: &[u8]) -> CookResult { for glyph in glyphs { if let std::collections::btree_map::Entry::Vacant(entry) = cache.entry(glyph.glyph_id) { let path = face.outline(glyph.glyph_id).map_err(|e| e.to_string())?; - outline_budget = outline_budget.checked_sub(path.elements().len()).ok_or("font exceeds the outline storage budget")?; - entry.insert(Glyph { bounds: path.bounding_box(), path }); + entry.insert(Glyph::new(path, pixels_per_unit, &mut outline_budget)?); } let ink = cache.get(&glyph.glyph_id).ok_or("missing glyph outline")?; let x = cursor + f64::from(glyph.x_offset); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index 12df685c..0404316b 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -59,6 +59,25 @@ The first pass classifies all 546 roots: 166 Parity and 380 Too hard. These meas ## 2026-11-27 root comparisons +### Quadratic glyph outlines in Points Preview + +In the same 30 whole-root settings, Points Preview with the same licensed font now matches **17,913/17,920 pixels** on both one and eight reference processors. The previous result was 17,869/17,920. The largest difference fell from 42 grayscale levels to one (.0039215684 on F32 readback). Point-only output matches 5,376/5,376. Labels alone match 5,371/5,376, and points plus labels including the empty input match 7,166/7,168. All seven remaining differences occur at count 12. The catalog-path comparison, where the reference resolves a different font, gives 17,548/17,920 and a maximum of .380392157. The root remains in progress. [Whole-root inputs, offsets and label sizes](#stored-and-wired-values-at-graph-instance-inputs) + +To isolate the contributing stage, render the original licensed four-line label sheet separately at 8², 16² and 16 × 8. Use the resulting byte field in place of Text in a private comparison graph. At root sizes 16², 32² and 32 × 16, use counts 4, 8 and 12 with labels alone, then count 12 with points and labels. MaterialCraft fed the reference sheet reproduces all 7,168/7,168 original reference pixels. Feeding its own sheet reproduces all 7,168/7,168 of its previous pixels. Reimporting the sheet as a linked bitmap in the reference also changes some final samples. The totals above compare the original Text graphs. + +For an independent TrueType face, give A one quadratic from (0,0) through control (512,1024) to (1024,0) and close the contour along the baseline. Use 1,024 units per em, ascent 768, descent −256, centered alignment, offset (−.0625,1/256), and grayscale on black. A second face replaces the curve by straight segments at equal parameter intervals. At 32² the reference gives exactly the four-segment raster at size .35 and the eight-segment raster at .35001. Both comparisons cover 1,024/1,024 F32 pixels, maximum zero. At size .5, use four segments at 16², eight at 32², 64², 128 × 64 and 64 × 128, and sixteen at 128². All six reference curves agree with their corresponding reference polygons. + +MaterialCraft now subdivides a quadratic while its midpoint is more than .35 pixels from the chord at the smaller axis scale. The existing outline storage budget also covers the new segments. Across 32 renders of the curved A, including fractional scales, shear, rotation, reflection and rectangular outputs, agreement improved from 79,823/81,152 to **81,132/81,152**, maximum .431372568 to .003921599. The 42 licensed-face sizes and strings improved from 81,267/83,328 to 82,571/83,328, maximum .631372556 to .533333357. The 96 straight-sided controls retain 261,700/262,144. [Original outline and font measurements](#text-block-bounds-for-linked-font-outlines) + +For each handoff below, save the configured graph normally and reopen it in both applications. Original and reopened counts agree on both reference processor settings. The reference before and after these saves matches all 5,120/5,120 pixels, maximum zero. The zero glyph uses the linked licensed monospace face, centered at size .5 with zero offset. + +| Text configuration | Size · seed · format | Previous exact pixels · maximum | Current exact pixels · maximum | +|---|---|---:|---:| +| Quadratic at .35 | 32² · 0 · U8 | 1,006/1,024 · 36 levels | 1,024/1,024 · 0 | +| Quadratic at .35001 | 32² · 42 · U16 | 1,002/1,024 · 8,224 levels | 1,024/1,024 · 0 | +| Quadratic at .5, matrix (.70710677,−.70710677,.70710677,.70710677) | 64 × 16 · 261017 · F16 | 988/1,024 · .431030273 | 1,024/1,024 · 0 | +| Single zero | 64 × 32 · 903331 · F32 | 1,973/2,048 · .450980395 | 2,021/2,048 · .415686272 | + ### Text block bounds for linked font outlines The shared Text renderer now clips glyph ink to the outward-rounded bounds of the transformed text block. It uses the horizontal header ascent and descent, line spacing and aligned line widths. An overhang may extend between two lines of the same block. A wrapped copy carries the same clip to its new position. diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 8e79fe67..c206570f 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -736,7 +736,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, 5,338/5,376 saved label-only pixels](parity-fixes.md#font-line-height-and-coverage-over-a-constant-background) · [17,869/17,920 same-font whole-root pixels after the Text clipping fix](parity-fixes.md#text-block-bounds-for-linked-font-outlines) | +| [spline_tools.sbs/internal_tools/points_preview](../assets/sbs/spline_tools.sbs) | 3 | Yes | [In progress · 17,913/17,920 same-font whole-root pixels, seven differ by one level](parity-fixes.md#quadratic-glyph-outlines-in-points-preview) · [25,088/25,088 empty and point-only pixels](parity-fixes.md#font-line-height-and-coverage-over-a-constant-background) · [Previous whole-root comparison](parity-fixes.md#text-block-bounds-for-linked-font-outlines) | | [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) |