Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

perf(gpu): blend plain layers several to a pass, P60/P61 111 -> 28 ms

Akos Arinton33dd5f0103c9
diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl
index 6457b1192..1b62e2d46 100644
--- a/crates/gpu/src/compose.wgsl
+++ b/crates/gpu/src/compose.wgsl
@@ -31,6 +31,13 @@ struct Op {
map_origin: vec2<i32>,
map_size: vec2<i32>,
p4: vec4<f32>,
+ // fs_layerbatch's third extra layer and the rest of its second (see `batch_layer`); zero
+ // elsewhere. With them the record fills its 256-byte stride.
+ q0: vec4<f32>,
+ q1: vec4<f32>,
+ q2: vec4<f32>,
+ q3: vec4<f32>,
+ q4: vec4<f32>,
};
const F_MASK: u32 = 1u; // layer has an enabled mask
@@ -53,6 +60,7 @@ const F_QUANT: u32 = 32768u; // lerp: A rounded to p0.x steps (adjustment res
const F_ADD_DIFF: u32 = 16384u; // lerp: A + (B - C) premultiplied (clips on pass-through groups)
const F_BLEND_IF: u32 = 524288u; // lerp: B back towards A by the Blend If ranges in p0..p3
const F_TEXT_GAMMA: u32 = 8192u; // blend / atop / fx merge: type layer, mix coverage at gamma p4.w
+const F_LAYER_SHAPE: u32 = 1048576u; // fx merge: B is the shape; layer = its colour at fill p0.x inside it × its alpha
@group(0) @binding(0) var<uniform> chunk: Chunk;
@group(0) @binding(1) var<uniform> op: Op;
@@ -312,6 +320,9 @@ fn fill_is_special(mode: i32) -> bool {
// colour (Hard Mix: (cb - f(1 - cs)) / (1 - f)) at `opacity`, Fill staying coverage over
// transparency. Lab documents mix Normal in CIELAB; type layers mix in the text gamma space.
fn composite_fill(mode: i32, b: vec4<f32>, s: vec4<f32>, opacity: f32, fill: f32, gamma_on: bool) -> vec4<f32> {
+ // The same code as fs_layerbatch_normal, so a layer gives the same bits whichever pass
+ // draws it (a render resumed from the prefix cache splits runs differently).
+ if (mode == M_NORMAL && !gamma_on && (op.flags & F_LAB) == 0u) { return composite_normal_fill(b, s, opacity, fill); }
let f = clamp(fill, 0.0, 1.0);
let special = f < 1.0 && fill_is_special(mode);
let ab = b.a;
@@ -340,6 +351,21 @@ fn composite_fill(mode: i32, b: vec4<f32>, s: vec4<f32>, opacity: f32, fill: f32
return vec4(text_dec(wb * text_enc(b.rgb, g) + wbs * text_enc(bl, g) + ws * text_enc(s.rgb, g), g), ao);
}
+// composite_fill for Normal outside Lab documents and without text gamma: Fill is plain coverage
+// and the blend is the source. Kept apart so fs_layerbatch_normal doesn't carry every other
+// mode's code, which costs registers and so pixels in flight.
+fn composite_normal_fill(b: vec4<f32>, s: vec4<f32>, opacity: f32, fill: f32) -> vec4<f32> {
+ let ab = b.a;
+ let over = s.a * opacity * clamp(fill, 0.0, 1.0);
+ if (over <= 0.0) { return b; }
+ let ao = ab + (1.0 - ab) * over;
+ if (ao <= 0.0) { return vec4(0.0); }
+ let wb = ab * (1.0 - over) / ao;
+ let wbs = ab * over / ao;
+ let ws = (1.0 - ab) * over / ao;
+ return vec4(wb * b.rgb + wbs * s.rgb + ws * s.rgb, ao);
+}
+
// photocraft_color::convert::{srgb_to_lab, lab_to_srgb} (D50, Bradford to sRGB).
const D50: vec3<f32> = vec3(0.96422, 1.0, 0.82521);
fn lab_f(t: f32) -> f32 {
@@ -812,12 +838,9 @@ fn fs_mask(in: VOut) -> @location(0) vec4<f32> {
return c;
}
-// blend_into(backdrop = A, src = B, mode, opacity), including Dissolve.
-@fragment
-fn fs_blend(in: VOut) -> @location(0) vec4<f32> {
- let p = local(in.pos);
- let b = textureLoad(tex_a, p, 0);
- var s = textureLoad(tex_b, p, 0);
+// blend_into(backdrop = b, src = s, mode, opacity) at chunk pixel p, including Dissolve.
+fn blend_px(p: vec2<i32>, b: vec4<f32>, src: vec4<f32>) -> vec4<f32> {
+ var s = src;
if (s.a <= 0.0) { return b; }
if (op.mode == M_DISSOLVE) {
s.a = select(0.0, 1.0, dissolve_noise(doc_px(p)) < s.a * op.opacity * op.fill);
@@ -826,6 +849,85 @@ fn fs_blend(in: VOut) -> @location(0) vec4<f32> {
return composite_fill(op.mode, b, s, op.opacity, op.fill, (op.flags & F_TEXT_GAMMA) != 0u);
}
+// blend_into(backdrop = A, src = B, mode, opacity), including Dissolve.
+@fragment
+fn fs_blend(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ return blend_px(p, textureLoad(tex_a, p, 0), textureLoad(tex_b, p, 0));
+}
+
+// fs_content then fs_blend in one pass: the layer's own pixels (times its mask) blended straight
+// onto A, without writing them to a chunk texture and reading them back.
+@fragment
+fn fs_layerblend(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let d = doc_px(p);
+ var s = layer_texel(d);
+ s.a = s.a * mask_value(d);
+ return blend_px(p, textureLoad(tex_a, p, 0), s);
+}
+
+// The pixel at document pixel d of an extra layer of fs_layerbatch: an unmasked plain layer whose
+// pixels are in texture `t` (0: tex_b, 1: tex_c, 2: map_tex). Three vec4 of the record describe
+// it: geo = (texture origin x, y, size w, h), color = its colour outside the texture,
+// prm = (opacity, fill, mode, 1 when it has a texture), all whole numbers stored as floats.
+fn batch_texel(t: i32, d: vec2<i32>, geo: vec4<f32>, color: vec4<f32>, prm: vec4<f32>) -> vec4<f32> {
+ let q = d - vec2<i32>(geo.xy);
+ if (prm.w > 0.5 && inside(q, vec2<i32>(geo.zw))) {
+ if (t == 0) {
+ return textureLoad(tex_b, q, 0);
+ } else if (t == 1) {
+ return textureLoad(tex_c, q, 0);
+ }
+ return textureLoad(map_tex, q, 0);
+ }
+ return color;
+}
+
+// One extra layer of fs_layerbatch (see batch_texel) blended onto b at document pixel d.
+fn batch_layer(t: i32, d: vec2<i32>, b: vec4<f32>, geo: vec4<f32>, color: vec4<f32>, prm: vec4<f32>) -> vec4<f32> {
+ let s = batch_texel(t, d, geo, color, prm);
+ if (s.a <= 0.0) { return b; }
+ return composite_fill(i32(prm.z), b, s, prm.x, prm.y, false);
+}
+
+// batch_layer of a Normal layer outside Lab documents.
+fn batch_layer_normal(t: i32, d: vec2<i32>, b: vec4<f32>, geo: vec4<f32>, color: vec4<f32>, prm: vec4<f32>) -> vec4<f32> {
+ let s = batch_texel(t, d, geo, color, prm);
+ if (s.a <= 0.0) { return b; }
+ return composite_normal_fill(b, s, prm.x, prm.y);
+}
+
+// fs_layerblend of this pass's layer, then `op.kind` (at most 3) more plain layers: consecutive
+// LayerBlend passes the executor draws as one, reading and writing the chunk once for all of them.
+@fragment
+fn fs_layerbatch(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let d = doc_px(p);
+ var s = layer_texel(d);
+ s.a = s.a * mask_value(d);
+ var b = blend_px(p, textureLoad(tex_a, p, 0), s);
+ if (op.kind >= 1) { b = batch_layer(0, d, b, op.p0, op.p1, op.p2); }
+ if (op.kind >= 2) { b = batch_layer(1, d, b, op.p3, op.q0, op.q1); }
+ if (op.kind >= 3) { b = batch_layer(2, d, b, op.q2, op.q3, op.q4); }
+ return b;
+}
+
+// fs_layerbatch for a run of Normal layers without text gamma, outside Lab documents.
+@fragment
+fn fs_layerbatch_normal(in: VOut) -> @location(0) vec4<f32> {
+ let p = local(in.pos);
+ let d = doc_px(p);
+ var s = layer_texel(d);
+ s.a = s.a * mask_value(d);
+ var b = textureLoad(tex_a, p, 0);
+ if (s.a > 0.0) { b = composite_normal_fill(b, s, op.opacity, op.fill); }
+ if (op.kind >= 1) { b = batch_layer_normal(0, d, b, op.p0, op.p1, op.p2); }
+ if (op.kind >= 2) { b = batch_layer_normal(1, d, b, op.p3, op.q0, op.q1); }
+ if (op.kind >= 3) { b = batch_layer_normal(2, d, b, op.q2, op.q3, op.q4); }
+ return b;
+}
+
// composite_atop(base = A, src = B): blend as if the base were opaque, keep its alpha.
@fragment
fn fs_atop(in: VOut) -> @location(0) vec4<f32> {
@@ -1168,8 +1270,12 @@ fn mix_premul(a: vec4<f32>, b: vec4<f32>, k: f32) -> vec4<f32> {
fn fs_fxmerge(in: VOut) -> @location(0) vec4<f32> {
let p = local(in.pos);
var w = textureLoad(tex_a, p, 0);
- let l = textureLoad(tex_b, p, 0);
+ var l = textureLoad(tex_b, p, 0);
let c = textureLoad(tex_c, p, 0);
+ if ((op.flags & F_LAYER_SHAPE) != 0u) {
+ // fs_fxinit INIT_INSIDE then INIT_ALPHA, on the shape in B.
+ l = vec4(l.rgb, select(0.0, op.p0.x, l.a > INSIDE_EPS) * min(l.a, 1.0));
+ }
if (l.a > 0.0 && (op.flags & F_NO_LAYER) == 0u) { w = composite_g(op.mode, w, l, 1.0, (op.flags & F_TEXT_GAMMA) != 0u); }
let atop = (op.flags & F_ATOP) != 0u;
var before = c;
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index e99dc5341..468649a10 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -70,7 +70,7 @@ const MAP16: wgpu::TextureFormat = wgpu::TextureFormat::R16Float;
pub const CHUNK: u32 = 1024;
const STRIDE: u64 = 256;
const CHUNK_UNIFORM: u64 = 16;
-const OP_UNIFORM: u64 = 176;
+const OP_UNIFORM: u64 = 256;
/// GPU memory the effect-map cache may hold before evicting layers not drawn this frame.
pub const FX_BUDGET: usize = 1536 << 20;
/// Largest side of the square pages layer surfaces are stored in on the GPU (smaller when the
@@ -139,6 +139,10 @@ pub struct Stats {
pub prefix_hits: usize,
/// Planned prefix passes skipped, summed over the reused chunks.
pub prefix_passes_skipped: usize,
+ /// Plain layers blended inside another layer's pass (`fs_layerbatch`), summed over chunks.
+ pub layers_batched: usize,
+ /// Batched passes drawn with Normal's code alone (`fs_layerbatch_normal`), summed over chunks.
+ pub normal_batches: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -1405,6 +1409,8 @@ impl Compositor {
.and_then(|_| chunks.iter().map(|c| self.prefix.restore_point(*c).map(|r| r.pass_end)).try_fold(usize::MAX, |m, p| Some(m.min(p?))))
.unwrap_or(0);
let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats);
+ // Runs of plain layers drawn as one pass each (`fs_layerbatch`).
+ let runs = batch_runs(plan, checkpoint.map(|c| c.pass_end));
// Chunk pool.
while self.pool.len() < plan.slots as usize {
@@ -1439,7 +1445,13 @@ impl Compositor {
}
let (tex, mask) = bound.views[i];
let map = bound.maps[i].as_ref().map(|(_, r)| *r);
- let w = op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), map);
+ let run = runs.get(i).copied().unwrap_or(1);
+ let w = if run > 1 {
+ let extras: Vec<_> = (i + 1..i + run).filter_map(|j| Some((plan.passes.get(j)?, bound.views.get(j).and_then(|v| v.0).map(|t| t.1)))).collect();
+ batch_op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), &extras)
+ } else {
+ op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), map)
+ };
let off = (op_base + i as u64 * STRIDE) as usize;
data[off..][..w.len()].copy_from_slice(&w);
}
@@ -1468,6 +1480,13 @@ impl Compositor {
let lv = fr.luts.get(i).and_then(Option::as_ref).map_or(dummy, |(_, v)| v);
let map = bound.maps[i].as_ref().map_or(dummy, |(v, _)| v);
let pat = fr.patterns.get(i).and_then(Option::as_ref).unwrap_or(dummy);
+ let run = runs.get(i).copied().unwrap_or(1);
+ if run > 1 {
+ // The extra layers' pixels in tex_b, tex_c and map_tex (`batch_layer`).
+ let extra = |e: usize| bound.views.get(i + e).and_then(|v| v.0).map_or(dummy, |(k, _)| resident_views[k]);
+ bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), extra(1), tv, mv, lv, extra(2), extra(3), pat])));
+ continue;
+ }
bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), slot(p.b), tv, mv, lv, slot(p.c), map, pat])));
}
@@ -1481,8 +1500,10 @@ impl Compositor {
stats.prefix_hits = stats.prefix_hits.saturating_add(1);
stats.prefix_passes_skipped = stats.prefix_passes_skipped.saturating_add(resume);
}
+ // Passes drawn inside the previous `fs_layerbatch` pass.
+ let mut batched_to = 0;
for (i, p) in plan.passes.iter().enumerate() {
- if i < resume {
+ if i < resume || i < batched_to {
continue;
}
// Chunk textures, uniforms and bind groups outlive the submit, and the queue
@@ -1542,7 +1563,21 @@ impl Compositor {
_ => {}
}
self.recorded += 1;
- let target = &self.pool[p.dst as usize].1;
+ // A run draws as one pass into the slot its last layer writes.
+ let run = runs.get(i).copied().unwrap_or(1);
+ let (kernel, dst) = match plan.passes.get(i + run - 1) {
+ Some(last) if run > 1 => {
+ batched_to = i + run;
+ stats.layers_batched = stats.layers_batched.saturating_add(run - 1);
+ let kernel = plan.passes.get(i..i + run).map_or(Kernel::LayerBatch, batch_kernel);
+ if kernel == Kernel::LayerBatchNormal {
+ stats.normal_batches = stats.normal_batches.saturating_add(1);
+ }
+ (kernel, last.dst)
+ }
+ _ => (p.kernel, p.dst),
+ };
+ let target = &self.pool[dst as usize].1;
let clear = p.kernel == Kernel::Clear;
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("pc_compose_pass"),
@@ -1563,7 +1598,7 @@ impl Compositor {
if clear {
continue;
}
- pass.set_pipeline(&self.kit.pipelines[&(p.kernel, self.acc_format)]);
+ pass.set_pipeline(&self.kit.pipelines[&(kernel, self.acc_format)]);
pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height());
pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]);
pass.set_bind_group(1, bg1[i].as_ref(), &[]);
@@ -2046,6 +2081,38 @@ fn web_time_now() -> Option<std::time::Instant> {
/// The uniform record of a pass.
fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option<Rect>) -> Vec<u8> {
+ words(&op_values(p, tex, mask, map))
+}
+
+/// The uniform record of the `fs_layerbatch` pass that draws `p` (whose texture and mask cover
+/// `tex` and `mask`) and then `extras`, each an unmasked plain layer's `LayerBlend` pass with the
+/// area its texture covers. Layout: see `batch_layer` in compose.wgsl.
+fn batch_op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, extras: &[(&plan::Pass<'_>, Option<[i32; 4]>)]) -> Vec<u8> {
+ let mut v = op_values(p, tex, mask, None);
+ // Word offsets of the record's vec4s holding the extra layers, three each: p0, p1, p2 | p3,
+ // q0, q1 | q2, q3, q4.
+ const AT: [usize; 9] = [20, 24, 28, 32, 44, 48, 52, 56, 60];
+ if let Some(kind) = v.get_mut(1) {
+ *kind = I(extras.len().min(AT.len() / 3) as i32);
+ }
+ for (e, (x, area)) in extras.iter().take(AT.len() / 3).enumerate() {
+ let r = area.unwrap_or([0; 4]);
+ let geo = [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32];
+ let prm = [x.opacity, x.fill, plan::mode_index(x.mode) as f32, if area.is_some() { 1.0 } else { 0.0 }];
+ for (k, vals) in [geo, x.color, prm].into_iter().enumerate() {
+ let at = AT[e * 3 + k];
+ for (c, f) in vals.into_iter().enumerate() {
+ if let Some(w) = v.get_mut(at + c) {
+ *w = F(f);
+ }
+ }
+ }
+ }
+ words(&v)
+}
+
+/// The words of a pass's uniform record (`Op` in compose.wgsl).
+fn op_values(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option<Rect>) -> Vec<W> {
let mut flags = p.flags;
let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]);
if let Some(r) = tex {
@@ -2092,7 +2159,67 @@ fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, m
}
v.extend([I(mpo[0]), I(mpo[1]), I(mps[0]), I(mps[1])]);
v.extend(p.extra.iter().map(|f| F(*f)));
- words(&v)
+ // q0..q4: only `fs_layerbatch` reads them (`batch_op_words`).
+ v.extend((0..20).map(|_| F(0.0)));
+ v
+}
+
+/// Most layers one `fs_layerbatch` pass blends: its own and the three more its record holds.
+const BATCH: usize = 4;
+
+/// For each pass, how many passes from it on the executor draws as one `fs_layerbatch` pass
+/// (1: the pass alone). A run starts at a `LayerBlend` pass over the whole chunk (no clip) that
+/// isn't a gradient (whose parameters use the words the extra layers go in), and continues while
+/// the next pass is a `LayerBlend` of an unmasked plain layer (no text gamma, no Dissolve) onto
+/// exactly what the previous pass wrote, a slot nothing else reads before it is written again.
+/// A run doesn't cross `capture`, the pass where this render captures its prefix checkpoint, and
+/// never ends in the slot it reads from.
+fn batch_runs(plan: &Plan<'_>, capture: Option<usize>) -> Vec<usize> {
+ let passes = &plan.passes;
+ let n = passes.len();
+ let reads = |p: &plan::Pass<'_>, s: plan::Slot| [p.a, p.b, p.c, p.d].contains(&Some(s));
+ // feeds_next[i]: what pass i writes is read by pass i + 1 alone.
+ let feeds_next: Vec<bool> = (0..n)
+ .map(|i| {
+ let (Some(this), Some(next)) = (passes.get(i), passes.get(i + 1)) else { return false };
+ let dst = this.dst;
+ if next.a != Some(dst) || [next.b, next.c, next.d].contains(&Some(dst)) {
+ return false;
+ }
+ for later in passes.iter().skip(i + 2) {
+ // A copy into a slot keeps what lies outside its rect: that is a read too.
+ if reads(later, dst) || (later.dst == dst && later.kernel == Kernel::CopyRect) {
+ return false;
+ }
+ if later.dst == dst {
+ return true;
+ }
+ }
+ dst != plan.root
+ })
+ .collect();
+ let lead = |p: &plan::Pass<'_>| p.kernel == Kernel::LayerBlend && p.clip.is_none() && !p.gradient;
+ let extra = |p: &plan::Pass<'_>| lead(p) && p.mask.is_none() && p.flags & plan::F_TEXT_GAMMA == 0 && p.mode != photocraft_color::BlendMode::Dissolve;
+ (0..n)
+ .map(|i| {
+ let Some(first) = passes.get(i).filter(|p| lead(p)) else { return 1 };
+ let (mut k, mut best) = (1, 1);
+ while k < BATCH && feeds_next.get(i + k - 1).copied().unwrap_or(false) && passes.get(i + k).is_some_and(extra) && capture != Some(i + k) {
+ k += 1;
+ if passes.get(i + k - 1).is_some_and(|p| Some(p.dst) != first.a) {
+ best = k;
+ }
+ }
+ best
+ })
+ .collect()
+}
+
+/// The pipeline that draws `run` (passes `batch_runs` joined): `fs_layerbatch_normal` when every
+/// layer blends Normal without text gamma outside Lab documents, else `fs_layerbatch`.
+fn batch_kernel(run: &[plan::Pass<'_>]) -> Kernel {
+ let normal = |p: &plan::Pass<'_>| p.mode == photocraft_color::BlendMode::Normal && p.flags & (plan::F_TEXT_GAMMA | plan::F_LAB) == 0;
+ if run.iter().all(normal) { Kernel::LayerBatchNormal } else { Kernel::LayerBatch }
}
/// Canvas rounded out to whole tiles.
@@ -2537,6 +2664,96 @@ pub fn render_to_vec_stats(
mod tests {
use super::*;
+ /// A run joins `LayerBlend` passes that only feed each other, at most `BATCH` of them, and
+ /// never ends in the slot it reads from.
+ fn check_runs(p: &Plan<'_>, capture: Option<usize>) -> Vec<usize> {
+ let runs = batch_runs(p, capture);
+ assert_eq!(runs.len(), p.passes.len());
+ for (i, &k) in runs.iter().enumerate() {
+ assert!((1..=BATCH).contains(&k), "pass {i}: run {k}");
+ if k > 1 {
+ assert_ne!(Some(p.passes[i + k - 1].dst), p.passes[i].a, "run at {i} renders into its input");
+ for j in i + 1..i + k {
+ assert_eq!(p.passes[j].kernel, Kernel::LayerBlend);
+ assert_eq!(p.passes[j].a, Some(p.passes[j - 1].dst), "run at {i}: pass {j} doesn't read the one before");
+ assert!(p.passes[j].mask.is_none() && p.passes[j].mode != photocraft_color::BlendMode::Dissolve, "run at {i}: pass {j}");
+ assert_ne!(capture, Some(j), "run at {i} skips the captured checkpoint");
+ }
+ }
+ }
+ runs
+ }
+
+ #[test]
+ fn plain_layers_batch_and_runs_stop_where_a_pass_must_stand_alone() {
+ use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
+ use photocraft_doc::{Document, Layer, LayerMask};
+ let mut d = Document::with_background("t", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ for i in 0..12 {
+ let mut l = Layer::raster(format!("l{i}"), d.pixel_format());
+ l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.2, 0.4, 0.6, 0.5]);
+ d.layers.push(l);
+ }
+ let p = plan::plan(&d).unwrap();
+ let runs = check_runs(&p, None);
+ assert!(runs.iter().any(|k| *k >= 3), "{runs:?}");
+ // A run stops at the checkpoint this render captures, wherever that is.
+ for cp in &p.checkpoints {
+ check_runs(&p, Some(cp.pass_end));
+ }
+ // A masked or Dissolve layer, or a clipped one, never joins a run as an extra layer.
+ d.layers[3].mask = Some(LayerMask::hide_all());
+ d.layers[6].blend = BlendMode::Dissolve;
+ d.layers[9].clipped = true;
+ check_runs(&plan::plan(&d).unwrap(), None);
+ // Nothing to batch: a lone layer.
+ d.layers.truncate(1);
+ assert_eq!(check_runs(&plan::plan(&d).unwrap(), None), vec![1; plan::plan(&d).unwrap().passes.len()]);
+ }
+
+ #[test]
+ fn batch_records_hold_three_extra_layers_in_the_spare_words() {
+ let lead = plan::Pass::new(Kernel::LayerBlend, 0);
+ let mut x = plan::Pass::new(Kernel::LayerBlend, 1);
+ x.opacity = 0.25;
+ x.fill = 0.5;
+ x.color = [0.1, 0.2, 0.3, 0.4];
+ let w = batch_op_words(&lead, None, None, &[(&x, Some([1, 2, 3, 4])), (&x, None), (&x, None), (&x, None)]);
+ assert_eq!(w.len() as u64, OP_UNIFORM);
+ let word = |i: usize| <[u8; 4]>::try_from(&w[i * 4..i * 4 + 4]).unwrap();
+ let f = |i: usize| f32::from_le_bytes(word(i));
+ // At most three extras; the first's geometry, colour and parameters in p0, p1, p2.
+ assert_eq!(i32::from_le_bytes(word(1)), 3);
+ assert_eq!([f(20), f(21), f(22), f(23)], [1.0, 2.0, 3.0, 4.0]);
+ assert_eq!([f(24), f(25), f(26), f(27)], [0.1, 0.2, 0.3, 0.4]);
+ assert_eq!([f(28), f(29), f(31)], [0.25, 0.5, 1.0]);
+ // The third's parameters in q4; one without pixels says so.
+ assert_eq!([f(60), f(61), f(63)], [0.25, 0.5, 0.0]);
+ // Other passes leave the batch words zero.
+ let plain = op_words(&x, None, None, None);
+ assert!(plain[44 * 4..].iter().all(|b| *b == 0));
+ }
+
+ #[test]
+ fn runs_of_normal_layers_draw_with_normal_code_alone() {
+ use photocraft_color::BlendMode;
+ let pass = |mode: BlendMode, flags: u32| {
+ let mut p = plan::Pass::new(Kernel::LayerBlend, 0);
+ p.mode = mode;
+ p.flags = flags;
+ p
+ };
+ let normal = pass(BlendMode::Normal, plan::F_HDR);
+ assert_eq!(batch_kernel(&[normal.clone(), pass(BlendMode::Normal, 0)]), Kernel::LayerBatchNormal);
+ // Any other mode, text gamma or a Lab document anywhere in the run takes the full shader.
+ for other in
+ [pass(BlendMode::Multiply, 0), pass(BlendMode::Dissolve, 0), pass(BlendMode::Normal, plan::F_TEXT_GAMMA), pass(BlendMode::Normal, plan::F_LAB)]
+ {
+ assert_eq!(batch_kernel(&[normal.clone(), other.clone()]), Kernel::LayerBatch);
+ assert_eq!(batch_kernel(&[other, normal.clone()]), Kernel::LayerBatch);
+ }
+ }
+
#[test]
fn uniform_buffer_sizes_are_checked_before_allocation() {
assert_eq!(uniform_buffer_len(1, 255, 65_536).unwrap(), 65_536);
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index 58ce6e429..6cb44b920 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -34,6 +34,14 @@ pub enum Kernel {
Content,
Mask,
Blend,
+ /// `Content` then `Blend` in one pass: a plain layer's pixels blended straight onto A.
+ LayerBlend,
+ /// A run of consecutive `LayerBlend` passes drawn as one (never planned: the executor draws
+ /// it in their place, see `batch_runs`).
+ LayerBatch,
+ /// `LayerBatch` of a run whose layers all blend Normal without text gamma, outside Lab
+ /// documents (never planned: the executor picks it, see `batch_kernel`).
+ LayerBatchNormal,
Atop,
Adjust,
AdjMix,
@@ -73,6 +81,9 @@ impl Kernel {
Kernel::Content => "fs_content",
Kernel::Mask => "fs_mask",
Kernel::Blend => "fs_blend",
+ Kernel::LayerBlend => "fs_layerblend",
+ Kernel::LayerBatch => "fs_layerbatch",
+ Kernel::LayerBatchNormal => "fs_layerbatch_normal",
Kernel::Atop => "fs_atop",
Kernel::Adjust => "fs_adjust",
Kernel::AdjMix => "fs_adjmix",
@@ -111,10 +122,13 @@ impl Kernel {
}
/// Every kernel with a pipeline.
- pub const DRAWN: [Kernel; 21] = [
+ pub const DRAWN: [Kernel; 24] = [
Kernel::Content,
Kernel::Mask,
Kernel::Blend,
+ Kernel::LayerBlend,
+ Kernel::LayerBatch,
+ Kernel::LayerBatchNormal,
Kernel::Atop,
Kernel::Adjust,
Kernel::AdjMix,
@@ -395,6 +409,10 @@ pub const F_ADD_DIFF: u32 = 16384;
pub const F_BLEND_IF: u32 = 524288;
/// Blend / Atop / FxMerge of a type layer: coverage mixed at `psblend::TEXT_GAMMA`.
pub const F_TEXT_GAMMA: u32 = 8192;
+/// `FxMerge`: B is the layer's shape (its content); the layer is its colour at fill opacity
+/// (`p0.x`) inside the shape, times the shape's alpha: `FxInit` `INIT_INSIDE` then
+/// `INIT_ALPHA` in the merge, for a layer with no interior effects between them.
+pub const F_LAYER_SHAPE: u32 = 1_048_576;
/// A layer's Blend If ranges for `F_BLEND_IF`: Gray, then the colour channels, each as
/// [this layer, underlying layer]; every range as two floats, `black low × 256 + black high` and
@@ -764,26 +782,36 @@ impl<'a> Planner<'a> {
}
return Ok(backdrop);
}
- let start = self.passes.len();
- let mut content = self.content(layer)?;
- for c in visible_clipped {
- content = self.atop(c, content)?;
- }
- if let Some(clip) = clip {
- // Everything that built the layer's content only matters inside its bounds.
- for p in &mut self.passes[start..] {
- if p.clip.is_none() && !matches!(p.kernel, Kernel::Clear | Kernel::CopyFull) {
- p.clip = Some(clip);
+ // A layer with nothing clipped to it whose content is one Content pass is blended
+ // straight from its pixels (`Kernel::LayerBlend`): one pass instead of two, and no
+ // scratch chunk written and read back.
+ let mut p = if visible_clipped.is_empty() && single_content_pass(layer) {
+ let mut p = self.content_pass(layer)?;
+ p.kernel = Kernel::LayerBlend;
+ p
+ } else {
+ let start = self.passes.len();
+ let mut content = self.content(layer)?;
+ for c in visible_clipped {
+ content = self.atop(c, content)?;
+ }
+ if let Some(clip) = clip {
+ // Everything that built the layer's content only matters inside its bounds.
+ for p in &mut self.passes[start..] {
+ if p.clip.is_none() && !matches!(p.kernel, Kernel::Clear | Kernel::CopyFull) {
+ p.clip = Some(clip);
+ }
}
}
- }
- let mut p = Pass::new(Kernel::Blend, 0);
+ let mut p = Pass::new(Kernel::Blend, 0);
+ p.b = Some(content);
+ p
+ };
p.a = Some(if clip.is_some() { self.retain(backdrop) } else { backdrop });
- p.b = Some(content);
p.mode = layer.blend;
p.opacity = layer.opacity;
p.fill = layer.fill_opacity;
- p.flags = gamma_flag(layer);
+ p.flags |= gamma_flag(layer);
p.extra[3] = photocraft_compose::text_gamma(layer);
p.clip = clip;
let merged = self.emit(p);
@@ -804,6 +832,11 @@ impl<'a> Planner<'a> {
/// Copy `merged` into `backdrop` over `clip` (in place when nothing else holds the backdrop);
/// returns the new backdrop. Consumes both.
fn write_back(&mut self, backdrop: Slot, merged: Slot, clip: Rect) -> Slot {
+ // A clip over the whole canvas left no pixel of `merged` uncomputed: it is the backdrop.
+ if clip.contains_rect(&self.cx.canvas) {
+ self.release(backdrop);
+ return merged;
+ }
let dst = if self.refs[backdrop as usize] == 1 {
backdrop
} else {
@@ -1129,6 +1162,25 @@ impl<'a> Planner<'a> {
}
}
+ // Only exterior effects (drop shadows, outer glows): nothing is painted between the
+ // layer's colour inside its shape and the shape's alpha, so the merge derives both from
+ // the shape (`F_LAYER_SHAPE`) instead of two passes building the layer.
+ let premerge = photocraft_compose::effects::premerges_layer(layer);
+ if !relative && !premerge && items.iter().all(|e| matches!(e, Effect::DropShadow(_) | Effect::OuterGlow(_))) {
+ let mut p = Pass::new(Kernel::FxMerge, 0);
+ p.a = Some(w);
+ p.b = Some(lay_src);
+ p.c = Some(self.retain(backdrop));
+ p.mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend };
+ p.opacity = layer.opacity;
+ p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer) | F_LAYER_SHAPE;
+ p.params[0][0] = layer.fill_opacity;
+ p.extra[3] = photocraft_compose::text_gamma(layer);
+ p.clip = Some(clip);
+ let merged = self.emit(p);
+ self.release(content);
+ return Ok(self.write_back(backdrop, merged, clip));
+ }
// The layer: its colour at fill opacity inside its shape; interior effects are painted
// relative to the shape (coverage within it), then the shape's alpha applies.
let mut l = if relative {
@@ -1139,7 +1191,6 @@ impl<'a> Planner<'a> {
};
// Blend Interior Effects as Group off: the layer merges in its mode first and the
// interior effects paint over the result (`effects::premerges_layer`).
- let premerge = photocraft_compose::effects::premerges_layer(layer);
if premerge {
let mut p = Pass::new(Kernel::Blend, 0);
p.a = Some(self.retain(w));
@@ -1806,6 +1857,16 @@ pub fn mode_index(m: BlendMode) -> i32 {
}
}
+/// Whether `Planner::content` draws `layer` as one `Planner::content_pass`: not a group's stack,
+/// an adjustment, or a pattern fill painted in passes.
+fn single_content_pass(layer: &Layer) -> bool {
+ match &layer.content {
+ LayerContent::Group(_) | LayerContent::Adjustment(_) => false,
+ LayerContent::Fill(f @ Fill::Pattern { .. }) => layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f),
+ _ => true,
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1946,15 +2007,15 @@ mod tests {
d.layers.push(Layer::raster(format!("l{i}"), d.pixel_format()));
}
let p = plan(&d).unwrap();
- // Empty layers draw nothing.
- assert_eq!(p.passes.len(), 1 + 2);
+ // Empty layers draw nothing: the clear and the background's one fused pass.
+ assert_eq!(p.passes.len(), 1 + 1);
for (i, l) in d.layers.iter_mut().skip(1).enumerate() {
l.surface_mut().unwrap().fill_rect(Rect::new(i as i32 % 4, 0, 4, 8), &[0.0, 0.0, 1.0, 1.0]);
}
let p = plan(&d).unwrap();
assert!(p.slots <= 3, "{} slots", p.slots);
- // The background, then each small layer over its bounds and copied back.
- assert_eq!(p.passes.len(), 1 + 2 + 10 * 3);
+ // The background, then each small layer blended over its bounds and copied back.
+ assert_eq!(p.passes.len(), 1 + 1 + 10 * 2);
}
#[test]
@@ -1989,11 +2050,44 @@ mod tests {
assert_eq!(p.fx.len(), 1);
let m = photocraft_compose::effects::margin(&d.layers[1]);
assert_eq!(p.fx[0].region, Rect::new(2, 2, 5, 5).inflate(m).intersect(&d.bounds().inflate(m)));
- // The effect result lands back in the backdrop slot.
+ // The effect region covers the whole canvas: the merged result is the backdrop, no copy.
+ assert!(p.fx[0].region.contains_rect(&d.bounds()));
let last = p.passes.last().unwrap();
- assert_eq!(last.kernel, Kernel::CopyRect);
+ assert_eq!(last.kernel, Kernel::FxMerge);
assert_eq!(last.dst, p.root);
assert!(p.slots <= 6, "{} slots", p.slots);
+ // On a larger canvas the result lands back in the backdrop slot over the region only.
+ let mut big = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ big.layers.push(d.layers[1].clone());
+ let p = plan(&big).unwrap();
+ assert!(!p.fx[0].region.contains_rect(&big.bounds()));
+ let last = p.passes.last().unwrap();
+ assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(p.fx[0].region)));
+ }
+
+ #[test]
+ fn exterior_effects_merge_from_the_shape() {
+ // A drop shadow alone: the layer's pixels, the shadow, the merge. With an interior effect
+ // the layer is built in passes of its own (colour inside the shape, the overlay, alpha).
+ let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ let mut l = Layer::raster("fx", d.pixel_format());
+ l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[1.0, 0.0, 0.0, 0.5]);
+ l.fill_opacity = 0.7;
+ l.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
+ d.layers.push(l);
+ let p = plan(&d).unwrap();
+ let fx: Vec<Kernel> = p.passes.iter().skip(2).map(|p| p.kernel).collect();
+ assert_eq!(fx, [Kernel::Content, Kernel::FxPaint, Kernel::FxMerge], "{:?}", p.passes);
+ let merge = p.passes.last().unwrap();
+ assert!(merge.flags & F_LAYER_SHAPE != 0);
+ assert_eq!(merge.params[0][0], 0.7);
+ d.layers[1]
+ .effects
+ .items
+ .push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE });
+ let p = plan(&d).unwrap();
+ assert!(p.passes.iter().all(|p| p.flags & F_LAYER_SHAPE == 0));
+ assert!(p.passes.iter().any(|p| p.kernel == Kernel::FxInit));
}
#[test]
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 84d3d0e93..b71d9ca52 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -1220,21 +1220,103 @@ fn small_layers_composite_over_their_bounds() {
fn many_layers_submit_inside_one_chunk() {
// P12: a refresh recorded every pass of a page cell into one command buffer, and with a few
// hundred layers Metal ran out of command buffers (device lost, "pc_compose_uniforms is
- // invalid"). 700 layers need well over 1000 passes in the document's only chunk.
+ // invalid"). 1200 layers need well over 1000 passes in the document's only chunk: each is
+ // masked, so it is drawn in a pass of its own rather than batched with its neighbours.
let Some(mut g) = gpu() else { return };
let mut d = base_doc(64, 48);
let modes: Vec<BlendMode> = BlendMode::layer_modes().collect();
- for (i, mode) in modes.iter().copied().cycle().take(700).enumerate() {
+ for (i, mode) in modes.iter().copied().cycle().take(1200).enumerate() {
let mut l = noise_layer("l", PixelFormat::RGBA8, Rect::from_xywh(0, 0, 64, 48), 500 + i as u32, 0.0);
l.blend = mode;
l.opacity = 0.9;
+ l.mask = Some(mask(Rect::from_xywh(0, 0, 64, 48), 3000 + i as u32, 1.0));
d.layers.push(l);
}
- let stats = diff_rect(&mut g, &d, d.bounds(), "700 layers").unwrap_or_else(|e| panic!("{e}"));
+ let stats = diff_rect(&mut g, &d, d.bounds(), "1200 layers").unwrap_or_else(|e| panic!("{e}"));
+ assert_eq!(stats.layers_batched, 0, "{stats:?}");
assert_eq!(stats.chunks, 1);
assert!(stats.flushes > 0, "{stats:?}");
}
+#[test]
+fn runs_of_plain_layers_blend_in_one_pass() {
+ // Consecutive plain layers are drawn several to a pass (`fs_layerbatch`). Every layer mode at
+ // varied opacity and fill (the fill-special modes included), solid fills, layers that end
+ // inside the canvas, and the layers that end a run: masked, Dissolve, small (clipped to their
+ // bounds) and clipping groups. Then an edit in the middle, so the prefix cache resumes
+ // part-way up the stack and runs start at its checkpoint.
+ let Some(mut g) = gpu() else { return };
+ let mut d = base_doc(96, 64);
+ let modes: Vec<BlendMode> = BlendMode::layer_modes().collect();
+ for (i, mode) in modes.iter().copied().cycle().take(90).enumerate() {
+ let i32_ = i as i32;
+ let rect = if i % 5 == 2 { Rect::from_xywh(-8, 10, 70, 40) } else { Rect::from_xywh(0, 0, 96, 64) };
+ let mut l = noise_layer("l", PixelFormat::RGBA8, rect, 900 + i as u32, 0.0);
+ l.blend = mode;
+ l.opacity = 0.35 + 0.05 * (i % 13) as f32;
+ l.fill_opacity = if i % 4 == 1 { 0.6 } else { 1.0 };
+ if i % 11 == 7 {
+ l.mask = Some(mask(Rect::from_xywh(i32_ % 30, 0, 50, 64), 70 + i as u32, 0.0));
+ }
+ if i % 23 == 9 {
+ l.clipped = true;
+ }
+ d.layers.push(l);
+ if i % 9 == 4 {
+ let mut f = Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgba(0.3, 0.6, 0.2, 0.4))));
+ f.blend = modes[i % modes.len()];
+ d.layers.push(f);
+ }
+ if i % 17 == 8 {
+ d.layers.push(noise_layer("small", PixelFormat::RGBA8, Rect::from_xywh(20, 20, 6, 5), 40 + i as u32, 0.5));
+ }
+ }
+ let stats = diff_rect(&mut g, &d, d.bounds(), "plain layer runs").unwrap_or_else(|e| panic!("{e}"));
+ assert!(stats.layers_batched > 0, "no layers were batched: {stats:?}");
+ let mid = d.layers.len() / 2;
+ d.layers[mid].opacity = 0.5;
+ let stats = diff_rect(&mut g, &d, d.bounds(), "plain layer runs, edited in the middle").unwrap_or_else(|e| panic!("{e}"));
+ assert!(stats.layers_batched > 0, "{stats:?}");
+}
+
+#[test]
+fn runs_of_normal_layers_blend_with_normal_code_alone() {
+ // Runs whose layers all blend Normal draw with `fs_layerbatch_normal`: varied opacity and fill
+ // over a partly transparent backdrop, masked layers leading runs, solid fills and layers that
+ // end inside the canvas, at every depth. Lab documents mix Normal in CIELAB, so their runs
+ // keep the full shader.
+ let Some(mut g) = gpu() else { return };
+ for (mode, depth) in
+ [(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Rgb, SampleType::F32), (ColorMode::Lab, SampleType::U8)]
+ {
+ let mut d = Document::new("normal", Size::new(96, 64), mode, depth);
+ let fmt = d.pixel_format();
+ d.layers.push(noise_layer("bg", fmt, Rect::from_xywh(0, 0, 96, 64), 5, 0.0));
+ for i in 0..40u32 {
+ let rect = if i % 5 == 3 { Rect::from_xywh(-6, 9, 70, 44) } else { Rect::from_xywh(0, 0, 96, 64) };
+ let mut l = noise_layer("n", fmt, rect, 600 + i, if i % 3 == 0 { 0.0 } else { 0.4 });
+ l.opacity = 0.2 + 0.07 * (i % 11) as f32;
+ l.fill_opacity = [1.0, 0.55, 0.0, 0.8][i as usize % 4];
+ if i % 7 == 2 {
+ l.mask = Some(mask(Rect::from_xywh(i as i32 % 25, 0, 60, 64), 50 + i, 0.0));
+ }
+ d.layers.push(l);
+ if i % 6 == 4 {
+ let mut f = Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgba(0.7, 0.2, 0.5, 0.6))));
+ f.opacity = 0.45;
+ d.layers.push(f);
+ }
+ }
+ let what = format!("normal runs {mode:?} {depth:?}");
+ let stats = diff_rect(&mut g, &d, d.bounds(), &what).unwrap_or_else(|e| panic!("{e}"));
+ if mode == ColorMode::Lab {
+ assert!(stats.layers_batched > 0 && stats.normal_batches == 0, "{what}: {stats:?}");
+ } else {
+ assert!(stats.normal_batches > 0, "{what}: {stats:?}");
+ }
+ }
+}
+
fn blob(name: &str, fmt: PixelFormat, cx: f32, cy: f32, r: f32, color: [f32; 3]) -> Layer {
let mut l = Layer::raster(name, fmt);
let rect = Rect::new((cx - r - 12.0) as i32, (cy - r - 4.0) as i32, (cx + r + 14.0) as i32, (cy + r + 4.0) as i32);
@@ -1570,6 +1652,60 @@ fn layer_effects_every_kind() {
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
+#[test]
+fn exterior_effects_merge_from_the_shape_at_any_fill() {
+ // Drop shadows and outer glows alone: the merge builds the layer from its shape (fill inside
+ // it, times its alpha) instead of passes of its own. Fill from 0 to 1, opacity, modes
+ // (including one that blends with the knocked-out shadow), both depths, a layer covering the
+ // canvas (no copy back), and the layer clipped onto a base (merged atop it).
+ let Some(mut g) = gpu() else { return };
+ let mut ds = shadow(BlendMode::Multiply, 0.75, 120.0, 6.0, 8.0, 0.0);
+ let mut ds_through = shadow(BlendMode::Normal, 0.9, 45.0, 4.0, 5.0, 0.2);
+ ds_through.knocks_out = false;
+ let og = glow(FxPaint::Color(Color::rgb(1.0, 0.9, 0.2)), GlowTechnique::Softer, 10.0, 0.3, GlowSource::Edge);
+ ds.use_global_light = true;
+ let stacks = [
+ ("drop shadow", vec![Effect::DropShadow(ds.clone())]),
+ ("drop shadow, not knocked out", vec![Effect::DropShadow(ds_through)]),
+ ("outer glow", vec![Effect::OuterGlow(og.clone())]),
+ ("shadow and glow", vec![Effect::OuterGlow(og), Effect::DropShadow(ds)]),
+ ];
+ for depth in [SampleType::U8, SampleType::U16] {
+ for (name, fx) in &stacks {
+ for (opacity, fill, blend) in [
+ (1.0, 1.0, BlendMode::Normal),
+ (0.8, 0.6, BlendMode::Normal),
+ (1.0, 0.0, BlendMode::Normal),
+ (0.7, 0.35, BlendMode::Multiply),
+ (1.0, 0.5, BlendMode::Screen),
+ ] {
+ let what = format!("{name} {depth:?} opacity {opacity} fill {fill} {blend:?}");
+ let mut d = fx_doc(96, 80, depth);
+ let mut l = blob("fx", d.pixel_format(), 46.0, 40.0, 22.0, [0.2, 0.6, 0.9]);
+ l.effects.items = fx.clone();
+ (l.opacity, l.fill_opacity, l.blend) = (opacity, fill, blend);
+ d.layers.push(l.clone());
+ fx_check(&mut g, &d, &what);
+ // The same layer clipped onto a base.
+ let mut base = blob("base", d.pixel_format(), 40.0, 44.0, 30.0, [0.9, 0.8, 0.3]);
+ base.effects.items.clear();
+ d.layers.pop();
+ d.layers.push(base);
+ l.clipped = true;
+ d.layers.push(l.clone());
+ fx_check(&mut g, &d, &format!("{what}, clipped"));
+ // A partly transparent layer over the whole canvas.
+ let mut d = fx_doc(64, 48, depth);
+ let mut full = noise_layer("full", d.pixel_format(), Rect::from_xywh(0, 0, 64, 48), 7, 0.2);
+ full.effects.items = fx.clone();
+ (full.opacity, full.fill_opacity, full.blend) = (opacity, fill, blend);
+ d.layers.push(full);
+ fx_check(&mut g, &d, &format!("{what}, full canvas"));
+ }
+ }
+ }
+}
+
#[test]
fn layer_effects_opacity_fill_blend_and_off_canvas() {
let Some(mut g) = gpu() else { return };
diff --git a/crates/gpu/tests/uniform_limits.rs b/crates/gpu/tests/uniform_limits.rs
index aea8fb6b1..994dbd750 100644
--- a/crates/gpu/tests/uniform_limits.rs
+++ b/crates/gpu/tests/uniform_limits.rs
@@ -59,7 +59,7 @@ fn a_deep_stack_above_the_device_buffer_limit_returns_an_error_without_panicking
let Some((adapter, device, queue)) = constrained_device() else { return };
let mut compositor = compositor(&adapter, &device);
healthy_control(&mut compositor, &device, &queue);
- let deep = fills(150);
+ let deep = fills(300);
eprintln!(
"uniform-limit reproduction: backend={:?}, buffer limit={}, page={}, passes={}",
adapter.get_info().backend,
@@ -80,7 +80,7 @@ fn an_oversized_stack_falls_back_without_faulting_the_watched_device() {
let mut compositor = compositor(&adapter, &device);
compositor.set_health(health.clone());
healthy_control(&mut compositor, &device, &queue);
- let deep = fills(150);
+ let deep = fills(300);
let fallback = match render_to_vec(&mut compositor, &device, &queue, &deep, deep.bounds()) {
Ok(_) => panic!("the oversized stack must return Unsupported for CPU fallback"),
Err(_) => photocraft_compose::flatten(&deep),
@@ -104,7 +104,8 @@ fn the_exact_buffer_limit_still_renders_with_cpu_parity() {
let health = DeviceHealth::watch(&device);
let mut compositor = compositor(&adapter, &device);
compositor.set_health(health.clone());
- let boundary = fills(127);
+ // Every fill layer is one pass (`Kernel::LayerBlend`) after the clear.
+ let boundary = fills(254);
assert_eq!(plan(&boundary).unwrap().passes.len(), 255, "one chunk plus255passes uses exactly65536bytes");
let expected = photocraft_compose::flatten(&boundary);
let actual = render_to_vec(&mut compositor, &device, &queue, &boundary, boundary.bounds()).expect("the exact supported buffer boundary is accepted");
@@ -121,7 +122,7 @@ fn later_oversized_page_cells_are_rejected_before_render_or_encode_calls_the_sin
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let Some((adapter, device, queue)) = constrained_device() else { return };
let health = DeviceHealth::watch(&device);
- let doc = fills_size(126, Size::new(4096, 2048));
+ let doc = fills_size(252, Size::new(4096, 2048));
let region = photocraft_geom::Rect::new(2047, 0, 4096, 2048);
assert_eq!(plan(&doc).unwrap().passes.len(), 253);
// Default pages are2048, chunks1024: the narrow first page has2chunks and fits;