crcbl_hal/query.rs
1//! GPU queries — timestamps first.
2//!
3//! Timestamp queries are in the seam from P0 on purpose. The engine's debug
4//! principle is that **profiling hooks live in the seam itself**
5//! (`docs/notes/backends.md`'s HAL rules): per-pass GPU timers feed the render
6//! graph's frame-timing report at P1 and the profiler HUD at P10, and a
7//! profiler bolted on afterwards is one that never covers the passes written
8//! before it.
9//!
10//! # Degrading, not breaking
11//!
12//! [`Features::TIMESTAMP_QUERY`](crate::Features::TIMESTAMP_QUERY) is optional
13//! because WebGPU's timestamp support is browser-dependent (topic 10's risk
14//! list). A backend without it must accept
15//! [`PassTimestampWrites`](crate::PassTimestampWrites) on a pass descriptor as a
16//! no-op and return zeros from
17//! [`Device::query_results`](crate::Device::query_results) — the HUD shows
18//! blanks, the frame still renders.
19//!
20//! # One rule lives here, and the rest are obligations on a backend
21//!
22//! The types are `Copy`, `PartialEq` and a field layout the compiler checks,
23//! and everything this module *documents* about them is an obligation on a
24//! backend — both halves of the degrading rule above are checked where they are
25//! implemented, in `crate::null`'s
26//! `timestamp_queries_read_back_zeros_without_failing` and
27//! `the_portable_preset_refuses_query_kinds_it_lacks`.
28//!
29//! [`QueryKind::check_supported`] is the exception, and it is here rather than
30//! in five backends because the thing it refuses is missing from *this* module:
31//! see [`QueryKind::Occlusion`].
32
33use crcbl_core::Handle;
34
35/// Marker type for query-set handles. Uninhabited.
36#[derive(Debug)]
37pub enum QuerySet {}
38
39/// A pool of queries of one kind.
40pub type QuerySetHandle = Handle<QuerySet>;
41
42/// What a query set measures.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
44pub enum QueryKind {
45 /// A GPU clock reading, taken at a pass boundary named by
46 /// [`PassTimestampWrites`](crate::PassTimestampWrites).
47 ///
48 /// [`Device::query_results`](crate::Device::query_results) reports it in
49 /// **nanoseconds** — the backend converts from whatever its API counts in,
50 /// because the conversion is the one part of a timestamp that has no
51 /// cross-API spelling. [`resolve_query_set`](crate::CommandEncoder::resolve_query_set)
52 /// writes the device's own values instead, unconverted; it is a GPU-side
53 /// copy with nothing to multiply by.
54 Timestamp,
55 /// Samples that passed the depth test between begin and end.
56 ///
57 /// **No backend will make you one**, and
58 /// [`check_supported`](Self::check_supported) is where each of them says so:
59 /// there is no begin and no end to count between, because
60 /// [`CommandEncoder`](crate::CommandEncoder) has no verb that opens a query
61 /// around a draw. The variant stays so that the day one arrives it is a
62 /// backend arm rather than a seam change; until then the kind is refused
63 /// rather than served, for the reason
64 /// [`NO_OCCLUSION_QUERY_VERB`](crate::NO_OCCLUSION_QUERY_VERB) gives.
65 ///
66 /// The engine's own occlusion culling never wanted this: it is a two-phase
67 /// depth pyramid in compute (topic 03 §3.3), so nothing here is waiting on
68 /// the verb.
69 Occlusion,
70 /// Primitive and invocation counts.
71 PipelineStatistics,
72}
73
74impl QueryKind {
75 /// Refuses [`Occlusion`](Self::Occlusion), the kind no backend serves.
76 ///
77 /// Every backend's
78 /// [`create_query_set`](crate::Device::create_query_set) runs this before it
79 /// builds anything, so the one refusal every one of them makes is written
80 /// once and reads the same wherever a caller meets it — the shape
81 /// [`ShaderStages::check_supported`](crate::ShaderStages::check_supported)
82 /// and [`ImageViewDesc::check`](crate::ImageViewDesc::check) already use for
83 /// a rule the whole seam keeps.
84 ///
85 /// **It is the seam that refuses, not the device**, which is why there is no
86 /// [`Features`](crate::Features) argument: Vulkan, D3D12, Metal and WebGPU
87 /// can all count samples, and
88 /// [`Features::OCCLUSION_QUERY`](crate::Features::OCCLUSION_QUERY) goes on
89 /// reporting that. What is absent is the verb that would scope a count, and
90 /// no device supplies one. [`NO_OCCLUSION_QUERY_VERB`](crate::NO_OCCLUSION_QUERY_VERB)
91 /// carries the whole argument, and is the same sentence
92 /// [`Device::supports`](crate::Device::supports) declares and
93 /// [`DIVERGENCES`](crate::DIVERGENCES) records.
94 ///
95 /// # Errors
96 ///
97 /// [`HalError::Unsupported`](crate::HalError::Unsupported) for
98 /// [`Occlusion`](Self::Occlusion), attributed to `backend` so a caller reads
99 /// the refusal in the voice of the backend it asked.
100 pub fn check_supported(self, backend: crate::BackendKind) -> Result<(), crate::HalError> {
101 match self {
102 Self::Occlusion => Err(crate::HalError::Unsupported {
103 backend,
104 what: crate::NO_OCCLUSION_QUERY_VERB,
105 }),
106 Self::Timestamp | Self::PipelineStatistics => Ok(()),
107 }
108 }
109}
110
111/// What the GPU counted over one pass: one
112/// [`QueryKind::PipelineStatistics`] query, read back by
113/// [`Device::pipeline_statistics`](crate::Device::pipeline_statistics).
114///
115/// **Every count is an `Option`, and `None` is not zero.** A device counts the
116/// stages it has and its API exposes: a device with no mesh stage reports no
117/// task or mesh count, and one whose API has no input-assembly counters
118/// reports none for those. `Some(0)` is a stage the device watched that did no
119/// work; `None` is one it cannot speak for.
120#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
121pub struct PipelineStatistics {
122 /// Vertices the input assembler read.
123 pub input_vertices: Option<u64>,
124 /// Primitives the input assembler assembled.
125 pub input_primitives: Option<u64>,
126 /// Vertex-stage invocations: at least one per vertex reaching the stage,
127 /// and a device may reuse a transformed vertex rather than count it again.
128 pub vertex_invocations: Option<u64>,
129 /// Primitives that reached the clipper.
130 pub clipper_invocations: Option<u64>,
131 /// Primitives that left the clipper for rasterisation.
132 pub clipper_primitives: Option<u64>,
133 /// Fragment-stage invocations.
134 pub fragment_invocations: Option<u64>,
135 /// Compute-stage invocations: workgroups times the workgroup's size.
136 pub compute_invocations: Option<u64>,
137 /// Task (amplification) stage invocations.
138 pub task_invocations: Option<u64>,
139 /// Mesh-stage invocations.
140 pub mesh_invocations: Option<u64>,
141 /// Primitives the mesh stage emitted.
142 pub mesh_primitives: Option<u64>,
143}
144
145/// Creation parameters for a query set.
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub struct QuerySetDesc<'a> {
148 /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
149 pub label: Option<&'a str>,
150 /// What it measures.
151 pub kind: QueryKind,
152 /// How many queries it holds. Query indices are `0..count`.
153 ///
154 /// Never zero: see
155 /// [`Device::create_query_set`](crate::Device::create_query_set), which
156 /// refuses one on every backend.
157 pub count: u32,
158}
159
160#[cfg(test)]
161mod tests {
162 use super::*;
163 use crate::{BackendKind, HalError};
164
165 /// **The one kind the seam refuses, and the two it does not.**
166 ///
167 /// Both halves are the check: an `Err` for [`QueryKind::Occlusion`] alone
168 /// says nothing while the other two could be refused too, and this is the
169 /// rule five `create_query_set` implementations delegate to, so a version
170 /// that refused everything would take the timestamp path down with it.
171 ///
172 /// **What turns it red.** The occlusion arm answering `Ok` — which is the
173 /// change that puts a pool nothing can write back in a caller's hands — or
174 /// either other arm answering `Err`.
175 #[test]
176 fn only_the_occlusion_kind_is_refused_and_it_is_refused_for_the_asking_backend() {
177 for backend in [
178 BackendKind::Vulkan,
179 BackendKind::WebGpu,
180 BackendKind::Metal,
181 BackendKind::Dx12,
182 BackendKind::Null,
183 ] {
184 let refused = QueryKind::Occlusion.check_supported(backend);
185 assert!(
186 matches!(
187 refused,
188 Err(HalError::Unsupported { backend: named, what })
189 if named == backend && what == crate::NO_OCCLUSION_QUERY_VERB
190 ),
191 "{backend}: {refused:?}"
192 );
193 QueryKind::Timestamp
194 .check_supported(backend)
195 .expect("a timestamp set is the kind this seam does fill");
196 QueryKind::PipelineStatistics
197 .check_supported(backend)
198 .expect("the statistics kind is refused per backend, not here");
199 }
200 }
201}