From d37c8632c99efe3bfdb098d4adf85be1d20646d3 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 27 Nov 2026 08:53:12 -0500 Subject: [PATCH] Round overlapping glyph coverage after each draw --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/eval/src/tests/font_resource.rs | 38 +++++++++-- crates/nodes/Cargo.toml | 2 +- crates/nodes/src/atomic/font.rs | 90 +++++++++++++++++++------- docs/parity-fixes.md | 19 ++++++ docs/sbs-root-nodes.md | 2 +- 7 files changed, 121 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a8f5d784..520abb36 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2955,7 +2955,7 @@ dependencies = [ "read-fonts 0.43.3", "serde_json", "unicode-bidi", - "vello_cpu", + "vello_common", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 22e662f0..23612fb5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -92,7 +92,7 @@ craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "4 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"] } +vello_common = { version = "0.2", default-features = false, features = ["std"] } # Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0 craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "453b0da782ccef39be9a6dac8d27c80b553ef1cc", features = ["egui"] } # Native dialogs that do not block the event loop: 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 561c6fe5..b8002235 100644 --- a/crates/eval/src/tests/font_resource.rs +++ b/crates/eval/src/tests/font_resource.rs @@ -2,11 +2,11 @@ use super::*; use materialcraft_core::{OutputFormat, Resource, ResourceBytes}; fn rectangle_font(height: i16, metrics: [i16; 3]) -> Vec { - outline_font(metrics, &[(0, 0, true), (0, height, true), (512, height, true), (512, 0, true)]) + outline_font(metrics, 640, &[(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 outline_font(metrics: [i16; 3], advance: i16, contour: &[(i16, i16, bool)]) -> Vec { fn words(values: &[i16]) -> Vec { values.iter().flat_map(|value| value.to_be_bytes()).collect() } @@ -31,7 +31,7 @@ fn outline_font(metrics: [i16; 3], contour: &[(i16, i16, bool)]) -> Vec { head[36..44].copy_from_slice(&words(&bounds)); 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[4..12].copy_from_slice(&words(&[metrics[0], metrics[1], metrics[2], advance])); hhea[34..].copy_from_slice(&2i16.to_be_bytes()); let mut maxp = vec![0; 32]; maxp[..4].copy_from_slice(&0x10000u32.to_be_bytes()); @@ -51,7 +51,8 @@ fn outline_font(metrics: [i16; 3], contour: &[(i16, i16, bool)]) -> Vec { } 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 tables = + [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", words(&[advance, 0, advance, 0])), (b"loca", loca), (b"maxp", maxp)]; let mut font = words(&[1, 0, 7, 64, 2, 48]); font.resize(12 + 16 * tables.len(), 0); let mut head_start = 0; @@ -169,7 +170,7 @@ fn package_font_quadratic_detail_tracks_the_text_scale() { 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)); + package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, 640, contour)); let result = cook(&package, 0, &options, &cache); assert_eq!(result.nodes[&id].error, None); result.image(id, 0).unwrap().clone() @@ -192,7 +193,7 @@ fn adjacent_quadratic_controls_place_their_join_in_whole_design_units() { &[ ("text", Value::Text("A".into())), ("fontsize", Value::Float(0.5)), - ("alignment", Value::Int(0)), + ("alignment", Value::Enum(0)), ("position", Value::Float2([-0.1875, 1.0 / 256.0])), ], ); @@ -200,7 +201,7 @@ fn adjacent_quadratic_controls_place_their_join_in_whole_design_units() { let explicit = [implicit[0], implicit[1], (273, -130, true), implicit[2], (583, 369, true), implicit[3], implicit[4]]; let cache = Mutex::new(Cache::default()); let mut render = |contour: &[(i16, i16, bool)]| { - package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, contour)); + package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, 640, contour)); let result = cook(&package, 0, &Options::new(&no_res), &cache); assert_eq!(result.nodes[&id].error, None); result.image(id, 0).unwrap().clone() @@ -213,6 +214,29 @@ fn adjacent_quadratic_controls_place_their_join_in_whole_design_units() { } } +#[test] +fn overlapping_glyphs_round_each_coverage_composition() { + let metrics = [768, -256, 0]; + let (mut package, id) = text_sample([5, 5], metrics, &[("fontsize", Value::Float(0.5)), ("alignment", Value::Enum(0))]); + let cache = Mutex::new(Cache::default()); + for (width, expected) in [(11, [44u8, 80, 110, 135]), (32, [128, 192, 224, 240])] { + let contour = [(0, 0, true), (0, 512, true), (width, 512, true), (width, 0, true)]; + package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, 0, &contour)); + for (count, code) in (1..=4).zip(expected) { + package.graphs[0].node_mut(id).unwrap().params.insert("text".into(), Value::Text("A".repeat(count))); + let cooked = cook(&package, 0, &Options::new(&no_res), &cache); + assert_eq!(cooked.nodes[&id].error, None); + let ink = cooked.image(id, 0).unwrap(); + for y in 0..32 { + for x in 0..32 { + let coverage = if x == 16 && (8..16).contains(&y) { code } else { 0 }; + assert_eq!(ink.get_gray(x, y, false), f32::from(coverage) / 255.0, "width {width}, {count} glyphs at ({x},{y})"); + } + } + } + } +} + #[test] fn package_font_coverage_interpolates_the_background_channels() { let (mut package, id) = text_sample( diff --git a/crates/nodes/Cargo.toml b/crates/nodes/Cargo.toml index 48e2861b..809ef653 100644 --- a/crates/nodes/Cargo.toml +++ b/crates/nodes/Cargo.toml @@ -15,7 +15,7 @@ craft-texture = { workspace = true } harfrust = { workspace = true } read-fonts = { workspace = true } unicode-bidi = { workspace = true } -vello_cpu = { workspace = true } +vello_common = { workspace = true } half = { workspace = true } rayon = { workspace = true } serde_json = { workspace = true } diff --git a/crates/nodes/src/atomic/font.rs b/crates/nodes/src/atomic/font.rs index dd5a3c00..53b21d83 100644 --- a/crates/nodes/src/atomic/font.rs +++ b/crates/nodes/src/atomic/font.rs @@ -4,10 +4,14 @@ use std::collections::BTreeMap; use craft_font_catalog::{FontOutline, RunGlyph, RunInput, ShapePlanCache, shape_run}; use harfrust::{Direction, Shaper}; use read_fonts::{TableProvider, tables::glyf::Glyph as StoredGlyph, types::GlyphId}; -use vello_cpu::{ - Pixmap, RenderContext, Resources, - color::palette::css::WHITE, - kurbo::{Affine, BezPath, ParamCurve, PathEl, Point, QuadBez, Rect, Shape}, +use vello_common::{ + fearless_simd::Level, + geometry::RectU16, + kurbo::{Affine, BezPath, ParamCurve, PathEl, Point, QuadBez, Rect, Shape, Vec2}, + peniko::Fill, + strip::{StripFillSegment, visit_strip_fill_segments}, + strip_generator::{StripGenerator, StripStorage}, + tile::Tile, }; use crate::{CookContext, CookResult, raster::composite_text}; @@ -115,14 +119,57 @@ fn copies(low: f64, high: f64, period: f64, tiled: bool) -> Result, + generator: StripGenerator, + strips: StripStorage, width: u16, height: u16, tiled: [bool; 2], remaining: usize, } +/// A solid span is opaque. An edge span stores one column of byte coverage at a time. +fn paint_strip(image: &mut [u8], stride: usize, clip: RectU16, span: StripFillSegment, alphas: Option<&[u8]>) { + let rect = span.pixel_rect().intersect(clip); + for y in rect.y0..rect.y1 { + let offset = usize::from(y) * stride; + let Some(row) = image.get_mut(offset + usize::from(rect.x0)..offset + usize::from(rect.x1)) else { continue }; + if let Some(alphas) = alphas { + let first = usize::from(rect.x0 - span.x0()) * usize::from(Tile::HEIGHT) + usize::from(y - span.y()); + for (dst, &src) in row.iter_mut().zip(alphas.iter().skip(first).step_by(usize::from(Tile::HEIGHT))) { + let alpha = u16::from(src); + *dst = (alpha + (u16::from(*dst) * (255 - alpha) + 127) / 255) as u8; + } + } else { + row.fill(255); + } + } +} + impl Drawing { + fn composite_glyph(&mut self, path: &BezPath, transform: Affine, window: Rect) { + let clip = RectU16::new(window.x0 as u16, window.y0 as u16, window.x1 as u16, window.y1 as u16); + if clip.is_empty() { + return; + } + // Generate coverage in canvas coordinates. Moving an edge into a temporary + // bitmap can change the last coverage bit at a fractional transform. + self.generator.generate_filled_path(path.iter(), Fill::NonZero, transform, None, &mut self.strips, None); + let tiles = RectU16::new(clip.x0 / Tile::WIDTH, clip.y0 / Tile::HEIGHT, clip.x1.div_ceil(Tile::WIDTH), clip.y1.div_ceil(Tile::HEIGHT)); + let stride = usize::from(self.width); + let alphas = &self.strips.alphas; + visit_strip_fill_segments( + &self.strips.strips, + tiles, + &mut self.coverage, + |image, span| { + let bytes = alphas.get(span.alpha_idx as usize..).unwrap_or_default(); + paint_strip(image, stride, clip, span.fill, Some(bytes)); + }, + |image, span| paint_strip(image, stride, clip, span, None), + ); + } + fn glyph(&mut self, ink: &Glyph, transform: Affine, text_bounds: Rect) -> Result<(), String> { if ink.path.elements().is_empty() { return Ok(()); @@ -132,30 +179,23 @@ impl Drawing { if !bounds.is_finite() { return Err("non-finite text outline transform".into()); } - let clip = (!text_bounds.contains_rect(bounds)).then(|| text_bounds.to_path(0.1)); let bounds = bounds.intersect(text_bounds); if bounds.is_zero_area() { return Ok(()); } - let elements = ink.path.elements().len() + clip.as_ref().map_or(0, |path| path.elements().len()); + let elements = ink.path.elements().len(); let columns = copies(bounds.x0, bounds.x1, width, self.tiled[0])?; let rows = copies(bounds.y0, bounds.y1, height, self.tiled[1])?; if (!self.tiled[0] && (bounds.x1 <= 0.0 || bounds.x0 >= width)) || (!self.tiled[1] && (bounds.y1 <= 0.0 || bounds.y0 >= height)) { return Ok(()); } + let canvas = Rect::new(0.0, 0.0, width, height); for row in rows { for column in columns.clone() { self.remaining = self.remaining.checked_sub(elements).ok_or("text outlines exceed the drawing budget")?; - let offset = Affine::translate((f64::from(column) * width, f64::from(row) * height)); - if let Some(path) = &clip { - self.context.set_transform(offset); - self.context.push_clip_layer(path); - } - self.context.set_transform(offset * transform); - self.context.fill_path(&ink.path); - if clip.is_some() { - self.context.pop_layer(); - } + let offset = Vec2::new(f64::from(column) * width, f64::from(row) * height); + let window = (bounds + offset).expand().intersect(canvas); + self.composite_glyph(&ink.path, Affine::translate(offset) * transform, window); } } Ok(()) @@ -184,8 +224,15 @@ pub fn text_with_font(context: &CookContext<'_>, bytes: &[u8]) -> CookResult { let (w, h) = craft_texture::clamp_size(context.w, context.h); let width = u16::try_from(w).map_err(|_| "text width exceeds the raster size")?; let height = u16::try_from(h).map_err(|_| "text height exceeds the raster size")?; - let mut drawing = Drawing { context: RenderContext::new(width, height), width, height, tiled: context.tiling_axes(), remaining: MAX_ELEMENTS }; - drawing.context.set_paint(WHITE); + let mut drawing = Drawing { + coverage: vec![0; usize::from(width) * usize::from(height)], + generator: StripGenerator::new(width, height, Level::try_detect().unwrap_or(Level::baseline())), + strips: StripStorage::default(), + width, + height, + tiled: context.tiling_axes(), + remaining: MAX_ELEMENTS, + }; 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() }; @@ -248,11 +295,8 @@ pub fn text_with_font(context: &CookContext<'_>, bytes: &[u8]) -> CookResult { drawing.glyph(ink, frame * Affine::translate((x, y)), text_bounds)?; } } - let mut target = Pixmap::new(width, height); - drawing.context.flush(); - drawing.context.render(&mut target, &mut Resources::new()); Ok(vec![composite_text(context, |x, y| { let index = y as usize * usize::from(width) + x as usize; - target.data().get(index).map_or(0.0, |pixel| f32::from(pixel.a) / 255.0) + drawing.coverage.get(index).map_or(0.0, |&alpha| f32::from(alpha) / 255.0) })]) } diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index b3c84f08..3a0cb3ab 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 +### Overlapping glyphs and Points Preview file handoff + +Points Preview now matches **26,880/26,880 pixels across 45 settings** with the same font on both sides. The licensed monospace face gives 17,920/17,920 in 30 settings. The original overlapping digit face improves from 8,952 to 8,960/8,960 in 15 settings. At 16², 32² and 32 × 16, use point counts 4, 8 and 12 with labels alone, count 4 with points alone and count 12 with both. For digit `i`, use 1,024 units per em, an advance of 640, ascent 768 and descent −256. Draw three rectangles with opposite corners (0,0) and (64 + 32(i mod 4),512), (224,640) and (416,1088 + 64(i mod 3)), and (128,−576 − 64(i mod 3)) and (416,−128). Both reference processor counts give zero maximum error. [Point fields, label sizes and offsets](#stored-and-wired-values-at-graph-instance-inputs) + +For the independent Text probe, use a zero-advance A consisting of a rectangle from (0,0) to (width,512). Draw one through four copies at 32², size .5, left alignment and zero offset. Widths 6, 8, 11, 32 and 41 give **20,480/20,480 pixels**, up from 20,392. At pixel (16,12), width 11 yields the successive byte values 44, 80, 110 and 135. Width 32 yields 128, 192, 224 and 240. MaterialCraft now composes the new glyph's coverage with the existing byte and rounds after each glyph. It reads edge coverage in canvas coordinates. The 32 quadratic controls retain 81,132/81,152, the 96 straight-sided controls retain 261,700/262,144 and all 83,328 licensed glyph and sheet pixels remain exact. + +| Original and normally reopened Text | Size · seed · format | Previous exact · maximum | Current exact · maximum | +|---|---|---:|---:| +| Width 11, two glyphs | 32² · 0 · U8 | 1,016/1,024 · 1 level | 1,024/1,024 · 0 | +| Width 32, three glyphs | 32² · 42 · U16 | 1,016/1,024 · 257 levels | 1,024/1,024 · 0 | +| Width 11, three glyphs | 32 × 64 · 261017 · F16 | 2,032/2,048 · .00390625 | 2,048/2,048 · 0 | +| Width 41, four glyphs | 64 × 32 · 903331 · F32 | 2,040/2,048 · .0039215684 | 2,048/2,048 · 0 | + +Save configured whole-root callers with their bound procedural point fields and open the files directly in both applications. Eight monospace cases give 5,632/5,632. All 15 overlapping-digit cases give 8,960/8,960. These counts are identical at one and eight processors, maximum zero. The caller requests U8, U16, F16 and F32 across the files. The root's observed output on these direct opens is U8 throughout. + +One ordinary handoff still fails. From a caller pointing directly to the loose spline package with its three-part format version, save four views at three sizes. MaterialCraft reproduces the expected 7,168/7,168 grayscale pixels. The reference app returns a transparent RGBA F32 image in all 12 files on both processor counts. The standalone compiler rejects the linked package before rendering. + +To isolate the dependency, take private copies of the six linked package files with the same licensed font. Use format revision `1.1.0.202401` for the five three-part package headers and zero for the braced file identifiers in dependency records. The reference compiler accepts the package when the spline package's top-level file identifier is still braced and its dependency file identifiers are numeric. Restoring the braced identifier in its self dependency makes the compiler reject it. With the compatible metadata, the original Points Preview graph body compares identically with the inventory graph. Rendering the 30 settings and comparing against MaterialCraft opening the original graph gives 17,920/17,920 on one and eight processors. The installed catalog path selects a different face and gives 17,548/17,920, maximum .380392157. The root remains in progress for the loose-file handoff. + ### Whole design coordinates at implicit glyph joins With the same linked, licensed monospace font, all **30 Points Preview settings match 17,920/17,920 pixels** on both one and eight reference processors, maximum zero. The seven previously differing pixels all had count 12. The independent 42 Text renders now match 83,328/83,328, up from 82,571. They cover individual glyphs, digits and the four-line label sheet from 8² through 128 × 64. The catalog-path comparison selects different faces and gives 17,548/17,920, maximum .380392157. [Whole-root inputs and sizes](#stored-and-wired-values-at-graph-instance-inputs) diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index 47065198..1bf94dbb 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 · 17,920/17,920 with the linked monospace face, 8,952/8,960 with the overlapping digit outlines](parity-fixes.md#whole-design-coordinates-at-implicit-glyph-joins) · [25,088/25,088 empty and point-only pixels](parity-fixes.md#font-line-height-and-coverage-over-a-constant-background) | +| [spline_tools.sbs/internal_tools/points_preview](../assets/sbs/spline_tools.sbs) | 3 | Yes | [In progress · 26,880/26,880 with two matched fonts, 14,592/14,592 on direct reopen with compatible dependencies, older loose links still fail](parity-fixes.md#overlapping-glyphs-and-points-preview-file-handoff) · [25,088/25,088 empty and point-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) |