Skip to main content

crcbl_hal/
command.rs

1//! Command recording: passes, barriers, copies, draws, dispatches, queries.
2//!
3//! # Flat scopes, not nested encoders
4//!
5//! [`CommandEncoder::begin_render_pass`] / [`end_render_pass`](CommandEncoder::end_render_pass)
6//! are flat calls on one encoder rather than a `begin` that returns a borrowed
7//! `RenderPassEncoder` sub-object. The sub-object form is more type-safe and is
8//! what `wgpu` does, but it does not survive `dyn`: returning
9//! `Box<dyn RenderPassEncoder + '_>` costs an allocation per pass, and the
10//! borrow relationship is awkward to express through a trait object.
11//!
12//! The safety this gives up is bought back elsewhere. The *only* caller of this
13//! trait is `crcbl-render`'s render graph, which emits passes from a compiled
14//! list and cannot mis-nest them by construction; the backends' validation
15//! layers catch it if it somehow does; and [`crate::null`] tracks scope
16//! explicitly and records a validation error, so the graph's own unit suite
17//! fails loudly on a mis-nested pass without a GPU in the room.
18//!
19//! # Barriers: resource states, not stage/access masks
20//!
21//! [`ResourceState`] is a small closed set of "what is this resource being used
22//! for right now" values. The backend expands one into a Vulkan `sync2`
23//! stage+access+layout triple, a DX12 enhanced-barrier state, a Metal fence, or
24//! nothing at all on WebGPU.
25//!
26//! Exposing raw stage/access masks was rejected: Metal cannot represent them,
27//! WebGPU has no barriers to give them to, and the render graph does not have
28//! finer information than the state anyway — a pass declares "I sample this",
29//! not "I sample this in the fragment stage with `SHADER_STORAGE_READ`". The
30//! cost is some over-synchronisation on Vulkan where a state maps to a broader
31//! stage mask than strictly needed. That is the *known* place this seam gives up
32//! performance, and refining it is a P1-or-later change confined to
33//! [`ResourceState`] and its backend translation.
34//!
35//! # Indirect is the steady state
36//!
37//! [`CommandEncoder::draw_indexed_indirect_count`] is the normal path (topic 03:
38//! a compute pass writes the arguments and the count, the CPU never learns how
39//! many draws happen). [`CommandEncoder::draw`] exists for full-screen triangles
40//! and bring-up. A device with no count buffer uses
41//! [`CommandEncoder::draw_indexed_indirect`] once per bucket — hence
42//! [`DrawIndirect::draw_count`], so even that is one call per bucket rather than
43//! one per draw.
44
45use core::ops::Range;
46
47use crcbl_core::Handle;
48
49use crate::{
50    BindGroupHandle, BufferHandle, ComputePipelineHandle, Extent3d, GraphicsPipelineHandle,
51    HalError, ImageHandle, ImageSubresourceLayers, ImageSubresourceRange, ImageViewHandle,
52    IndexFormat, Offset3d, PipelineLayoutHandle, QuerySetHandle, Rect2d, ShaderStages, Viewport,
53    device::QueueHandle,
54};
55
56/// Marker type for command-buffer handles. Uninhabited.
57#[derive(Debug)]
58pub enum CommandBuffer {}
59
60/// A finished command buffer, ready to submit.
61pub type CommandBufferHandle = Handle<CommandBuffer>;
62
63/// Reversed-Z depth constants.
64///
65/// The engine's depth convention is **1.0 at the near plane, 0.0 at infinity,
66/// with an infinite far plane** (locked in stage 2; see `docs/notes/backends.md`). A
67/// sector-tiled world with 300 m+ sightlines z-fights immediately on a
68/// conventional `0..1` buffer, and retrofitting the convention after P1
69/// invalidates every blessed golden frame.
70///
71/// These constants exist so no call site writes a bare `1.0` whose meaning
72/// depends on a convention documented elsewhere.
73///
74/// ```
75/// use crcbl_hal::{ClearValue, CompareOp, DepthStencilState, depth};
76///
77/// // Clear to the far plane, test with Greater: nearer fragments win.
78/// assert_eq!(depth::CLEAR, 0.0);
79/// assert_eq!(DepthStencilState::default().depth_compare, CompareOp::Greater);
80/// assert_eq!(ClearValue::default().depth, depth::CLEAR);
81/// ```
82pub mod depth {
83    /// Depth value at the near plane: **1.0**.
84    pub const NEAR: f32 = 1.0;
85
86    /// Depth value at infinity: **0.0**. The far plane is infinite, so this is
87    /// a limit rather than a distance.
88    pub const FAR: f32 = 0.0;
89
90    /// The value a depth attachment is cleared to — [`FAR`], so that any real
91    /// geometry passes a [`CompareOp::Greater`](crate::CompareOp) test.
92    ///
93    /// Clearing to `1.0` (the conventional-Z value) with the engine's default
94    /// compare op renders nothing at all, which is a confusing enough symptom to
95    /// be worth a named constant.
96    pub const CLEAR: f32 = FAR;
97}
98
99/// Stencil constants the seam guarantees rather than inherits.
100///
101/// ```
102/// use crcbl_hal::stencil;
103///
104/// assert_eq!(stencil::INITIAL_REFERENCE, 0);
105/// ```
106pub mod stencil {
107    /// The reference value a render pass starts with, before any
108    /// [`set_stencil_reference`](crate::CommandEncoder::set_stencil_reference).
109    ///
110    /// **Zero, and stated here because it is a promise rather than an
111    /// observation.** WebGPU and Metal both start an encoder at zero on their
112    /// own; D3D12's `OMSetStencilRef` is command-list state that outlives a
113    /// pass, and Vulkan's reference is *undefined* until
114    /// `vkCmdSetStencilReference` is called, since `crcbl-vk` declares
115    /// `VK_DYNAMIC_STATE_STENCIL_REFERENCE` on every pipeline. Those two
116    /// backends set this value as their passes open so that all four agree.
117    pub const INITIAL_REFERENCE: u32 = 0;
118}
119
120/// What to do with an attachment's existing contents at the start of a pass.
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
122pub enum LoadOp {
123    /// Preserve them. The most expensive option on tile-based GPUs; use only
124    /// when the pass genuinely reads what was there.
125    Load,
126    /// Replace them with the attachment's clear value.
127    Clear,
128    /// Leave them undefined. Correct whenever the pass writes every pixel — and
129    /// the right default for a swapchain image, whose previous contents are
130    /// never meaningful.
131    #[default]
132    DontCare,
133}
134
135/// What to do with an attachment's contents at the end of a pass.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
137pub enum StoreOp {
138    /// Write them to memory.
139    #[default]
140    Store,
141    /// Discard them. For depth buffers nothing reads afterwards, and for MSAA
142    /// targets that were resolved.
143    Discard,
144}
145
146/// Clear values for a render pass attachment.
147///
148/// One struct rather than a colour/depth union: an attachment is colour *or*
149/// depth-stencil, and its own descriptor already says which, so a union would
150/// only add a mismatch to check.
151///
152/// [`Default`] clears to transparent black and to [`depth::CLEAR`] — the
153/// reversed-Z far plane, **not** `1.0`.
154#[derive(Clone, Copy, Debug, PartialEq)]
155pub struct ClearValue {
156    /// RGBA clear colour, in the attachment's own space (linear for
157    /// [`Rgba16Float`](crate::Format::Rgba16Float), display-referred for an
158    /// sRGB swapchain).
159    pub color: [f32; 4],
160    /// Depth clear value. Defaults to [`depth::CLEAR`].
161    pub depth: f32,
162    /// Stencil clear value.
163    pub stencil: u32,
164}
165
166impl Default for ClearValue {
167    fn default() -> Self {
168        Self {
169            color: [0.0; 4],
170            depth: depth::CLEAR,
171            stencil: 0,
172        }
173    }
174}
175
176impl ClearValue {
177    /// A colour clear, with the reversed-Z depth default left in place.
178    #[must_use]
179    pub const fn color(rgba: [f32; 4]) -> Self {
180        Self {
181            color: rgba,
182            depth: depth::CLEAR,
183            stencil: 0,
184        }
185    }
186}
187
188/// One colour attachment of a render pass.
189#[derive(Clone, Copy, Debug, PartialEq)]
190pub struct ColorAttachment {
191    /// View rendered into. Must already be in
192    /// [`ResourceState::ColorAttachment`]; the HAL does not transition it.
193    pub view: ImageViewHandle,
194    /// MSAA resolve destination, if any.
195    ///
196    /// Like [`view`](Self::view), and for the same reason it says so: this must
197    /// already be in [`ResourceState::ColorAttachment`]. Every backend reads it
198    /// that way — `crcbl-vk` names `COLOR_ATTACHMENT_OPTIMAL` as the resolve
199    /// image's layout and `crcbl-dx12` transitions out of `RENDER_TARGET` and
200    /// back — so the seam should say it rather than leave three backends
201    /// agreeing by coincidence..
202    pub resolve: Option<ImageViewHandle>,
203    /// Start-of-pass behaviour.
204    pub load: LoadOp,
205    /// End-of-pass behaviour.
206    pub store: StoreOp,
207    /// Used when `load` is [`LoadOp::Clear`].
208    pub clear: ClearValue,
209}
210
211/// The depth/stencil attachment of a render pass.
212#[derive(Clone, Copy, Debug, PartialEq)]
213pub struct DepthStencilAttachment {
214    /// View rendered into. Must already be in
215    /// [`ResourceState::DepthStencilWrite`] or
216    /// [`ResourceState::DepthStencilRead`] — see
217    /// [`read_only`](Self::read_only), which is how the backend is told which.
218    pub view: ImageViewHandle,
219    /// Whether the pass only *tests* depth/stencil — the depth-prepass-read
220    /// shape.
221    ///
222    /// **Which of the two states the view is already in**, and the backend has
223    /// no other way to know. Vulkan and DX12 both give a read-only depth
224    /// attachment a different image layout from a written one
225    /// (`DEPTH_STENCIL_READ_ONLY_OPTIMAL` vs `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`),
226    /// and `vkCmdBeginRendering` requires the layout named here to be the one
227    /// the image is actually in. Guessing from the store op is not equivalent:
228    /// a pass may read depth and store nothing, or write depth and discard it.
229    ///
230    /// `true` pairs with [`ResourceState::DepthStencilRead`], `false` with
231    /// [`ResourceState::DepthStencilWrite`].
232    pub read_only: bool,
233    /// Depth start-of-pass behaviour.
234    pub depth_load: LoadOp,
235    /// Depth end-of-pass behaviour.
236    pub depth_store: StoreOp,
237    /// Stencil start-of-pass behaviour.
238    pub stencil_load: LoadOp,
239    /// Stencil end-of-pass behaviour.
240    pub stencil_store: StoreOp,
241    /// Used when either load op is [`LoadOp::Clear`]. Defaults to
242    /// [`depth::CLEAR`] — see [`ClearValue`].
243    pub clear: ClearValue,
244}
245
246/// The two timestamps that bracket a pass — **the seam's only timestamp verb**.
247///
248/// A timestamp is named by the pass it brackets rather than by a point in the
249/// command stream, because a point in the command stream is not something every
250/// API can express. Vulkan's `vkCmdWriteTimestamp2` and D3D12's `EndQuery` on a
251/// timestamp heap take one anywhere; Metal samples only where a device's
252/// `MTLCounterSamplingPoint` values allow, which is stage boundaries; and
253/// WebGPU takes them *only* through `GPURenderPassDescriptor.timestampWrites`
254/// and `GPUComputePassDescriptor.timestampWrites`, whose
255/// `beginningOfPassWriteIndex`/`endOfPassWriteIndex` this struct is. Half the
256/// backends cannot honour an arbitrary point at all, so the pass boundary is the
257/// intersection — and putting it in the descriptor makes it a *shape* rather
258/// than a rule a caller has to remember, because there is no free-standing call
259/// left to record in the wrong place.
260///
261/// Consequently a pass is the smallest thing this seam can time. A copy or a
262/// barrier is not inside one, so what a profiler attributes to a pass is the
263/// pass alone, and the transitions the caller emitted around it are attributed
264/// to nothing.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub struct PassTimestampWrites {
267    /// Set the two queries are written into. Must hold
268    /// [`QueryKind::Timestamp`](crate::QueryKind::Timestamp) queries; a backend
269    /// fails the encoder rather than writing a timestamp into a pool of another
270    /// kind.
271    pub set: QuerySetHandle,
272    /// Query written when the pass begins.
273    pub beginning_of_pass: u32,
274    /// Query written when the pass ends.
275    ///
276    /// **Distinct from [`beginning_of_pass`](Self::beginning_of_pass)**: WebGPU
277    /// requires the two indices to differ, and a pass that wrote both ends into
278    /// one query would report the second over the first on every other backend,
279    /// so a backend refuses the pair rather than measuring nothing.
280    pub end_of_pass: u32,
281}
282
283/// The pipeline-statistics query that brackets a pass: what the GPU counted
284/// while the pass ran, read back with
285/// [`Device::pipeline_statistics`](crate::Device::pipeline_statistics).
286///
287/// **Named by the pass, as [`PassTimestampWrites`] is, and for its reason**:
288/// Metal attaches counter sampling to a pass descriptor and to nothing else,
289/// so a pass is the one scope every backend that counts at all can count over.
290/// A backend that cannot count fails the encoder when one is given, rather
291/// than leaving the query holding nothing a reader could tell from zero work.
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub struct PassStatisticsWrites {
294    /// Set the query is in. Must hold
295    /// [`QueryKind::PipelineStatistics`](crate::QueryKind::PipelineStatistics)
296    /// queries.
297    pub set: QuerySetHandle,
298    /// The query, reset since its last use, that counts this pass.
299    pub query: u32,
300}
301
302/// A render pass, in dynamic-rendering form: attachments are named inline and
303/// there is no `RenderPass` or `Framebuffer` object to keep compatible.
304#[derive(Clone, Copy, Debug, PartialEq)]
305pub struct RenderPassDesc<'a> {
306    /// Pass name. Shows up in RenderDoc/PIX capture trees, in the render
307    /// graph's text dump, and in the null backend's recorded stream — which is
308    /// what makes "this frame emitted these passes in this order" assertable.
309    pub label: Option<&'a str>,
310    /// Colour attachments, in shader output order.
311    pub color_attachments: &'a [ColorAttachment],
312    /// Depth/stencil attachment, if any.
313    pub depth_stencil_attachment: Option<DepthStencilAttachment>,
314    /// Region rendered. Usually the full attachment size.
315    pub render_area: Rect2d,
316    /// Timestamps bracketing this pass, if it is being timed. See
317    /// [`PassTimestampWrites`].
318    pub timestamp_writes: Option<PassTimestampWrites>,
319    /// The statistics query counting this pass, if it is being counted. See
320    /// [`PassStatisticsWrites`].
321    pub statistics_writes: Option<PassStatisticsWrites>,
322}
323
324/// A compute pass.
325///
326/// Compute has no attachments, so this exists purely to give the pass a name
327/// and a timestamp boundary — which is exactly what the per-pass GPU timer
328/// report needs (topic 03 §3.5).
329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
330pub struct ComputePassDesc<'a> {
331    /// Pass name; see [`RenderPassDesc::label`].
332    pub label: Option<&'a str>,
333    /// Timestamps bracketing this pass; see
334    /// [`RenderPassDesc::timestamp_writes`].
335    pub timestamp_writes: Option<PassTimestampWrites>,
336    /// The statistics query counting this pass; see
337    /// [`RenderPassDesc::statistics_writes`].
338    pub statistics_writes: Option<PassStatisticsWrites>,
339}
340
341// --- barriers --------------------------------------------------------------
342
343/// What a resource is being used for.
344///
345/// The seam's entire synchronisation vocabulary. A backend expands one of these
346/// into whatever its API needs; see the module docs for why raw stage/access
347/// masks are not exposed.
348///
349/// States are *uses*, not permissions: a resource is in exactly one state at a
350/// time from the graph's point of view, and moving between two states is a
351/// barrier.
352#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
353pub enum ResourceState {
354    /// Contents are undefined. The only legal *source* state for a freshly
355    /// created image, and for a swapchain image just acquired. Transitioning
356    /// *from* `Undefined` discards contents, which is free; transitioning *to*
357    /// it is meaningless.
358    #[default]
359    Undefined,
360    /// Read as a sampled texture or a read-only storage buffer/image in any
361    /// shader stage.
362    ShaderRead,
363    /// Written by a shader (storage buffer or storage image).
364    ShaderWrite,
365    /// Both read and written by a shader in the same pass.
366    ShaderReadWrite,
367    /// A colour attachment being rendered into.
368    ColorAttachment,
369    /// A depth/stencil attachment being written.
370    DepthStencilWrite,
371    /// A depth/stencil attachment being tested but not written — the state for
372    /// a pass drawing against an existing depth prepass.
373    DepthStencilRead,
374    /// Source of a copy.
375    TransferSrc,
376    /// Destination of a copy, clear or fill.
377    TransferDst,
378    /// Read as indirect draw/dispatch arguments or an indirect count. The state
379    /// a culling pass's output must reach before the draws that consume it —
380    /// the single most important barrier in a GPU-driven frame, and the one
381    /// whose absence produces "sometimes nothing draws".
382    IndirectArgument,
383    /// Read as an index buffer.
384    IndexBuffer,
385    /// Mapped and read by the CPU.
386    HostRead,
387    /// Ready to be handed to the compositor.
388    Present,
389}
390
391impl ResourceState {
392    /// Whether this state writes the resource.
393    ///
394    /// Read→read transitions need no barrier at all, so a graph asks this to
395    /// skip emitting one.
396    ///
397    /// [`Self::DepthStencilRead`] is a read, and every backend agrees: Vulkan
398    /// ends such a pass with `VK_ATTACHMENT_STORE_OP_NONE`, which stores
399    /// nothing and declares no attachment write; D3D12 has no store op at all
400    /// and runs a depth-test-only pass with a zero depth-write mask; WebGPU
401    /// takes `depthReadOnly` and forbids the store op entirely; and Metal,
402    /// whose `MTLStoreAction` has no no-op action, stores contents the pass did
403    /// not change. Two such passes in a row therefore hazard against nothing
404    /// and the barrier between them is the one to skip.
405    ///
406    /// It answered `true` until the backends were checked one by one, which was
407    /// conservatism rather than description — see `docs/notes/backends.md`.
408    #[must_use]
409    pub const fn is_write(self) -> bool {
410        matches!(
411            self,
412            Self::ShaderWrite
413                | Self::ShaderReadWrite
414                | Self::ColorAttachment
415                | Self::DepthStencilWrite
416                | Self::TransferDst
417        )
418    }
419
420    /// Whether a transition between two states requires a barrier.
421    ///
422    /// `false` only when both states are reads *and* they are the same state —
423    /// two different read states still differ in image layout on Vulkan and
424    /// DX12, so they need a transition even though no memory hazard exists.
425    #[must_use]
426    pub const fn needs_barrier(from: Self, to: Self) -> bool {
427        if from.is_write() || to.is_write() {
428            return true;
429        }
430        // Both reads: only a layout change remains.
431        from as u8 != to as u8
432    }
433}
434
435/// Queue-family ownership transfer attached to a barrier.
436///
437/// MVP uploads share the graphics+compute queue, so this is `None` everywhere
438/// today. It exists from P0 because stage 2's design review required
439/// that "the render graph's barrier model must nonetheless represent
440/// queue-family acquire/release from the start so a dedicated transfer queue is
441/// additive later rather than a barrier-model rewrite".
442///
443/// A transfer is expressed as **two** barriers with identical fields: a release
444/// recorded on `from`'s queue and an acquire recorded on `to`'s. The HAL relays
445/// both; deciding to emit them is the graph's job.
446#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
447pub struct QueueTransfer {
448    /// Queue releasing ownership.
449    pub from: QueueHandle,
450    /// Queue acquiring ownership.
451    pub to: QueueHandle,
452}
453
454/// A buffer state transition.
455#[derive(Clone, Copy, Debug, PartialEq, Eq)]
456pub struct BufferBarrier {
457    /// Buffer affected.
458    pub buffer: BufferHandle,
459    /// State being left.
460    pub from: ResourceState,
461    /// State being entered.
462    pub to: ResourceState,
463    /// Ownership transfer, if any.
464    pub queue_transfer: Option<QueueTransfer>,
465}
466
467impl BufferBarrier {
468    /// A same-queue transition.
469    #[must_use]
470    pub const fn new(buffer: BufferHandle, from: ResourceState, to: ResourceState) -> Self {
471        Self {
472            buffer,
473            from,
474            to,
475            queue_transfer: None,
476        }
477    }
478}
479
480/// An image state (and, on Vulkan/DX12, layout) transition.
481#[derive(Clone, Copy, Debug, PartialEq, Eq)]
482pub struct ImageBarrier {
483    /// Image affected.
484    pub image: ImageHandle,
485    /// Subrange affected.
486    pub range: ImageSubresourceRange,
487    /// State being left. [`ResourceState::Undefined`] discards contents.
488    pub from: ResourceState,
489    /// State being entered.
490    pub to: ResourceState,
491    /// Ownership transfer, if any.
492    pub queue_transfer: Option<QueueTransfer>,
493}
494
495impl ImageBarrier {
496    /// A same-queue transition of a whole image.
497    #[must_use]
498    pub const fn new(
499        image: ImageHandle,
500        range: ImageSubresourceRange,
501        from: ResourceState,
502        to: ResourceState,
503    ) -> Self {
504        Self {
505            image,
506            range,
507            from,
508            to,
509            queue_transfer: None,
510        }
511    }
512}
513
514/// A batch of barriers recorded as one call.
515///
516/// Batched rather than one-at-a-time because every backend pays a fixed cost per
517/// barrier *call*, and a graph that computed six transitions between two passes
518/// should emit one call, not six. An empty `Barriers` is legal and does nothing.
519#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
520pub struct Barriers<'a> {
521    /// Buffer transitions.
522    pub buffers: &'a [BufferBarrier],
523    /// Image transitions.
524    pub images: &'a [ImageBarrier],
525    /// Global execution+memory barrier with no specific resource, for the cases
526    /// where a graph knows a dependency exists but not which resource carries
527    /// it. Prefer the typed lists; this is the sledgehammer.
528    pub global: bool,
529}
530
531// --- copies ----------------------------------------------------------------
532
533/// A buffer-to-buffer copy region.
534#[derive(Clone, Copy, Debug, PartialEq, Eq)]
535pub struct BufferCopy {
536    /// Source buffer.
537    pub src: BufferHandle,
538    /// Byte offset in the source.
539    pub src_offset: u64,
540    /// Destination buffer.
541    pub dst: BufferHandle,
542    /// Byte offset in the destination.
543    pub dst_offset: u64,
544    /// Bytes copied.
545    pub size: u64,
546}
547
548/// A buffer↔image copy region.
549///
550/// One struct for both directions; which is the source is determined by the
551/// method called, not by a field, so the two can never disagree.
552#[derive(Clone, Copy, Debug, PartialEq, Eq)]
553pub struct BufferImageCopy {
554    /// Buffer side.
555    pub buffer: BufferHandle,
556    /// Byte offset in the buffer.
557    pub buffer_offset: u64,
558    /// Texels per row in the buffer; `0` means tightly packed. Must satisfy the
559    /// backend's row-pitch alignment when non-zero.
560    pub buffer_row_length: u32,
561    /// Rows per layer in the buffer; `0` means tightly packed.
562    pub buffer_image_height: u32,
563    /// Image side.
564    pub image: ImageHandle,
565    /// Mip level and layers touched.
566    pub image_subresource: ImageSubresourceLayers,
567    /// Texel offset within the image.
568    pub image_offset: Offset3d,
569    /// Region size in texels.
570    pub image_extent: Extent3d,
571}
572
573/// An image-to-image copy region.
574#[derive(Clone, Copy, Debug, PartialEq, Eq)]
575pub struct ImageCopy {
576    /// Source image.
577    pub src: ImageHandle,
578    /// Source mip level and layers.
579    pub src_subresource: ImageSubresourceLayers,
580    /// Source texel offset.
581    pub src_offset: Offset3d,
582    /// Destination image.
583    pub dst: ImageHandle,
584    /// Destination mip level and layers.
585    pub dst_subresource: ImageSubresourceLayers,
586    /// Destination texel offset.
587    pub dst_offset: Offset3d,
588    /// Region size in texels.
589    pub extent: Extent3d,
590}
591
592// --- indirect --------------------------------------------------------------
593
594/// Arguments for an indirect draw whose *count* is known on the CPU.
595///
596/// The argument buffer's contents are still GPU-written; only how many argument
597/// structures to read is fixed. This is
598/// [`GeometryPath::IndirectPerBatch`](crate::GeometryPath::IndirectPerBatch)'s
599/// draw path: one call per bucket with `draw_count` set to the bucket's
600/// capacity.
601///
602/// `draw_count > 1` requires
603/// [`Features::MULTI_DRAW_INDIRECT`](crate::Features::MULTI_DRAW_INDIRECT).
604///
605/// **Which structure the words are is the call's, not this type's.**
606/// [`draw_indirect`](CommandEncoder::draw_indirect) reads four words,
607/// [`draw_indexed_indirect`](CommandEncoder::draw_indexed_indirect) five and
608/// [`draw_mesh_tasks_indirect`](CommandEncoder::draw_mesh_tasks_indirect)
609/// three; each method's docs name the API structure it is. `stride` is what
610/// keeps them apart in a buffer, so it is spelled at the call site rather than
611/// derived here.
612#[derive(Clone, Copy, Debug, PartialEq, Eq)]
613pub struct DrawIndirect {
614    /// Buffer holding the argument structures. Must be in
615    /// [`ResourceState::IndirectArgument`].
616    pub args: BufferHandle,
617    /// Byte offset of the first argument structure.
618    pub offset: u64,
619    /// Number of argument structures to read.
620    pub draw_count: u32,
621    /// Bytes between consecutive argument structures.
622    pub stride: u32,
623}
624
625/// Arguments for an indirect draw whose count is *also* read from GPU memory.
626///
627/// [`GeometryPath::IndirectCount`](crate::GeometryPath::IndirectCount)'s
628/// steady-state draw call: a compute pass writes both the arguments and the
629/// count, and the CPU never learns how many draws happen. Requires
630/// [`Features::DRAW_INDIRECT_COUNT`](crate::Features::DRAW_INDIRECT_COUNT).
631#[derive(Clone, Copy, Debug, PartialEq, Eq)]
632pub struct DrawIndirectCount {
633    /// Buffer holding the argument structures.
634    pub args: BufferHandle,
635    /// Byte offset of the first argument structure.
636    pub args_offset: u64,
637    /// Buffer holding a `u32` draw count.
638    pub count_buffer: BufferHandle,
639    /// Byte offset of the count.
640    pub count_offset: u64,
641    /// Upper bound on draws, regardless of what the count buffer says. Bounded
642    /// by [`Limits::max_draw_indirect_count`](crate::Limits::max_draw_indirect_count).
643    pub max_draw_count: u32,
644    /// Bytes between consecutive argument structures.
645    pub stride: u32,
646}
647
648// --- the encoder -----------------------------------------------------------
649
650/// Records commands into a command buffer.
651///
652/// Obtained from [`Device::create_command_encoder`](crate::Device::create_command_encoder)
653/// and consumed by [`finish`](CommandEncoder::finish). One encoder produces one
654/// command buffer.
655///
656/// # Scope rules
657///
658/// * Draw commands, [`set_viewport`](CommandEncoder::set_viewport),
659///   [`set_scissor`](CommandEncoder::set_scissor) and
660///   [`bind_graphics_pipeline`](CommandEncoder::bind_graphics_pipeline) are legal
661///   only between `begin_render_pass` and `end_render_pass`.
662/// * [`dispatch`](CommandEncoder::dispatch) and
663///   [`bind_compute_pipeline`](CommandEncoder::bind_compute_pipeline) are legal
664///   only inside a compute pass.
665/// * Copies, barriers and query resets/resolves are legal only **outside** any
666///   pass — Vulkan forbids them inside dynamic rendering, and the render graph
667///   places them between passes anyway. Timestamps are the exception that
668///   proves the rule: they are not a call at all, but
669///   [`PassTimestampWrites`] on the pass descriptor.
670/// * Passes do not nest.
671///
672/// A backend may assume these hold. [`crate::null`] checks them and records a
673/// validation error, which is how the graph's unit suite catches a violation
674/// without a GPU.
675///
676/// # Thread safety
677///
678/// `Send + Sync` on native, through
679/// [`HalThreadSafe`](crate::threading::HalThreadSafe) — an encoder may be moved
680/// to a worker thread and recorded there, which the P8 job system will do.
681///
682/// Vulkan's external-synchronisation rule for command buffers ("two threads may
683/// not record into one") is discharged by `&mut self` on every recording
684/// method, not by dropping `Sync`: two threads cannot hold `&mut` to the same
685/// encoder, and `&self` alone can record nothing. An earlier version of this
686/// doc claimed `Send` but not `Sync`, which contradicted the trait's own bound
687/// — every implementor has always had to be `Sync`.
688///
689/// On `wasm32` the bound is vacuous, because wgpu's web types are `!Send` and
690/// the browser is single-threaded.
691pub trait CommandEncoder: core::fmt::Debug + crate::threading::HalThreadSafe {
692    // --- debug ---
693
694    /// Opens a named region in capture tools and profilers.
695    ///
696    /// Accepted and dropped when
697    /// [`Features::DEBUG_MARKERS`](crate::Features::DEBUG_MARKERS) is absent —
698    /// debug instrumentation degrades, it does not break the build (topic 10's
699    /// stated policy).
700    fn begin_debug_label(&mut self, label: &str);
701
702    /// Closes the most recent [`begin_debug_label`](CommandEncoder::begin_debug_label).
703    fn end_debug_label(&mut self);
704
705    /// Inserts a zero-width marker.
706    fn insert_debug_marker(&mut self, label: &str);
707
708    // --- sync ---
709
710    /// Records a batch of state transitions.
711    ///
712    /// The only way to synchronise inside a command buffer. See the module docs
713    /// for the division of labour: this seam expresses barriers, the render
714    /// graph decides where they go.
715    fn pipeline_barrier(&mut self, barriers: &Barriers<'_>);
716
717    // --- copies ---
718
719    /// Buffer-to-buffer copy.
720    fn copy_buffer_to_buffer(&mut self, copy: &BufferCopy);
721
722    /// Buffer-to-image copy — the texture upload path.
723    fn copy_buffer_to_image(&mut self, copy: &BufferImageCopy);
724
725    /// Image-to-buffer copy — the readback path (`crcbl screenshot`, the
726    /// delayed debug ring).
727    fn copy_image_to_buffer(&mut self, copy: &BufferImageCopy);
728
729    /// Image-to-image copy.
730    fn copy_image_to_image(&mut self, copy: &ImageCopy);
731
732    /// Zeroes a buffer range.
733    ///
734    /// **Zero and nothing else, which is why it is a clear rather than a fill.**
735    /// This took a `value: u32` until 2026-08-19 and promised "a repeating
736    /// 32-bit value", which two of the four backends could never keep: Metal's
737    /// `fillBuffer:range:value:` repeats a *byte*, so only a word with four
738    /// equal bytes has an encoding, and WebGPU offers `clearBuffer` and no
739    /// valued fill at all. A parameter three backends had to refuse most values
740    /// of is not a seam, and `Capability::BufferFillRepeatedByte` and
741    /// `BufferFillWord` existed only to describe how badly each one could keep
742    /// the promise.
743    ///
744    /// The name follows what the backends call it — `clearBuffer` on WebGPU,
745    /// `clear_buffer` on wgpu — rather than what one of them could do.
746    ///
747    /// Zeroing an indirect count at the top of a frame is the use this was
748    /// written for, and it is **not** what the renderer does: a clear is legal
749    /// only outside a pass, and a render-graph frame is passes end to end. See
750    /// `crcbl_shaders::clear_counters`, which zeroes from inside the graph and
751    /// is what let those counters become device-local.
752    fn clear_buffer(&mut self, buffer: BufferHandle, offset: u64, size: u64);
753
754    // --- render scope ---
755
756    /// Opens a render pass. Attachments must already be in the right state.
757    fn begin_render_pass(&mut self, desc: &RenderPassDesc<'_>);
758
759    /// Closes the current render pass.
760    fn end_render_pass(&mut self);
761
762    /// Sets the viewport transform. See [`Viewport`] on the depth range and
763    /// reversed-Z.
764    fn set_viewport(&mut self, viewport: &Viewport);
765
766    /// Sets the scissor rectangle.
767    fn set_scissor(&mut self, rect: &Rect2d);
768
769    /// Sets the stencil reference value for subsequent draws — the value each
770    /// [`StencilFaceState::compare`](crate::StencilFaceState::compare) tests
771    /// against and [`StencilOp::Replace`](crate::StencilOp::Replace) writes.
772    ///
773    /// **The only channel there is.** [`StencilState`](crate::StencilState)
774    /// carries no reference of its own, because two of the APIs behind this
775    /// seam have no pipeline field to put one in. The rule every backend
776    /// implements, and which
777    /// [`Capability::StencilReference`](crate::Capability::StencilReference)
778    /// stands for:
779    ///
780    /// * The reference is **pass state**: a pass opens holding
781    ///   [`stencil::INITIAL_REFERENCE`] and
782    ///   keeps whatever this call last set until it ends.
783    /// * **Binding a graphics pipeline does not disturb it.** A call made
784    ///   before a bind is still in force for the draws after it.
785    fn set_stencil_reference(&mut self, reference: u32);
786
787    /// Binds a graphics pipeline.
788    fn bind_graphics_pipeline(&mut self, pipeline: GraphicsPipelineHandle);
789
790    /// Binds an index buffer.
791    ///
792    /// There is no `bind_vertex_buffer`: geometry is pulled from storage
793    /// buffers. See [`crate::pipeline`].
794    fn bind_index_buffer(&mut self, buffer: BufferHandle, offset: u64, format: IndexFormat);
795
796    // --- bindings, shared by both scopes ---
797
798    /// Binds a bind group at `slot`, with dynamic offsets for any
799    /// dynamic-offset bindings in its layout, in binding order.
800    ///
801    /// `dynamic_offsets` is the substitute for push constants on a device
802    /// without them — see
803    /// [`BindingKind::UniformBuffer`](crate::BindingKind::UniformBuffer).
804    fn bind_group(
805        &mut self,
806        slot: u32,
807        group: BindGroupHandle,
808        dynamic_offsets: &[u32],
809        layout: PipelineLayoutHandle,
810    );
811
812    /// Writes push constants.
813    ///
814    /// Requires [`Features::PUSH_CONSTANTS`](crate::Features::PUSH_CONSTANTS).
815    /// A backend without it must fail loudly at pipeline-layout creation rather
816    /// than silently dropping the write here.
817    fn push_constants(
818        &mut self,
819        stages: ShaderStages,
820        offset: u32,
821        data: &[u8],
822        layout: PipelineLayoutHandle,
823    );
824
825    // --- draws ---
826
827    /// Non-indexed draw. For full-screen triangles and bring-up; the geometry
828    /// path is indirect.
829    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
830
831    /// Indexed draw.
832    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
833
834    /// Indirect non-indexed draw with a CPU-known draw count.
835    fn draw_indirect(&mut self, draw: &DrawIndirect);
836
837    /// Indirect indexed draw with a CPU-known draw count.
838    /// **[`GeometryPath::IndirectPerBatch`](crate::GeometryPath::IndirectPerBatch)'s
839    /// draw path**, one call per bucket.
840    fn draw_indexed_indirect(&mut self, draw: &DrawIndirect);
841
842    /// Indirect non-indexed draw with a GPU-read draw count.
843    fn draw_indirect_count(&mut self, draw: &DrawIndirectCount);
844
845    /// Indirect indexed draw with a GPU-read draw count.
846    /// **[`GeometryPath::IndirectCount`](crate::GeometryPath::IndirectCount)'s
847    /// steady-state draw call** — one per pass, regardless of scene size.
848    fn draw_indexed_indirect_count(&mut self, draw: &DrawIndirectCount);
849
850    /// Launches a mesh-shading workload, in workgroups —
851    /// **[`GeometryPath::MeshShader`](crate::GeometryPath::MeshShader)'s draw
852    /// call**.
853    ///
854    /// `x`, `y` and `z` count workgroups of the *first* stage the bound
855    /// pipeline has: the task stage when
856    /// [`MeshPipelineDesc::task`](crate::MeshPipelineDesc::task) was `Some`,
857    /// and the mesh stage otherwise. That is Vulkan's rule for
858    /// `vkCmdDrawMeshTasksEXT`, D3D12's for `DispatchMesh`, and Metal's for
859    /// `drawMeshThreadgroups:`, so it is the seam's rule too.
860    ///
861    /// This is a *draw*, not a dispatch: it belongs inside a render pass with a
862    /// mesh pipeline bound, and its output is fragments rather than buffer
863    /// writes. The three-dimensional count is why it does not reuse
864    /// [`draw`](CommandEncoder::draw)'s vertex/instance ranges — there are no
865    /// vertices to range over.
866    ///
867    /// Requires [`Features::MESH_SHADER`](crate::Features::MESH_SHADER), which
868    /// [`create_mesh_pipeline`](crate::Device::create_mesh_pipeline) has
869    /// already refused without.
870    fn draw_mesh_tasks(&mut self, x: u32, y: u32, z: u32);
871
872    /// [`draw_mesh_tasks`](CommandEncoder::draw_mesh_tasks) with the workgroup
873    /// counts read from GPU memory — **the shape a culling pass's output needs
874    /// to reduce work rather than only output**.
875    ///
876    /// # The argument layout
877    ///
878    /// One argument structure is **three consecutive 32-bit words**: the x, y
879    /// and z workgroup counts, in that order, of the same stage
880    /// [`draw_mesh_tasks`](CommandEncoder::draw_mesh_tasks) counts groups of.
881    /// The layout is not this seam's to choose — it is
882    /// `VkDrawMeshTasksIndirectCommandEXT`, `D3D12_DISPATCH_MESH_ARGUMENTS` and
883    /// Metal's `MTLDispatchThreadgroupsIndirectArguments`, which are the same
884    /// three words in the same order, because a driver reads these bytes
885    /// directly.
886    ///
887    /// [`DrawIndirect::stride`] is therefore 12 for a tightly packed buffer, and
888    /// [`DrawIndirect::offset`] must be a multiple of 4.
889    /// [`draw_count`](DrawIndirect::draw_count) `> 1` requires
890    /// [`Features::MULTI_DRAW_INDIRECT`](crate::Features::MULTI_DRAW_INDIRECT),
891    /// exactly as it does for the indexed form.
892    ///
893    /// [`DrawIndirect::args`] must be in
894    /// [`ResourceState::IndirectArgument`] — a buffer the same pass also reads
895    /// as a storage buffer is in one state or the other, never both, so a
896    /// caller that needs both wants two buffers.
897    ///
898    /// # Capability
899    ///
900    /// Requires [`Features::MESH_SHADER`](crate::Features::MESH_SHADER) and
901    /// nothing more. There is no separate flag because none of the three APIs
902    /// has one: `VK_EXT_mesh_shader` defines `vkCmdDrawMeshTasksIndirectEXT`
903    /// alongside `vkCmdDrawMeshTasksEXT`, D3D12 mesh shader tier 1 admits
904    /// `D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH` in a command signature, and
905    /// a Metal device with mesh functions has
906    /// `drawMeshThreadgroupsWithIndirectBuffer:`. A device that can launch this
907    /// stage at all can launch it from memory.
908    fn draw_mesh_tasks_indirect(&mut self, draw: &DrawIndirect);
909
910    // --- compute scope ---
911
912    /// Opens a compute pass.
913    fn begin_compute_pass(&mut self, desc: &ComputePassDesc<'_>);
914
915    /// Closes the current compute pass.
916    fn end_compute_pass(&mut self);
917
918    /// Binds a compute pipeline.
919    fn bind_compute_pipeline(&mut self, pipeline: ComputePipelineHandle);
920
921    /// Dispatches a compute workload, in workgroups.
922    fn dispatch(&mut self, x: u32, y: u32, z: u32);
923
924    /// Dispatches with the workgroup counts read from GPU memory — the shape a
925    /// variable-size culling or compaction pass needs.
926    fn dispatch_indirect(&mut self, args: BufferHandle, offset: u64);
927
928    // --- queries ---
929
930    /// Resets a query range so it can be written again.
931    ///
932    /// Required on Vulkan before every write; a no-op on backends that reset
933    /// implicitly. Callers always call it, so the Vulkan path is never the
934    /// special case.
935    ///
936    /// **What is written between a reset and a resolve is
937    /// [`RenderPassDesc::timestamp_writes`]**, not a call of its own: see
938    /// [`PassTimestampWrites`] for why the seam has no free-standing timestamp.
939    fn reset_query_set(&mut self, set: QuerySetHandle, range: Range<u32>);
940
941    /// Copies query results into a buffer, **as the device wrote them**.
942    ///
943    /// The counterpart of [`Device::query_results`](crate::Device::query_results)
944    /// and the one place the two read paths differ: that one reports a
945    /// [`QueryKind::Timestamp`](crate::QueryKind::Timestamp) in nanoseconds, and
946    /// this one cannot. It records a GPU-side copy — `vkCmdCopyQueryPoolResults`,
947    /// `ResolveQueryData`, `GPUCommandEncoder.resolveQuerySet` — so the values
948    /// never pass through the CPU and there is nowhere to apply a scale. A
949    /// caller reading the destination gets the device's own clock units, and
950    /// what those are worth is a question only the backend can answer.
951    ///
952    /// So this is for feeding a delta back to the GPU — a shader that compares
953    /// two readings, which needs no unit — and
954    /// [`Device::query_results`](crate::Device::query_results) is for a number a
955    /// human or a HUD is going to read.
956    fn resolve_query_set(
957        &mut self,
958        set: QuerySetHandle,
959        range: Range<u32>,
960        dst: BufferHandle,
961        dst_offset: u64,
962    );
963
964    // --- finish ---
965
966    /// Ends recording and produces a submittable command buffer.
967    ///
968    /// Takes `Box<Self>` rather than `self` so the method stays object-safe:
969    /// `Box<dyn CommandEncoder>` can call it, a bare `self` receiver could not.
970    ///
971    /// # Errors
972    ///
973    /// Returns [`HalError`] if the backend rejected the recorded stream — an
974    /// unclosed pass, an out-of-range value, or an out-of-memory condition in
975    /// the command pool.
976    fn finish(self: Box<Self>) -> Result<CommandBufferHandle, HalError>;
977}
978
979/// Creation parameters for a command encoder.
980#[derive(Clone, Copy, Debug, PartialEq, Eq)]
981pub struct CommandEncoderDesc<'a> {
982    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
983    pub label: Option<&'a str>,
984    /// Queue the resulting command buffer will be submitted to.
985    ///
986    /// Named at creation because Vulkan command pools are per-queue-family and
987    /// DX12 command allocators are per-type; discovering it at submit time
988    /// would force a copy.
989    pub queue: QueueHandle,
990}
991
992#[cfg(test)]
993mod tests {
994    use super::*;
995
996    #[test]
997    fn clear_defaults_to_the_reversed_z_far_plane() {
998        let clear = ClearValue::default();
999        assert_eq!(clear.depth, depth::CLEAR);
1000        assert_eq!(clear.depth, 0.0);
1001        assert_eq!(clear.color, [0.0; 4]);
1002        // A colour clear must not quietly reintroduce conventional-Z depth.
1003        assert_eq!(ClearValue::color([1.0, 0.0, 0.0, 1.0]).depth, depth::CLEAR);
1004    }
1005
1006    #[test]
1007    fn depth_constants_bracket_the_range_in_reversed_order() {
1008        assert_eq!(depth::NEAR, 1.0);
1009        assert_eq!(depth::FAR, 0.0);
1010        // A const block: the relationship is a compile-time invariant of the
1011        // depth convention, not a runtime property.
1012        const {
1013            assert!(
1014                depth::NEAR > depth::FAR,
1015                "reversed-Z: the near plane holds the larger value"
1016            );
1017        }
1018    }
1019
1020    #[test]
1021    fn attachment_load_defaults_to_dont_care() {
1022        // Preserving contents must be asked for: `Load` is the expensive option
1023        // on tile-based GPUs and is wrong for a swapchain image.
1024        assert_eq!(LoadOp::default(), LoadOp::DontCare);
1025        assert_eq!(StoreOp::default(), StoreOp::Store);
1026    }
1027
1028    #[test]
1029    fn write_states_are_classified() {
1030        assert!(ResourceState::ColorAttachment.is_write());
1031        assert!(ResourceState::TransferDst.is_write());
1032        assert!(ResourceState::ShaderReadWrite.is_write());
1033        // Its name argues for this one and so does the store op: no backend
1034        // writes an attachment left in this state, so two read-only depth
1035        // passes in a row need no barrier between them.
1036        assert!(!ResourceState::DepthStencilRead.is_write());
1037        assert!(!ResourceState::ShaderRead.is_write());
1038        assert!(!ResourceState::IndirectArgument.is_write());
1039        assert!(!ResourceState::Undefined.is_write());
1040    }
1041
1042    #[test]
1043    fn read_to_same_read_needs_no_barrier_but_read_to_other_read_does() {
1044        use ResourceState as S;
1045        assert!(!S::needs_barrier(S::ShaderRead, S::ShaderRead));
1046        // Different reads still differ in image layout on vk/dx12.
1047        assert!(S::needs_barrier(S::ShaderRead, S::IndirectArgument));
1048        assert!(S::needs_barrier(S::ShaderRead, S::TransferSrc));
1049        // Anything involving a write always needs one.
1050        assert!(S::needs_barrier(S::ShaderWrite, S::ShaderWrite));
1051        assert!(S::needs_barrier(S::ShaderWrite, S::IndirectArgument));
1052        assert!(S::needs_barrier(S::Undefined, S::ColorAttachment));
1053        // Back-to-back depth-test-only passes: nothing stores, so nothing
1054        // orders. The prepass that filled the image is still a write and still
1055        // gets one.
1056        assert!(!S::needs_barrier(S::DepthStencilRead, S::DepthStencilRead));
1057        assert!(S::needs_barrier(S::DepthStencilWrite, S::DepthStencilRead));
1058    }
1059
1060    #[test]
1061    fn barriers_default_to_empty_and_non_global() {
1062        let barriers = Barriers::default();
1063        assert!(barriers.buffers.is_empty());
1064        assert!(barriers.images.is_empty());
1065        assert!(!barriers.global);
1066    }
1067
1068    #[test]
1069    fn same_queue_barrier_constructors_leave_ownership_alone() {
1070        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
1071        let buffer: BufferHandle = pool.insert(0).cast();
1072        let barrier = BufferBarrier::new(
1073            buffer,
1074            ResourceState::ShaderWrite,
1075            ResourceState::IndirectArgument,
1076        );
1077        assert!(barrier.queue_transfer.is_none());
1078        assert_eq!(barrier.to, ResourceState::IndirectArgument);
1079    }
1080
1081    #[test]
1082    fn default_resource_state_is_undefined() {
1083        // A freshly created resource has no meaningful contents, and the graph's
1084        // first transition must therefore be free to discard them.
1085        assert_eq!(ResourceState::default(), ResourceState::Undefined);
1086    }
1087}