Skip to main content

crcbl_frame/
graph.rs

1//! The render graph: passes declare what they touch, and the graph works out
2//! the barriers.
3//!
4//! ```text
5//! RenderGraph ──add_render_pass()──▶ declarations
6//!      │                                  │
7//!      │  compile()                       │  reads/writes of virtual resources
8//!      ▼                                  ▼
9//! CompiledGraph ──▶ ordered passes + exact barriers + layout transitions
10//!      │                        │
11//!      │  dump()                │  execute(device, pool, encoder)
12//!      ▼                        ▼
13//!   text a human reads    the only code in the engine that calls
14//!                         `CommandEncoder::pipeline_barrier`
15//! ```
16//!
17//! Stage 2 §2.4 states the contract in one sentence:
18//! "passes declare reads/writes of virtual resources; graph compiles to ordered
19//! passes + exact `sync2` barriers + image layout transitions. **No manual
20//! barriers outside the graph, ever.**" The sandbox used to hand-write two image
21//! barriers around its frame; it no longer contains the word.
22//!
23//! # Deliberately not a scheduler
24//!
25//! The same section's risk list says: "**Graph over-engineering.** MVP graph =
26//! linear pass list with computed barriers. No multi-queue scheduling, no
27//! reordering. Resist." So:
28//!
29//! * **Passes execute in declaration order.** There is no topological sort,
30//!   because there is nothing to sort — the order the caller wrote *is* the
31//!   dependency order, and a graph that reordered would have to prove it had not
32//!   changed the picture.
33//! * **No dead-pass culling.** Declaring a pass runs it. Culling is the feature
34//!   that makes a graph unpredictable ("why did my debug pass not run?") in
35//!   exchange for saving work a caller could have simply not declared.
36//! * **No multi-queue scheduling.** Every pass names a queue and the barrier
37//!   model carries [`QueueTransfer`], so a dedicated transfer queue is additive
38//!   later — which stage 2's corrections require "from
39//!   the start so a dedicated transfer queue is additive later rather than a
40//!   barrier-model rewrite". Nothing *decides* to use a second queue.
41//!
42//! What it does do is the part that is genuinely error-prone by hand: track
43//! every resource's state, emit exactly the transitions that are needed, batch
44//! them into one call per pass, alias transients whose lifetimes do not overlap,
45//! and return every imported resource to the state its owner requires.
46//!
47//! # The physical resource outlives the frame
48//!
49//! A graph is built and thrown away every frame. The *images* are not: a
50//! steady-state frame gets the same [`ImageHandle`] out of the
51//! [`TransientPool`] it got last frame, and a graph is aliasing when two of its
52//! virtual images land on one of them. So state tracking is per **physical**
53//! resource — and a physical resource's history does not start at this frame's
54//! first pass.
55//!
56//! Treating it as though it did is a real bug and not a subtle one. A barrier
57//! whose source state is [`ResourceState::Undefined`] carries *no source scope*
58//! at all — on Vulkan it expands to `srcStageMask = NONE, srcAccessMask = NONE`
59//! — so a frame that opens by transitioning its depth buffer from `Undefined`
60//! orders that transition against nothing, while the previous frame's
61//! depth writes to the very same image may still be in flight. Two submissions,
62//! no dependency, both writing: a write-after-write hazard that
63//! `CRCBL_VK_SYNC_VALIDATION=1` reports as `write_barriers: 0`, and that a
64//! driver is free to resolve either way.
65//!
66//! So the graph asks the pool what it left each physical resource in, and the
67//! first barrier that touches one names *that* as its source:
68//!
69//! ```text
70//! frame n-1 ─ forward pass writes depth ─▶ pool remembers DepthStencilWrite
71//!                                                │
72//! frame n   ─ compile(&pool) ────────────────────┘
73//!             first barrier: DepthStencilWrite ──▶ DepthStencilWrite
74//!             (a real source scope, so the two frames are ordered)
75//! ```
76//!
77//! Aliasing *within* a frame is the same story one scale down, and used to have
78//! the same hole: handing a slot from one virtual image to the next does not
79//! change which `VkImage` it is, so the incoming resource's barrier must name
80//! the state the outgoing one left, not `Undefined`. Discarding contents is only
81//! free when there are contents worth discarding — with one handle and one
82//! description there is nothing to discard, and pretending otherwise costs the
83//! source scope that made the two passes ordered.
84//!
85//! **Imported resources are the owner's problem**, deliberately: the graph
86//! cannot know what happened to a swapchain image before it was handed one, so
87//! [`ImportedImage::initial`] is a declaration and the owner is the one who has
88//! to be right. See its docs for what makes `Undefined` correct there.
89//!
90//! It is a declaration the graph *audits*, though, wherever auditing is
91//! possible. An import that says [`InitialClaim::Tracked`] is one its owner
92//! keeps across frames, so the pool remembers what the last graph left it in —
93//! [`ImportedImage::final_state`], which the trailing barrier reaches — and the
94//! next [`RenderGraph::compile`] rejects an `initial` that disagrees. That is
95//! [`GraphError::ImportStateMismatch`], and it is the compile-time form of two
96//! bugs this engine has actually shipped: a readback path and a 1×1 shadow
97//! placeholder, each declaring a state the image was not in on every frame
98//! after the first, and each found only by a validation layer on CI. An
99//! [`InitialClaim::Acquired`] import is
100//! exempt because a semaphore, not a barrier, is what orders it; the variant's
101//! docs say why that is a real exemption rather than an escape hatch.
102//!
103//! **A buffer import is audited the same way and has no exemption at all.**
104//! [`ImportedBuffer::initial`] is the identical declaration about a resource
105//! with no layout, which is what makes getting it wrong worse rather than
106//! milder: a capture of a mislabelled image at least shows the wrong layout,
107//! and a buffer whose barrier lost its source scope looks like nothing until the
108//! numbers it carries are wrong. So every buffer import is checked against the
109//! ledger — [`GraphError::BufferImportStateMismatch`] — and [`ImportedBuffer`]
110//! carries no claim, because nothing hands this engine a buffer from behind a
111//! semaphore the way a swapchain hands it an image.
112//!
113//! # Compilation is pure, and that is what makes it testable
114//!
115//! [`RenderGraph::compile`] takes no device and touches no GPU. It reads the
116//! pool — a plain table of "what was this last used for" — and produces a
117//! [`CompiledGraph`] whose barriers name *virtual* resources; only
118//! [`CompiledGraph::execute`] resolves those to handles. That split is why
119//! `docs/notes/process.md` can call the graph-compile suite a
120//! non-negotiable anchor and have it mean something: the interesting half runs
121//! on any machine, in microseconds, with no ICD in the room — including the
122//! cross-frame half, which needs two `compile` calls against one
123//! [`TransientPool::new`] and no driver at all.
124//!
125//! # The graph explains itself
126//!
127//! [`CompiledGraph::dump`] prints the pass order, every barrier with its from
128//! and to states, and which transients ended up sharing a physical resource.
129//! Stage 2 §2.4 asks for exactly this ("the graph must
130//! be able to explain itself") and makes "graph dump readable and correct for
131//! the sandbox frame" a P1 exit criterion.
132
133use core::fmt;
134
135use crcbl_hal::{
136    Barriers, BufferBarrier, BufferHandle, BufferUsage, ClearValue, ColorAttachment,
137    CommandEncoder, ComputePassDesc, DepthStencilAttachment, Device, Format, HalError, ImageAspect,
138    ImageBarrier, ImageHandle, ImageSubresourceRange, ImageUsage, ImageViewHandle, LoadOp,
139    QueueHandle, QueueTransfer, Rect2d, RenderPassDesc, ResourceState, StoreOp, Viewport, depth,
140};
141
142use crate::timing::PassTimers;
143use crate::transient::{TransientBufferDesc, TransientImageDesc, TransientPool, TransientUse};
144
145/// A virtual image inside one graph.
146///
147/// Only meaningful to the [`RenderGraph`] that issued it. Deliberately not a
148/// [`Handle`](crcbl_core::Handle): a graph is built and thrown away every frame,
149/// so there is no use-after-free to protect against, and a plain index keeps
150/// compilation allocation-free.
151#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
152pub struct ImageId(u32);
153
154/// A virtual buffer inside one graph. See [`ImageId`].
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
156pub struct BufferId(u32);
157
158impl ImageId {
159    fn index(self) -> usize {
160        self.0 as usize
161    }
162}
163
164impl BufferId {
165    fn index(self) -> usize {
166        self.0 as usize
167    }
168}
169
170/// What backs an importer's claim about [`ImportedImage::initial`].
171///
172/// `initial` is the one thing in a graph the graph cannot derive, and getting
173/// it wrong is silent: a barrier out of a state the image is not in still
174/// records, still renders, and still passes every golden — it just carries the
175/// wrong source scope, and `Undefined` carries none at all. So the importer has
176/// to say *how it knows*, and that answer decides whether the graph can check
177/// the claim or has to take it.
178///
179/// **Images only, and that is a fact about the resources rather than about the
180/// check.** [`ImportedBuffer::initial`] is the same declaration and is audited
181/// on the same ledger, but it has no counterpart to this enum: [`Acquired`] is
182/// the only reason an import escapes the audit, an acquire is what a swapchain
183/// does, and a swapchain hands out images. Giving a buffer a claim field with
184/// one legal value would be an escape hatch with no case behind it — and the
185/// [`Acquired`] docs below are about how such a hatch is how the check gets
186/// lost.
187///
188/// [`Acquired`]: InitialClaim::Acquired
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum InitialClaim {
191    /// The importer owns this image across frames, so `initial` is checkable.
192    ///
193    /// [`RenderGraph::compile`] looks the image up in the pool's ledger of what
194    /// the last graph *left* each tracked import in, and rejects a declaration
195    /// that disagrees with it — see [`GraphError::ImportStateMismatch`]. A
196    /// handle the ledger has never heard of is accepted: the graph has left it
197    /// in nothing, so there is nothing for the claim to contradict, and an
198    /// image put into `ShaderRead` by an upload outside the graph is the
199    /// ordinary case of that.
200    ///
201    /// The right answer for anything the importer keeps and re-imports — a
202    /// shadow atlas, a 1×1 placeholder, an offscreen target it renders into
203    /// twice. Both of the bugs this check exists to stop were images of exactly
204    /// that kind: one declared [`ResourceState::Undefined`] on a placeholder the
205    /// frame before had left in [`ResourceState::ShaderRead`], which is a
206    /// write-after-read with no source scope; the other named
207    /// [`ResourceState::ColorAttachment`] on an image the graph had already
208    /// returned to [`ResourceState::Present`], which is an illegal old layout.
209    Tracked,
210    /// An acquire semaphore stands between the last use and this frame, so
211    /// there is nothing left for `initial` to order against.
212    ///
213    /// The freshly acquired swapchain image, and only that shape. Its
214    /// [`ResourceState::Undefined`] is not a lie the graph should catch: the
215    /// semaphore the acquire signalled is waited on by the submission that runs
216    /// this graph, so the frame is *already* ordered after everything the
217    /// presentation engine and the previous frame did with the image, and the
218    /// first barrier has no ordering left to carry — only a layout to reach.
219    ///
220    /// Which is also why the graph cannot check one. The image goes back into
221    /// the presentation ring at [`ResourceState::Present`] and the window system
222    /// does what it likes with it; a ledger entry saying what this frame left
223    /// would be a claim about an image the engine no longer controls. So the
224    /// ledger does not record these at all, and nothing reads them.
225    ///
226    /// **Reaching for this to quiet a rejection is how the check gets lost.** A
227    /// tracked image marked `Acquired` opts out of the whole guard and reads as
228    /// verified; if a declaration is refused and there is no acquire in the
229    /// chain, the declaration is what is wrong.
230    Acquired,
231}
232
233/// An image the graph did not create, and does not own.
234///
235/// The swapchain image is the canonical one: it belongs to the swapchain, it
236/// arrives in an undefined layout, and it must leave in
237/// [`ResourceState::Present`]. Saying that once, here, is what removes the
238/// hand-written barriers from every frame loop in the engine.
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub struct ImportedImage {
241    /// The image itself.
242    pub image: ImageHandle,
243    /// A view covering what the passes will render into or sample.
244    pub view: ImageViewHandle,
245    /// Texel format, which fixes the subresource aspects a barrier names.
246    pub format: Format,
247    /// Size in pixels, which fixes the render area of any pass that attaches it.
248    pub extent: (u32, u32),
249    /// The state it is in when the graph starts.
250    ///
251    /// [`ResourceState::Undefined`] for a freshly acquired swapchain image —
252    /// which discards its contents, which is free, and which is the only
253    /// correct source for one.
254    ///
255    /// Unlike a transient, this is a **declaration the owner makes**, not
256    /// something the graph can derive: the graph never created this image and
257    /// has no description of it to look up. `Undefined` is right for an
258    /// acquired swapchain image because the acquire's semaphore — waited on by
259    /// the submission that runs this graph — already orders the frame after
260    /// everything the presentation engine and the previous frame did with it,
261    /// so the barrier has no ordering left to carry and only has to reach the
262    /// layout. An importer with no such semaphore in the chain owes the graph
263    /// the truth here instead, or it is asking for the same write-after-write
264    /// the module docs describe.
265    ///
266    /// [`claim`](Self::claim) says which of those two an importer is, and a
267    /// [`InitialClaim::Tracked`] one is checked rather than taken on trust.
268    pub initial: ResourceState,
269    /// How the importer knows [`initial`](Self::initial), and so whether the
270    /// graph checks it. See [`InitialClaim`].
271    pub claim: InitialClaim,
272    /// The state the graph must leave it in.
273    ///
274    /// [`ResourceState::Present`] for a swapchain image. The graph emits a
275    /// trailing barrier if the last pass left it somewhere else, and emits
276    /// nothing if it did not — so this is what the image is in once the frame
277    /// has run either way, which is exactly why it is what the ledger behind
278    /// [`InitialClaim::Tracked`] records.
279    pub final_state: ResourceState,
280}
281
282/// A buffer the graph did not create, and does not own.
283///
284/// The importer-owned per-frame ring is the canonical one: a cull counter, a
285/// light grid, a readback slot. Each belongs to something that keeps it across
286/// frames and hands the same handle back every time its turn comes round, so
287/// what orders this frame's first access is a barrier out of the state the last
288/// frame on that handle left it in — and [`ImportedBuffer::initial`] is where
289/// that state is named.
290///
291/// Unlike [`ImportedImage`] there is no [`InitialClaim`] here, because there is
292/// nothing for one to say. A buffer never arrives from a presentation engine,
293/// so no buffer import in this engine has an acquire semaphore standing between
294/// the last use and this frame; every one of them is a resource whose whole
295/// history is frames of this graph, and every one is therefore checked. See
296/// [`GraphError::BufferImportStateMismatch`].
297#[derive(Clone, Copy, Debug, PartialEq, Eq)]
298pub struct ImportedBuffer {
299    /// The buffer itself.
300    pub buffer: BufferHandle,
301    /// The state it is in when the graph starts.
302    ///
303    /// A **declaration the owner makes**, exactly as
304    /// [`ImportedImage::initial`] is and for the same reason: the graph did not
305    /// create this buffer and has no description of it to look up. The right
306    /// answer is what the last thing to touch it left it in —
307    /// [`final_state`](Self::final_state) on a buffer this graph has run with
308    /// before, and whatever the upload or copy outside the graph did on one it
309    /// has not.
310    ///
311    /// [`ResourceState::Undefined`] is the answer only when nothing has written
312    /// the buffer *at all*: it names no source scope, so a barrier out of it
313    /// orders this frame against nothing, and using it on a buffer another
314    /// frame's dispatch or copy wrote is precisely the write-after-write the
315    /// module docs describe. The graph rejects that rather than believing it,
316    /// on the ledger the previous frame left — see
317    /// [`GraphError::BufferImportStateMismatch`].
318    pub initial: ResourceState,
319    /// The state the graph must leave it in.
320    ///
321    /// The graph emits a trailing barrier if the last pass left it somewhere
322    /// else and emits nothing if it did not, so this is what the buffer is in
323    /// once the frame has run either way — which is why it is what the ledger
324    /// records, and so what the next frame's `initial` has to say.
325    pub final_state: ResourceState,
326}
327
328#[derive(Clone, Copy, Debug)]
329enum ImageSource {
330    Imported(ImportedImage),
331    Transient(TransientImageDesc),
332}
333
334#[derive(Clone, Copy, Debug)]
335enum BufferSource {
336    Imported(ImportedBuffer),
337    Transient(TransientBufferDesc),
338}
339
340#[derive(Clone, Debug)]
341struct ImageNode {
342    label: String,
343    source: ImageSource,
344}
345
346#[derive(Clone, Debug)]
347struct BufferNode {
348    label: String,
349    source: BufferSource,
350}
351
352impl ImageNode {
353    fn format(&self) -> Format {
354        match self.source {
355            ImageSource::Imported(imported) => imported.format,
356            ImageSource::Transient(desc) => desc.format,
357        }
358    }
359
360    fn extent(&self) -> (u32, u32) {
361        match self.source {
362            ImageSource::Imported(imported) => imported.extent,
363            ImageSource::Transient(desc) => desc.extent,
364        }
365    }
366}
367
368/// How a pass attaches an image, if it attaches it at all.
369#[derive(Clone, Copy, Debug, PartialEq)]
370pub enum Attachment {
371    /// A colour attachment at `index` in shader output order.
372    Color {
373        /// Output slot.
374        index: u32,
375        /// Start-of-pass behaviour.
376        load: LoadOp,
377        /// End-of-pass behaviour.
378        store: StoreOp,
379        /// Used when `load` is [`LoadOp::Clear`].
380        clear: ClearValue,
381    },
382    /// The depth/stencil attachment.
383    Depth {
384        /// Start-of-pass behaviour.
385        load: LoadOp,
386        /// End-of-pass behaviour.
387        store: StoreOp,
388        /// Used when `load` is [`LoadOp::Clear`]. Defaults to the reversed-Z far
389        /// plane; see [`crcbl_hal::depth`].
390        clear: ClearValue,
391        /// Whether the pass writes depth. `false` is a pass drawing against an
392        /// existing prepass, and is the difference between
393        /// [`ResourceState::DepthStencilWrite`] and
394        /// [`ResourceState::DepthStencilRead`].
395        write: bool,
396    },
397}
398
399#[derive(Clone, Copy, Debug)]
400struct ImageAccess {
401    image: ImageId,
402    state: ResourceState,
403    attachment: Option<Attachment>,
404    /// The sub-resource range this access covers. `None` means the whole image
405    /// (every mip, every layer), resolved at execute time from the image's format.
406    /// Passes that only touch one mip or one layer declare `Some`; the graph then
407    /// emits barriers scoped to just that range rather than the full resource.
408    range: Option<ImageSubresourceRange>,
409}
410
411#[derive(Clone, Copy, Debug)]
412struct BufferAccess {
413    buffer: BufferId,
414    state: ResourceState,
415}
416
417/// Which scope a pass opens.
418#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
419pub enum PassKind {
420    /// A render pass, with attachments.
421    Render,
422    /// A compute pass, with none.
423    Compute,
424    /// A copy, which opens **no** scope at all.
425    ///
426    /// The seam's rule is that "copies, barriers and query writes are legal only
427    /// *outside* any pass", so a body that copies cannot run inside either of
428    /// the other two. The graph still computes this pass's barriers and orders
429    /// it against its neighbours exactly as it does for them — the only
430    /// difference is that [`CompiledGraph::execute`] opens nothing around the
431    /// body.
432    Copy,
433}
434
435impl PassKind {
436    /// What this kind is called in the graph dump and in errors.
437    #[must_use]
438    pub const fn name(self) -> &'static str {
439        match self {
440            Self::Render => "render",
441            Self::Compute => "compute",
442            Self::Copy => "copy",
443        }
444    }
445}
446
447type PassBody<'a> = Box<dyn FnOnce(&mut PassContext<'_>) + 'a>;
448
449struct Pass<'a> {
450    label: String,
451    kind: PassKind,
452    queue: QueueHandle,
453    images: Vec<ImageAccess>,
454    buffers: Vec<BufferAccess>,
455    body: PassBody<'a>,
456}
457
458impl fmt::Debug for Pass<'_> {
459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460        f.debug_struct("Pass")
461            .field("label", &self.label)
462            .field("kind", &self.kind)
463            .field("images", &self.images)
464            .field("buffers", &self.buffers)
465            .finish_non_exhaustive()
466    }
467}
468
469/// A frame's worth of passes, before compilation.
470///
471/// Built fresh every frame. The lifetime is the passes' closures': they borrow
472/// whatever persistent state the renderer holds, and the graph never outlives a
473/// frame, so nothing has to be cloned into them.
474pub struct RenderGraph<'a> {
475    images: Vec<ImageNode>,
476    buffers: Vec<BufferNode>,
477    passes: Vec<Pass<'a>>,
478    default_queue: QueueHandle,
479    /// The first import that disagreed with an earlier import of the same
480    /// handle, held until [`RenderGraph::compile`] can return it.
481    ///
482    /// Recorded where it happens because that is the only place both
483    /// declarations are in hand, and answered from `compile` because that is
484    /// where this file reports a graph it will not execute — the importer's
485    /// signature says `ImageId`, not `Result<ImageId, _>`, and the subsystem
486    /// that imports second is rarely the one that can decide who is right. The
487    /// first conflict only: the rest of validation names one problem and stops.
488    import_conflict: Option<GraphError>,
489}
490
491impl fmt::Debug for RenderGraph<'_> {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        f.debug_struct("RenderGraph")
494            .field("images", &self.images)
495            .field("buffers", &self.buffers)
496            .field("passes", &self.passes)
497            .field("import_conflict", &self.import_conflict)
498            .finish()
499    }
500}
501
502impl<'a> RenderGraph<'a> {
503    /// An empty graph whose passes default to `queue`.
504    #[must_use]
505    pub fn new(queue: QueueHandle) -> Self {
506        Self {
507            images: Vec::new(),
508            buffers: Vec::new(),
509            passes: Vec::new(),
510            default_queue: queue,
511            import_conflict: None,
512        }
513    }
514
515    /// Declares an image the graph owns for the duration of the frame.
516    ///
517    /// Backed by the [`TransientPool`], and **aliased** with any other transient
518    /// of the same description whose lifetime does not overlap this one.
519    pub fn create_image(&mut self, label: impl Into<String>, desc: TransientImageDesc) -> ImageId {
520        let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
521        self.images.push(ImageNode {
522            label: label.into(),
523            source: ImageSource::Transient(desc),
524        });
525        id
526    }
527
528    /// Declares a buffer the graph owns for the duration of the frame.
529    pub fn create_buffer(
530        &mut self,
531        label: impl Into<String>,
532        desc: TransientBufferDesc,
533    ) -> BufferId {
534        let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
535        self.buffers.push(BufferNode {
536            label: label.into(),
537            source: BufferSource::Transient(desc),
538        });
539        id
540    }
541
542    /// Brings an externally owned image into the graph.
543    ///
544    /// **One handle is one node.** Importing an image this graph already has
545    /// returns the id already issued for it rather than a second one, and that
546    /// is what makes two subsystems importing the same target — the base-colour
547    /// page a monitor feeds and a forward pass binds, an offscreen target two
548    /// renderers both draw into — the ordinary case it looks like. Two ids on
549    /// one image would carry *independent* state trackers, each starting from
550    /// its own declared [`initial`](ImportedImage::initial), so the graph would
551    /// see nothing to order between a write through one and a read through the
552    /// other and emit no barrier at all.
553    ///
554    /// The node keeps the **first** label. A later import naming it differently
555    /// is not an error — subsystems name the same image for their own reasons —
556    /// but every barrier record and [`CompiledGraph::dump`] line already names
557    /// it, and a label that depended on which subsystem imported last would
558    /// make the dump move under a caller reordering two unrelated imports.
559    ///
560    /// A repeat import whose declaration *disagrees* with the first is refused:
561    /// see [`GraphError::ImportDeclarationConflict`], which
562    /// [`compile`](Self::compile) returns.
563    pub fn import_image(&mut self, label: impl Into<String>, imported: ImportedImage) -> ImageId {
564        // A linear scan rather than a map from handle to id: a frame has few
565        // resources — the same assumption the id conversion below makes — and a
566        // second structure to keep in step with `images` buys nothing at this
567        // size.
568        let existing = self
569            .images
570            .iter()
571            .enumerate()
572            .find_map(|(index, node)| match node.source {
573                ImageSource::Imported(existing) if existing.image == imported.image => {
574                    Some((index, existing))
575                }
576                _ => None,
577            });
578        if let Some((index, first)) = existing {
579            if let Some((field, first, second)) = image_import_conflict(&first, &imported) {
580                self.record_import_conflict(GraphError::ImportDeclarationConflict {
581                    resource: self.images[index].label.clone(),
582                    field,
583                    first,
584                    second,
585                });
586            }
587            return ImageId(u32::try_from(index).expect("a frame has few resources"));
588        }
589        let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
590        self.images.push(ImageNode {
591            label: label.into(),
592            source: ImageSource::Imported(imported),
593        });
594        id
595    }
596
597    /// Brings an externally owned buffer into the graph.
598    ///
599    /// One handle is one node, exactly as [`import_image`](Self::import_image)
600    /// describes and for the same reason — a second id would be a second state
601    /// tracker, and a buffer written through one id and read through the other
602    /// would be a read-after-write the graph never barriered. The first label
603    /// wins, and a repeat import that disagrees is
604    /// [`GraphError::BufferImportDeclarationConflict`].
605    pub fn import_buffer(
606        &mut self,
607        label: impl Into<String>,
608        imported: ImportedBuffer,
609    ) -> BufferId {
610        let existing =
611            self.buffers
612                .iter()
613                .enumerate()
614                .find_map(|(index, node)| match node.source {
615                    BufferSource::Imported(existing) if existing.buffer == imported.buffer => {
616                        Some((index, existing))
617                    }
618                    _ => None,
619                });
620        if let Some((index, first)) = existing {
621            if let Some((field, first, second)) = buffer_import_conflict(&first, &imported) {
622                self.record_import_conflict(GraphError::BufferImportDeclarationConflict {
623                    resource: self.buffers[index].label.clone(),
624                    field,
625                    first,
626                    second,
627                });
628            }
629            return BufferId(u32::try_from(index).expect("a frame has few resources"));
630        }
631        let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
632        self.buffers.push(BufferNode {
633            label: label.into(),
634            source: BufferSource::Imported(imported),
635        });
636        id
637    }
638
639    /// Keeps the first conflicting import for [`compile`](Self::compile) to
640    /// return. Later ones are dropped: the graph is already refused, and the
641    /// second declaration has to come back past `compile` once it is fixed.
642    fn record_import_conflict(&mut self, error: GraphError) {
643        if self.import_conflict.is_none() {
644            self.import_conflict = Some(error);
645        }
646    }
647
648    /// Starts declaring a render pass. Add it with
649    /// [`PassBuilder::execute`].
650    pub fn add_render_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
651        PassBuilder::new(self, PassKind::Render, label.into())
652    }
653
654    /// Starts declaring a compute pass. Add it with
655    /// [`PassBuilder::execute`].
656    pub fn add_compute_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
657        PassBuilder::new(self, PassKind::Compute, label.into())
658    }
659
660    /// Starts declaring a copy. Add it with [`PassBuilder::execute`].
661    ///
662    /// **The one way a copy happens inside a frame.** The seam only allows a
663    /// copy outside a pass scope, so a body that calls
664    /// [`copy_buffer_to_buffer`](CommandEncoder::copy_buffer_to_buffer) from a
665    /// render or compute pass is a scope violation the null backend records —
666    /// which is why this is a kind of its own rather than a convention about
667    /// what a compute body may do.
668    ///
669    /// It is otherwise an ordinary pass: it declares what it reads in
670    /// [`ResourceState::TransferSrc`] and what it writes in
671    /// [`ResourceState::TransferDst`], and the graph emits the transitions
672    /// around it.
673    ///
674    /// **Declare the destination too**, even when it is a
675    /// [`MemoryLocation::HostReadback`](crcbl_hal::MemoryLocation::HostReadback)
676    /// staging buffer no pass can bind and nothing else in the frame touches.
677    /// A destination the graph does not know about gets no barrier, and the
678    /// access it needs ordering against is not in this frame at all: it is the
679    /// *previous* write to the same buffer, one turn of a ring ago, in another
680    /// submission. That is a write-after-write with `write_barriers: 0`, and it
681    /// is the bug `crcbl_render::cull_stats` shipped and this sentence exists to stop
682    /// repeating — import it with what the last frame left it in, exactly as
683    /// every other cross-frame resource here is imported.
684    pub fn add_copy_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
685        PassBuilder::new(self, PassKind::Copy, label.into())
686    }
687
688    /// How many passes have been declared.
689    #[must_use]
690    pub fn pass_count(&self) -> usize {
691        self.passes.len()
692    }
693
694    /// What this graph knows about `image` before anything is realised: its
695    /// format, its extent, and — for a transient only — the usage it will be
696    /// created with. `None` for an id this graph never issued.
697    ///
698    /// For a pass that has to refuse a source *when it is declared* rather than
699    /// let the device refuse the copy at execution:
700    /// `crcbl_render::sprite_pass`'s atlas copies check a rendered image against the
701    /// slot it is copied into here. An import carries no usage, so the second
702    /// half of the answer is the importer's to have got right.
703    #[must_use]
704    pub fn image_facts(&self, image: ImageId) -> Option<(Format, (u32, u32), Option<ImageUsage>)> {
705        let node = self.images.get(image.index())?;
706        let usage = match node.source {
707            ImageSource::Imported(_) => None,
708            ImageSource::Transient(desc) => Some(desc.usage),
709        };
710        Some((node.format(), node.extent(), usage))
711    }
712
713    /// Turns declarations into an ordered pass list with exact barriers.
714    ///
715    /// Pure: no device, no allocation of GPU memory, no side effects. See the
716    /// module docs for why that split exists.
717    ///
718    /// `pool` is read, never touched: it is the same [`TransientPool`]
719    /// [`CompiledGraph::execute`] will realise against, and the only thing
720    /// asked of it is what it left each physical transient in last frame. That
721    /// is what lets the first barrier of a frame carry a source scope covering
722    /// the *previous* frame's writes rather than `Undefined`, which covers
723    /// nothing — see the module docs. Passing a pool the graph will not execute
724    /// against is the one way to get this wrong, which is why the parameter is
725    /// the pool itself rather than a detachable snapshot of it.
726    ///
727    /// # Errors
728    ///
729    /// [`GraphError`] for a graph that cannot be executed as written —
730    /// conflicting accesses within one pass, a render pass with no attachments
731    /// or with attachments of different sizes, a transient nothing uses, or two
732    /// imports of one handle that disagree about what they imported.
733    pub fn compile(self, pool: &TransientPool) -> Result<CompiledGraph<'a>, GraphError> {
734        compile(self, pool)
735    }
736}
737
738/// Declares one pass. `#[must_use]` because a builder that is dropped rather
739/// than [`executed`](PassBuilder::execute) adds nothing to the graph, and a
740/// silently missing pass is a long afternoon.
741#[must_use = "a pass reaches the graph only through `execute`"]
742pub struct PassBuilder<'g, 'a> {
743    graph: &'g mut RenderGraph<'a>,
744    kind: PassKind,
745    label: String,
746    queue: QueueHandle,
747    images: Vec<ImageAccess>,
748    buffers: Vec<BufferAccess>,
749    next_color: u32,
750}
751
752impl fmt::Debug for PassBuilder<'_, '_> {
753    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754        f.debug_struct("PassBuilder")
755            .field("label", &self.label)
756            .field("kind", &self.kind)
757            .finish_non_exhaustive()
758    }
759}
760
761impl<'g, 'a> PassBuilder<'g, 'a> {
762    fn new(graph: &'g mut RenderGraph<'a>, kind: PassKind, label: String) -> Self {
763        let queue = graph.default_queue;
764        Self {
765            graph,
766            kind,
767            label,
768            queue,
769            images: Vec::new(),
770            buffers: Vec::new(),
771            next_color: 0,
772        }
773    }
774
775    /// Runs this pass on a queue other than the graph's default.
776    ///
777    /// Nothing in the MVP does — uploads share the graphics+compute queue, as
778    /// stage 2's corrections state rather than assume.
779    /// It exists because the *barrier model* has to represent queue-family
780    /// acquire/release from the start, and it does: a resource whose last user
781    /// was on another queue gets a release/acquire pair rather than a plain
782    /// transition.
783    pub fn on_queue(mut self, queue: QueueHandle) -> Self {
784        self.queue = queue;
785        self
786    }
787
788    /// Attaches `image` as the next colour attachment.
789    pub fn color(
790        mut self,
791        image: ImageId,
792        load: LoadOp,
793        store: StoreOp,
794        clear: ClearValue,
795    ) -> Self {
796        let index = self.next_color;
797        self.next_color += 1;
798        self.images.push(ImageAccess {
799            image,
800            state: ResourceState::ColorAttachment,
801            attachment: Some(Attachment::Color {
802                index,
803                load,
804                store,
805                clear,
806            }),
807            range: None,
808        });
809        self
810    }
811
812    /// Attaches `image` as the next colour attachment, cleared to `rgba` and
813    /// stored.
814    pub fn clear_color(self, image: ImageId, rgba: [f32; 4]) -> Self {
815        self.color(
816            image,
817            LoadOp::Clear,
818            StoreOp::Store,
819            ClearValue::color(rgba),
820        )
821    }
822
823    /// Attaches `image` as the depth attachment with depth writes on.
824    pub fn depth(
825        mut self,
826        image: ImageId,
827        load: LoadOp,
828        store: StoreOp,
829        clear: ClearValue,
830    ) -> Self {
831        self.images.push(ImageAccess {
832            image,
833            state: ResourceState::DepthStencilWrite,
834            attachment: Some(Attachment::Depth {
835                load,
836                store,
837                clear,
838                write: true,
839            }),
840            range: None,
841        });
842        self
843    }
844
845    /// Attaches `image` as the depth attachment, cleared to the **reversed-Z**
846    /// far plane and discarded at the end of the pass.
847    ///
848    /// [`depth::CLEAR`] rather than a literal, and discarded rather than stored
849    /// because nothing reads a depth buffer after the pass that wrote it until
850    /// there is a prepass to read — at which point [`PassBuilder::depth`] takes
851    /// a [`StoreOp`] and says so.
852    pub fn clear_depth(self, image: ImageId) -> Self {
853        self.depth(
854            image,
855            LoadOp::Clear,
856            StoreOp::Discard,
857            ClearValue {
858                depth: depth::CLEAR,
859                ..ClearValue::default()
860            },
861        )
862    }
863
864    /// Attaches `image` as a **read-only** depth attachment: tested, not
865    /// written.
866    pub fn depth_read(mut self, image: ImageId) -> Self {
867        self.images.push(ImageAccess {
868            image,
869            state: ResourceState::DepthStencilRead,
870            attachment: Some(Attachment::Depth {
871                load: LoadOp::Load,
872                store: StoreOp::Store,
873                clear: ClearValue::default(),
874                write: false,
875            }),
876            range: None,
877        });
878        self
879    }
880
881    /// Declares that this pass samples or otherwise shader-reads `image`.
882    pub fn read_image(self, image: ImageId) -> Self {
883        self.use_image(image, ResourceState::ShaderRead)
884    }
885
886    /// Declares that this pass samples or otherwise shader-reads `image`,
887    /// but only within the given sub-resource `range` (one mip, one layer,
888    /// etc.). The barrier emitted will cover only that range.
889    pub fn read_subresource(self, image: ImageId, range: ImageSubresourceRange) -> Self {
890        self.use_subresource(image, ResourceState::ShaderRead, range)
891    }
892
893    /// Declares an image access in an arbitrary state — a storage-image write, a
894    /// copy destination, anything the named helpers do not cover.
895    pub fn use_image(mut self, image: ImageId, state: ResourceState) -> Self {
896        self.images.push(ImageAccess {
897            image,
898            state,
899            attachment: None,
900            range: None,
901        });
902        self
903    }
904
905    /// Declares an image access confined to a specific sub-resource range.
906    ///
907    /// The graph emits a barrier scoped to `range` rather than the whole image.
908    /// Passes that read one mip and write another on the same image declare
909    /// disjoint ranges; the graph still tracks one whole-image state (emitting
910    /// conservative barriers when ranges differ), which is correct for the
911    /// linear pass model.
912    pub fn use_subresource(
913        mut self,
914        image: ImageId,
915        state: ResourceState,
916        range: ImageSubresourceRange,
917    ) -> Self {
918        self.images.push(ImageAccess {
919            image,
920            state,
921            attachment: None,
922            range: Some(range),
923        });
924        self
925    }
926
927    /// Declares that this pass shader-reads `buffer` — a uniform block, a
928    /// pulled vertex stream, an instance array.
929    pub fn read_buffer(self, buffer: BufferId) -> Self {
930        self.use_buffer(buffer, ResourceState::ShaderRead)
931    }
932
933    /// Declares that this pass reads `buffer` as an index buffer.
934    pub fn index_buffer(self, buffer: BufferId) -> Self {
935        self.use_buffer(buffer, ResourceState::IndexBuffer)
936    }
937
938    /// Declares a buffer access in an arbitrary state.
939    pub fn use_buffer(mut self, buffer: BufferId, state: ResourceState) -> Self {
940        self.buffers.push(BufferAccess { buffer, state });
941        self
942    }
943
944    /// Adds the pass to the graph, with `body` as the recording callback.
945    ///
946    /// `body` runs inside the pass scope: the graph has already emitted the
947    /// barriers, opened the pass and set a full-target viewport and scissor, so
948    /// a body is normally a pipeline bind, a bind group and a draw. A
949    /// [`PassKind::Copy`] body runs outside every scope instead — see
950    /// [`RenderGraph::add_copy_pass`].
951    pub fn execute(self, body: impl FnOnce(&mut PassContext<'_>) + 'a) {
952        self.graph.passes.push(Pass {
953            label: self.label,
954            kind: self.kind,
955            queue: self.queue,
956            images: self.images,
957            buffers: self.buffers,
958            body: Box::new(body),
959        });
960    }
961}
962
963// --- compiled form ---------------------------------------------------------
964
965/// A barrier the graph computed, in terms of a virtual image.
966#[derive(Clone, Copy, Debug, PartialEq, Eq)]
967pub struct GraphImageBarrier {
968    /// Image transitioned.
969    pub image: ImageId,
970    /// State being left.
971    pub from: ResourceState,
972    /// State being entered.
973    pub to: ResourceState,
974    /// Queue ownership transfer, when the previous user was on another queue.
975    pub queue_transfer: Option<QueueTransfer>,
976    /// Sub-resource range this barrier covers. `None` means the whole image,
977    /// resolved at execute time from the image's format.
978    pub range: Option<ImageSubresourceRange>,
979}
980
981/// A barrier the graph computed, in terms of a virtual buffer.
982#[derive(Clone, Copy, Debug, PartialEq, Eq)]
983pub struct GraphBufferBarrier {
984    /// Buffer transitioned.
985    pub buffer: BufferId,
986    /// State being left.
987    pub from: ResourceState,
988    /// State being entered.
989    pub to: ResourceState,
990    /// Queue ownership transfer, when the previous user was on another queue.
991    pub queue_transfer: Option<QueueTransfer>,
992}
993
994/// One batch of barriers, emitted as a single
995/// [`pipeline_barrier`](CommandEncoder::pipeline_barrier) call.
996#[derive(Clone, Debug, Default, PartialEq, Eq)]
997pub struct GraphBarriers {
998    /// Image transitions, in declaration order.
999    pub images: Vec<GraphImageBarrier>,
1000    /// Buffer transitions, in declaration order.
1001    pub buffers: Vec<GraphBufferBarrier>,
1002}
1003
1004impl GraphBarriers {
1005    /// Whether this batch would do nothing, in which case the graph emits no
1006    /// call at all.
1007    #[must_use]
1008    pub fn is_empty(&self) -> bool {
1009        self.images.is_empty() && self.buffers.is_empty()
1010    }
1011
1012    /// How many transitions it carries.
1013    #[must_use]
1014    pub fn len(&self) -> usize {
1015        self.images.len() + self.buffers.len()
1016    }
1017}
1018
1019/// One pass, after compilation.
1020pub struct CompiledPass<'a> {
1021    label: String,
1022    kind: PassKind,
1023    queue: QueueHandle,
1024    /// Barriers emitted **before** this pass opens.
1025    barriers: GraphBarriers,
1026    /// Barriers emitted **after** this pass closes: the release half of a
1027    /// queue-ownership transfer whose acquire a later pass records. Empty in
1028    /// every single-queue frame, which is every frame the MVP runs.
1029    release_barriers: GraphBarriers,
1030    images: Vec<ImageAccess>,
1031    buffers: Vec<BufferAccess>,
1032    render_area: Rect2d,
1033    body: PassBody<'a>,
1034}
1035
1036impl fmt::Debug for CompiledPass<'_> {
1037    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1038        f.debug_struct("CompiledPass")
1039            .field("label", &self.label)
1040            .field("kind", &self.kind)
1041            .field("barriers", &self.barriers)
1042            .finish_non_exhaustive()
1043    }
1044}
1045
1046impl CompiledPass<'_> {
1047    /// The pass's name, as it appears in captures and in the dump.
1048    #[must_use]
1049    pub fn label(&self) -> &str {
1050        &self.label
1051    }
1052
1053    /// Whether it is a render or a compute pass.
1054    #[must_use]
1055    pub const fn kind(&self) -> PassKind {
1056        self.kind
1057    }
1058
1059    /// The barriers emitted immediately before it.
1060    #[must_use]
1061    pub const fn barriers(&self) -> &GraphBarriers {
1062        &self.barriers
1063    }
1064
1065    /// The barriers emitted immediately after it — the release half of any
1066    /// queue-ownership transfer a later pass acquires. See
1067    /// [`crcbl_hal::QueueTransfer`] on why a transfer is two barriers.
1068    #[must_use]
1069    pub const fn release_barriers(&self) -> &GraphBarriers {
1070        &self.release_barriers
1071    }
1072
1073    /// The queue it was declared on.
1074    ///
1075    /// Always the graph's default in the MVP — uploads share the
1076    /// graphics+compute queue — but the field is what makes a second queue
1077    /// additive rather than a barrier-model rewrite, which
1078    /// stage 2's corrections require from the start.
1079    #[must_use]
1080    pub const fn queue(&self) -> QueueHandle {
1081        self.queue
1082    }
1083
1084    /// The region a render pass covers. Zero-sized for a compute pass.
1085    #[must_use]
1086    pub const fn render_area(&self) -> Rect2d {
1087        self.render_area
1088    }
1089
1090    /// Whether it declared a read of `buffer`.
1091    ///
1092    /// Compilation walks passes in declaration order and never reorders them,
1093    /// so a pass that omits the declaration still runs after the barrier the
1094    /// first reader earned — the omission is invisible in the compiled
1095    /// barriers. This is what lets a test assert the declaration itself.
1096    #[must_use]
1097    pub fn reads_buffer(&self, buffer: BufferId) -> bool {
1098        self.buffers
1099            .iter()
1100            .any(|access| access.buffer == buffer && access.state == ResourceState::ShaderRead)
1101    }
1102}
1103
1104/// Which physical resource a virtual one ended up on.
1105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1106enum Slot {
1107    /// Externally owned; no pool involvement.
1108    Imported,
1109    /// Index into the compiled graph's transient slot list.
1110    Transient(usize),
1111}
1112
1113/// A compiled graph: ordered passes, exact barriers, and a transient plan.
1114pub struct CompiledGraph<'a> {
1115    images: Vec<ImageNode>,
1116    buffers: Vec<BufferNode>,
1117    passes: Vec<CompiledPass<'a>>,
1118    /// Barriers returning imported resources to their required final states.
1119    final_barriers: GraphBarriers,
1120    image_slots: Vec<Slot>,
1121    buffer_slots: Vec<Slot>,
1122    transient_images: Vec<TransientImageDesc>,
1123    transient_buffers: Vec<TransientBufferDesc>,
1124    /// What this frame leaves each physical transient image in, parallel to
1125    /// `transient_images`. Handed to the pool by
1126    /// [`CompiledGraph::execute`] so the *next* frame's first barrier has a
1127    /// source scope; computed here because compilation is what knows it.
1128    transient_image_end: Vec<TransientUse>,
1129    /// The same for buffers.
1130    transient_buffer_end: Vec<TransientUse>,
1131    /// What this frame leaves each [`InitialClaim::Tracked`] import in, which
1132    /// is [`ImportedImage::final_state`] because the trailing barrier is what
1133    /// reaches it. Handed to the pool by [`CompiledGraph::execute`], where the
1134    /// next frame's [`RenderGraph::compile`] checks a declaration against it.
1135    imported_image_end: Vec<(ImageHandle, ResourceState)>,
1136    /// The same for every imported buffer, which is all of them: a buffer
1137    /// import has no [`InitialClaim::Acquired`] counterpart to leave out.
1138    imported_buffer_end: Vec<(BufferHandle, ResourceState)>,
1139}
1140
1141impl fmt::Debug for CompiledGraph<'_> {
1142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143        f.debug_struct("CompiledGraph")
1144            .field("passes", &self.passes)
1145            .field("final_barriers", &self.final_barriers)
1146            .field("transient_images", &self.transient_images)
1147            .field("transient_buffers", &self.transient_buffers)
1148            .finish_non_exhaustive()
1149    }
1150}
1151
1152impl<'a> CompiledGraph<'a> {
1153    /// The compiled passes, in execution order.
1154    #[must_use]
1155    pub fn passes(&self) -> &[CompiledPass<'a>] {
1156        &self.passes
1157    }
1158
1159    /// The barriers emitted after the last pass, returning imported resources to
1160    /// the states their owners require.
1161    #[must_use]
1162    pub const fn final_barriers(&self) -> &GraphBarriers {
1163        &self.final_barriers
1164    }
1165
1166    /// How many physical images the transients were packed onto.
1167    ///
1168    /// Lower than the number of transients declared exactly when aliasing
1169    /// happened, which is what makes the saving assertable.
1170    #[must_use]
1171    pub fn physical_image_count(&self) -> usize {
1172        self.transient_images.len()
1173    }
1174
1175    /// How many physical buffers the transients were packed onto.
1176    #[must_use]
1177    pub fn physical_buffer_count(&self) -> usize {
1178        self.transient_buffers.len()
1179    }
1180
1181    /// Whether two virtual images share one physical image.
1182    #[must_use]
1183    pub fn images_alias(&self, first: ImageId, second: ImageId) -> bool {
1184        matches!(
1185            (
1186                self.image_slots.get(first.index()),
1187                self.image_slots.get(second.index())
1188            ),
1189            (Some(Slot::Transient(a)), Some(Slot::Transient(b))) if a == b
1190        )
1191    }
1192
1193    /// Every barrier the frame will emit, batch by batch, ending with the final
1194    /// batch. The shape a test asserts on.
1195    #[must_use]
1196    pub fn barrier_batches(&self) -> Vec<&GraphBarriers> {
1197        self.passes
1198            .iter()
1199            .flat_map(|pass| [&pass.barriers, &pass.release_barriers])
1200            .chain(core::iter::once(&self.final_barriers))
1201            .filter(|batch| !batch.is_empty())
1202            .collect()
1203    }
1204
1205    /// The graph, as text a human reads.
1206    ///
1207    /// Stage 2 §2.4's debug-tools principle: "the graph
1208    /// must be able to explain itself", and its exit criteria require the dump
1209    /// to be "readable and correct for the sandbox frame". Every line is derived
1210    /// from the compiled form rather than re-walked from the declarations, so a
1211    /// dump that says a barrier happened is evidence that it will.
1212    #[must_use]
1213    pub fn dump(&self) -> String {
1214        let mut out = String::new();
1215        self.write_dump(&mut out).expect("writing to a String");
1216        out
1217    }
1218
1219    fn write_dump(&self, out: &mut impl fmt::Write) -> fmt::Result {
1220        let aliased = self
1221            .image_slots
1222            .iter()
1223            .filter(|slot| matches!(slot, Slot::Transient(_)))
1224            .count()
1225            .saturating_sub(self.transient_images.len());
1226        writeln!(
1227            out,
1228            "render graph: {} pass(es), {} transient image(s) on {} physical, \
1229             {} transient buffer(s) on {} physical, {} barrier(s)",
1230            self.passes.len(),
1231            self.transient_image_users(),
1232            self.transient_images.len(),
1233            self.transient_buffer_users(),
1234            self.transient_buffers.len(),
1235            self.passes
1236                .iter()
1237                .map(|pass| pass.barriers.len() + pass.release_barriers.len())
1238                .sum::<usize>()
1239                + self.final_barriers.len(),
1240        )?;
1241        if aliased > 0 {
1242            writeln!(out, "  aliasing saved {aliased} physical image(s)")?;
1243        }
1244
1245        for (index, pass) in self.passes.iter().enumerate() {
1246            self.write_barriers(out, &pass.barriers, &format!("[{index}] "))?;
1247            writeln!(
1248                out,
1249                "[{index}] {} pass {:?}  {}x{}",
1250                pass.kind.name(),
1251                pass.label,
1252                pass.render_area.width,
1253                pass.render_area.height
1254            )?;
1255            for access in &pass.images {
1256                let node = &self.images[access.image.index()];
1257                let role = match access.attachment {
1258                    Some(Attachment::Color {
1259                        index, load, store, ..
1260                    }) => {
1261                        format!("color[{index}] load={load:?} store={store:?}")
1262                    }
1263                    Some(Attachment::Depth {
1264                        load, store, write, ..
1265                    }) => format!(
1266                        "depth load={load:?} store={store:?} write={}",
1267                        if write { "yes" } else { "no" }
1268                    ),
1269                    None => "sampled/storage".to_string(),
1270                };
1271                writeln!(
1272                    out,
1273                    "        image  {:<20} {:<20} {role} [{}]",
1274                    node.label,
1275                    format!("{:?}", access.state),
1276                    self.slot_note(self.image_slots[access.image.index()]),
1277                )?;
1278            }
1279            for access in &pass.buffers {
1280                let node = &self.buffers[access.buffer.index()];
1281                writeln!(
1282                    out,
1283                    "        buffer {:<20} {:<20} [{}]",
1284                    node.label,
1285                    format!("{:?}", access.state),
1286                    self.slot_note(self.buffer_slots[access.buffer.index()]),
1287                )?;
1288            }
1289            self.write_barriers(out, &pass.release_barriers, &format!("[{index}] release "))?;
1290        }
1291
1292        self.write_barriers(out, &self.final_barriers, "[final] ")?;
1293        Ok(())
1294    }
1295
1296    fn transient_image_users(&self) -> usize {
1297        self.image_slots
1298            .iter()
1299            .filter(|slot| matches!(slot, Slot::Transient(_)))
1300            .count()
1301    }
1302
1303    fn transient_buffer_users(&self) -> usize {
1304        self.buffer_slots
1305            .iter()
1306            .filter(|slot| matches!(slot, Slot::Transient(_)))
1307            .count()
1308    }
1309
1310    fn slot_note(&self, slot: Slot) -> String {
1311        match slot {
1312            Slot::Imported => "imported".to_string(),
1313            Slot::Transient(index) => format!("transient #{index}"),
1314        }
1315    }
1316
1317    fn write_barriers(
1318        &self,
1319        out: &mut impl fmt::Write,
1320        barriers: &GraphBarriers,
1321        prefix: &str,
1322    ) -> fmt::Result {
1323        if barriers.is_empty() {
1324            return Ok(());
1325        }
1326        writeln!(out, "{prefix}barriers ({})", barriers.len())?;
1327        for barrier in &barriers.images {
1328            writeln!(
1329                out,
1330                "        image  {:<20} {:>18} -> {:<18}{}",
1331                self.images[barrier.image.index()].label,
1332                format!("{:?}", barrier.from),
1333                format!("{:?}", barrier.to),
1334                queue_note(barrier.queue_transfer),
1335            )?;
1336        }
1337        for barrier in &barriers.buffers {
1338            writeln!(
1339                out,
1340                "        buffer {:<20} {:>18} -> {:<18}{}",
1341                self.buffers[barrier.buffer.index()].label,
1342                format!("{:?}", barrier.from),
1343                format!("{:?}", barrier.to),
1344                queue_note(barrier.queue_transfer),
1345            )?;
1346        }
1347        Ok(())
1348    }
1349
1350    /// Records the whole frame into `encoder`.
1351    ///
1352    /// Realises the transients out of `pool`, then for each pass in order:
1353    /// emits its barrier batch as one call, opens the pass — naming the two
1354    /// queries `timers` gave it, which the backend samples where the pass opens
1355    /// and closes — sets a full-target viewport and scissor, runs the body and
1356    /// closes the pass. A [`PassKind::Copy`] is the exception twice over: its
1357    /// body runs with no scope open at all, because that is the only place the
1358    /// seam permits a copy, and having no scope it has no boundary to time.
1359    /// Finally emits the barriers that return
1360    /// imported resources to their required states, and tells `pool` what this
1361    /// frame left each physical transient in — which is what the *next* frame's
1362    /// first barrier uses as its source scope.
1363    ///
1364    /// `pool` must be the one [`RenderGraph::compile`] was given, or the
1365    /// barriers name states the resources are not in.
1366    ///
1367    /// The encoder is left outside any pass, with nothing to clean up.
1368    ///
1369    /// # Errors
1370    ///
1371    /// [`GraphError::Hal`] if the pool could not create a transient. Nothing
1372    /// else can fail here — everything checkable was checked at compile time.
1373    pub fn execute(
1374        self,
1375        device: &dyn Device,
1376        pool: &mut TransientPool,
1377        encoder: &mut dyn CommandEncoder,
1378        mut timers: Option<&mut PassTimers>,
1379    ) -> Result<(), GraphError> {
1380        let realised = self.realise(device, pool)?;
1381        let Self {
1382            images,
1383            passes,
1384            final_barriers,
1385            transient_images,
1386            transient_buffers,
1387            transient_image_end,
1388            transient_buffer_end,
1389            imported_image_end,
1390            imported_buffer_end,
1391            ..
1392        } = self;
1393
1394        if let Some(timers) = timers.as_deref_mut() {
1395            timers.begin_frame(device, encoder, &passes);
1396        }
1397
1398        for (index, pass) in passes.into_iter().enumerate() {
1399            emit(encoder, &images, &realised, &pass.barriers);
1400            // The pass's own boundaries, not a call around it: the seam takes a
1401            // timestamp only where a pass opens and closes, so the barriers just
1402            // emitted are outside what this pass will report.
1403            let timestamp_writes = timers
1404                .as_deref()
1405                .and_then(|timers| timers.pass_writes(index));
1406
1407            match pass.kind {
1408                PassKind::Render => {
1409                    let (colors, depth_stencil) = attachments(&realised, &pass.images);
1410                    encoder.begin_render_pass(&RenderPassDesc {
1411                        label: Some(&pass.label),
1412                        color_attachments: &colors,
1413                        depth_stencil_attachment: depth_stencil,
1414                        render_area: pass.render_area,
1415                        timestamp_writes,
1416                    });
1417                    // Dynamic state, set by the graph rather than by every pass
1418                    // body: a pipeline that baked a viewport in would have to be
1419                    // rebuilt on every resize, and every body would otherwise
1420                    // repeat the same two lines with the same chance of using
1421                    // the wrong extent.
1422                    encoder.set_viewport(&Viewport::from_size(
1423                        pass.render_area.width,
1424                        pass.render_area.height,
1425                    ));
1426                    encoder.set_scissor(&pass.render_area);
1427                }
1428                PassKind::Compute => {
1429                    encoder.begin_compute_pass(&ComputePassDesc {
1430                        label: Some(&pass.label),
1431                        timestamp_writes,
1432                    });
1433                }
1434                // Nothing is opened: a copy is only legal outside every scope.
1435                PassKind::Copy => {}
1436            }
1437
1438            {
1439                let mut context = PassContext {
1440                    device,
1441                    encoder,
1442                    realised: &realised,
1443                    render_area: pass.render_area,
1444                };
1445                (pass.body)(&mut context);
1446            }
1447
1448            match pass.kind {
1449                PassKind::Render => encoder.end_render_pass(),
1450                PassKind::Compute => encoder.end_compute_pass(),
1451                PassKind::Copy => {}
1452            }
1453            // The release half of any queue-ownership transfer a later pass
1454            // acquires. Outside the pass scope, because the seam only allows
1455            // barriers there.
1456            emit(encoder, &images, &realised, &pass.release_barriers);
1457        }
1458
1459        emit(encoder, &images, &realised, &final_barriers);
1460
1461        // The handover to the next frame. It happens after the commands are
1462        // recorded rather than during compilation because a graph that is
1463        // compiled and dropped ran nothing, and a pool that remembered a frame
1464        // that never happened would order the following frame against writes
1465        // the GPU never performed.
1466        for (slot, desc) in transient_images.iter().enumerate() {
1467            pool.set_image_use(
1468                *desc,
1469                ordinal(&transient_images, slot),
1470                transient_image_end[slot],
1471            );
1472        }
1473        for (slot, desc) in transient_buffers.iter().enumerate() {
1474            pool.set_buffer_use(
1475                *desc,
1476                ordinal(&transient_buffers, slot),
1477                transient_buffer_end[slot],
1478            );
1479        }
1480        // The same handover for the imports the owner says it tracks, and for
1481        // the same reason one turn further out: the next graph's `compile` is
1482        // what reads these, and it reads them to *refuse* a declaration that
1483        // disagrees rather than to barrier against them.
1484        for (image, state) in imported_image_end {
1485            pool.set_imported_image_use(image, state);
1486        }
1487        for (buffer, state) in imported_buffer_end {
1488            pool.set_imported_buffer_use(buffer, state);
1489        }
1490        Ok(())
1491    }
1492
1493    fn realise(
1494        &self,
1495        device: &dyn Device,
1496        pool: &mut TransientPool,
1497    ) -> Result<Realised, GraphError> {
1498        pool.begin_frame();
1499        let mut physical_images = Vec::with_capacity(self.transient_images.len());
1500        for desc in &self.transient_images {
1501            physical_images.push(pool.image(device, *desc)?);
1502        }
1503        let mut physical_buffers = Vec::with_capacity(self.transient_buffers.len());
1504        for desc in &self.transient_buffers {
1505            physical_buffers.push(pool.buffer(device, *desc)?);
1506        }
1507
1508        let images = self
1509            .images
1510            .iter()
1511            .zip(&self.image_slots)
1512            .map(|(node, slot)| match (slot, node.source) {
1513                (Slot::Imported, ImageSource::Imported(imported)) => {
1514                    (imported.image, imported.view)
1515                }
1516                (Slot::Transient(index), _) => physical_images[*index],
1517                // Unreachable: `compile` assigns `Imported` only to imported
1518                // nodes. Stated as a panic rather than an `unwrap` so the
1519                // invariant is named where it is relied on.
1520                (Slot::Imported, ImageSource::Transient(_)) => {
1521                    unreachable!("a transient image was assigned the imported slot")
1522                }
1523            })
1524            .collect();
1525        let buffers = self
1526            .buffers
1527            .iter()
1528            .zip(&self.buffer_slots)
1529            .map(|(node, slot)| match (slot, node.source) {
1530                (Slot::Imported, BufferSource::Imported(imported)) => imported.buffer,
1531                (Slot::Transient(index), _) => physical_buffers[*index],
1532                (Slot::Imported, BufferSource::Transient(_)) => {
1533                    unreachable!("a transient buffer was assigned the imported slot")
1534                }
1535            })
1536            .collect();
1537
1538        Ok(Realised { images, buffers })
1539    }
1540}
1541
1542fn queue_note(transfer: Option<QueueTransfer>) -> String {
1543    transfer.map_or_else(String::new, |transfer| {
1544        format!("  queue {:?} -> {:?}", transfer.from, transfer.to)
1545    })
1546}
1547
1548/// Virtual resources resolved to real handles, for the duration of one
1549/// [`CompiledGraph::execute`].
1550#[derive(Debug)]
1551struct Realised {
1552    images: Vec<(ImageHandle, ImageViewHandle)>,
1553    buffers: Vec<BufferHandle>,
1554}
1555
1556/// What a pass body is handed.
1557///
1558/// It has an encoder already inside the pass scope, the device (for the rare
1559/// body that has to build something against a transient's handle), and a way to
1560/// turn a virtual id into the handle it landed on.
1561#[derive(Debug)]
1562pub struct PassContext<'a> {
1563    device: &'a dyn Device,
1564    encoder: &'a mut dyn CommandEncoder,
1565    realised: &'a Realised,
1566    render_area: Rect2d,
1567}
1568
1569impl PassContext<'_> {
1570    /// The encoder, already inside this pass's scope.
1571    pub fn encoder(&mut self) -> &mut dyn CommandEncoder {
1572        self.encoder
1573    }
1574
1575    /// The device, for a body that must create something against a transient's
1576    /// handle — a bind group naming a graph-owned image view, typically.
1577    #[must_use]
1578    pub fn device(&self) -> &dyn Device {
1579        self.device
1580    }
1581
1582    /// The handle a virtual image landed on.
1583    ///
1584    /// # Panics
1585    ///
1586    /// If `id` came from a different graph.
1587    #[must_use]
1588    pub fn image(&self, id: ImageId) -> ImageHandle {
1589        self.realised.images[id.index()].0
1590    }
1591
1592    /// The view of a virtual image.
1593    ///
1594    /// Stable frame to frame while the graph's shape is, which is what lets a
1595    /// caller cache a bind group against it and rebuild only on a resize.
1596    ///
1597    /// # Panics
1598    ///
1599    /// If `id` came from a different graph.
1600    #[must_use]
1601    pub fn image_view(&self, id: ImageId) -> ImageViewHandle {
1602        self.realised.images[id.index()].1
1603    }
1604
1605    /// The handle a virtual buffer landed on.
1606    ///
1607    /// # Panics
1608    ///
1609    /// If `id` came from a different graph.
1610    #[must_use]
1611    pub fn buffer(&self, id: BufferId) -> BufferHandle {
1612        self.realised.buffers[id.index()]
1613    }
1614
1615    /// The region this pass renders, in pixels. The viewport and scissor are
1616    /// already set to it.
1617    #[must_use]
1618    pub const fn render_area(&self) -> Rect2d {
1619        self.render_area
1620    }
1621}
1622
1623fn emit(
1624    encoder: &mut dyn CommandEncoder,
1625    images: &[ImageNode],
1626    realised: &Realised,
1627    barriers: &GraphBarriers,
1628) {
1629    if barriers.is_empty() {
1630        return;
1631    }
1632    let image_barriers: Vec<ImageBarrier> = barriers
1633        .images
1634        .iter()
1635        .map(|barrier| ImageBarrier {
1636            image: realised.images[barrier.image.index()].0,
1637            range: barrier.range.unwrap_or_else(|| {
1638                ImageSubresourceRange::all(images[barrier.image.index()].format())
1639            }),
1640            from: barrier.from,
1641            to: barrier.to,
1642            queue_transfer: barrier.queue_transfer,
1643        })
1644        .collect();
1645    let buffer_barriers: Vec<BufferBarrier> = barriers
1646        .buffers
1647        .iter()
1648        .map(|barrier| BufferBarrier {
1649            buffer: realised.buffers[barrier.buffer.index()],
1650            from: barrier.from,
1651            to: barrier.to,
1652            queue_transfer: barrier.queue_transfer,
1653        })
1654        .collect();
1655    encoder.pipeline_barrier(&Barriers {
1656        buffers: &buffer_barriers,
1657        images: &image_barriers,
1658        global: false,
1659    });
1660}
1661
1662fn attachments(
1663    realised: &Realised,
1664    accesses: &[ImageAccess],
1665) -> (Vec<ColorAttachment>, Option<DepthStencilAttachment>) {
1666    let mut colors: Vec<(u32, ColorAttachment)> = Vec::new();
1667    let mut depth_stencil = None;
1668    for access in accesses {
1669        let view = realised.images[access.image.index()].1;
1670        match access.attachment {
1671            Some(Attachment::Color {
1672                index,
1673                load,
1674                store,
1675                clear,
1676            }) => colors.push((
1677                index,
1678                ColorAttachment {
1679                    view,
1680                    resolve: None,
1681                    load,
1682                    store,
1683                    clear,
1684                },
1685            )),
1686            Some(Attachment::Depth {
1687                load,
1688                store,
1689                clear,
1690                write,
1691            }) => {
1692                depth_stencil = Some(DepthStencilAttachment {
1693                    view,
1694                    // `PassBuilder::depth_read` declares
1695                    // `ResourceState::DepthStencilRead`, which puts the image in
1696                    // a *different* layout from a written depth attachment. The
1697                    // backend cannot infer that from the ops, so the pass's own
1698                    // `write` flag is what tells it.
1699                    read_only: !write,
1700                    depth_load: load,
1701                    depth_store: store,
1702                    // No stencil plane in anything the engine renders yet; a
1703                    // `D32_SFLOAT` attachment has none to load or store.
1704                    stencil_load: LoadOp::DontCare,
1705                    stencil_store: StoreOp::Discard,
1706                    clear,
1707                });
1708            }
1709            None => {}
1710        }
1711    }
1712    // Attachment order in the descriptor is shader-output order, which is the
1713    // `index` a caller gave — not the order it happened to declare them in.
1714    colors.sort_by_key(|(index, _)| *index);
1715    (
1716        colors
1717            .into_iter()
1718            .map(|(_, attachment)| attachment)
1719            .collect(),
1720        depth_stencil,
1721    )
1722}
1723
1724// --- compilation -----------------------------------------------------------
1725
1726/// Why a graph could not be compiled.
1727#[derive(Debug, thiserror::Error)]
1728pub enum GraphError {
1729    /// One pass declared two different states for the same resource.
1730    #[error(
1731        "pass `{pass}` accesses `{resource}` as both {first:?} and {second:?}; a resource is in \
1732         one state per pass, so this needs two passes or one state"
1733    )]
1734    ConflictingAccess {
1735        /// Pass label.
1736        pass: String,
1737        /// Resource label.
1738        resource: String,
1739        /// The first state declared.
1740        first: ResourceState,
1741        /// The second, incompatible state.
1742        second: ResourceState,
1743    },
1744    /// A render pass attached nothing.
1745    #[error(
1746        "render pass `{pass}` has no attachments; a pass that renders nowhere is a declaration \
1747         mistake, not an optimisation"
1748    )]
1749    NoAttachments {
1750        /// Pass label.
1751        pass: String,
1752    },
1753    /// A render pass attached images of different sizes.
1754    #[error(
1755        "render pass `{pass}` attaches `{first}` at {first_extent:?} and `{second}` at \
1756         {second_extent:?}; every attachment must be the same size"
1757    )]
1758    AttachmentExtentMismatch {
1759        /// Pass label.
1760        pass: String,
1761        /// The first attachment's label.
1762        first: String,
1763        /// Its size.
1764        first_extent: (u32, u32),
1765        /// The disagreeing attachment's label.
1766        second: String,
1767        /// Its size.
1768        second_extent: (u32, u32),
1769    },
1770    /// A render pass attached two depth images.
1771    #[error("render pass `{pass}` attaches more than one depth image")]
1772    DuplicateDepthAttachment {
1773        /// Pass label.
1774        pass: String,
1775    },
1776    /// One pass declared the same resource twice over the same subrange.
1777    ///
1778    /// `.color(image, ..).color(image, ..)` used to be accepted and produced
1779    /// two colour attachments over one view — two shader outputs writing the
1780    /// same pixels, in an order nothing defines. A pass that genuinely touches
1781    /// two parts of one image declares two *different* subresource ranges.
1782    #[error(
1783        "pass `{pass}` declares `{resource}` twice over the same subrange; a resource is declared \
1784         once per pass, and two attachments over one view is not a second attachment"
1785    )]
1786    DuplicateDeclaration {
1787        /// Pass label.
1788        pass: String,
1789        /// Resource label.
1790        resource: String,
1791    },
1792    /// A pass named a mip level or array layer the image does not have.
1793    #[error(
1794        "pass `{pass}` uses `{resource}` at mip {base_mip}+{mip_count} / layer \
1795         {base_layer}+{layer_count}, but the image has {mip_levels} mip level(s) and \
1796         {layers} layer(s); a barrier on a subresource that does not exist covers nothing"
1797    )]
1798    SubresourceOutOfRange {
1799        /// Pass label.
1800        pass: String,
1801        /// Resource label.
1802        resource: String,
1803        /// First mip named.
1804        base_mip: u32,
1805        /// Mip levels named.
1806        mip_count: u32,
1807        /// First layer named.
1808        base_layer: u32,
1809        /// Layers named.
1810        layer_count: u32,
1811        /// Mip levels the image has.
1812        mip_levels: u32,
1813        /// Array layers the image has.
1814        layers: u32,
1815    },
1816    /// A pass that opens no render scope attached something.
1817    #[error("{kind} pass `{pass}` attaches `{resource}`; only a render pass has attachments")]
1818    AttachmentOutsideRenderPass {
1819        /// Which kind of pass declared it — [`PassKind::name`].
1820        kind: &'static str,
1821        /// Pass label.
1822        pass: String,
1823        /// Resource label.
1824        resource: String,
1825    },
1826    /// A transient was declared and never used, so it has no lifetime and no
1827    /// reason to exist.
1828    #[error(
1829        "`{resource}` is a transient no pass reads or writes; either a pass forgot to declare it \
1830         or the resource should not have been created"
1831    )]
1832    UnusedTransient {
1833        /// Resource label.
1834        resource: String,
1835    },
1836    /// An [`InitialClaim::Tracked`] import declared a state the last graph did
1837    /// not leave the image in.
1838    ///
1839    /// The whole point of the claim: the owner said it tracks this image across
1840    /// frames, and the pool remembers what the previous graph's trailing
1841    /// barrier actually reached. When those disagree the first barrier of this
1842    /// frame names a source scope the GPU never visits — and if the declaration
1843    /// is [`ResourceState::Undefined`] it names no source scope at all, so the
1844    /// transition orders against nothing while the previous frame is still
1845    /// reading the same image.
1846    #[error(
1847        "`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
1848         barrier out of a state the image is not in carries the wrong source scope — declare \
1849         what was left, or say `InitialClaim::Acquired` if a semaphore already orders this frame"
1850    )]
1851    ImportStateMismatch {
1852        /// Resource label.
1853        resource: String,
1854        /// What the import declared as [`ImportedImage::initial`].
1855        declared: ResourceState,
1856        /// What the last graph to execute against this pool left it in.
1857        left: ResourceState,
1858    },
1859    /// A buffer import declared a state the last graph did not leave it in.
1860    ///
1861    /// [`GraphError::ImportStateMismatch`] for a resource with no layout, and
1862    /// its own variant rather than the same one because the two answers a reader
1863    /// needs differ. An image has a way out — say [`InitialClaim::Acquired`] and
1864    /// mean it — and telling a buffer's importer to reach for a field
1865    /// [`ImportedBuffer`] does not have would send them looking for an escape
1866    /// that is not there and should not be. What is left when that clause goes
1867    /// is the whole of the advice: declare what the last frame left.
1868    #[error(
1869        "`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
1870         barrier out of a state the buffer is not in carries the wrong source scope, and \
1871         `Undefined` carries none at all — declare what was left"
1872    )]
1873    BufferImportStateMismatch {
1874        /// Resource label.
1875        resource: String,
1876        /// What the import declared as [`ImportedBuffer::initial`].
1877        declared: ResourceState,
1878        /// What the last graph to execute against this pool left it in.
1879        left: ResourceState,
1880    },
1881    /// One image handle was imported twice with declarations that disagree.
1882    ///
1883    /// [`RenderGraph::import_image`] hands the second importer the id the first
1884    /// one got, because one handle has to be one node with one state tracker
1885    /// for the graph to barrier between two passes that reach it through
1886    /// different ids. That leaves exactly one thing it cannot do quietly: two
1887    /// declarations that are not the same declaration. Keeping the first would
1888    /// be the graph ignoring the second — silently sampling through a view it
1889    /// was not handed, or barriering out of a state the other importer says the
1890    /// image is not in — so the frame is refused instead and the two importers
1891    /// have to agree.
1892    #[error(
1893        "`{resource}` is imported more than once with different declarations: `{field}` is \
1894         {first} in one and {second} in the other; one handle is one node with one state \
1895         tracker, so the graph cannot honour both — import it once and share the id"
1896    )]
1897    ImportDeclarationConflict {
1898        /// Resource label — the **first** import's, which is the one the node
1899        /// kept.
1900        resource: String,
1901        /// Which field of [`ImportedImage`] disagreed.
1902        field: ImportField,
1903        /// What the first import declared it as, [`Debug`](fmt::Debug)-printed.
1904        first: String,
1905        /// What the later import declared it as.
1906        second: String,
1907    },
1908    /// One buffer handle was imported twice with declarations that disagree.
1909    ///
1910    /// [`GraphError::ImportDeclarationConflict`] for a resource with no layout,
1911    /// and a variant of its own for the same reason
1912    /// [`GraphError::BufferImportStateMismatch`] is one: the message names the
1913    /// resource kind, and a caller matching on the error is usually looking at
1914    /// one kind of resource.
1915    #[error(
1916        "`{resource}` is imported more than once with different declarations: `{field}` is \
1917         {first} in one and {second} in the other; one handle is one node with one state \
1918         tracker, so the graph cannot honour both — import it once and share the id"
1919    )]
1920    BufferImportDeclarationConflict {
1921        /// Resource label — the **first** import's, which is the one the node
1922        /// kept.
1923        resource: String,
1924        /// Which field of [`ImportedBuffer`] disagreed.
1925        field: ImportField,
1926        /// What the first import declared it as, [`Debug`](fmt::Debug)-printed.
1927        first: String,
1928        /// What the later import declared it as.
1929        second: String,
1930    },
1931    /// The seam refused something at execution time.
1932    #[error(transparent)]
1933    Hal(#[from] HalError),
1934}
1935
1936/// Which field of a repeated import declaration disagreed with the first one.
1937///
1938/// Carried by [`GraphError::ImportDeclarationConflict`] and
1939/// [`GraphError::BufferImportDeclarationConflict`] so a caller can tell the
1940/// kinds of disagreement apart without parsing a message: two subsystems
1941/// disagreeing about the state an image arrives in is a synchronisation bug in
1942/// one of them, and two disagreeing about which view they bind is usually one
1943/// of them importing the wrong thing entirely.
1944///
1945/// It spells [`ImportedImage`]'s fields, of which an [`ImportedBuffer`] has
1946/// only [`Initial`](Self::Initial) and [`FinalState`](Self::FinalState); the
1947/// handle itself is absent because it is what the two declarations are matched
1948/// on, so it cannot be what they differ in. [`Display`](fmt::Display) prints
1949/// the field's name as it is spelled in the struct, so a message points at
1950/// something a reader can go and look at.
1951#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1952pub enum ImportField {
1953    /// [`ImportedImage::view`].
1954    View,
1955    /// [`ImportedImage::format`].
1956    Format,
1957    /// [`ImportedImage::extent`].
1958    Extent,
1959    /// [`ImportedImage::initial`] or [`ImportedBuffer::initial`].
1960    Initial,
1961    /// [`ImportedImage::claim`].
1962    Claim,
1963    /// [`ImportedImage::final_state`] or [`ImportedBuffer::final_state`].
1964    FinalState,
1965}
1966
1967impl fmt::Display for ImportField {
1968    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1969        f.write_str(match self {
1970            Self::View => "view",
1971            Self::Format => "format",
1972            Self::Extent => "extent",
1973            Self::Initial => "initial",
1974            Self::Claim => "claim",
1975            Self::FinalState => "final_state",
1976        })
1977    }
1978}
1979
1980/// The first field two declarations of one imported image disagree about.
1981///
1982/// First rather than all of them, because that is how the rest of this file
1983/// reports: one problem named, and the fixed declaration comes back past
1984/// `compile` anyway. Compares the values and formats only what it returns —
1985/// deciding "same declaration" off the printed text would make two handles that
1986/// happen to print alike into one.
1987fn image_import_conflict(
1988    first: &ImportedImage,
1989    second: &ImportedImage,
1990) -> Option<(ImportField, String, String)> {
1991    // Binds nothing; it is here so that adding a field to `ImportedImage` stops
1992    // compiling until this function has decided about it. A field the
1993    // comparison forgets is a disagreement reported as agreement, which is the
1994    // one failure this whole check exists to prevent — and the six blocks below
1995    // look alike enough that a missing seventh would read as complete.
1996    let ImportedImage {
1997        image: _,
1998        view: _,
1999        format: _,
2000        extent: _,
2001        initial: _,
2002        claim: _,
2003        final_state: _,
2004    } = first;
2005    if first.view != second.view {
2006        return Some((
2007            ImportField::View,
2008            format!("{:?}", first.view),
2009            format!("{:?}", second.view),
2010        ));
2011    }
2012    if first.format != second.format {
2013        return Some((
2014            ImportField::Format,
2015            format!("{:?}", first.format),
2016            format!("{:?}", second.format),
2017        ));
2018    }
2019    if first.extent != second.extent {
2020        return Some((
2021            ImportField::Extent,
2022            format!("{:?}", first.extent),
2023            format!("{:?}", second.extent),
2024        ));
2025    }
2026    if first.initial != second.initial {
2027        return Some((
2028            ImportField::Initial,
2029            format!("{:?}", first.initial),
2030            format!("{:?}", second.initial),
2031        ));
2032    }
2033    if first.claim != second.claim {
2034        return Some((
2035            ImportField::Claim,
2036            format!("{:?}", first.claim),
2037            format!("{:?}", second.claim),
2038        ));
2039    }
2040    if first.final_state != second.final_state {
2041        return Some((
2042            ImportField::FinalState,
2043            format!("{:?}", first.final_state),
2044            format!("{:?}", second.final_state),
2045        ));
2046    }
2047    None
2048}
2049
2050/// The first field two declarations of one imported buffer disagree about. See
2051/// [`image_import_conflict`]; a buffer declaration is the two state fields and
2052/// the handle they are about.
2053fn buffer_import_conflict(
2054    first: &ImportedBuffer,
2055    second: &ImportedBuffer,
2056) -> Option<(ImportField, String, String)> {
2057    // See [`image_import_conflict`]: binds nothing, and stops compiling when
2058    // `ImportedBuffer` grows a field this comparison has not decided about.
2059    let ImportedBuffer {
2060        buffer: _,
2061        initial: _,
2062        final_state: _,
2063    } = first;
2064    if first.initial != second.initial {
2065        return Some((
2066            ImportField::Initial,
2067            format!("{:?}", first.initial),
2068            format!("{:?}", second.initial),
2069        ));
2070    }
2071    if first.final_state != second.final_state {
2072        return Some((
2073            ImportField::FinalState,
2074            format!("{:?}", first.final_state),
2075            format!("{:?}", second.final_state),
2076        ));
2077    }
2078    None
2079}
2080
2081/// Array layers a [`TransientImageDesc`] image has. The pool creates them
2082/// single-layer, and the description has no field to say otherwise.
2083const TRANSIENT_LAYERS: u32 = 1;
2084
2085/// Per-physical-resource tracking during compilation.
2086///
2087/// Keyed on the *physical* resource, and seeded from what that resource was
2088/// last used for — [`ImportedImage::initial`] for an import, the pool's memory
2089/// of the previous frame for a transient. There is no "and now the slot is
2090/// fresh" case: a slot handed from one virtual resource to another is the same
2091/// object, in the state the previous one left it, and the module docs explain
2092/// why pretending otherwise loses the barrier.
2093#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2094struct Tracked {
2095    state: ResourceState,
2096    queue: Option<QueueHandle>,
2097    /// Index of the pass in *this* graph that last used it, which is where the
2098    /// release half of a queue-ownership transfer has to be recorded.
2099    last_pass: Option<usize>,
2100}
2101
2102impl Tracked {
2103    const fn carried(last: TransientUse) -> Self {
2104        Self {
2105            state: last.state,
2106            queue: last.queue,
2107            last_pass: None,
2108        }
2109    }
2110
2111    const fn declared(state: ResourceState) -> Self {
2112        Self {
2113            state,
2114            queue: None,
2115            last_pass: None,
2116        }
2117    }
2118
2119    const fn end(self) -> TransientUse {
2120        TransientUse {
2121            state: self.state,
2122            queue: self.queue,
2123        }
2124    }
2125}
2126
2127/// A half-open mip × layer rectangle of one image.
2128///
2129/// The unit of image state tracking. Whole-image is just the rectangle covering
2130/// everything — the graph does not need a second representation for it.
2131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2132struct Subrect {
2133    mips: (u32, u32),
2134    layers: (u32, u32),
2135}
2136
2137impl Subrect {
2138    /// The rectangle a resource with unknown extents starts at. Imported
2139    /// images do not say how many levels or layers they have, and every access
2140    /// to one in this engine covers the whole thing.
2141    const UNBOUNDED: Self = Self {
2142        mips: (0, u32::MAX),
2143        layers: (0, u32::MAX),
2144    };
2145
2146    const fn bounded(mip_levels: u32, layers: u32) -> Self {
2147        Self {
2148            mips: (0, mip_levels),
2149            layers: (0, layers),
2150        }
2151    }
2152
2153    const fn is_empty(self) -> bool {
2154        self.mips.0 >= self.mips.1 || self.layers.0 >= self.layers.1
2155    }
2156
2157    fn intersect(self, other: Self) -> Self {
2158        Self {
2159            mips: (self.mips.0.max(other.mips.0), self.mips.1.min(other.mips.1)),
2160            layers: (
2161                self.layers.0.max(other.layers.0),
2162                self.layers.1.min(other.layers.1),
2163            ),
2164        }
2165    }
2166
2167    /// `self` minus `cut`, as up to four disjoint rectangles.
2168    ///
2169    /// `cut` must already be an intersection with `self`, so the pieces tile
2170    /// the difference exactly.
2171    fn subtract(self, cut: Self) -> Vec<Self> {
2172        let mut out = Vec::new();
2173        if cut.mips.0 > self.mips.0 {
2174            out.push(Self {
2175                mips: (self.mips.0, cut.mips.0),
2176                layers: self.layers,
2177            });
2178        }
2179        if self.mips.1 > cut.mips.1 {
2180            out.push(Self {
2181                mips: (cut.mips.1, self.mips.1),
2182                layers: self.layers,
2183            });
2184        }
2185        if cut.layers.0 > self.layers.0 {
2186            out.push(Self {
2187                mips: cut.mips,
2188                layers: (self.layers.0, cut.layers.0),
2189            });
2190        }
2191        if self.layers.1 > cut.layers.1 {
2192            out.push(Self {
2193                mips: cut.mips,
2194                layers: (cut.layers.1, self.layers.1),
2195            });
2196        }
2197        out
2198    }
2199
2200    fn to_range(self, aspect: crcbl_hal::ImageAspect) -> ImageSubresourceRange {
2201        ImageSubresourceRange {
2202            aspect,
2203            base_mip: self.mips.0,
2204            mip_count: if self.mips.1 == u32::MAX {
2205                ImageSubresourceRange::ALL
2206            } else {
2207                self.mips.1 - self.mips.0
2208            },
2209            base_layer: self.layers.0,
2210            layer_count: if self.layers.1 == u32::MAX {
2211                ImageSubresourceRange::ALL
2212            } else {
2213                self.layers.1 - self.layers.0
2214            },
2215        }
2216    }
2217}
2218
2219/// `ALL` means "every remaining", so it resolves against the image's own size.
2220fn subrect_of(range: ImageSubresourceRange, bounds: Subrect) -> Subrect {
2221    let mip_end = if range.mip_count == ImageSubresourceRange::ALL {
2222        bounds.mips.1
2223    } else {
2224        range.base_mip.saturating_add(range.mip_count)
2225    };
2226    let layer_end = if range.layer_count == ImageSubresourceRange::ALL {
2227        bounds.layers.1
2228    } else {
2229        range.base_layer.saturating_add(range.layer_count)
2230    };
2231    Subrect {
2232        mips: (range.base_mip, mip_end),
2233        layers: (range.base_layer, layer_end),
2234    }
2235}
2236
2237/// One transition the tracker decided is needed.
2238#[derive(Clone, Copy, Debug)]
2239struct SubBarrier {
2240    from: ResourceState,
2241    queue_transfer: Option<QueueTransfer>,
2242    /// The part of the image it covers, or `None` when the whole access range
2243    /// is in one state and the access's own range already describes it.
2244    rect: Option<Subrect>,
2245    /// Pass that last used this part, for the release half of a transfer.
2246    last_pass: Option<usize>,
2247}
2248
2249/// Per-**subresource** image state.
2250///
2251/// A whole-image tracker was wrong in a way that only a per-mip pass could
2252/// notice, and did: writing mip 0 and then mip 1 produced a barrier on mip 1
2253/// whose `from` was the state mip 0 had been left in, which mip 1 had never
2254/// been in. A barrier that names a source state its subresource never occupied
2255/// is a barrier the driver is free to interpret as covering nothing.
2256#[derive(Clone, Debug)]
2257struct ImageTracker {
2258    bounds: Subrect,
2259    /// Disjoint rectangles tiling `bounds`, each with the state of that part.
2260    segments: Vec<(Subrect, Tracked)>,
2261}
2262
2263impl ImageTracker {
2264    fn new(bounds: Subrect, tracked: Tracked) -> Self {
2265        Self {
2266            bounds,
2267            segments: vec![(bounds, tracked)],
2268        }
2269    }
2270
2271    /// Applies an access covering `rect`, returning the barriers it needs.
2272    fn transition(
2273        &mut self,
2274        rect: Subrect,
2275        want: ResourceState,
2276        queue: QueueHandle,
2277        pass: usize,
2278    ) -> Vec<SubBarrier> {
2279        let mut outside: Vec<(Subrect, Tracked)> = Vec::new();
2280        let mut inside: Vec<(Subrect, Tracked)> = Vec::new();
2281        for (segment, tracked) in self.segments.drain(..) {
2282            let overlap = segment.intersect(rect);
2283            if overlap.is_empty() {
2284                outside.push((segment, tracked));
2285                continue;
2286            }
2287            outside.extend(
2288                segment
2289                    .subtract(overlap)
2290                    .into_iter()
2291                    .map(|piece| (piece, tracked)),
2292            );
2293            inside.push((overlap, tracked));
2294        }
2295
2296        let mut barriers = Vec::new();
2297        for (piece, tracked) in &inside {
2298            let queue_transfer = match tracked.queue {
2299                Some(previous) if previous != queue => Some(QueueTransfer {
2300                    from: previous,
2301                    to: queue,
2302                }),
2303                _ => None,
2304            };
2305            // A queue-family transfer is a barrier even between two identical
2306            // states: ownership has to move, or the second queue reads memory
2307            // the first has not released.
2308            if ResourceState::needs_barrier(tracked.state, want) || queue_transfer.is_some() {
2309                barriers.push(SubBarrier {
2310                    from: tracked.state,
2311                    queue_transfer,
2312                    rect: Some(*piece),
2313                    last_pass: tracked.last_pass,
2314                });
2315            }
2316        }
2317
2318        // The common case: every part of the access was in one state, so the
2319        // access's own declared range describes the barrier exactly and there
2320        // is no reason to spell out the pieces.
2321        if barriers.len() == inside.len()
2322            && barriers.windows(2).all(|pair| {
2323                pair[0].from == pair[1].from && pair[0].queue_transfer == pair[1].queue_transfer
2324            })
2325        {
2326            barriers.truncate(1.min(barriers.len()));
2327            if let Some(first) = barriers.first_mut() {
2328                first.rect = None;
2329            }
2330        }
2331
2332        let entered = Tracked {
2333            state: want,
2334            queue: Some(queue),
2335            last_pass: Some(pass),
2336        };
2337        self.segments = outside;
2338        for (piece, tracked) in inside {
2339            // A read that needed no barrier stays in the state it was in — two
2340            // reads of the same kind are the same state by definition.
2341            let state = if ResourceState::needs_barrier(tracked.state, want) {
2342                want
2343            } else {
2344                tracked.state
2345            };
2346            self.segments.push((piece, Tracked { state, ..entered }));
2347        }
2348        self.coalesce();
2349        barriers
2350    }
2351
2352    /// Collapses back to one segment once the whole image agrees again, so a
2353    /// frame of whole-image passes never grows the list.
2354    fn coalesce(&mut self) {
2355        let Some((_, first)) = self.segments.first().copied() else {
2356            return;
2357        };
2358        if self.segments.iter().all(|(_, tracked)| *tracked == first) {
2359            self.segments = vec![(self.bounds, first)];
2360        }
2361    }
2362
2363    /// The state of the base subresource.
2364    ///
2365    /// [`TransientUse`] holds one state per resource, so a frame that leaves an
2366    /// image in mixed states can only hand the pool the one the next frame's
2367    /// whole-image barrier will name — which is the base level's.
2368    fn end(&self) -> TransientUse {
2369        self.segments
2370            .iter()
2371            .find(|(rect, _)| {
2372                rect.mips.0 == self.bounds.mips.0 && rect.layers.0 == self.bounds.layers.0
2373            })
2374            .or_else(|| self.segments.first())
2375            .map_or_else(TransientUse::default, |(_, tracked)| tracked.end())
2376    }
2377}
2378
2379/// How many earlier entries of `descs` carry the same description as `descs[at]`.
2380///
2381/// The pool hands out the *n*-th resource of a description for the *n*-th
2382/// request, and [`CompiledGraph::realise`] requests them in slot order — so this
2383/// is the number that turns "physical slot 3" into "the pool entry slot 3 will
2384/// get", both before it has been realised and after.
2385fn ordinal<D: PartialEq>(descs: &[D], at: usize) -> usize {
2386    descs[..at]
2387        .iter()
2388        .filter(|other| **other == descs[at])
2389        .count()
2390}
2391
2392fn compile<'a>(
2393    graph: RenderGraph<'a>,
2394    pool: &TransientPool,
2395) -> Result<CompiledGraph<'a>, GraphError> {
2396    let RenderGraph {
2397        images,
2398        buffers,
2399        passes,
2400        default_queue: _,
2401        import_conflict,
2402    } = graph;
2403
2404    // First, because it is the earliest thing that went wrong: every check
2405    // below runs against a node whose declaration is already known to have been
2406    // contradicted, so any error they found would be about the wrong half.
2407    if let Some(conflict) = import_conflict {
2408        return Err(conflict);
2409    }
2410    validate(&images, &buffers, &passes)?;
2411    validate_imports(&images, &buffers, pool)?;
2412
2413    let image_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.images), |a| {
2414        a.image.0
2415    });
2416    let buffer_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.buffers), |a| {
2417        a.buffer.0
2418    });
2419
2420    // Aliasing: pack transients onto as few physical resources as their
2421    // lifetimes allow.
2422    let mut transient_images = Vec::new();
2423    let image_slots = assign(
2424        &images,
2425        &image_lifetimes,
2426        |node| match node.source {
2427            ImageSource::Transient(desc) => Some(desc),
2428            ImageSource::Imported(_) => None,
2429        },
2430        |node| node.label.clone(),
2431        &mut transient_images,
2432    )?;
2433    let mut transient_buffers = Vec::new();
2434    let buffer_slots = assign(
2435        &buffers,
2436        &buffer_lifetimes,
2437        |node| match node.source {
2438            BufferSource::Transient(desc) => Some(desc),
2439            BufferSource::Imported(_) => None,
2440        },
2441        |node| node.label.clone(),
2442        &mut transient_buffers,
2443    )?;
2444
2445    // State tracking is per **physical** resource, because that is what a
2446    // barrier actually names. Imported resources get one tracker each (keyed by
2447    // their own id); transients share one per physical slot.
2448    //
2449    // Every tracker starts where its resource actually is. For an import that
2450    // is what the owner declared; for a transient it is what the pool remembers
2451    // of the last frame that used the very same handle, which is the whole of
2452    // the cross-frame fix.
2453    let mut image_state: Vec<ImageTracker> = images
2454        .iter()
2455        .zip(&image_slots)
2456        .map(|(node, slot)| match (slot, node.source) {
2457            (Slot::Imported, ImageSource::Imported(imported)) => {
2458                ImageTracker::new(Subrect::UNBOUNDED, Tracked::declared(imported.initial))
2459            }
2460            _ => ImageTracker::new(
2461                Subrect::UNBOUNDED,
2462                Tracked::declared(ResourceState::Undefined),
2463            ),
2464        })
2465        .collect();
2466    let mut transient_image_state: Vec<ImageTracker> = (0..transient_images.len())
2467        .map(|slot| {
2468            let desc = transient_images[slot];
2469            ImageTracker::new(
2470                // A transient is a single-layer 2D image whose level count the
2471                // description now states, so a range naming a level it does not
2472                // have is a compile error rather than a barrier on nothing.
2473                Subrect::bounded(desc.mip_levels.max(1), 1),
2474                Tracked::carried(pool.image_use(desc, ordinal(&transient_images, slot))),
2475            )
2476        })
2477        .collect();
2478    let mut buffer_state: Vec<Tracked> = buffers
2479        .iter()
2480        .zip(&buffer_slots)
2481        .map(|(node, slot)| Tracked {
2482            state: match (slot, node.source) {
2483                (Slot::Imported, BufferSource::Imported(imported)) => imported.initial,
2484                _ => ResourceState::Undefined,
2485            },
2486            queue: None,
2487            last_pass: None,
2488        })
2489        .collect();
2490    let mut transient_buffer_state: Vec<Tracked> = (0..transient_buffers.len())
2491        .map(|slot| {
2492            Tracked::carried(
2493                pool.buffer_use(transient_buffers[slot], ordinal(&transient_buffers, slot)),
2494            )
2495        })
2496        .collect();
2497
2498    let mut compiled: Vec<CompiledPass<'a>> = Vec::with_capacity(passes.len());
2499    for (index, pass) in passes.into_iter().enumerate() {
2500        let mut barriers = GraphBarriers::default();
2501
2502        for access in &pass.images {
2503            let node = &images[access.image.index()];
2504            let aspect = access
2505                .range
2506                .map_or_else(|| ImageAspect::of(node.format()), |range| range.aspect);
2507            let tracked = tracker(
2508                image_slots[access.image.index()],
2509                access.image.0,
2510                &mut image_state,
2511                &mut transient_image_state,
2512            );
2513            let rect = access
2514                .range
2515                .map_or(tracked.bounds, |range| subrect_of(range, tracked.bounds));
2516            for sub in tracked.transition(rect, access.state, pass.queue, index) {
2517                let range = match sub.rect {
2518                    None => access.range,
2519                    Some(piece) => Some(piece.to_range(aspect)),
2520                };
2521                let barrier = GraphImageBarrier {
2522                    image: access.image,
2523                    from: sub.from,
2524                    to: access.state,
2525                    queue_transfer: sub.queue_transfer,
2526                    range,
2527                };
2528                // A transfer is *two* barriers with identical fields: a release
2529                // on the source queue and an acquire on the destination
2530                // (`crcbl_hal::QueueTransfer`). The release goes after the last
2531                // pass that used the resource, which is the only point at which
2532                // the source queue is finished with it.
2533                if sub.queue_transfer.is_some()
2534                    && let Some(source) = sub.last_pass
2535                {
2536                    compiled[source].release_barriers.images.push(barrier);
2537                }
2538                barriers.images.push(barrier);
2539            }
2540        }
2541        for access in &pass.buffers {
2542            let tracked = tracker(
2543                buffer_slots[access.buffer.index()],
2544                access.buffer.0,
2545                &mut buffer_state,
2546                &mut transient_buffer_state,
2547            );
2548            if let Some(barrier) = transition(tracked, access.state, pass.queue, index) {
2549                let compiled_barrier = GraphBufferBarrier {
2550                    buffer: access.buffer,
2551                    from: barrier.0,
2552                    to: access.state,
2553                    queue_transfer: barrier.1,
2554                };
2555                if barrier.1.is_some()
2556                    && let Some(source) = barrier.2
2557                {
2558                    compiled[source]
2559                        .release_barriers
2560                        .buffers
2561                        .push(compiled_barrier);
2562                }
2563                barriers.buffers.push(compiled_barrier);
2564            }
2565        }
2566
2567        let render_area = render_area(&images, &pass)?;
2568        compiled.push(CompiledPass {
2569            label: pass.label,
2570            kind: pass.kind,
2571            queue: pass.queue,
2572            barriers,
2573            release_barriers: GraphBarriers::default(),
2574            images: pass.images,
2575            buffers: pass.buffers,
2576            render_area,
2577            body: pass.body,
2578        });
2579    }
2580
2581    // Return every imported resource to the state its owner requires. This is
2582    // the barrier that used to be hand-written after the render pass in
2583    // `apps/sandbox`, and the reason it can be computed rather than remembered.
2584    let mut final_barriers = GraphBarriers::default();
2585    for (index, node) in images.iter().enumerate() {
2586        let ImageSource::Imported(imported) = node.source else {
2587            continue;
2588        };
2589        let tracker = &image_state[index];
2590        let aspect = ImageAspect::of(imported.format);
2591        let whole = tracker.segments.len() == 1;
2592        // `!=` rather than `needs_barrier`: this transition guards nothing —
2593        // the graph is finished with the resource — so its only job is to leave
2594        // the layout its owner asked for. A write-after-write between two passes
2595        // is a hazard and gets a barrier; a write followed by *nothing* is not.
2596        for (rect, tracked) in &tracker.segments {
2597            if tracked.state != imported.final_state {
2598                final_barriers.images.push(GraphImageBarrier {
2599                    image: ImageId(u32::try_from(index).expect("a frame has few resources")),
2600                    from: tracked.state,
2601                    to: imported.final_state,
2602                    queue_transfer: None,
2603                    range: if whole {
2604                        None
2605                    } else {
2606                        Some(rect.to_range(aspect))
2607                    },
2608                });
2609            }
2610        }
2611    }
2612    for (index, node) in buffers.iter().enumerate() {
2613        let BufferSource::Imported(imported) = node.source else {
2614            continue;
2615        };
2616        let tracked = buffer_state[index];
2617        if tracked.state != imported.final_state {
2618            final_barriers.buffers.push(GraphBufferBarrier {
2619                buffer: BufferId(u32::try_from(index).expect("a frame has few resources")),
2620                from: tracked.state,
2621                to: imported.final_state,
2622                queue_transfer: None,
2623            });
2624        }
2625    }
2626
2627    // What the pool is told once these commands are actually recorded. Read off
2628    // the trackers rather than re-derived, so the state the next frame barriers
2629    // against is by construction the state this frame's last barrier reached.
2630    let transient_image_end = transient_image_state
2631        .iter()
2632        .map(ImageTracker::end)
2633        .collect();
2634    let transient_buffer_end = transient_buffer_state.iter().map(|t| t.end()).collect();
2635    // Read off the declaration rather than off the tracker, because the loop
2636    // above has just made them the same thing: every segment of an imported
2637    // image that is not already at `final_state` gets a trailing barrier into
2638    // it, so `final_state` is where the image is once this frame has run.
2639    //
2640    // One entry per handle rather than per import call, and one trailing
2641    // barrier for the same reason: `RenderGraph::import_image` gives a repeat
2642    // import the id the first one got, so there is no second node here to
2643    // barrier the image somewhere else and then overwrite the ledger with it.
2644    let imported_image_end = images
2645        .iter()
2646        .filter_map(|node| match node.source {
2647            ImageSource::Imported(imported) if imported.claim == InitialClaim::Tracked => {
2648                Some((imported.image, imported.final_state))
2649            }
2650            _ => None,
2651        })
2652        .collect();
2653    // And every imported buffer, for the same reason off the same loop, with no
2654    // subset to select: there is no buffer whose declaration the graph takes on
2655    // trust, so there is none whose ending state it has no business recording.
2656    let imported_buffer_end = buffers
2657        .iter()
2658        .filter_map(|node| match node.source {
2659            BufferSource::Imported(imported) => Some((imported.buffer, imported.final_state)),
2660            BufferSource::Transient(_) => None,
2661        })
2662        .collect();
2663
2664    Ok(CompiledGraph {
2665        images,
2666        buffers,
2667        passes: compiled,
2668        final_barriers,
2669        image_slots,
2670        buffer_slots,
2671        transient_images,
2672        transient_buffers,
2673        transient_image_end,
2674        transient_buffer_end,
2675        imported_image_end,
2676        imported_buffer_end,
2677    })
2678}
2679
2680fn tracker<'s, T>(
2681    slot: Slot,
2682    id: u32,
2683    per_resource: &'s mut [T],
2684    per_slot: &'s mut [T],
2685) -> &'s mut T {
2686    match slot {
2687        Slot::Imported => &mut per_resource[id as usize],
2688        Slot::Transient(index) => &mut per_slot[index],
2689    }
2690}
2691
2692/// Decides whether a transition is needed, and updates the tracker.
2693///
2694/// Returns `(from, queue_transfer)` when a barrier must be emitted.
2695///
2696/// There is no special case for a physical slot changing hands. It used to
2697/// start such a transition from [`ResourceState::Undefined`], on the argument
2698/// that the outgoing resource's pixels are garbage to the incoming one and
2699/// discarding them is free. The pixels are indeed garbage — but `Undefined` on
2700/// this seam does not only mean "discard", it means "no source scope", and the
2701/// outgoing resource's *writes* are not garbage: they are in flight. Naming the
2702/// real previous state costs nothing here (one handle, one description, so
2703/// there is no layout change and nothing to decompress) and is the difference
2704/// between the two uses being ordered and racing.
2705fn transition(
2706    tracked: &mut Tracked,
2707    want: ResourceState,
2708    queue: QueueHandle,
2709    pass: usize,
2710) -> Option<(ResourceState, Option<QueueTransfer>, Option<usize>)> {
2711    let queue_transfer = match tracked.queue {
2712        Some(previous) if previous != queue => Some(QueueTransfer {
2713            from: previous,
2714            to: queue,
2715        }),
2716        _ => None,
2717    };
2718    let from = tracked.state;
2719    let source_pass = tracked.last_pass;
2720    tracked.queue = Some(queue);
2721    tracked.last_pass = Some(pass);
2722
2723    // A queue-family transfer is a barrier even between two identical states:
2724    // ownership has to move, or the second queue reads memory the first has not
2725    // released.
2726    if !ResourceState::needs_barrier(from, want) && queue_transfer.is_none() {
2727        return None;
2728    }
2729    tracked.state = want;
2730    Some((from, queue_transfer, source_pass))
2731}
2732
2733/// First and last pass index that touches each resource.
2734fn lifetimes<'p, A: 'p, I>(
2735    pass_count: usize,
2736    accesses: impl Iterator<Item = I>,
2737    id_of: impl Fn(&A) -> u32,
2738) -> Vec<Option<(usize, usize)>>
2739where
2740    I: IntoIterator<Item = &'p A>,
2741{
2742    let mut spans: Vec<Option<(usize, usize)>> = Vec::new();
2743    for (pass, list) in accesses.enumerate() {
2744        debug_assert!(pass < pass_count);
2745        for access in list {
2746            let id = id_of(access) as usize;
2747            if spans.len() <= id {
2748                spans.resize(id + 1, None);
2749            }
2750            spans[id] = Some(match spans[id] {
2751                Some((first, last)) => (first.min(pass), last.max(pass)),
2752                None => (pass, pass),
2753            });
2754        }
2755    }
2756    spans
2757}
2758
2759/// Packs transients onto physical slots, reusing one whose lifetime has ended.
2760fn assign<N, D: Copy + PartialEq>(
2761    nodes: &[N],
2762    spans: &[Option<(usize, usize)>],
2763    desc_of: impl Fn(&N) -> Option<D>,
2764    label_of: impl Fn(&N) -> String,
2765    physical: &mut Vec<D>,
2766) -> Result<Vec<Slot>, GraphError> {
2767    // `free_from[slot]` is the first pass at which the slot is available again.
2768    let mut free_from: Vec<usize> = Vec::new();
2769    let mut slots = Vec::with_capacity(nodes.len());
2770
2771    // Ordered by first use so a single left-to-right sweep is optimal for the
2772    // interval-packing problem this is: identical descriptions, no preemption.
2773    let mut order: Vec<usize> = (0..nodes.len()).collect();
2774    order.sort_by_key(|index| {
2775        spans
2776            .get(*index)
2777            .copied()
2778            .flatten()
2779            .map_or(usize::MAX, |s| s.0)
2780    });
2781
2782    slots.resize(nodes.len(), Slot::Imported);
2783    for index in order {
2784        let Some(desc) = desc_of(&nodes[index]) else {
2785            continue;
2786        };
2787        let Some((first, last)) = spans.get(index).copied().flatten() else {
2788            return Err(GraphError::UnusedTransient {
2789                resource: label_of(&nodes[index]),
2790            });
2791        };
2792        let reused =
2793            (0..physical.len()).find(|slot| physical[*slot] == desc && free_from[*slot] <= first);
2794        let slot = match reused {
2795            Some(slot) => slot,
2796            None => {
2797                physical.push(desc);
2798                free_from.push(0);
2799                physical.len() - 1
2800            }
2801        };
2802        free_from[slot] = last + 1;
2803        slots[index] = Slot::Transient(slot);
2804    }
2805    Ok(slots)
2806}
2807
2808/// Checks every checkable import against what the last graph left it in.
2809///
2810/// The half of validation that needs the pool, which is why it is not inside
2811/// [`validate`]: everything there is a property of the declarations alone, and
2812/// this is a property of the declarations *and* the frames before them.
2813///
2814/// Every buffer import is checkable and only a [`InitialClaim::Tracked`] image
2815/// is — see [`ImportedBuffer`] for why the asymmetry belongs to the resources
2816/// rather than to this function.
2817///
2818/// Silence for a resource the ledger has never heard of is deliberate and is
2819/// not a hole. The ledger records what a graph left, so an absent entry means no
2820/// graph has left this one in anything — an image an upload put into
2821/// [`ResourceState::ShaderRead`] before any frame ran is the ordinary case, and
2822/// there is no previous frame for the declaration to be wrong about.
2823fn validate_imports(
2824    images: &[ImageNode],
2825    buffers: &[BufferNode],
2826    pool: &TransientPool,
2827) -> Result<(), GraphError> {
2828    for node in images {
2829        let ImageSource::Imported(imported) = node.source else {
2830            continue;
2831        };
2832        if imported.claim != InitialClaim::Tracked {
2833            continue;
2834        }
2835        let Some(left) = pool.imported_image_use(imported.image) else {
2836            continue;
2837        };
2838        if left != imported.initial {
2839            return Err(GraphError::ImportStateMismatch {
2840                resource: node.label.clone(),
2841                declared: imported.initial,
2842                left,
2843            });
2844        }
2845    }
2846    for node in buffers {
2847        let BufferSource::Imported(imported) = node.source else {
2848            continue;
2849        };
2850        let Some(left) = pool.imported_buffer_use(imported.buffer) else {
2851            continue;
2852        };
2853        if left != imported.initial {
2854            return Err(GraphError::BufferImportStateMismatch {
2855                resource: node.label.clone(),
2856                declared: imported.initial,
2857                left,
2858            });
2859        }
2860    }
2861    Ok(())
2862}
2863
2864fn validate(
2865    images: &[ImageNode],
2866    buffers: &[BufferNode],
2867    passes: &[Pass<'_>],
2868) -> Result<(), GraphError> {
2869    for pass in passes {
2870        let mut seen_depth = false;
2871        for (position, access) in pass.images.iter().enumerate() {
2872            if pass.kind != PassKind::Render && access.attachment.is_some() {
2873                return Err(GraphError::AttachmentOutsideRenderPass {
2874                    kind: pass.kind.name(),
2875                    pass: pass.label.clone(),
2876                    resource: images[access.image.index()].label.clone(),
2877                });
2878            }
2879            if matches!(access.attachment, Some(Attachment::Depth { .. })) {
2880                if seen_depth {
2881                    return Err(GraphError::DuplicateDepthAttachment {
2882                        pass: pass.label.clone(),
2883                    });
2884                }
2885                seen_depth = true;
2886            }
2887            // A transient states how many levels and layers it has, so a range
2888            // naming one it does not is a mistake the graph can name here
2889            // rather than a barrier on nothing three passes later. An import
2890            // does not say, so there is nothing to check.
2891            if let (Some(range), ImageSource::Transient(desc)) =
2892                (access.range, images[access.image.index()].source)
2893            {
2894                let mip_levels = desc.mip_levels.max(1);
2895                let mips_ok = range.mip_count == ImageSubresourceRange::ALL
2896                    || range.base_mip.saturating_add(range.mip_count) <= mip_levels;
2897                let layers_ok = range.layer_count == ImageSubresourceRange::ALL
2898                    || range.base_layer.saturating_add(range.layer_count) <= TRANSIENT_LAYERS;
2899                if !mips_ok || !layers_ok || range.base_mip >= mip_levels {
2900                    return Err(GraphError::SubresourceOutOfRange {
2901                        pass: pass.label.clone(),
2902                        resource: images[access.image.index()].label.clone(),
2903                        base_mip: range.base_mip,
2904                        mip_count: range.mip_count,
2905                        base_layer: range.base_layer,
2906                        layer_count: range.layer_count,
2907                        mip_levels,
2908                        layers: TRANSIENT_LAYERS,
2909                    });
2910                }
2911            }
2912            for other in &pass.images[position + 1..] {
2913                if other.image != access.image {
2914                    continue;
2915                }
2916                if other.state != access.state {
2917                    return Err(GraphError::ConflictingAccess {
2918                        pass: pass.label.clone(),
2919                        resource: images[access.image.index()].label.clone(),
2920                        first: access.state,
2921                        second: other.state,
2922                    });
2923                }
2924                if other.range == access.range {
2925                    return Err(GraphError::DuplicateDeclaration {
2926                        pass: pass.label.clone(),
2927                        resource: images[access.image.index()].label.clone(),
2928                    });
2929                }
2930            }
2931        }
2932        for (position, access) in pass.buffers.iter().enumerate() {
2933            for other in &pass.buffers[position + 1..] {
2934                if other.buffer != access.buffer {
2935                    continue;
2936                }
2937                if other.state != access.state {
2938                    return Err(GraphError::ConflictingAccess {
2939                        pass: pass.label.clone(),
2940                        resource: buffers[access.buffer.index()].label.clone(),
2941                        first: access.state,
2942                        second: other.state,
2943                    });
2944                }
2945                return Err(GraphError::DuplicateDeclaration {
2946                    pass: pass.label.clone(),
2947                    resource: buffers[access.buffer.index()].label.clone(),
2948                });
2949            }
2950        }
2951    }
2952    Ok(())
2953}
2954
2955fn render_area(images: &[ImageNode], pass: &Pass<'_>) -> Result<Rect2d, GraphError> {
2956    if pass.kind != PassKind::Render {
2957        return Ok(Rect2d::from_size(0, 0));
2958    }
2959    let mut area: Option<(&str, (u32, u32))> = None;
2960    for access in &pass.images {
2961        if access.attachment.is_none() {
2962            continue;
2963        }
2964        let node = &images[access.image.index()];
2965        let extent = node.extent();
2966        match area {
2967            None => area = Some((&node.label, extent)),
2968            Some((first, first_extent)) if first_extent != extent => {
2969                return Err(GraphError::AttachmentExtentMismatch {
2970                    pass: pass.label.clone(),
2971                    first: first.to_string(),
2972                    first_extent,
2973                    second: node.label.clone(),
2974                    second_extent: extent,
2975                });
2976            }
2977            Some(_) => {}
2978        }
2979    }
2980    match area {
2981        Some((_, (width, height))) => Ok(Rect2d::from_size(width, height)),
2982        None => Err(GraphError::NoAttachments {
2983            pass: pass.label.clone(),
2984        }),
2985    }
2986}
2987
2988impl TransientBufferDesc {
2989    /// A device-local storage buffer of `size` bytes.
2990    #[must_use]
2991    pub const fn storage(size: u64) -> Self {
2992        Self {
2993            size,
2994            usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_DST),
2995        }
2996    }
2997}