fix: integrate latest upstream and preserve editable clipboard copies

This commit is contained in:
jonathanwxh-cell committed 2026-10-20 11:50:34 +08:00
commit 8f4db4bc4f
25 files changed
+1491 -204

No files matched your search

Generated
+2
View File
@@ -4972,6 +4972,7 @@ dependencies = [
"photocraft-color",
"photocraft-geom",
"proptest",
"rayon",
"serde",
]
@@ -5024,6 +5025,7 @@ dependencies = [
"photocraft-geom",
"photocraft-psd",
"photocraft-raster",
"rayon",
"skrifa",
]
+120 -31
View File
@@ -1528,13 +1528,16 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern
tent(&mut h, g.width);
h
} else {
let sharp = sharp_edges(shape);
let (din, dout) = (bevel_dist_inside(shape, &sharp, size), bevel_dist_outside(shape, &sharp, size));
let mut h = Map::new(shape.w, shape.h, 0.0);
let [din, dout] = bevel_dists(shape, size);
let soft = g.chisel_soft > 0.0;
for i in 0..h.v.len() {
h.v[i] = bevel_chisel_h(g.paint, size, din[i], dout[i], soft);
}
let w = shape.w;
let v = par_fill(w, shape.h, 0.0, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
let i = y * w + x;
*o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft);
}
});
let mut h = Map { w, h: shape.h, v };
// Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel
// Hard's across a straight edge); emboss styles keep the blur until measured.
if soft && g.paint == BevelPaint::Both {
@@ -1555,14 +1558,23 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern
let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0);
let k = t.depth / unit;
let (x0, y0) = (tex.rect.x0, tex.rect.y0);
for y in 0..h.h {
for x in 0..h.w {
let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5);
let p = tile.sample(u, v);
let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3];
h.v[y * h.w + x] += k * if t.invert { 1.0 - l } else { l };
}
}
let w = h.w;
par_units(
h.v.len(),
&mut h.v,
w,
&mut [] as &mut [()],
0,
|| (),
|_, y, row, _| {
for (x, o) in row.iter_mut().enumerate() {
let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5);
let p = tile.sample(u, v);
let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3];
*o += k * if t.invert { 1.0 - l } else { l };
}
},
);
}
if b.soften >= 1.0 {
tent(&mut h, b.soften);
@@ -1644,23 +1656,33 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat
};
let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) {
let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0));
for y in 0..shape.h as i64 {
for x in 0..shape.w as i64 {
let i = y as usize * shape.w + x as usize;
let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth;
let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth;
let n = [-gx, -gy, 1.0];
let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len;
let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) };
let k = shade - se;
if k > 0.0 {
hi.v[i] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region;
} else {
sh.v[i] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region;
// Rows on threads: every pixel reads only `hmap` and `shape`.
par_units(
hi.v.len(),
&mut hi.v,
shape.w,
&mut sh.v,
shape.w,
|| (),
|_, y, hi_row, sh_row| {
let y = y as i64;
for x in 0..shape.w as i64 {
let i = y as usize * shape.w + x as usize;
let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth;
let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth;
let n = [-gx, -gy, 1.0];
let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len;
let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) };
let k = shade - se;
if k > 0.0 {
hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region;
} else {
sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region;
}
}
}
}
},
);
(apply_contour(hi, &b.gloss_contour), apply_contour(sh, &b.gloss_contour))
};
let maps = match g.paint {
@@ -1676,7 +1698,13 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat
let (hi, sh) = shade_into(g.depth, 0);
let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1);
let mix = |a: Map, b: Map| -> Map {
let v = a.v.iter().zip(&b.v).zip(&shape.v).map(|((x, y), s)| if *s > INSIDE_EPS { *x } else { 0.0 } + y * (1.0 - s.min(1.0))).collect();
let v = par_fill(a.w, a.h, 0.0, |y, row| {
for (x, o) in row.iter_mut().enumerate() {
let i = y * a.w + x;
let (x, y, s) = (a.v[i], b.v[i], shape.v[i]);
*o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0));
}
});
Map { w: a.w, h: a.h, v }
};
vec![mix(hi, ho), mix(sh, so)]
@@ -2309,6 +2337,18 @@ pub fn distance_field(kind: FieldKind, alpha: Vec<f32>, w: usize, h: usize, reac
}
}
/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its
/// [`distance_field`], with the sharp edges they both start from found once.
pub fn bevel_distance_fields(alpha: Vec<f32>, w: usize, h: usize, reach: f32) -> [Vec<f32>; 2] {
bevel_dists(&Map { w, h, v: alpha }, reach)
}
/// The inside and outside bevel distances of `s`, from one set of sharp edges.
fn bevel_dists(s: &Map, reach: f32) -> [Vec<f32>; 2] {
let sharp = sharp_edges(s);
[bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2951,6 +2991,55 @@ mod tests {
}
}
#[test]
fn bevel_maps_do_not_depend_on_the_threads() {
// Every style and technique, softened or not, and a texture; one thread (in order) is the reference.
let mut patchy = aa_disc(101, 101, 40.0);
for (i, v) in patchy.v.iter_mut().enumerate() {
if (i % 101 / 13 + i / 101 / 17) % 5 == 0 {
*v *= 0.6;
}
}
let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy];
let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]);
sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]);
let pats = [Pattern::new("stripes", sf, 4, 4)];
let light = GlobalLight::default();
let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss];
for (k, shape) in shapes.iter().enumerate() {
let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) };
for style in styles {
for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] {
for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] {
let mut b = bevel_of(style, technique);
(b.size, b.soften) = (size, soften);
if textured {
b.texture = Some(photocraft_doc::BevelTexture {
name: "stripes".into(),
id: String::new(),
scale: 1.0,
depth: 1.0,
invert: false,
link: true,
phase: (0.0, 0.0),
});
}
let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0;
let one = with_threads(1, run);
for threads in [2, 5, 16] {
let many = with_threads(threads, run);
assert_eq!(one.len(), many.len());
for (j, (a, m)) in one.iter().zip(&many).enumerate() {
assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads");
}
}
}
}
}
}
}
/// The four fields that use the distance transform, of `m`.
fn distance_field_of(m: &Map, reach: f32) -> Vec<Vec<f32>> {
[FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside]
+76 -14
View File
@@ -49,13 +49,32 @@ pub(crate) fn file_bytes(p: &Value, cmd: &str, what: &str) -> Result<(Vec<u8>, S
Ok((bytes, stem))
}
/// A name not used by any preset in `taken` (case-insensitive): `name`, `name 2`, `name 3`…
fn unique(name: &str, taken: &[String]) -> String {
let free = |n: &str| !taken.iter().any(|t| t.eq_ignore_ascii_case(n));
if free(name) {
return name.to_string();
/// The preset names in use, for naming new presets.
struct UniqueNames {
/// Every name in use, ASCII-lowercased.
taken: std::collections::HashSet<String>,
/// The next number to try for each repeated name (lowercased).
next: std::collections::HashMap<String, usize>,
}
impl UniqueNames {
fn new<'a>(names: impl IntoIterator<Item = &'a str>) -> Self {
UniqueNames { taken: names.into_iter().map(str::to_ascii_lowercase).collect(), next: std::collections::HashMap::new() }
}
/// A name not in use (case-insensitive): `name`, `name 2`, `name 3`… It is in use from then on.
fn unique(&mut self, name: &str) -> String {
let key = name.to_ascii_lowercase();
if self.taken.insert(key.clone()) {
return name.to_string();
}
// Resume numbering per name, so a file of identical names stays linear.
let from = self.next.get(&key).copied().unwrap_or(2);
let i = (from..).find(|i| !self.taken.contains(&format!("{key} {i}"))).unwrap_or(from);
self.taken.insert(format!("{key} {i}"));
self.next.insert(key, i + 1);
format!("{name} {i}")
}
(2..).map(|i| format!("{name} {i}")).find(|n| free(n)).unwrap_or_else(|| name.to_string())
}
fn import_abr(s: &mut Session, p: &Value) -> Result<Value> {
@@ -93,11 +112,10 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io
if p.get("replace").and_then(Value::as_bool).unwrap_or(true) {
s.tools.presets.retain(|x| x.builtin || x.group != group);
}
let mut taken: Vec<String> = s.tools.presets.iter().map(|x| x.name.clone()).collect();
let mut taken = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str()));
let mut names = Vec::with_capacity(imp.presets.len());
for mut preset in imp.presets {
preset.name = unique(&preset.name, &taken);
taken.push(preset.name.clone());
preset.name = taken.unique(&preset.name);
names.push(preset.name.clone());
s.tools.presets.push(preset);
}
@@ -180,8 +198,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result<Value> {
let doc = crate::file_cmds::import(decode_name, &bytes)?;
let (v, w, h) = image_paint(&doc, cmd)?;
let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?;
let taken: Vec<String> = s.tools.presets.iter().map(|x| x.name.clone()).collect();
let name = unique(&name, &taken);
let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name);
s.tools.presets.push(photocraft_paint::BrushPreset {
name: name.clone(),
brush: brush.clone(),
@@ -526,10 +543,55 @@ mod tests {
assert_eq!(s.tools.presets.len(), n, "a failed import adds nothing");
}
/// A version 1 brush with a computed tip and no name is named after its tip ("9 px Round"). The
/// import used to number each repeated name by searching the preset names once for every number
/// it tried, so importing 10,000 such brushes took minutes. The test fails when the import takes
/// more than 20 seconds.
#[test]
fn repeated_brush_names_are_numbered_in_linear_time() {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut s = Session::new();
s.execute("brush.presets.save", json!({"name": "9 PX ROUND 3"})).unwrap();
let round = LegacyBrush {
name: String::new(),
spacing: 25,
anti_alias: true,
tip: LegacyTip::Computed { diameter: 9, hardness: 100, angle: 0, roundness: 100 },
};
let data = photocraft_paint::tile::b64_encode(&write_v12(1, &vec![round; 10_000], false).unwrap());
let r = s.execute("brush.presets.importAbr", json!({"data": data})).unwrap();
let names: Vec<String> = r["imported"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
let _ = tx.send(names);
});
let names = match rx.recv_timeout(std::time::Duration::from_secs(20)) {
Ok(names) => names,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!("importing the brushes did not finish"),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => panic!("the import thread panicked"),
};
// Numbering starts at 2 and skips the number a preset already uses, in any letter case.
assert_eq!(names[..4], ["9 px Round", "9 px Round 2", "9 px Round 4", "9 px Round 5"]);
assert_eq!(names.last(), Some(&format!("9 px Round {}", names.len() + 1)));
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len());
}
#[test]
fn repeated_brush_names_take_the_first_free_number() {
let mut s = Session::new();
s.execute("brush.presets.save", json!({"name": "speckle 3"})).unwrap();
let tip = AbrSample { id: String::new(), width: 6, height: 4, depth: 8, data: vec![255; 24] };
let brush = |name: &str| LegacyBrush { name: name.into(), spacing: 25, anti_alias: true, tip: LegacyTip::Sampled(tip.clone()) };
let file = write_v12(2, &["Speckle", "SPECKLE", "speckle", "Speckle 2", "Speckle", "hard round"].map(brush), true).unwrap();
let r = s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&file)})).unwrap();
// Names that differ only in letter case count as the same name. The file's "Speckle 2" comes
// after "SPECKLE" took that name, and "hard round" clashes with the built-in Hard Round.
assert_eq!(r["imported"], json!(["Speckle", "SPECKLE 2", "speckle 4", "Speckle 2 2", "Speckle 5", "hard round 2"]));
}
#[test]
fn unique_names() {
let taken = vec!["A".to_string(), "a 2".to_string()];
assert_eq!(unique("a", &taken), "a 3");
assert_eq!(unique("B", &taken), "B");
let mut taken = UniqueNames::new(["A", "a 2"]);
assert_eq!(taken.unique("a"), "a 3");
assert_eq!(taken.unique("B"), "B");
}
}
+84 -15
View File
@@ -203,6 +203,11 @@ impl B {
self.fields.push((kind, reach_for(width)));
In::Field(kind)
}
/// A chiselled bevel's inside and outside fields, always asked for together ([`bevel_fields`]
/// computes them as one).
fn bevel_fields(&mut self, width: f32) -> [In; 2] {
[FieldKind::BevelInside, FieldKind::BevelOutside].map(|k| self.field(k, width))
}
/// `Map::shifted` by whole pixels (`invert`: of `1 - a`); identity shifts of the plain map
/// are skipped.
fn shift(&mut self, src: In, dx: f32, dy: f32, outside: f32, invert: bool) -> In {
@@ -374,8 +379,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool,
let mut h = if bv.technique == BevelTechnique::Smooth {
b.conv(In::Shape, photocraft_compose::effects::tent_kernel(g.width))
} else {
let din = b.field(FieldKind::BevelInside, size);
let dout = b.field(FieldKind::BevelOutside, size);
let [din, dout] = b.bevel_fields(size);
let soft = g.chisel_soft > 0.0;
let h = b.push(stage(Kernel::MBevelH, Some(din), Some(dout), [paint(g.paint), size, f32::from(u8::from(soft)), 0.0], 0));
// As `effects::bevel_height`: only emboss styles blur a Chisel Soft ramp.
@@ -542,20 +546,51 @@ fn threaded_inside(kind: FieldKind) -> bool {
/// fields run on all threads inside `distance_field`, from one window. That is also the window the CPU
/// compositor computes them from, so a rebuilt field is exactly the one it gives.
fn field_banded(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: Rect, halo: i32) -> Vec<f32> {
if threaded_inside(kind) {
let win = out.inflate(halo).intersect(&region);
if win.is_empty() {
return Vec::new();
}
let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32);
return if win == out { f } else { crop(&f, win, out) };
}
let parts = par_map(bands(out, BAND.max(halo)), |band| {
let win = band.inflate(halo).intersect(&region);
let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32);
crop(&f, win, band)
let [f] = fields_in_windows(threaded_inside(kind), shape, region, out, halo, |s, w, h| {
[photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)]
});
parts.concat()
f
}
/// [`field`] of both bevel fields over the same `out`, `[BevelInside, BevelOutside]`, with the
/// sharp edges of each window found once (the two kinds have the same radius and threading).
pub(crate) fn bevel_fields(reach: i32, shape: &[f32], region: Rect, out: Rect) -> [Vec<f32>; 2] {
let kind = FieldKind::BevelInside;
fields_in_windows(threaded_inside(kind), shape, region, out, field_radius(kind, reach) + 1, |s, w, h| {
photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)
})
}
/// The fields `compute` gives for a `w × h` window of the region-sized `shape`, over `out` (inside
/// `region`), each window grown by `halo`: `out` as one window when `whole` (the field spreads over
/// threads itself), else bands of it in parallel.
fn fields_in_windows<const N: usize>(
whole: bool,
shape: &[f32],
region: Rect,
out: Rect,
halo: i32,
compute: impl Fn(Vec<f32>, usize, usize) -> [Vec<f32>; N] + Sync + Send,
) -> [Vec<f32>; N] {
let part = |r: Rect| -> [Vec<f32>; N] {
let win = r.inflate(halo).intersect(&region);
if win.is_empty() {
return std::array::from_fn(|_| Vec::new());
}
let f = compute(crop(shape, region, win), win.width() as usize, win.height() as usize);
if win == r { f } else { f.map(|f| crop(&f, win, r)) }
};
if whole {
return part(out);
}
let parts = par_map(bands(out, BAND.max(halo)), part);
std::array::from_fn(|k| {
let mut f = Vec::with_capacity(parts.iter().map(|p| p[k].len()).sum());
for p in &parts {
f.extend_from_slice(&p[k]);
}
f
})
}
/// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands.
@@ -875,6 +910,40 @@ mod tests {
assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing");
}
/// Both bevel fields from one window (sharp edges found once) are bit for bit the fields
/// computed one at a time, over the whole region and over a part of it.
#[test]
fn paired_bevel_fields_equal_the_fields_one_at_a_time() {
let region = Rect::new(-20, -10, 300, 290);
let (w, h) = (region.width() as usize, region.height() as usize);
let mut shape = vec![0.0f32; w * h];
for y in 0..h {
for x in 0..w {
let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0);
let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos();
shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 };
}
}
let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
for reach in [3, 9, 40] {
for out in [region, Rect::new(40, 30, 170, 120), Rect::new(-20, 200, 300, 290)] {
let [inside, outside] = bevel_fields(reach, &shape, region, out);
assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}");
assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}");
// The banded path (wasm) pairs them per band the same way.
let halo = field_radius(FieldKind::BevelInside, reach) + 1;
let banded =
fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32));
for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() {
let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| {
[photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)]
});
assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}");
}
}
}
}
/// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact
/// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU
/// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop
+39 -24
View File
@@ -1169,7 +1169,7 @@ impl Compositor {
let aprons: Vec<i32> = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect();
for (f, &pg) in plan.fx.iter().zip(&paged) {
if !pg {
self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats);
self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?;
}
}
let fr = self.frame_res(device, queue, canvas, &plan);
@@ -1200,7 +1200,7 @@ impl Compositor {
continue;
}
let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region);
self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats);
self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?;
}
let chunks = grid_rects(part, self.chunk);
stats.chunks += chunks.len();
@@ -1811,7 +1811,7 @@ impl Compositor {
key: FxKey,
region: Rect,
stats: &mut Stats,
) {
) -> Result<(), Unsupported> {
let layer = f.layer;
let canvas = doc.bounds();
let is_group = matches!(layer.content, LayerContent::Group(_));
@@ -1882,13 +1882,13 @@ impl Compositor {
}
// Present: kept or (re)inserted above.
let stamp = self.stamp;
let Some(e) = self.fx.get_mut(&key) else { return };
let Some(e) = self.fx.get_mut(&key) else { return Ok(()) };
e.last_used = frame;
e.stamp = stamp;
e.doc = doc.id;
e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)];
if region.is_empty() {
return;
return Ok(());
}
let t_trace = web_time_now();
@@ -1910,27 +1910,41 @@ impl Compositor {
layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect();
let want = field_reaches(&progs);
e.fields.retain(|k, _| want.contains_key(k));
for (&kind, &reach) in &want {
let have = e.fields.get(&kind).map(|(r, _)| *r);
let out = match have {
Some(r) if r >= reach => {
if damage.is_empty() {
continue;
}
damage.inflate(fx::field_radius(kind, r)).intersect(&region)
// Each field to recompute: over which rectangle, exact up to which reach.
let jobs: Vec<(FieldKind, Rect, i32)> = want
.iter()
.filter_map(|(&kind, &reach)| match e.fields.get(&kind).map(|(r, _)| *r) {
Some(r) if r >= reach => (!damage.is_empty()).then(|| (kind, damage.inflate(fx::field_radius(kind, r)).intersect(&region), r)),
_ => Some((kind, region, reach)),
})
.collect();
// A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they
// are recomputed together, over one rectangle at one reach.
let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2));
let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside));
if bevel_in != bevel_out {
return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name)));
}
for (kind, out, reach) in jobs {
let fields = match kind {
FieldKind::BevelInside => {
let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out);
vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)]
}
_ => region,
// Computed with BevelInside, over the same rectangle at the same reach (checked above).
FieldKind::BevelOutside => continue,
_ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))],
};
let reach = have.filter(|r| *r >= reach).unwrap_or(reach);
let v = fx::field(kind, reach, &e.shape_cpu, region, out);
if have.is_none_or(|r| r < reach) {
e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32)));
for (kind, v) in fields {
if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) {
e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32)));
}
if let Some((_, t)) = e.fields.get(&kind) {
t.write_r32(queue, region, out, &v);
}
staged += v.len() as u64 * 4;
stats.fx_pixels += out.width() as u64 * out.height() as u64;
}
if let Some((_, t)) = e.fields.get(&kind) {
t.write_r32(queue, region, out, &v);
}
staged += v.len() as u64 * 4;
stats.fx_pixels += out.width() as u64 * out.height() as u64;
}
if let Some(t) = t_trace.filter(|_| !damage.is_empty()) {
@@ -1945,7 +1959,7 @@ impl Compositor {
if prog.maps == 0 {
continue;
}
let Some(e) = self.fx.get_mut(&key) else { return };
let Some(e) = self.fx.get_mut(&key) else { return Ok(()) };
let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps;
let d = if same { damage } else { region };
if d.is_empty() {
@@ -1960,6 +1974,7 @@ impl Compositor {
stats.fx_programs += 1;
self.run_program(device, queue, encoder, key, i, prog, d, stats);
}
Ok(())
}
/// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`.
+157
View File
@@ -0,0 +1,157 @@
//! Guides ⇄ PSD beyond image resource 1032.
//!
//! Photoshop writes two undocumented resources next to 1032 (Grid and Guides), layout
//! inferred from the psd-tools, ag-psd and Photoshop-authored corpora (#5965):
//!
//! * 1092, Grid and Guides version 2: `u32` version 2, `u32` horizontal and vertical grid
//! cycle (576 = 18 px in 1/32 px, as in 1032), `u32` count, then per guide 9 bytes: `i32`
//! position in 1/32 px, `u8` direction (0 vertical, 1 horizontal), one `u8` that is always 0
//! in the corpora, and the guide's colour as `u8` R, G, B. In every corpus file its guides
//! equal 1032's, in the same order.
//! * 1097: `u32` count (1092's), then per guide a length-prefixed ASCII GUID, a `u32` 0 and a
//! second length-prefixed GUID, always all zeros.
//!
//! Import takes the guides' own colours from 1092 (a guide in Photoshop's default colour keeps
//! following the preference colour). Export keeps both resources only while 1092 still
//! describes the document's guides and colours; otherwise it leaves both out, so the file
//! carries 1032 alone, as Photoshop files before version 2 did (#5966).
use photocraft_doc::{Document, Guides};
/// Grid and Guides, version 2 (positions, directions and colours).
pub const GUIDES_V2: u16 = 1092;
/// One GUID per guide, in 1092's order.
pub const GUIDE_IDS: u16 = 1097;
/// Photoshop's default guide colour (Cyan, `#4affff`), which 1092 also stores for guides
/// that use the preference colour.
pub const DEFAULT_GUIDE_RGB: [u8; 3] = [0x4a, 0xff, 0xff];
/// One guide of a 1092 resource.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct GuideV2 {
/// Position in 1/32 px.
pub location: i32,
pub vertical: bool,
pub rgb: [u8; 3],
}
fn be_u32(data: &[u8], at: usize) -> Option<u32> {
let b = data.get(at..at.checked_add(4)?)?;
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
/// The guides of a 1092 resource, or `None` when it is not version 2 or is cut short.
pub fn parse_v2(data: &[u8]) -> Option<Vec<GuideV2>> {
if be_u32(data, 0)? != 2 {
return None;
}
let count = usize::try_from(be_u32(data, 12)?).ok()?;
// Each guide takes 9 bytes: a count the data can't hold is not a 1092 we understand.
if count > data.len().saturating_sub(16) / 9 {
return None;
}
(0..count)
.map(|i| {
let at = 16 + i * 9;
let g = data.get(at..at + 9)?;
Some(GuideV2 { location: i32::from_be_bytes([g[0], g[1], g[2], g[3]]), vertical: g[4] != 1, rgb: [g[6], g[7], g[8]] })
})
.collect()
}
/// The number of entries a 1097 resource declares.
pub fn ids_count(data: &[u8]) -> Option<u32> {
be_u32(data, 0)
}
/// The document's guides as 1092 would store them, sorted.
fn expected(guides: &Guides) -> Vec<GuideV2> {
let mut v: Vec<GuideV2> = [(&guides.vertical, true), (&guides.horizontal, false)]
.into_iter()
.flat_map(|(list, vertical)| {
list.iter().map(move |&p| GuideV2 { location: (p * 32.0).round() as i32, vertical, rgb: guides.color(vertical, p).unwrap_or(DEFAULT_GUIDE_RGB) })
})
.collect();
v.sort();
v
}
/// Whether an imported 1092 still describes the document's guides: the same positions,
/// directions and colours, in any order.
pub fn describes(doc: &Document, data: &[u8]) -> bool {
let Some(mut stored) = parse_v2(data) else { return false };
stored.sort();
stored == expected(&doc.guides)
}
/// Whether to write back an imported 1092 or 1097: only while 1092 describes the guides
/// (and, for 1097, holds as many entries as 1092).
pub fn keep_resource(doc: &Document, id: u16, data: &[u8]) -> bool {
match id {
GUIDES_V2 => describes(doc, data),
GUIDE_IDS => {
let v2 = doc.metadata.psd_resources.iter().find(|(rid, _, _)| *rid == GUIDES_V2);
v2.is_some_and(|(_, _, d)| describes(doc, d) && parse_v2(d).map(|g| g.len()).and_then(|n| u32::try_from(n).ok()) == ids_count(data))
}
_ => true,
}
}
/// Gives the document's guides the colours an imported 1092 stores. Only guides that 1032
/// also has are coloured, and Photoshop's default colour is left to the preference.
pub fn apply_colors(doc: &mut Document) {
let Some(stored) = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == GUIDES_V2).and_then(|(_, _, d)| parse_v2(d)) else {
return;
};
for g in stored {
if g.rgb == DEFAULT_GUIDE_RGB {
continue;
}
let pos = f64::from(g.location) / 32.0;
let list = if g.vertical { &doc.guides.vertical } else { &doc.guides.horizontal };
if list.contains(&pos) {
doc.guides.set_color(g.vertical, pos, Some(g.rgb));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn v2(guides: &[(i32, u8, [u8; 3])]) -> Vec<u8> {
let mut v = Vec::new();
for n in [2u32, 576, 576, guides.len() as u32] {
v.extend_from_slice(&n.to_be_bytes());
}
for (loc, dir, rgb) in guides {
v.extend_from_slice(&loc.to_be_bytes());
v.extend_from_slice(&[*dir, 0]);
v.extend_from_slice(rgb);
}
v
}
#[test]
fn parses_corpus_layout() {
// clipping-mask4.psd (psd-tools): one vertical and one horizontal guide at 16 px.
let d = v2(&[(512, 0, DEFAULT_GUIDE_RGB), (512, 1, DEFAULT_GUIDE_RGB)]);
let g = parse_v2(&d).unwrap();
assert_eq!(g.len(), 2);
assert!(g[0].vertical && !g[1].vertical);
assert_eq!(g[1].location, 512);
}
#[test]
fn rejects_other_versions_and_short_or_hostile_data() {
let mut d = v2(&[(512, 0, DEFAULT_GUIDE_RGB)]);
assert!(parse_v2(&d[..d.len() - 1]).is_none());
d[3] = 1;
assert!(parse_v2(&d).is_none());
let mut huge = v2(&[]);
huge[12..16].copy_from_slice(&u32::MAX.to_be_bytes());
assert!(parse_v2(&huge).is_none());
assert!(parse_v2(&[]).is_none());
assert!(ids_count(&[0, 0]).is_none());
}
}
+1
View File
@@ -45,6 +45,7 @@ pub mod effects_map;
pub mod exr_parts;
mod flat;
mod gradient_bake;
pub mod guides_map;
pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient};
mod kra;
pub mod linked;
+100 -41
View File
@@ -43,40 +43,43 @@ pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: Sampl
let ch = planes.len();
let row = ch * bps;
let mut out = vec![0u8; n * row];
// One band of rows per core, written straight into its slice of the shared output: the
// per-pixel channel loop stays, but a band holds ~1/cores of a 20 MP image's iterations
// instead of all of them.
if out.is_empty() {
return out;
}
let bs = bands(n);
let parts: Vec<Vec<u8>> = par_map(bs.clone(), |band| {
let mut part = vec![0u8; band.len() * row];
for (i, p) in band.clone().enumerate() {
for (c, plane) in planes.iter().enumerate() {
let dst = &mut part[(i * ch + c) * bps..(i * ch + c + 1) * bps];
match plane {
Some(pl) if pl.len() >= (p + 1) * bps => {
let src = &pl[p * bps..(p + 1) * bps];
for k in 0..bps {
dst[k] = src[bps - 1 - k];
}
if cfg!(target_endian = "big") {
dst.copy_from_slice(src);
}
if invert[c] {
invert_sample(dst, s);
}
}
_ => dst.copy_from_slice(&fill[c]),
}
let step = bs.first().map_or(n, |b| b.len()) * row;
par_map(bs.into_iter().zip(out.chunks_mut(step)).collect(), |(band, part)| {
for (c, plane) in planes.iter().enumerate() {
let src = plane.and_then(|p| p.get(band.start * bps..)).unwrap_or_default();
let inv = src.len() >= bps && invert[c];
let fill = fill.get(c).map(Vec::as_slice).unwrap_or_default();
match s {
SampleType::U8 => write_channel(part, ch, c, src, fill, |[v]| [if inv { 255 - v } else { v }]),
SampleType::U16 => write_channel(part, ch, c, src, fill, |v| {
let v = u16::from_be_bytes(v);
(if inv { 65535 - v } else { v }).to_ne_bytes()
}),
SampleType::F32 => write_channel(part, ch, c, src, fill, |v| {
// Preserve float bits when no inversion is requested.
if inv { (1.0 - f32::from_be_bytes(v)).to_ne_bytes() } else { u32::from_be_bytes(v).to_ne_bytes() }
}),
}
}
part
});
for (band, part) in bs.into_iter().zip(parts) {
out[band.start * row..band.end * row].copy_from_slice(&part);
}
out
}
fn write_channel<const N: usize>(out: &mut [u8], ch: usize, c: usize, src: &[u8], fill: &[u8], decode: impl Fn([u8; N]) -> [u8; N]) {
let mut samples = src.as_chunks::<N>().0.iter();
for pixel in out.chunks_exact_mut(ch * N) {
let dst = &mut pixel[c * N..(c + 1) * N];
match samples.next() {
Some(sample) => dst.copy_from_slice(&decode(*sample)),
None => dst.copy_from_slice(fill),
}
}
}
/// Splits interleaved native-endian bytes into big-endian planes.
pub fn deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) -> Vec<Vec<u8>> {
let bps = s.bytes();
@@ -217,21 +220,29 @@ pub fn bands(n: usize) -> Vec<std::ops::Range<usize>> {
mod tests {
use super::*;
#[test]
fn banded_shuffles_match_a_sequential_reference() {
fn seq_interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: SampleType, invert: &[bool]) -> Vec<u8> {
let bps = s.bytes();
let ch = planes.len();
let mut out = vec![0u8; n * ch * bps];
for (c, plane) in planes.iter().enumerate() {
for i in 0..n {
let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps];
pub(super) fn previous_interleave(planes: &[Option<&[u8]>], fill: &[Vec<u8>], n: usize, s: SampleType, invert: &[bool]) -> Vec<u8> {
let bps = s.bytes();
let ch = planes.len();
let row = ch * bps;
let mut out = vec![0u8; n * row];
// One band of rows per core, written straight into its slice of the shared output: the
// per-pixel channel loop stays, but a band holds ~1/cores of a 20 MP image's iterations
// instead of all of them.
let bs = bands(n);
let parts: Vec<Vec<u8>> = par_map(bs.clone(), |band| {
let mut part = vec![0u8; band.len() * row];
for (i, p) in band.clone().enumerate() {
for (c, plane) in planes.iter().enumerate() {
let dst = &mut part[(i * ch + c) * bps..(i * ch + c + 1) * bps];
match plane {
Some(p) if p.len() >= (i + 1) * bps => {
let src = &p[i * bps..(i + 1) * bps];
Some(pl) if pl.len() >= (p + 1) * bps => {
let src = &pl[p * bps..(p + 1) * bps];
for k in 0..bps {
dst[k] = src[bps - 1 - k];
}
if cfg!(target_endian = "big") {
dst.copy_from_slice(src);
}
if invert[c] {
invert_sample(dst, s);
}
@@ -240,8 +251,16 @@ mod tests {
}
}
}
out
part
});
for (band, part) in bs.into_iter().zip(parts) {
out[band.start * row..band.end * row].copy_from_slice(&part);
}
out
}
#[test]
fn banded_shuffles_match_a_sequential_reference() {
fn seq_deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) -> Vec<Vec<u8>> {
let bps = s.bytes();
let n = bytes.len() / (ch * bps).max(1);
@@ -260,16 +279,17 @@ mod tests {
planes
}
// Odd pixel counts cross band boundaries; a missing plane exercises the fill path.
for n in [1usize, 7, 64, 1000] {
for n in [0usize, 1, 7, 64, 1000] {
for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
let bps = s.bytes();
let planes: Vec<Vec<u8>> = (0..4).map(|c| (0..n * bps).map(|i| (i * 13 + c * 5) as u8).collect()).collect();
let mut refs: Vec<Option<&[u8]>> = planes.iter().map(|p| Some(&p[..])).collect();
refs[2] = None;
refs[3] = Some(&planes[3][..(n * bps).saturating_sub(1)]);
let fill: Vec<Vec<u8>> = (0..4).map(|c| vec![c as u8 * 40; bps]).collect();
let invert = [false, true, false, true];
let got = interleave(&refs, &fill, n, s, &invert);
let want = seq_interleave(&refs, &fill, n, s, &invert);
let want = previous_interleave(&refs, &fill, n, s, &invert);
assert_eq!(got, want, "interleave n={n}");
let planes_back = deinterleave(&got, 4, s, &invert);
let want_back = seq_deinterleave(&got, 4, s, &invert);
@@ -287,6 +307,7 @@ mod tests {
let fill = vec![zero_sample(s); 3];
let inv = [false, true, false];
let il = interleave(&refs, &fill, 4, s, &inv);
assert_eq!(interleave(&refs, &[], 4, s, &inv), il);
let back = deinterleave(&il, 3, s, &inv);
if s == SampleType::F32 {
// 1 - (1 - v) may not be exact for floats; only check non-inverted planes.
@@ -302,6 +323,12 @@ mod tests {
fn missing_planes_use_fill() {
let il = interleave(&[None, Some(&[5, 6])], &[vec![9], vec![0]], 2, SampleType::U8, &[false, false]);
assert_eq!(il, vec![9, 5, 9, 6]);
for s in [SampleType::U8, SampleType::U16, SampleType::F32] {
for n in [1, 1000] {
let fill = vec![vec![9; s.bytes()]; 2];
assert_eq!(interleave(&[None, Some(&[1, 2, 3][..s.bytes() - 1])], &fill, n, s, &[]), vec![9; n * 2 * s.bytes()]);
}
}
}
#[test]
@@ -343,3 +370,35 @@ mod tests {
assert_eq!(decode_be(&f, 0, SampleType::F32), 2.5);
}
}
#[cfg(test)]
mod measurement {
use super::*;
#[test]
#[ignore = "manual 24 MP release benchmark"]
fn benchmark_interleave() {
use std::{hint::black_box, time::Instant};
const N: usize = 24_000_000;
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let bps = sample.bytes();
let planes: Vec<Vec<u8>> = (0..4).map(|c| (0..N * bps).map(|i| (i * 13 + c * 5) as u8).collect()).collect();
let refs: Vec<_> = planes.iter().map(|p| Some(p.as_slice())).collect();
let fill = vec![vec![0; bps]; 4];
let invert = [false, true, false, true];
assert_eq!(tests::previous_interleave(&refs, &fill, N, sample, &invert), interleave(&refs, &fill, N, sample, &invert));
for trial in 0..6 {
let mut paths = [("main", tests::previous_interleave as fn(_, _, _, _, _) -> _), ("split", interleave)];
if trial % 2 == 1 {
paths.reverse();
}
for (name, path) in paths {
let t = Instant::now();
let out = black_box(path)(&refs, &fill, N, sample, &invert);
let elapsed = t.elapsed().as_secs_f64() * 1000.0;
black_box(&out);
println!("interleave,{sample:?},{trial},{name},{elapsed:.6}");
}
}
}
}
}
+4
View File
@@ -1274,6 +1274,10 @@ pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bo
if !crate::annotations_map::keep_resource(doc, id) {
return false;
}
// Guides v2 and guide GUIDs: only while they still describe the document's guides.
if !crate::guides_map::keep_resource(doc, id, data) {
return false;
}
// A preserved clipping-path resource is only valid while it names the current one.
if id == crate::vector_map::CLIPPING_PATH {
let n = usize::from(data.first().copied().unwrap_or(0));
+1
View File
@@ -836,6 +836,7 @@ pub(crate) fn psd_to_document_decoded(
id => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))),
}
}
crate::guides_map::apply_colors(&mut doc);
for b in &file.global_blocks {
doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone())));
}
+128
View File
@@ -0,0 +1,128 @@
//! Image resources 1092 (guides with colours) and 1097 (guide GUIDs) next to 1032 (#5966).
use photocraft_io::guides_map::{DEFAULT_GUIDE_RGB, GUIDE_IDS, GUIDES_V2};
use photocraft_io::*;
use photocraft_psd::testgen;
use photocraft_psd::{Compression, ImageResource, PsdFile, Version};
const RED: [u8; 3] = [0xff, 0x00, 0x00];
type Edit = fn(&mut photocraft_doc::Document);
fn guides_v1(guides: &[(i32, u8)]) -> Vec<u8> {
let mut v = Vec::new();
for n in [1u32, 576, 576, guides.len() as u32] {
v.extend_from_slice(&n.to_be_bytes());
}
for (loc, dir) in guides {
v.extend_from_slice(&loc.to_be_bytes());
v.push(*dir);
}
v
}
fn guides_v2(guides: &[(i32, u8, [u8; 3])]) -> Vec<u8> {
let mut v = Vec::new();
for n in [2u32, 576, 576, guides.len() as u32] {
v.extend_from_slice(&n.to_be_bytes());
}
for (loc, dir, rgb) in guides {
v.extend_from_slice(&loc.to_be_bytes());
v.extend_from_slice(&[*dir, 0]);
v.extend_from_slice(rgb);
}
v
}
fn guide_ids(n: u32) -> Vec<u8> {
let mut v = n.to_be_bytes().to_vec();
for i in 0..n {
let id = format!("0000000{i}-1111-2222-3333-444444444444");
let zero = "00000000-0000-0000-0000-000000000000";
v.extend_from_slice(&36u32.to_be_bytes());
v.extend_from_slice(id.as_bytes());
v.extend_from_slice(&0u32.to_be_bytes());
v.extend_from_slice(&36u32.to_be_bytes());
v.extend_from_slice(zero.as_bytes());
}
v
}
/// A file as Photoshop writes it: a vertical guide at 16 px in the default colour and a red
/// horizontal one at 10 px, in 1032, 1092 and 1097.
fn photoshop_file() -> PsdFile {
let mut f = testgen::small(Version::Psd, Compression::Raw);
f.resources.push(ImageResource::new(1032, guides_v1(&[(512, 0), (320, 1)])));
f.resources.push(ImageResource::new(GUIDES_V2, guides_v2(&[(512, 0, DEFAULT_GUIDE_RGB), (320, 1, RED)])));
f.resources.push(ImageResource::new(GUIDE_IDS, guide_ids(2)));
f
}
fn resource(f: &PsdFile, id: u16) -> Option<&[u8]> {
f.resources.iter().find(|r| r.id == id).map(|r| r.data.as_slice())
}
#[test]
fn colours_come_from_guides_v2() {
let (d, _) = psd_to_document(&photoshop_file());
assert_eq!(d.guides.vertical, [16.0]);
assert_eq!(d.guides.horizontal, [10.0]);
assert_eq!(d.guides.color(false, 10.0), Some(RED));
// The default colour stays with the preference.
assert_eq!(d.guides.color(true, 16.0), None);
}
#[test]
fn unchanged_guides_keep_both_resources_byte_exact() {
let f = photoshop_file();
let (d, _) = psd_to_document(&f);
let out = document_to_psd(&d);
assert_eq!(resource(&out, GUIDES_V2), resource(&f, GUIDES_V2));
assert_eq!(resource(&out, GUIDE_IDS), resource(&f, GUIDE_IDS));
}
#[test]
fn edited_guides_drop_both_resources() {
let (base, _) = psd_to_document(&photoshop_file());
let edits: [(&str, Edit); 4] = [
("clear", |d| d.guides = Default::default()),
("add", |d| d.guides.horizontal.push(40.0)),
("move", |d| {
d.guides.vertical[0] = 20.0;
}),
("recolour", |d| d.guides.set_color(true, 16.0, Some(RED))),
];
for (name, edit) in edits {
let mut d = base.clone();
edit(&mut d);
let out = document_to_psd(&d);
assert!(resource(&out, GUIDES_V2).is_none(), "{name}: stale 1092 written");
assert!(resource(&out, GUIDE_IDS).is_none(), "{name}: stale 1097 written");
let (back, _) = psd_to_document(&out);
assert_eq!(back.guides.vertical, d.guides.vertical, "{name}");
assert_eq!(back.guides.horizontal, d.guides.horizontal, "{name}");
}
}
#[test]
fn mismatched_ids_or_malformed_v2_are_not_kept() {
let mut f = photoshop_file();
f.resources.retain(|r| r.id != GUIDE_IDS);
f.resources.push(ImageResource::new(GUIDE_IDS, guide_ids(3)));
let (d, _) = psd_to_document(&f);
let out = document_to_psd(&d);
assert!(resource(&out, GUIDES_V2).is_some());
assert!(resource(&out, GUIDE_IDS).is_none());
let mut f = photoshop_file();
for r in &mut f.resources {
if r.id == GUIDES_V2 {
r.data.truncate(20);
}
}
let (d, _) = psd_to_document(&f);
assert_eq!(d.guides.color(false, 10.0), None);
let out = document_to_psd(&d);
assert!(resource(&out, GUIDES_V2).is_none());
assert!(resource(&out, GUIDE_IDS).is_none());
}
+4
View File
@@ -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 }
+258 -65
View File
@@ -117,6 +117,16 @@ pub struct Surface {
tiles: BTreeMap<TileCoord, Arc<Tile>>,
}
/// Use stack storage when it fits, otherwise reuse a dynamically sized sample buffer.
fn sample_buffer<'a>(channels: usize, stack: &'a mut [f32], heap: &'a mut Vec<f32>) -> &'a mut [f32] {
if let Some(samples) = stack.get_mut(..channels) {
samples
} else {
heap.resize(channels, 0.0);
heap
}
}
/// Tiles of one pixel value met while moving a surface ([`Surface::translated`]): each scanned
/// once, and one tile kept per value so the targets share it.
#[derive(Default)]
@@ -166,6 +176,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.
@@ -239,11 +298,20 @@ impl Surface {
decode_pixel(&self.format, &self.default_pixel)
}
/// Decode the default pixel, using dynamic storage only when the stack buffer is too small.
fn default_samples<'a>(&self, stack: &'a mut [f32], heap: &'a mut Vec<f32>) -> &'a mut [f32] {
let px = sample_buffer(self.channels(), stack, heap);
for (i, v) in px.iter_mut().enumerate() {
*v = read_sample(&self.default_pixel, self.format.sample, i);
}
px
}
/// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it.
pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile {
let fmt = self.format;
let dp = self.default_pixel.clone();
let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, &dp)));
let dp = &self.default_pixel;
let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp)));
Arc::make_mut(arc)
}
@@ -319,9 +387,9 @@ impl Surface {
/// Drop tiles that are entirely the default pixel.
pub fn prune(&mut self) {
let dp = self.default_pixel.clone();
let dp = self.default_pixel.as_ref();
let bpp = dp.len();
self.tiles.retain(|_, t| t.data.chunks_exact(bpp).any(|px| px != &*dp));
self.tiles.retain(|_, t| t.data.chunks_exact(bpp).any(|px| px != dp));
}
#[inline]
@@ -411,14 +479,27 @@ impl Surface {
let w = r.width() as usize;
out.clear();
out.resize(w * r.height() as usize * n, 0.0);
let dp = self.default_pixel();
self.read_samples_into(r, out);
}
/// Copy samples into a zero-initialized buffer sized for `r`.
fn read_samples_into(&self, r: Rect, out: &mut [f32]) {
let n = self.channels();
let w = r.width() as usize;
let mut stack = [0.0; 8];
let mut heap = Vec::new();
let dp = self.default_samples(&mut stack, &mut heap);
let zero = self.default_pixel.iter().all(|&b| b == 0);
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
let tile = self.tiles.get(&tc);
if tile.is_none() && zero {
continue;
}
for y in tr.y0..tr.y1 {
let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n;
let span = tr.width() as usize * n;
let dst = &mut out[o..o + span];
let Some(dst) = out.get_mut(o..o + span) else { continue };
match tile {
Some(t) => {
let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n;
@@ -426,9 +507,10 @@ impl Surface {
*d = read_sample(&t.data, self.format.sample, base + i);
}
}
None if n == 1 => dst.fill(dp[0]),
None => {
for px in dst.chunks_exact_mut(n) {
px.copy_from_slice(&dp);
px.copy_from_slice(dp);
}
}
}
@@ -445,7 +527,10 @@ impl Surface {
debug_assert_eq!(out.len(), w * r.height() as usize);
let fmt = self.format;
let n = fmt.channels();
let dp = to_rgba(&fmt, &self.default_pixel());
let mut stack = [0.0; 8];
let mut heap = Vec::new();
let px = self.default_samples(&mut stack, &mut heap);
let dp = to_rgba(&fmt, px);
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
let tile = self.tiles.get(&tc);
@@ -489,12 +574,11 @@ impl Surface {
}
}
_ => {
let mut px = [0.0f32; 8];
for (i, d) in dst.iter_mut().enumerate() {
for (c, v) in px.iter_mut().enumerate().take(n) {
for (c, v) in px.iter_mut().enumerate() {
*v = read_sample(&t.data, fmt.sample, base + i * n + c);
}
*d = to_rgba(&fmt, &px[..n]);
*d = to_rgba(&fmt, px);
}
}
}
@@ -510,7 +594,9 @@ impl Surface {
let fmt = self.format;
let rgba8 = matches!((fmt.mode, fmt.sample, fmt.alpha), (ColorMode::Rgb, SampleType::U8, true));
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let dp = to_rgba(&fmt, &self.default_pixel());
let mut stack = [0.0; 8];
let mut heap = Vec::new();
let dp = to_rgba(&fmt, self.default_samples(&mut stack, &mut heap));
let dp8 = [q(dp[0]), q(dp[1]), q(dp[2]), q(dp[3])];
let mut row = Vec::new();
for tc in r.tiles() {
@@ -551,68 +637,43 @@ impl Surface {
let n = self.channels();
let w = r.width() as usize;
let mut out = vec![0.0f32; w * r.height() as usize * n];
let dp = self.default_pixel();
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
let tile = self.tiles.get(&tc);
for y in tr.y0..tr.y1 {
for x in tr.x0..tr.x1 {
let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n;
match tile {
Some(t) => {
let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n;
for i in 0..n {
out[o + i] = read_sample(&t.data, self.format.sample, base + i);
}
}
None => out[o..o + n].copy_from_slice(&dp),
}
}
}
}
self.read_samples_into(r, &mut out);
out
}
/// Write interleaved normalised floats into a rectangle.
/// Write interleaved normalised floats into a rectangle, on the calling thread.
///
/// This never enters Rayon, so it is safe inside a `OnceLock` initializer or any other
/// section that must not run another Rayon job on its stack. [`Surface::write_region_par`]
/// writes the same bytes on all cores.
pub fn write_region(&mut self, r: Rect, data: &[f32]) {
let n = self.channels();
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());
}
}
}
}
write_tile(self.tile_mut(tc), tc, r, data, w, n, sample);
}
}
/// [`Surface::write_region`] with the tiles converted on all cores (serially on the web).
///
/// This enters Rayon: while it waits for its tiles, the calling worker may run any other
/// queued Rayon job. Callers inside a `OnceLock` initializer or another section that must
/// not do that use [`Surface::write_region`].
pub fn write_region_par(&mut self, r: Rect, data: &[f32]) {
let n = self.channels();
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;
// The tiles are disjoint, so converting them in any order (and on any thread) writes
// exactly the same bytes. `take_tiles` gives the missing tiles as one shared
// default-filled tile, copied per tile by `Arc::make_mut` in `convert_tiles`.
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 default
/// pixel), so they can be edited elsewhere, e.g. in parallel: `Arc::unwrap_or_clone` copies a
/// tile only if an undo snapshot still shares it. Give them back with [`Surface::put_tiles`].
@@ -1102,6 +1163,60 @@ pub fn is_hdr(sample: SampleType) -> bool {
#[cfg(test)]
mod tests {
/// Manually compare allocating reads with the previous implementation.
#[test]
#[ignore = "manual 24 MP release benchmark"]
fn benchmark_sparse_reads() {
use std::{hint::black_box, time::Instant};
let rect = Rect::new(0, 0, 6000, 4000);
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for default in [0.0, 0.25] {
let mut s = Surface::with_default(PixelFormat::GRAY8.with_sample(depth), &[default]);
s.fill_rect(Rect::new(257, 257, 266, 266), &[0.75]);
assert_eq!(s.read_region(rect), previous_read_region(&s, rect));
for trial in 0..6 {
let mut paths = [("main", previous_read_region as fn(&Surface, Rect) -> Vec<f32>), ("split", Surface::read_region)];
if trial % 2 == 1 {
paths.reverse();
}
for (name, path) in paths {
let t = Instant::now();
let out = black_box(path)(&s, rect);
let elapsed = t.elapsed().as_secs_f64() * 1000.0;
black_box(&out);
println!("sparse,{depth:?}-{default},{trial},{name},{elapsed:.6}");
}
}
}
}
}
/// Previous allocating read path, retained as the bitwise-equivalence oracle.
fn previous_read_region(surface: &Surface, r: Rect) -> Vec<f32> {
let n = surface.channels();
let w = r.width() as usize;
let mut out = vec![0.0f32; w * r.height() as usize * n];
let dp = surface.default_pixel();
for tc in r.tiles() {
let tr = tc.rect().intersect(&r);
let tile = surface.tiles.get(&tc);
for y in tr.y0..tr.y1 {
for x in tr.x0..tr.x1 {
let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n;
match tile {
Some(t) => {
let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n;
for i in 0..n {
out[o + i] = read_sample(&t.data, surface.format.sample, base + i);
}
}
None => out[o..o + n].copy_from_slice(&dp),
}
}
}
}
out
}
/// Distinct tile allocations in `s`.
fn distinct_tiles(s: &Surface) -> usize {
let mut seen: Vec<*const Tile> = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect();
@@ -1213,19 +1328,52 @@ mod tests {
.collect();
let snapshot = actual.clone();
let snapshot_bytes = snapshot.to_interleaved(rect.inflate(1));
let mut par = actual.clone();
actual.write_region(rect, &data);
par.write_region_par(rect, &data);
write_region_reference(&mut expected, rect, &data);
assert_eq!(actual, expected, "{fmt:?}, {rect:?}");
assert_eq!(par, expected, "parallel {fmt:?}, {rect:?}");
assert_eq!(snapshot.to_interleaved(rect.inflate(1)), snapshot_bytes, "COW snapshot changed");
// Repeat against already materialised, unshared tiles too.
actual.write_region(rect, &data);
par.write_region_par(rect, &data);
assert_eq!(actual, expected);
assert_eq!(par, expected);
}
}
}
}
}
/// Mask builds call `write_region` inside a `OnceLock` initializer, where entering Rayon can
/// run another tile's job that waits on the same lock. With every global worker held, a write
/// that queued work on Rayon could not finish.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn write_region_does_not_enter_rayon() {
use std::sync::{Barrier, mpsc};
let workers = rayon::current_num_threads();
let held = Arc::new(Barrier::new(workers + 1));
let release = Arc::new(Barrier::new(workers + 1));
let (h, rel) = (held.clone(), release.clone());
rayon::spawn_broadcast(move |_| {
h.wait();
rel.wait();
});
held.wait();
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let r = Rect::new(0, 0, 2 * TILE_SIZE, 2 * TILE_SIZE);
let mut s = Surface::new(PixelFormat::RGBA8);
s.write_region(r, &vec![0.5; (r.width() * r.height() * 4) as usize]);
tx.send(()).ok();
});
let done = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok();
release.wait();
assert!(done, "write_region waited on the Rayon pool");
}
#[test]
fn from_rgba_into_matches_from_rgba() {
for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] {
@@ -1235,29 +1383,74 @@ mod tests {
}
}
/// Sample counts above the stack capacity use writable storage without truncating channels.
#[test]
fn sample_buffer_keeps_stack_fast_path_and_supports_dynamic_channels() {
for channels in [1, 8, 9, 32] {
let mut stack = [0.0; 8];
let mut heap = Vec::new();
let samples = sample_buffer(channels, &mut stack, &mut heap);
assert_eq!(samples.len(), channels);
samples.fill(0.25);
if channels <= stack.len() {
assert!(heap.is_empty());
assert_eq!(&stack[..channels], vec![0.25; channels]);
} else {
assert_eq!(heap, vec![0.25; channels]);
}
}
}
/// Compare sparse reads and converted accessors with the previous allocating path.
#[test]
fn zero_alloc_accessors_match_read_region() {
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::GRAY8] {
let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]);
for (fmt, default) in [
PixelFormat::RGBA8,
PixelFormat::RGBA16,
PixelFormat::RGBA32F,
PixelFormat::GRAYA8,
PixelFormat::CMYKA8,
PixelFormat::GRAY8,
PixelFormat::GRAY8.with_sample(SampleType::F32),
PixelFormat::new(ColorMode::Lab, SampleType::U16, true),
]
.into_iter()
.flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default)))
{
let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]);
let mut stack = [0.0; 8];
let mut heap = Vec::new();
for capacity in [0, stack.len()] {
let decoded = s.default_samples(&mut stack[..capacity], &mut heap);
assert!(decoded.iter().map(|v| v.to_bits()).eq(s.default_pixel().into_iter().map(f32::to_bits)));
}
let r = Rect::new(-300, -20, 300, 40);
for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() {
let px: Vec<f32> = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect();
s.write_pixel(x, y, &px);
}
let region = s.read_region(r);
assert!(region.iter().map(|v| v.to_bits()).eq(previous_read_region(&s, r).into_iter().map(f32::to_bits)));
let mut into = vec![9.0; 3];
s.read_region_into(r, &mut into);
assert_eq!(region, into);
let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize];
s.read_rgba_into(r, &mut rgba);
let mut rgba8 = vec![[0; 4]; rgba.len()];
s.read_rgba8_into(r, &mut rgba8);
let n = fmt.channels();
for (i, p) in region.chunks_exact(n).enumerate() {
let want = to_rgba(&fmt, p);
assert_eq!(rgba8[i], want.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8));
for c in 0..4 {
assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}");
}
let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32);
assert_eq!(s.sample_channel(x, y, 0), p[0]);
for c in 0..n {
let bits = s.sample_channel(x, y, c).to_bits();
assert_eq!(bits, p[c].to_bits());
assert_eq!(bits, into[i * n + c].to_bits());
}
}
assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1)));
assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001)));
+2
View File
@@ -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.
+36 -11
View File
@@ -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_par(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`]).
+33 -1
View File
@@ -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();
+38 -1
View File
@@ -29,6 +29,8 @@ pub(crate) struct BlendPreview {
area: Option<Rect>,
/// The document shown for `mode`, with its key.
shown: Option<(u64, Arc<Document>)>,
/// GPU preview key, affected region (including effects), and rectangles already refreshed.
covered: Option<(u64, Rect, Vec<Rect>)>,
}
/// The Layers panel, each frame it draws `layer`'s blend-mode dropdown: the mode under the
@@ -54,7 +56,7 @@ pub(crate) fn hover(app: &mut PhotocraftApp, layers: &[LayerId], mode: Option<Bl
_ => None,
};
}
Some(BlendPreview { doc, revision, layers: layers.to_vec(), mode: Some(mode), frame, area, shown: None })
Some(BlendPreview { doc, revision, layers: layers.to_vec(), mode: Some(mode), frame, area, shown: None, covered: None })
});
}
@@ -96,6 +98,41 @@ pub(crate) fn damage(app: &PhotocraftApp, doc: DocId, revision: u64, seen: u64,
(seen != now && ours(seen) && ours(now) && (is_preview_key(seen) || is_preview_key(now))).then_some(p.area)?
}
/// Limit an active preview to the view. Returning to the document restores the whole region.
pub(crate) fn clip_damage(app: &mut PhotocraftApp, doc: DocId, revision: u64, key: u64, region: Rect, visible: Rect) -> Rect {
let Some(p) = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision) else { return region };
if !p.shown.as_ref().is_some_and(|(shown, _)| *shown == key) {
p.covered = None;
return region;
}
let shown = region.intersect(&visible);
p.covered = Some((key, region, vec![shown]));
shown
}
/// A pan or zoom can expose pixels not yet rendered for the current preview key.
pub(crate) fn uncovered(app: &mut PhotocraftApp, doc: DocId, revision: u64, key: u64, visible: Rect) -> Option<Rect> {
let p = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision)?;
let (covered_key, region, covered) = p.covered.as_mut()?;
if *covered_key != key {
return None;
}
let want = region.intersect(&visible);
if want.is_empty() || covered.iter().any(|r| r.contains_rect(&want)) {
return None;
}
// Keep disjoint views without marking the unrendered gaps between them as covered.
// Bound bookkeeping during long pans: after eight rectangles, render the whole affected
// region once. A different mode/revision resets coverage through `clip_damage`.
covered.retain(|r| !want.contains_rect(r));
let refresh = if covered.len() < 8 { want } else { *region };
if refresh == *region {
covered.clear();
}
covered.push(refresh);
Some(refresh)
}
fn is_preview_key(key: u64) -> bool {
(BASE..BASE << 1).contains(&key)
}
+34
View File
@@ -138,3 +138,37 @@ fn a_hovered_mode_previews_on_every_selected_layer() {
hover(&mut app, &[top], Some(BlendMode::Multiply));
assert_ne!(display_doc(&mut app, 0).unwrap().1, key);
}
#[test]
fn blend_hover_disjoint_coverage_retains_views_without_hiding_gaps() {
let (s, top) = session();
let mut app = PhotocraftApp::new(s, crate::Services::default());
hover(&mut app, &[top], Some(BlendMode::Multiply));
let (_, key) = display_doc(&mut app, 0).unwrap();
let st = app.session.active().unwrap();
let (id, revision, region) = (st.doc.id, st.revision, st.doc.bounds());
let a = photocraft_geom::Rect::new(0, 0, 2, 2);
let b = photocraft_geom::Rect::new(4, 0, 6, 2);
assert_eq!(super::clip_damage(&mut app, id, revision, key, region, a), a);
assert_eq!(super::uncovered(&mut app, id, revision, key, b), Some(b));
assert_eq!(super::uncovered(&mut app, id, revision, key, a), None);
let gap = photocraft_geom::Rect::new(2, 0, 4, 2);
assert_eq!(super::uncovered(&mut app, id, revision, key, gap), Some(gap));
// Repeated distinct views have bounded bookkeeping, then the whole region is current.
let mut fell_back = false;
for x in (8..40).step_by(4) {
let visible = photocraft_geom::Rect::new(x, 0, x + 2, 2);
if super::uncovered(&mut app, id, revision, key, visible) == Some(region) {
fell_back = true;
break;
}
}
assert!(fell_back);
assert_eq!(super::uncovered(&mut app, id, revision, key, region), None);
hover(&mut app, &[top], Some(BlendMode::Screen));
let (_, next) = display_doc(&mut app, 0).unwrap();
assert_eq!(super::clip_damage(&mut app, id, revision, next, region, a), a);
assert_eq!(super::uncovered(&mut app, id, revision, next, b), Some(b));
hover(&mut app, &[top], None);
assert_eq!(super::clip_damage(&mut app, id, revision, 0, region, a), region);
}
+16 -1
View File
@@ -1608,10 +1608,16 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible:
};
let (doc, raw_key) = display_doc(app, idx);
let (display, _) = canvas_display(app, &doc, None);
// Repeated pattern tiles sample the same texture, including pixels outside the unwrapped
// viewport. Refresh the affected document region while Pattern Preview is enabled.
let blend_visible = if app.ui.view.pattern_preview { doc.bounds() } else { visible };
// The texture is shared by every display: only what it stores counts, not the monitor.
let display_key = texture_key(display.as_deref());
let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key));
let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage));
if let Some(region) = damage {
damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, blend_visible));
}
// To an adjustment dialog's preview: only what the view shows now (the rest as it moves there).
if damage.is_some()
&& let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::switch_region(app, id, revision, s.1 ^ display_key, raw_key))
@@ -1671,7 +1677,12 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible:
let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref());
app.perf.record_refresh(&r);
}
return true;
// Blend previews keep offscreen pixels untouched until the view reaches them.
// Use the normal refresh path so CPU fallback and pending redraws stay synchronized.
damage = crate::blend_preview::uncovered(app, id, revision, raw_key, blend_visible);
if damage.is_none() {
return true;
}
}
// Display textures for a canvas this large would not fit the GPU: the reduced CPU canvas
// draws it (checked before the memory budget, which walks the history, every frame).
@@ -8959,3 +8970,7 @@ mod rotation_preview_isolation_tests {
#[cfg(test)]
#[path = "canvas_display_memo_tests.rs"]
mod display_memo_tests;
#[cfg(test)]
#[path = "canvas/blend_viewport_tests.rs"]
mod blend_viewport_regression;
@@ -0,0 +1,198 @@
use super::*;
use photocraft_color::BlendMode;
use serde_json::json;
fn render_state() -> Option<eframe::egui_wgpu::RenderState> {
match std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) {
Ok(rs) => Some(rs),
Err(error) => {
if std::env::var_os("PHOTOCRAFT_REQUIRE_GPU_TESTS").is_some() {
std::panic::resume_unwind(error);
}
eprintln!("skipping blend viewport regression: no GPU adapter");
None
}
}
}
#[test]
fn blend_hover_refresh_is_limited_to_visible_canvas() {
check_blend_viewport(false, false);
}
#[test]
fn blend_hover_cpu_fallback_refresh_tracks_visible_canvas() {
check_blend_viewport(true, false);
}
#[test]
fn blend_hover_multiple_layers_tracks_visible_canvas() {
check_blend_viewport(false, true);
}
#[test]
fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() {
let _guard = photocraft_testkit::gpu_lock();
let Some(rs) = render_state() else { return };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.set_wgpu(rs);
app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap();
let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
app.run("edit.fill", json!({"color":"#cc8844"})).unwrap();
let ctx = egui::Context::default();
let a = DRect::new(724, 200, 1324, 500);
let b = DRect::new(0, 200, 300, 500);
assert!(ensure_gpu(&mut app, &ctx, 0, a));
app.ui.view.pattern_preview = true;
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply));
assert!(ensure_gpu(&mut app, &ctx, 0, a));
assert_visible_pixels(&mut app, b);
let bounds = app.session.active().unwrap().doc.bounds();
assert_visible_pixels(&mut app, bounds);
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None);
assert!(ensure_gpu(&mut app, &ctx, 0, a));
assert_visible_pixels(&mut app, bounds);
app.ui.view.pattern_preview = false;
for mode in [BlendMode::Multiply, BlendMode::Screen] {
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(mode));
assert!(ensure_gpu(&mut app, &ctx, 0, a));
assert!(ensure_gpu(&mut app, &ctx, 0, b));
for visible in [a, b, a, b] {
app.perf.last_refresh_px = 0;
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
assert_eq!(app.perf.last_refresh_px, 0, "unchanged views must retain coverage together");
assert_visible_pixels(&mut app, visible.intersect(&bounds));
}
}
// Enabling periodic display during an existing hover must catch up the unseen gap too.
app.ui.view.pattern_preview = true;
assert!(ensure_gpu(&mut app, &ctx, 0, a));
assert_visible_pixels(&mut app, bounds);
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None);
assert!(ensure_gpu(&mut app, &ctx, 0, a));
assert_visible_pixels(&mut app, bounds);
}
#[test]
fn blend_hover_during_background_redraw_restores_committed_pixels() {
let _guard = photocraft_testkit::gpu_lock();
let Some(rs) = render_state() else { return };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.set_wgpu(rs);
app.background_jobs = true;
app.run("file.new", json!({"width":2600,"height":1700,"background":"#336699"})).unwrap();
let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
app.run("edit.fill", json!({"color":"#cc8844"})).unwrap();
app.run("layer.layerStyle.blendingOptions", json!({"knockout":"shallow"})).unwrap();
let ctx = egui::Context::default();
let visible = DRect::new(256, 256, 512, 512);
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
assert!(!app.redraws.is_empty(), "fixture must start a deferred full redraw");
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply));
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
let panned = DRect::new(2048, 1024, 2304, 1280);
assert!(ensure_gpu(&mut app, &ctx, 0, panned));
settle_redraw(&mut app);
assert_visible_pixels(&mut app, panned);
crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None);
assert!(ensure_gpu(&mut app, &ctx, 0, panned));
settle_redraw(&mut app);
let bounds = app.session.active().unwrap().doc.bounds();
assert_visible_pixels(&mut app, bounds);
}
fn settle_redraw(app: &mut PhotocraftApp) {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
let gpu = app.gpu.clone().unwrap();
let id = app.session.active().unwrap().doc.id;
while !app.redraws.is_empty() {
crate::background_redraw::poll(app, &gpu, id);
assert!(std::time::Instant::now() < deadline, "background redraw did not finish");
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
fn assert_visible_pixels(app: &mut PhotocraftApp, visible: DRect) {
let (doc, _) = display_doc(app, 0);
let gpu = app.gpu.clone().unwrap();
let reference = doc.id.0 ^ (1u64 << 60);
let (display, _) = canvas_display(app, &doc, None);
gpu.upload_composite(reference, &doc, display.as_deref());
let (_, size, shown) = gpu.read_texels(doc.id.0).unwrap();
let (_, _, want) = gpu.read_texels(reference).unwrap();
for y in visible.y0..visible.y1 {
for x in visible.x0..visible.x1 {
let index = y as usize * size[0] as usize + x as usize;
for channel in 0..4 {
assert!((shown[index][channel] - want[index][channel]).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel{channel}");
}
}
}
}
fn check_blend_viewport(cpu_fallback: bool, multiple_layers: bool) {
let _guard = photocraft_testkit::gpu_lock();
let Some(rs) = render_state() else { return };
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.set_wgpu(rs);
app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap();
let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
app.run("edit.fill", json!({"color":"#cc8844"})).unwrap();
if cpu_fallback {
app.run("layer.layerStyle.blendingOptions", json!({"knockout":"shallow"})).unwrap();
}
let mut layers = vec![photocraft_doc::LayerId(layer)];
if multiple_layers {
let other = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
app.run("edit.fill", json!({"color": "#4488cc"})).unwrap();
app.run("layer.setProps", json!({"layer": other, "opacity": 0.5})).unwrap();
layers.push(photocraft_doc::LayerId(other));
}
let ctx = egui::Context::default();
let visible = DRect::new(256, 256, 512, 512);
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
assert!(app.redraws.is_empty(), "small fixture must finish synchronously");
if cpu_fallback {
assert!(!app.perf.last_refresh.starts_with("gpu"), "fixture must exercise CPU composition fallback");
}
let id = app.session.active().unwrap().doc.id;
let gpu = app.gpu.clone().unwrap();
let original = gpu.read_texels(id.0).unwrap();
crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply));
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 256 * 256, app.perf.gpu_info);
assert_eq!(app.perf.last_refresh_px, 256 * 256, "hover must not recomposite offscreen pixels of a full-canvas layer");
assert_visible_pixels(&mut app, visible);
app.perf.last_refresh_px = 0;
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture");
let zoomed_out = DRect::new(128, 128, 640, 640);
assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out));
assert_eq!(app.perf.last_refresh_px, 512 * 512, "zooming out catches up the larger visible area");
let panned = DRect::new(640, 256, 896, 512);
assert!(ensure_gpu(&mut app, &ctx, 0, panned));
assert_eq!(app.perf.last_refresh_px, 256 * 256, "newly exposed pixels must catch up without a mode change");
crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Screen));
assert!(ensure_gpu(&mut app, &ctx, 0, panned));
assert_eq!(app.perf.last_refresh_px, 256 * 256);
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
assert_eq!(app.perf.last_refresh_px, 256 * 256, "returning view must show the current mode");
assert_visible_pixels(&mut app, visible);
assert_visible_pixels(&mut app, panned);
crate::blend_preview::hover(&mut app, &layers, None);
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
assert_eq!(gpu.read_texels(id.0).unwrap(), original, "cancel must restore the whole texture, including previously previewed offscreen pixels");
crate::blend_preview::hover(&mut app, &layers, Some(BlendMode::Multiply));
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
app.run("layer.setProps", json!({"layer":layer,"blend":"Multiply"})).unwrap();
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
let bounds = app.session.active().unwrap().doc.bounds();
assert_visible_pixels(&mut app, bounds);
app.run("file.new", json!({"width":1024,"height":768,"background":"white"})).unwrap();
assert!(ensure_gpu(&mut app, &ctx, 1, visible));
app.session.set_active(0);
app.sync_views();
assert!(ensure_gpu(&mut app, &ctx, 0, visible));
assert_visible_pixels(&mut app, bounds);
}
+1
View File
@@ -143,6 +143,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.
| Date | Change | Summary |
|---|---|---|
| 2026-10-15 | minor | PNG: a stereo PNG's `sTER` pairing (PNG Extensions 1.4.0 §3.6) is read on open and written back on save, so the file still says it is a stereo pair (#6063) |
| 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) |
| 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 |
| 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) |
| 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |
+46
View File
@@ -0,0 +1,46 @@
# PSD pixel buffer allocation
Write PSD interleaved pixels directly into the final buffer. Direct RLE output is already on main. The unrelated export-side sample-encoder inlining hint is removed locally.
Whole-photo imports improve by about 4–7%, and the authored designs by about 20–26%. An added export-side inlining hint accompanied a separately confirmed 2.3% float PSD export slowdown (2440.168 → 2497.423 ms). Removing that one line leaves export source equal to main; follow-up float export is +0.4% and 16-bit export +0.9%, with both paired intervals crossing zero. These results supersede the much larger previous interleave-only percentages.
Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions.
The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used.
The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance.
| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes |
|---|---|---:|---:|---:|---:|---:|
| panasonic-32 | psd-export (fixed) | 2471.456 | 2481.877 | +0.4% | -0.1..+1.7% | 461,042,978 / 461,042,978 |
| panasonic-16 | psd-export (fixed) | 2649.246 | 2673.071 | +0.9% | -5.2..+1.6% | 274,409,683 / 274,409,683 |
| panasonic-8 | psd-import | 275.828 | 262.237 | -4.9% | -5.9..-4.1% | 98,823,859 / 98,823,859 |
| panasonic-8 | psd-export | 2937.854 | 2915.929 | -0.7% | -11.5..+5.6% | 98,823,859 / 98,823,859 |
| panasonic-16 | psd-import | 365.901 | 349.827 | -4.4% | -4.4..-2.6% | 274,409,683 / 274,409,683 |
| panasonic-32 | psd-import | 360.706 | 334.838 | -7.2% | -12.6..-4.4% | 461,042,978 / 461,042,978 |
| canon-8 | psd-import | 141.331 | 135.878 | -3.9% | -5.1..-3.6% | 56,209,597 / 56,209,597 |
| canon-8 | psd-export | 1052.421 | 1054.472 | +0.2% | -0.6..+1.3% | 56,209,597 / 56,209,597 |
| canon-16 | psd-import | 177.327 | 169.952 | -4.2% | -5.5..-1.7% | 140,673,004 / 140,673,004 |
| canon-16 | psd-export | 1248.449 | 1239.159 | -0.7% | -1.6..+0.6% | 140,673,004 / 140,673,004 |
| canon-32 | psd-import | 175.721 | 163.271 | -7.1% | -9.3..-4.9% | 228,234,238 / 228,234,238 |
| canon-32 | psd-export | 1008.772 | 1005.356 | -0.3% | -1.8..+0.7% | 228,234,238 / 228,234,238 |
| layout-masks | psd-import | 12.509 | 9.981 | -20.2% | -20.8..-14.5% | 493,006 / 493,006 |
| layout-masks | psd-export | 55.113 | 54.714 | -0.7% | -2.3..+1.2% | 493,006 / 493,006 |
| layout-mask-index | psd-import | 3.299 | 2.443 | -25.9% | -30.8..-23.4% | 411,435 / 411,435 |
| layout-mask-index | psd-export | 18.200 | 18.397 | +1.1% | -0.1..+1.7% | 411,435 / 411,435 |
Real PSD exports remain byte-identical and imported layer/mask float samples match main. The committed literal previous-interleave oracle covers depths, bands, fills, truncation and inversion.
Current local checks: affected `pixels::` unit tests (five passed, one ignored manual benchmark); strict all-target IO Clippy; affected IO wasm32 check. All passed. Follow-up exports at float and 16-bit depth remain byte-identical to main; no synthetic timing test was run.
Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run.
## Earlier split validation
These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed.
- `cargo test -p photocraft-io --locked`: passed (617 passed, 6 ignored).
- `cargo clippy -p photocraft-io --locked --all-targets -- -D warnings`: passed.
- `cargo xtask layers`: passed.
- `cargo check -p photocraft-io --locked --target wasm32-unknown-unknown`: passed.
- `cargo xtask test-corpus -p io`: passed (646 passed, 6 ignored).
+45
View File
@@ -0,0 +1,45 @@
# Sparse raster reads
Skip absent zero-default tiles and avoid temporary default-pixel allocations and copies. ZIP CRC acceleration is already on main.
A roughly 4% median dense 16-bit city-photo read slowdown repeated, with paired intervals crossing zero. The local fix shares the existing contiguous row loop between allocating and reusable-buffer reads, removes duplicated code, and preserves zero-filled allocation for allocating reads. Final measurements include all photo depths and authored designs; all outputs match bit for bit.
Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions.
The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used.
The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance.
| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes |
|---|---|---:|---:|---:|---:|---:|
| panasonic-16 | read (fixed) | 54.689 | 41.140 | -24.8% | -28.0..-23.8% | — |
| panasonic-16 | render (fixed) | 38.492 | 38.345 | -0.4% | -1.8..+2.0% | — |
| canon-16 | read (fixed) | 27.634 | 19.236 | -30.4% | -34.0..-23.3% | — |
| panasonic-8 | read (fixed) | 50.429 | 20.210 | -59.9% | -62.2..-56.7% | — |
| panasonic-8 | render (fixed) | 30.953 | 30.670 | -0.9% | -3.4..+1.5% | — |
| panasonic-32 | read (fixed) | 91.120 | 69.922 | -23.3% | -23.6..-20.7% | — |
| panasonic-32 | render (fixed) | 39.436 | 39.867 | +1.1% | -4.5..+3.7% | — |
| canon-8 | read (fixed) | 24.899 | 10.543 | -57.7% | -58.5..-54.9% | — |
| canon-8 | render (fixed) | 16.925 | 16.901 | -0.1% | -5.6..+5.5% | — |
| canon-16 | render (fixed) | 21.569 | 21.716 | +0.7% | -2.2..+2.4% | — |
| canon-32 | read (fixed) | 45.494 | 35.200 | -22.6% | -23.5..-21.5% | — |
| canon-32 | render (fixed) | 22.056 | 22.180 | +0.6% | -1.8..+6.9% | — |
| layout-masks | read (fixed) | 35.240 | 3.438 | -90.2% | -90.7..-89.9% | — |
| layout-masks | render (fixed) | 8.167 | 7.461 | -8.6% | -10.6..-8.3% | — |
| layout-mask-index | read (fixed) | 2.314 | 1.051 | -54.6% | -61.7..-50.0% | — |
| layout-mask-index | render (fixed) | 1.926 | 1.827 | -5.1% | -13.0..+0.6% | — |
All real read-region and render float bits match main. The committed previous-read-region oracle also covers sparse boundaries, negative coordinates, signed zero, defaults and eight pixel formats.
Current local checks: `cargo test -p photocraft-raster --locked --lib` (27 passed, one ignored manual benchmark); strict all-target Clippy; affected wasm32 check. All passed. The existing previous-read-path oracle covers the shared loop.
Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run.
## Earlier split validation
These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed.
- `cargo test -p photocraft-raster --locked`: passed (27 passed, 1 ignored).
- `cargo clippy -p photocraft-raster --locked --all-targets -- -D warnings`: passed.
- `cargo xtask layers`: passed.
- `cargo check -p photocraft-raster --locked --target wasm32-unknown-unknown`: passed.
+63
View File
@@ -0,0 +1,63 @@
# 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 run on all cores (rayon, native only; the web
build keeps the serial loops, since wasm has no threads). The rasterizer writes its tiles with
`Surface::write_region_par`; `Surface::write_region` stays serial, because mask builds call it inside
a `OnceLock` initializer, which must not enter rayon. 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_writes_match_scalar_bytes_for_every_format` compares `write_region` and `write_region_par`
against a scalar 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.
+5
View File
@@ -168,6 +168,9 @@ pub fn parse_budgets(text: &str) -> Result<Budgets, String> {
if !(b.settings.regression_pct.is_finite() && b.settings.regression_pct > 0.0) {
return Err(format!("{BUDGETS}: settings.regression_pct must be > 0"));
}
if !(b.settings.regression_min_ms.is_finite() && b.settings.regression_min_ms >= 0.0) {
return Err(format!("{BUDGETS}: settings.regression_min_ms must be finite and >= 0"));
}
Ok(b)
}
@@ -980,6 +983,8 @@ not_measurable = "needs a frame harness"
.is_err()
);
assert!(parse_budgets("[settings]\nregression_pct = 0\n").is_err());
assert!(parse_budgets("[settings]\nregression_min_ms = -1\n").is_err());
assert!(parse_budgets("[settings]\nregression_min_ms = 0\n").is_ok());
assert!(parse_budgets("bogus = 1\n").is_err());
assert!(parse_budgets("not toml [").is_err());
}