Skip to content

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

fix(gpu): batch runs no longer depend on the prefix cache

Akos Arintone4c2867494ac
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 468649a10..31627bbad 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -1165,7 +1165,17 @@ impl Compositor {
// Only render owns submission. A caller may discard encode's command buffer, so it
// cannot establish (or consume) a checkpoint whose GPU copy might never execute.
- let checkpoint = if flush { self.prefix.prepare(doc, &plan) } else { None };
+ // Runs of plain layers drawn as one pass each (`fs_layerbatch`). The grouping is the same
+ // for every render of this plan, so a layer's bits don't depend on the cache: renders
+ // capture and resume only where a run starts.
+ let runs = batch_runs(&plan);
+ let checkpoint = if flush {
+ let starts = run_starts(&runs);
+ let resumable: Vec<_> = plan.checkpoints.iter().filter(|c| starts.get(c.pass_end).copied().unwrap_or(false)).copied().collect();
+ self.prefix.prepare(doc, &resumable)
+ } else {
+ None
+ };
// Effect maps of whole regions first (they may render group shapes through sub-plans);
// regions larger than the limit are built per cell below.
@@ -1210,7 +1220,7 @@ impl Compositor {
stats.chunks += chunks.len();
work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64;
let mut batch = flush.then_some(&mut last_submit);
- self.run_cell(device, queue, encoder, doc.id, &plan, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch);
+ self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch);
// The device was lost in a submit inside the cell: issue no more work.
if let Some(f) = self.fault() {
return Err(Unsupported(f.to_string()));
@@ -1381,8 +1391,8 @@ impl Compositor {
Bound { views, keys, maps }
}
- /// Run `plan` over the `chunks` of one page cell (document rects, at most a chunk square),
- /// handing each finished chunk to `sink`.
+ /// Run `plan` (drawn as `runs`, its `batch_runs`) over the `chunks` of one page cell
+ /// (document rects, at most a chunk square), handing each finished chunk to `sink`.
#[allow(clippy::too_many_arguments)]
fn run_cell(
&mut self,
@@ -1391,6 +1401,7 @@ impl Compositor {
encoder: &mut wgpu::CommandEncoder,
doc: DocId,
plan: &Plan<'_>,
+ runs: &[usize],
paged: &[bool],
cell: Cell,
fr: &FrameRes,
@@ -1409,8 +1420,6 @@ 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 {
@@ -2172,9 +2181,12 @@ const BATCH: usize = 4;
/// 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> {
+/// A run never ends in the slot it reads from.
+///
+/// The runs depend on the plan alone, never on the prefix cache: a compiler may give a layer
+/// other bits batched than drawn alone (FXC on D3D12 does), and reusing a prefix must stay exact
+/// (#5286). The cache captures and resumes only at `run_starts` instead.
+fn batch_runs(plan: &Plan<'_>) -> 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));
@@ -2204,7 +2216,7 @@ fn batch_runs(plan: &Plan<'_>, capture: Option<usize>) -> Vec<usize> {
.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) {
+ while k < BATCH && feeds_next.get(i + k - 1).copied().unwrap_or(false) && passes.get(i + k).is_some_and(extra) {
k += 1;
if passes.get(i + k - 1).is_some_and(|p| Some(p.dst) != first.a) {
best = k;
@@ -2215,6 +2227,18 @@ fn batch_runs(plan: &Plan<'_>, capture: Option<usize>) -> Vec<usize> {
.collect()
}
+/// For each pass and the end of the plan, whether the executor draws `runs` (`batch_runs`) so
+/// that a pass starts there rather than inside a run.
+fn run_starts(runs: &[usize]) -> Vec<bool> {
+ let mut starts = vec![false; runs.len() + 1];
+ let mut i = 0;
+ while let Some(s) = starts.get_mut(i) {
+ *s = true;
+ i += runs.get(i).copied().unwrap_or(1).max(1);
+ }
+ starts
+}
+
/// 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 {
@@ -2666,8 +2690,8 @@ mod tests {
/// 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);
+ fn check_runs(p: &Plan<'_>) -> Vec<usize> {
+ let runs = batch_runs(p);
assert_eq!(runs.len(), p.passes.len());
for (i, &k) in runs.iter().enumerate() {
assert!((1..=BATCH).contains(&k), "pass {i}: run {k}");
@@ -2677,7 +2701,6 @@ mod tests {
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");
}
}
}
@@ -2695,20 +2718,30 @@ mod tests {
d.layers.push(l);
}
let p = plan::plan(&d).unwrap();
- let runs = check_runs(&p, None);
+ let runs = check_runs(&p);
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));
- }
+ // The cache resumes only where a run starts, so a cached render draws the passes above
+ // its checkpoint in the same runs as an uncached one; checkpoints inside a run are
+ // skipped, but a stack of plain layers keeps some to resume at.
+ let starts = run_starts(&runs);
+ assert_eq!(starts.len(), runs.len() + 1);
+ assert!(starts[0] && starts[runs.len()]);
+ let (mut at, mut i) = (Vec::new(), 0);
+ while i < runs.len() {
+ at.push(i);
+ i += runs[i];
+ }
+ assert_eq!(starts.iter().enumerate().filter(|(_, s)| **s).map(|(i, _)| i).collect::<Vec<_>>(), [at, vec![runs.len()]].concat());
+ let resumable = p.checkpoints.iter().filter(|c| c.pass_end > 1 && starts[c.pass_end]).count();
+ assert!(resumable >= 2 && resumable < p.checkpoints.len(), "{resumable} of {:?}", p.checkpoints);
// 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);
+ check_runs(&plan::plan(&d).unwrap());
// 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()]);
+ assert_eq!(check_runs(&plan::plan(&d).unwrap()), vec![1; plan::plan(&d).unwrap().passes.len()]);
}
#[test]
diff --git a/crates/gpu/src/prefix.rs b/crates/gpu/src/prefix.rs
index cf53a6285..31406c644 100644
--- a/crates/gpu/src/prefix.rs
+++ b/crates/gpu/src/prefix.rs
@@ -18,7 +18,7 @@ use std::collections::HashMap;
use photocraft_doc::{Document, Layer};
use photocraft_geom::Rect;
-use crate::plan::{Checkpoint, Plan};
+use crate::plan::Checkpoint;
pub(crate) const MAX_BYTES: u64 = 512 << 20;
@@ -104,8 +104,10 @@ impl Prefix {
self.context.as_ref().map(|d| d.id)
}
- /// Drops the chunks `doc` invalidated and returns the checkpoint this render captures at.
- pub(crate) fn prepare(&mut self, doc: &Document, plan: &Plan<'_>) -> Option<Checkpoint> {
+ /// Drops the chunks `doc` invalidated and returns the checkpoint this render captures at, one
+ /// of `checkpoints` (the plan's that a batch run starts at). A chunk held at any other point
+ /// is dropped too: resuming there would group the layers above it differently.
+ pub(crate) fn prepare(&mut self, doc: &Document, checkpoints: &[Checkpoint]) -> Option<Checkpoint> {
if self.budget == 0 {
return None;
}
@@ -125,7 +127,7 @@ impl Prefix {
if same_context {
let mut freed = 0u64;
self.chunks.retain(|_, c| {
- let keep = changed.is_none_or(|ch| c.checkpoint.layer_end <= ch) && plan.checkpoints.contains(&c.checkpoint);
+ let keep = changed.is_none_or(|ch| c.checkpoint.layer_end <= ch) && checkpoints.contains(&c.checkpoint);
if !keep {
freed = freed.saturating_add(c.bytes);
}
@@ -135,12 +137,12 @@ impl Prefix {
} else {
self.clear();
}
- let kept = self.checkpoint.filter(|c| same_context && changed.is_none() && plan.checkpoints.contains(c));
+ let kept = self.checkpoint.filter(|c| same_context && changed.is_none() && checkpoints.contains(c));
let checkpoint = kept.or_else(|| match changed {
// Just below the edit; nothing when it is at the bottom.
- Some(changed) if same_context => plan.checkpoints.iter().rev().find(|c| c.layer_end <= changed && c.pass_end > 1).copied(),
+ Some(changed) if same_context => checkpoints.iter().rev().find(|c| c.layer_end <= changed && c.pass_end > 1).copied(),
_ => {
- let mut useful = plan.checkpoints.iter().rev().filter(|c| c.pass_end > 1);
+ let mut useful = checkpoints.iter().rev().filter(|c| c.pass_end > 1);
let last = useful.next().copied();
useful.next().copied().or(last)
}
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 62202fcaf..a37a78948 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -159,6 +159,14 @@ fn mask(rect: Rect, seed: u32, default: f32) -> LayerMask {
m
}
+/// `l` with a mask that reveals everything, so the executor draws it in a pass of its own rather
+/// than batched with the layer below: prefix tests resume at any layer (only where a batch run
+/// starts, `batch_runs`).
+fn alone(mut l: Layer) -> Layer {
+ l.mask = Some(LayerMask::reveal_all());
+ l
+}
+
fn base_doc(w: u32, h: u32) -> Document {
let mut d = Document::new("t", Size::new(w, h), ColorMode::Rgb, SampleType::U8);
d.layers.push(noise_layer("bg", PixelFormat::RGBA8, Rect::from_xywh(0, 0, w, h), 1, 0.3));
@@ -240,7 +248,7 @@ fn stack_prefix_reuse_matches_uncached_gpu_and_cpu_at_every_depth() {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
let mut doc = Document::new("reuse", Size::new(300, 70), ColorMode::Rgb, depth);
for seed in 1..=4 {
- doc.layers.push(noise_layer("layer", doc.pixel_format(), doc.bounds(), seed, 0.2));
+ doc.layers.push(alone(noise_layer("layer", doc.pixel_format(), doc.bounds(), seed, 0.2)));
}
check(&mut g, &doc, "populate prefix");
for (opacity, fill, blend, visible) in [
@@ -278,22 +286,31 @@ fn stack_prefix_reuse_matches_uncached_gpu_and_cpu_at_every_depth() {
/// Duplicating a layer high in the stack, undoing and redoing it (#5286): the render resumes
/// from the lower cached prefix and moves the cache up to just below the copy, so the undo and
/// the redo skip more passes. Every render matches an uncached compositor bit for bit, at every
-/// depth.
+/// depth, also when plain layers are drawn several to a pass and the cache can only resume where
+/// a batch starts.
#[test]
fn prefix_follows_an_edit_up_the_stack_and_stays_exact() {
let Some(mut g) = gpu() else { return };
let mut uncached = Compositor::new(&g.device);
uncached.set_composite_cache_budget(0);
- for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for (depth, batched) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().flat_map(|d| [(d, false), (d, true)]) {
let mut doc = Document::new("follow", Size::new(300, 70), ColorMode::Rgb, depth);
for seed in 1..=6 {
- doc.layers.push(noise_layer("layer", doc.pixel_format(), doc.bounds(), seed, 0.2));
+ let l = noise_layer("layer", doc.pixel_format(), doc.bounds(), seed, 0.2);
+ doc.layers.push(if batched { l } else { alone(l) });
}
let mut exact = |g: &mut Gpu, doc: &Document, what: &str| -> photocraft_gpu::Stats {
let stats = diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}"));
let cached = render_to_vec(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).unwrap();
- let cold = render_to_vec(&mut uncached, &g.device, &g.queue, doc, doc.bounds()).unwrap();
- assert_eq!(cached, cold, "{depth:?} {what}: reuse preserves the GPU accumulator exactly");
+ let (cold, cold_stats) = photocraft_gpu::render_to_vec_stats(&mut uncached, &g.device, &g.queue, doc, doc.bounds()).unwrap();
+ assert_eq!(cached, cold, "{depth:?} batched {batched} {what}: reuse preserves the GPU accumulator exactly");
+ // Batched and single-layer draws needn't give the same bits on every backend (FXC
+ // on D3D12): a render that captures the prefix groups the layers as an uncached one
+ // does, wherever its checkpoint is.
+ if stats.prefix_hits == 0 {
+ assert_eq!(stats.layers_batched, cold_stats.layers_batched, "{depth:?} {what}: capturing changed the batches");
+ }
+ assert_eq!(cold_stats.layers_batched > 0, batched, "{depth:?} {what}");
stats
};
exact(&mut g, &doc, "populate");
@@ -304,15 +321,17 @@ fn prefix_follows_an_edit_up_the_stack_and_stays_exact() {
let copy = doc.layers[4].duplicate();
doc.layers.insert(5, copy);
let first = exact(&mut g, &doc, "duplicate");
- assert!(first.prefix_hits > 0, "{depth:?} the duplicate resumes from the low prefix");
let undo = exact(&mut g, &low, "undo");
- assert!(undo.prefix_hits > 0, "{depth:?}");
- assert!(undo.prefix_passes_skipped > first.prefix_passes_skipped, "{depth:?} the cache moved up: {first:?} {undo:?}");
+ assert!(undo.prefix_hits > 0, "{depth:?} batched {batched}");
+ if !batched {
+ assert!(first.prefix_hits > 0, "{depth:?} the duplicate resumes from the low prefix");
+ assert!(undo.prefix_passes_skipped > first.prefix_passes_skipped, "{depth:?} the cache moved up: {first:?} {undo:?}");
+ }
let redo = exact(&mut g, &doc, "redo");
- assert_eq!(redo.prefix_passes_skipped, undo.prefix_passes_skipped, "{depth:?}");
+ assert_eq!(redo.prefix_passes_skipped, undo.prefix_passes_skipped, "{depth:?} batched {batched}");
// An edit below the moved cache still invalidates it.
doc.layers[2].opacity = 0.4;
- assert_eq!(exact(&mut g, &doc, "lower edit").prefix_hits, 0, "{depth:?}");
+ assert_eq!(exact(&mut g, &doc, "lower edit").prefix_hits, 0, "{depth:?} batched {batched}");
}
}
@@ -327,7 +346,7 @@ fn chunks_keep_their_own_checkpoint_after_a_partial_refresh() {
uncached.set_composite_cache_budget(0);
let mut doc = base_doc(600, 300);
for seed in 2..=5 {
- doc.layers.push(noise_layer("layer", PixelFormat::RGBA8, doc.bounds(), seed, 0.2));
+ doc.layers.push(alone(noise_layer("layer", PixelFormat::RGBA8, doc.bounds(), seed, 0.2)));
}
let mut render = |g: &mut Gpu, doc: &Document, rect: Rect, what: &str| -> photocraft_gpu::Stats {
let (cached, stats) = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, doc, rect).unwrap();
@@ -443,8 +462,8 @@ fn disjoint_partial_damages_admit_whole_chunks_not_damage_rects() {
fn prefix_partial_damage_context_occlusion_and_budget_are_conservative() {
let Some(mut g) = gpu() else { return };
let mut doc = base_doc(600, 300);
- doc.layers.push(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2));
- doc.layers.push(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2));
+ doc.layers.push(alone(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2)));
+ doc.layers.push(alone(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2)));
check(&mut g, &doc, "full prefix");
// A partial rectangle inside an already-covered whole chunk is served as a sub-rect copy —
// after a full render every in-bounds rectangle is covered, which is the point of whole