PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(text): rasterize a type layer's pixels on all cores, bit for bit the same
ebosido444-aifcd337e1fc7b
diff --git a/Cargo.lock b/Cargo.lockindex 0167dea3b..b0afa7513 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4944,6 +4944,7 @@ dependencies = ["photocraft-color","photocraft-geom","proptest",+ "rayon","serde",]@@ -4996,6 +4997,7 @@ dependencies = ["photocraft-geom","photocraft-psd","photocraft-raster",+ "rayon","skrifa",]diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.tomlindex 956d1c954..41b188a94 100644--- a/crates/raster/Cargo.toml+++ b/crates/raster/Cargo.toml@@ -12,5 +12,9 @@ photocraft-geom = { workspace = true }photocraft-color = { workspace = true }serde = { workspace = true }+# Native only: converting a region's tiles is independent per tile, so it runs on all cores.+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+rayon = { workspace = true }+[dev-dependencies]proptest = { workspace = true }diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rsindex 20b809764..883c244aa 100644--- a/crates/raster/src/lib.rs+++ b/crates/raster/src/lib.rs@@ -166,6 +166,55 @@ impl PartialEq for Surface {}}+/// Converts the `data` span covering one tile into that tile's bytes.+fn write_tile(t: &mut Tile, tc: TileCoord, r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) {+ let tr = tc.rect().intersect(&r);+ // Convert contiguous channel samples a row at a time. Dispatching on depth here removes the+ // per-pixel channel loop and lets the compiler vectorise conversion.+ let span = tr.width() as usize * n;+ for y in tr.y0..tr.y1 {+ let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n;+ let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n;+ let src = &data[o..o + span];+ let bytes = sample.bytes();+ let dst = &mut t.data[base * bytes..(base + span) * bytes];+ match sample {+ SampleType::U8 => {+ for (d, v) in dst.iter_mut().zip(src) {+ *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;+ }+ }+ SampleType::U16 => {+ for (d, v) in dst.as_chunks_mut::<2>().0.iter_mut().zip(src) {+ let q = (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;+ d.copy_from_slice(&q.to_ne_bytes());+ }+ }+ SampleType::F32 => {+ for (d, v) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) {+ d.copy_from_slice(&v.to_ne_bytes());+ }+ }+ }+ }+}++/// Converts the tiles of a region write. A tile holds no state another tile reads, so the tiles+/// are converted on all cores; each writes only its own bytes, in the same arithmetic.+#[cfg(not(target_arch = "wasm32"))]+fn convert_tiles(tiles: &mut [(TileCoord, Arc<Tile>)], r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) {+ use rayon::prelude::*;+ tiles.par_iter_mut().for_each(|(tc, t)| write_tile(Arc::make_mut(t), *tc, r, data, w, n, sample));+}++/// Serial counterpart, for the web build (there are no threads to spread tiles over).+#[cfg(target_arch = "wasm32")]+fn convert_tiles(tiles: &mut [(TileCoord, Arc<Tile>)], r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) {+ for (tc, t) in tiles.iter_mut() {+ write_tile(Arc::make_mut(t), *tc, r, data, w, n, sample);+ }+}+impl Surface {/// Reads a region into a newly allocated buffer, returning an error instead of aborting if/// the requested pixel buffer cannot be represented or reserved.@@ -579,38 +628,13 @@ impl Surface {let w = r.width() as usize;assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch");let sample = self.format.sample;- for tc in r.tiles() {- let tr = tc.rect().intersect(&r);- let t = self.tile_mut(tc);- // Convert contiguous channel samples a row at a time. Dispatching on depth here- // removes the per-pixel channel loop and lets the compiler vectorise conversion.- let span = tr.width() as usize * n;- for y in tr.y0..tr.y1 {- let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n;- let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n;- let src = &data[o..o + span];- let bytes = sample.bytes();- let dst = &mut t.data[base * bytes..(base + span) * bytes];- match sample {- SampleType::U8 => {- for (d, v) in dst.iter_mut().zip(src) {- *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;- }- }- SampleType::U16 => {- for (d, v) in dst.as_chunks_mut::<2>().0.iter_mut().zip(src) {- let q = (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;- d.copy_from_slice(&q.to_ne_bytes());- }- }- SampleType::F32 => {- for (d, v) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) {- d.copy_from_slice(&v.to_ne_bytes());- }- }- }- }- }+ // Each tile's own span of `data` is converted on its own: the tiles are disjoint, so+ // converting them in any order (and on any thread) writes exactly the same bytes.+ // `take_tiles` reserves the whole result before removing anything, and gives the missing+ // tiles as one shared default-filled tile, copied per tile by `Arc::make_mut` below.+ let mut tiles = self.take_tiles(r);+ convert_tiles(&mut tiles, r, data, w, n, sample);+ self.put_tiles(tiles);}/// Take the tiles covering `r` out of the surface (missing ones filled with the defaultdiff --git a/crates/text/Cargo.toml b/crates/text/Cargo.tomlindex 985f627e9..0c251d163 100644--- a/crates/text/Cargo.toml+++ b/crates/text/Cargo.toml@@ -25,8 +25,10 @@ flate2 = { workspace = true }# line breaking. Native only: the CJK dictionary alone is 3.8 MB of wasm, and the web build must# stay under Cloudflare's 25 MiB per-file cap (packaging/web/package.sh). The web build falls back# to the generic Unicode rules for those scripts.+# Native only: the glyph rasteriser composites and converts its pixel buffers on all cores.[target.'cfg(not(target_arch = "wasm32"))'.dependencies]parley = { version = "0.11", default-features = false, features = ["std", "complex-scripts"] }+rayon = { workspace = true }[build-dependencies]# Deflates the bundled fonts (build.rs); `flate2` above inflates them.diff --git a/crates/text/src/render.rs b/crates/text/src/render.rsindex af29dd10d..5cf6baea1 100644--- a/crates/text/src/render.rs+++ b/crates/text/src/render.rs@@ -12,6 +12,9 @@ use crate::layout::{GlyphOrient, PlacedGlyph, TextLayout};use crate::raster::{Bounds, Coverage, LineSink, Pen, Xform, rect_to};use crate::warp::{Placement, Warp};+#[cfg(not(target_arch = "wasm32"))]+use rayon::prelude::*;+/// Faux-italic slant in degrees (Photoshop-like).pub const FAUX_ITALIC_DEG: f32 = 12.0;/// Faux-bold ring radius as a fraction of the font size (tuned so stem weight stays close to the old summed-coverage look).@@ -276,35 +279,57 @@ pub fn rasterize_warped(layout: &TextLayout, transform: &Affine, format: PixelFo}let comps = color_in(&format, c);let a = c.alpha.clamp(0.0, 1.0);- for (i, &cv) in cov.iter().enumerate() {- let cv = if antialias == AntiAlias::None { if cv >= 0.5 { 1.0 } else { 0.0 } } else { cv };+ composite(&mut acc, &cov, w, stride, &comps, a, antialias);+ }+ // Unpremultiply.+ unpremultiply(&mut acc, n, stride, format.sample);+ surface.write_region(rect, &acc);+ surface.prune();+ Rendered { surface, rect }+}++/// Composites one colour's coverage over the premultiplied accumulator, resolving `AntiAlias::None`+/// to 0/1 first. A pixel's maths reads and writes only its own slots, so the rows are done in any+/// order — one per thread — for exactly the same bytes.+fn composite(acc: &mut [f32], cov: &[f32], width: usize, stride: usize, comps: &[f32], a: f32, antialias: AntiAlias) {+ let n = comps.len();+ let row = |acc: &mut [f32], cov: &[f32]| {+ for (cv, px) in cov.iter().zip(acc.chunks_exact_mut(stride)) {+ let cv = if antialias == AntiAlias::None { if *cv >= 0.5 { 1.0 } else { 0.0 } } else { *cv };let s = cv * a;if s <= 0.0 {continue;}- let px = &mut acc[i * stride..(i + 1) * stride];let keep = 1.0 - s;for j in 0..n {px[j] = comps[j] * s + px[j] * keep;}px[n] = s + px[n] * keep;}- }- // Unpremultiply.- for px in acc.chunks_exact_mut(stride) {+ };+ #[cfg(not(target_arch = "wasm32"))]+ acc.par_chunks_mut(width * stride).zip(cov.par_chunks(width)).for_each(|(a, c)| row(a, c));+ #[cfg(target_arch = "wasm32")]+ acc.chunks_mut(width * stride).zip(cov.chunks(width)).for_each(|(a, c)| row(a, c));+}++/// Divides the premultiplied accumulator back to straight colour. Each pixel stands alone.+fn unpremultiply(acc: &mut [f32], n: usize, stride: usize, sample: SampleType) {+ let one = |px: &mut [f32]| {let a = px[n];if a > 0.0 {for v in &mut px[..n] {let straight = *v / a;// Float text can carry HDR and signed colours. Keep integer output bounded// and retain the old handling of non-finite intermediate values.- *v = if format.sample == SampleType::F32 && straight.is_finite() { straight } else { straight.clamp(0.0, 1.0) };+ *v = if sample == SampleType::F32 && straight.is_finite() { straight } else { straight.clamp(0.0, 1.0) };}}- }- surface.write_region(rect, &acc);- surface.prune();- Rendered { surface, rect }+ };+ #[cfg(not(target_arch = "wasm32"))]+ acc.par_chunks_exact_mut(stride).for_each(one);+ #[cfg(target_arch = "wasm32")]+ acc.chunks_exact_mut(stride).for_each(one);}/// One element of a glyph outline in document space (see [`outlines`]).diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rsindex 894ecf4e4..c055e1881 100644--- a/crates/text/src/tests.rs+++ b/crates/text/src/tests.rs@@ -1,6 +1,6 @@use photocraft_color::{Color, PixelFormat, SampleType};use photocraft_doc::TextLayer;-use photocraft_doc::text::{Caps, CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape};+use photocraft_doc::text::{AntiAlias, Caps, CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape};use photocraft_geom::Affine;use crate::{TextEngine, fonts};@@ -13,6 +13,38 @@ fn styled(text: &str, style: CharStyle) -> TextLayer {TextLayer { text: text.into(), runs: vec![TextRun { len: text.len(), style }], ..Default::default() }}+/// The rasteriser's pixel stages — composing one colour's coverage, unpremultiplying it, and+/// converting the tiles — are per pixel: no pixel reads a slot another pixel wrote. Spreading them+/// over threads therefore has to leave every byte as it was, which a one-thread pool checks.+#[cfg(not(target_arch = "wasm32"))]+#[test]+fn parallel_raster_matches_a_single_thread() {+ let one = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("one-thread pool");+ let mut e = TextEngine::new();+ let boxed = TextShape::Box { x: 0.0, y: 0.0, width: 220.0, height: 90.0 };+ let paragraph = TextLayer {+ text: "A paragraph box that wraps over several lines and covers many tiles, so the whole raster is exercised.".into(),+ font_family: "Inter".into(),+ size_pt: 18.0,+ shape: boxed,+ ..Default::default()+ };+ let no_aa = TextLayer { text: "No AA edge".into(), font_family: "Inter".into(), size_pt: 30.0, antialias: AntiAlias::None, ..Default::default() };+ let cases: Vec<(TextLayer, f32, PixelFormat)> = vec![+ (point("Parallel", 48.0), 72.0, PixelFormat::RGBA8),+ (styled("Bold italic", CharStyle { size_pt: 40.0, faux_bold: true, faux_italic: true, ..Default::default() }), 300.0, PixelFormat::RGBA8),+ (no_aa, 150.0, PixelFormat::RGBA16),+ (styled("Wide gamut", CharStyle { size_pt: 36.0, color: Color::rgba(2.5, -0.25, 0.5, 0.4), ..Default::default() }), 96.0, PixelFormat::RGBA32F),+ (with_para(paragraph, ParagraphStyle::default()), 144.0, PixelFormat::RGBA8),+ ];+ for (layer, dpi, format) in cases {+ let (_, spread) = e.render(&layer, dpi, format);+ let (_, single) = one.install(|| e.render(&layer, dpi, format));+ assert_eq!(spread.rect, single.rect, "{}", layer.text);+ assert_eq!(spread.surface, single.surface, "{}", layer.text);+ }+}+#[test]fn raster_preserves_hdr_and_signed_float_text_colors() {let mut e = TextEngine::new();diff --git a/docs/text-raster-performance.md b/docs/text-raster-performance.mdnew file mode 100644index 000000000..87ccdf849--- /dev/null+++ b/docs/text-raster-performance.md@@ -0,0 +1,60 @@+# Text rasterization: what a type render costs++Measured 2026-10-17 on Windows 11, `i5-10300H` (4 cores / 8 threads, 16 GB), release build,+`rustc 1.98.1`, with a probe that renders one paragraph layer through+`photocraft_text::render::rasterize_warped` and times each stage of it.++Document: 300 dpi, a 2400 × 1600 px paragraph box holding 4000 characters at 14 pt — the worst+case a type edit has (a whole page of text at print resolution; 1851 laid-out glyphs, 2329 × 1610 px+of ink = 3.75 MP).++| Stage | ms | What it does |+|---|---:|---|+| ink rectangle (`ink_rect_warped`) | 4.1 | its own pass over every glyph, to size the surface |+| draw (`draw_pass` into `Coverage`) | 18.6–22.9 | glyph outlines, curve flattening (0.03 px tolerance), winding scanlines |+| prefix sum (`Coverage::finish`) | 7.0–8.1 | resolves the winding accumulator to coverage 0…1, one running sum over 3.75 M pixels |+| composite | 22.6–33.4 | each colour's coverage over the premultiplied accumulator |+| unpremultiply | 11.2–14.0 | divides the accumulator back to straight colour |+| `Surface::write_region` | 23.8 | converts to the document format and fills the tiles |+| `Surface::prune` | 3.1 | drops tiles that came back the layer's default |+| **total** | **86–104** | |++So the glyph geometry — what one would expect to dominate — is under a quarter of it. The rest is+scalar work over the pixel buffers, and every one of those passes is per pixel: a pixel's maths+reads and writes only its own slots.++## What runs in parallel now++`composite`, `unpremultiply` and the tile conversion of `write_region` run on all cores (rayon,+native only; the web build keeps the serial loops, since wasm has no threads). Nothing about them+is order-dependent, so each pixel still sees the same operations on the same inputs — the pixels+are identical, not merely close.++| | before | after |+|---|---:|---:|+| the 3.75 MP case above | 98.3–103.9 ms | 60.3–61.8 ms |++`crates/text/src/tests.rs::parallel_raster_matches_a_single_thread` renders the shapes the pipeline+can take (plain, faux bold italic, no antialias, wide gamut, a wrapping paragraph box; 8/16/32-bit)+on a one-thread pool and on the default pool and compares the surfaces; `crates/raster`'s existing+region proptests compare `write_region` against its serial reference implementation, tile for tile.++## What stays on one thread, and why++- **draw** (19–23 ms): the winding accumulator carries across scanlines and rows — a pixel's value+ depends on the rows above it, and one scanline can spill into the next row's first pixel. A band+ split can be exact (bands keep absolute coordinates, carry the spill in band order, and are+ assembled before the prefix sum), but each band re-traverses every glyph — the traversal is not+ free, so the win is bounded by the band count. Worth doing when the draw matters more than it does+ now.+- **prefix sum** (7–8 ms): a running f32 sum over the whole image. Splitting it per row needs the+ row's starting sum, which is that same sequential chain — the only exactly-known starting sums are+ the ones the chain computes.+- **ink rectangle** (4.1 ms): a second full traversal into a bounds sink. Per-glyph bounds reduce by+ min/max, which is associative and exact, so this is a candidate for the same treatment as the+ stages above (a glyph-range split, not a band split).++## Related++Byte-identical output matters here beyond taste: text pixels reach a PSD's saved cache and the+round-trip corpora. `cargo xtask test-corpus` and the Photoshop oracle tests are the gate.