crcbl_hal/caps.rs
1//! Adapter identification and device capability reporting.
2//!
3//! This module is what makes topic 39's **capability-driven degradation**
4//! expressible. The renderer never asks "am I on Vulkan?" — it asks
5//! [`Features::contains`] or one of the derived path selectors, exactly as
6//! `crcbl-shell` exposes `ShellCaps` instead of letting anyone sniff for
7//! Wayland.
8//!
9//! ```text
10//! MESH_SHADER, DRAW_INDIRECT_COUNT -> GeometryPath
11//! DESCRIPTOR_INDEXING -> BindingModel
12//! RAY_QUERY, ACCELERATION_STRUCTURE -> LightingPath
13//! ```
14//!
15//! Per topic 39, **a missing feature degrades by default**: each selector is
16//! ordered best-first and resolves downward, every value consumes the same
17//! geometry pools, instance buffers and material tables, and only the
18//! draw-emission tail differs. A caller that genuinely cannot run without a
19//! feature names it in
20//! [`DeviceDesc::required_features`](crate::DeviceDesc::required_features), and
21//! its absence is then a loud, named failure at device creation rather than a
22//! picture that is quietly a different game. There is deliberately no third
23//! behaviour and no single tier value: two buckets cannot hold three
24//! independent axes.
25
26use core::fmt;
27
28/// Which backend implementation is behind the seam.
29///
30/// For logs, capture-tool selection and bug reports only. Renderer *behaviour*
31/// must key off [`Features`] and the selectors derived from it, never off this
32/// — that is the difference between a capability system and platform sniffing.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum BackendKind {
35 /// `crcbl-vk` — Vulkan 1.3.
36 Vulkan,
37 /// `crcbl-webgpu` — WebGPU reached directly from wasm.
38 ///
39 /// The browser's only GPU backend. It shared this enum with a `Wgpu` variant
40 /// until 2026-08-21, kept selectable apart so a log line could say which of
41 /// the two drew the frame; `crcbl-wgpu` was deleted once this one had
42 /// replaced it everywhere.
43 WebGpu,
44 /// `crcbl-mtl` — Metal (P14).
45 Metal,
46 /// `crcbl-dx12` — Direct3D 12 (P14).
47 Dx12,
48 /// The in-crate recording no-op backend. See [`crate::null`].
49 Null,
50}
51
52impl BackendKind {
53 /// Whether this backend actually drives a GPU.
54 ///
55 /// [`Null`](Self::Null) records commands instead of executing them, so it is
56 /// outside the parity model in [`crate::capability`]: a recorder accepting
57 /// everything is not evidence that anything works, and listing it beside the
58 /// four real backends would make a parity sweep read one wider than it is.
59 ///
60 /// **This is also what [`crate::parity_blockers`] filters on.** It used to
61 /// filter on a separate `is_parity_target`, which excluded `Wgpu` — the
62 /// bridge backend that was always going to be deleted, and whose divergences
63 /// were therefore not work anybody would do. With that crate gone the two
64 /// predicates were the same function, and the second was deleted rather than
65 /// kept as a place for a hypothetical successor to declare itself.
66 ///
67 /// A `match` rather than `!matches!(self, Self::Null)`, so a backend added
68 /// later has to say which side it is on.
69 #[must_use]
70 pub const fn is_gpu(self) -> bool {
71 match self {
72 Self::Vulkan | Self::WebGpu | Self::Metal | Self::Dx12 => true,
73 Self::Null => false,
74 }
75 }
76}
77
78impl fmt::Display for BackendKind {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 let name = match self {
81 Self::Vulkan => "vulkan",
82 Self::WebGpu => "webgpu",
83 Self::Metal => "metal",
84 Self::Dx12 => "dx12",
85 Self::Null => "null",
86 };
87 f.write_str(name)
88 }
89}
90
91/// Broad class of physical device.
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
93pub enum DeviceType {
94 /// Software rasteriser — lavapipe, WARP, swiftshader. Correct, slow; the
95 /// P1 golden-image CI target.
96 Cpu,
97 /// A GPU integrated with the CPU package.
98 Integrated,
99 /// A separate GPU card.
100 Discrete,
101 /// A virtualised or para-virtualised GPU.
102 Virtual,
103 /// The backend declined to say.
104 Other,
105}
106
107/// Index of an adapter in [`Instance::adapters`](crate::Instance::adapters).
108///
109/// A newtype rather than a bare `u32` so it cannot be confused with a queue
110/// index or an image index at a call site — those are all `u32` too.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
112pub struct AdapterId(pub u32);
113
114/// Who an adapter is, as enumeration lists it, with no device opened.
115///
116/// What it can *do* is a separate question,
117/// [`Instance::adapter_caps`](crate::Instance::adapter_caps), because on D3D12
118/// answering it means creating a driver device — a fifth of a second per
119/// adapter — and a program that will open one adapter should not pay that for
120/// every adapter it could have opened.
121///
122/// Cloneable and owned: adapter enumeration happens once at startup, so the two
123/// `String`s are not worth avoiding, and the alternative (borrowing from the
124/// instance) would infect every consumer with a lifetime.
125#[derive(Clone, Debug, PartialEq)]
126pub struct AdapterInfo {
127 /// Position in the enumeration; pass to [`DeviceDesc`](crate::DeviceDesc).
128 pub id: AdapterId,
129 /// Human-readable device name, e.g. `"AMD Radeon RX 7900 XTX (RADV)"`.
130 pub name: String,
131 /// PCI vendor id, or `0` if unknown.
132 pub vendor_id: u32,
133 /// PCI device id, or `0` if unknown.
134 pub device_id: u32,
135 /// Device class.
136 pub device_type: DeviceType,
137 /// Driver name and version, as the backend reports them.
138 pub driver: String,
139 /// Which backend enumerated it.
140 pub backend: BackendKind,
141 /// The adapter's locally unique id, where the backend has one: DXGI's
142 /// `AdapterLuid`, or Vulkan's `deviceLUID` when the driver says it is
143 /// valid. `None` elsewhere.
144 ///
145 /// Unique among the adapters of one machine until it reboots, and the same
146 /// adapter reports the same value through D3D12 and Vulkan, which is what
147 /// makes it the key that joins the two — two cards of one model share a
148 /// name and PCI ids, never a LUID. Packed as the high half above the low
149 /// half, which is a Windows `LUID` read as a little-endian `u64`.
150 pub luid: Option<u64>,
151}
152
153bitflags::bitflags! {
154 /// Optional device capabilities.
155 ///
156 /// A caller asks for what it needs rather than for a bundle: a flag in
157 /// [`DeviceDesc::required_features`](crate::DeviceDesc::required_features)
158 /// that the adapter lacks is a named failure at device creation, and
159 /// everything else degrades. They are flags rather than a tier because
160 /// devices genuinely vary along independent axes — WebGPU has no bindless,
161 /// no multi-draw-indirect, no buffer device address and no push constants,
162 /// timestamp queries are browser-dependent, and Metal has
163 /// multi-draw-indirect with no GPU-side count at all.
164 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
165 pub struct Features: u64 {
166 /// Runtime-sized descriptor arrays with partial binding and
167 /// update-after-bind — the bindless model [`BindingModel::Bindless`]
168 /// selects. Vulkan `descriptorIndexing`, DX12 SM6.6 dynamic resources,
169 /// Metal argument buffers tier 2. Absent on WebGPU.
170 const DESCRIPTOR_INDEXING = 1 << 0;
171 /// Shaders can dereference raw GPU pointers. Vulkan
172 /// `bufferDeviceAddress`, DX12 GPU virtual addresses, Metal 3
173 /// `gpuAddress`. Absent on WebGPU, which uses indexed SSBO lookups
174 /// instead.
175 const BUFFER_DEVICE_ADDRESS = 1 << 1;
176 /// [`draw_indirect_count`](crate::CommandEncoder::draw_indirect_count)
177 /// and its indexed sibling are usable: the draw count itself comes from
178 /// a GPU buffer, so the CPU never learns how many draws happen.
179 /// Absent on WebGPU.
180 const DRAW_INDIRECT_COUNT = 1 << 2;
181 /// One indirect call may emit more than one draw (`draw_count > 1` in
182 /// [`DrawIndirect`](crate::DrawIndirect)). Distinct from
183 /// `DRAW_INDIRECT_COUNT`: WebGPU has neither, but a backend could
184 /// plausibly have this without the count buffer.
185 const MULTI_DRAW_INDIRECT = 1 << 3;
186 /// `first_instance` in an indirect draw argument is honoured rather
187 /// than required to be zero. WebGPU requires zero.
188 const INDIRECT_FIRST_INSTANCE = 1 << 4;
189 /// Timestamp queries are supported. Optional and browser-dependent on
190 /// WebGPU, which is why the profiler HUD must degrade rather than
191 /// break (topic 10 risk list).
192 const TIMESTAMP_QUERY = 1 << 5;
193 /// Pipeline statistics queries (primitives generated, invocations).
194 const PIPELINE_STATISTICS_QUERY = 1 << 6;
195 /// Occlusion queries.
196 const OCCLUSION_QUERY = 1 << 7;
197 /// Compute shaders. Effectively universal — WebGPU has them, which is
198 /// why GPU culling stays GPU-side on every [`GeometryPath`] — but the
199 /// bit still has to exist so a device without them can say so:
200 /// [`crate::null`] refuses `create_compute_pipeline` outright when its
201 /// caps omit it.
202 const COMPUTE = 1 << 8;
203 /// Timeline semaphores: monotonic counters usable for both GPU-GPU and
204 /// CPU-GPU waits. Vulkan `timelineSemaphore`, DX12 `ID3D12Fence`,
205 /// Metal `MTLSharedEvent`. WebGPU has no semaphores at all; see
206 /// [`crate::sync`].
207 const TIMELINE_SEMAPHORE = 1 << 9;
208 /// A queue family that supports compute independently of graphics, so
209 /// async compute is possible. Async compute is post-MVP, but the seam
210 /// models queues plural from the start.
211 const ASYNC_COMPUTE_QUEUE = 1 << 10;
212 /// A transfer-only queue family exists. MVP uploads share the
213 /// graphics+compute queue; this flag is what a later dedicated
214 /// transfer queue keys off.
215 const TRANSFER_QUEUE = 1 << 11;
216 /// Push constants / root constants are available.
217 /// [`Limits::max_push_constant_size`] gives the budget. **Absent on
218 /// WebGPU**, which substitutes a dynamic-offset uniform buffer — a
219 /// data-layout consequence the renderer must plan for.
220 const PUSH_CONSTANTS = 1 << 12;
221 /// Depth clamping (as opposed to clipping) — shadow-map rendering
222 /// wants it so caster geometry behind the near plane still writes
223 /// depth.
224 const DEPTH_CLAMP = 1 << 13;
225 /// A non-zero [`DepthBias::clamp`](crate::DepthBias::clamp) is honoured.
226 const DEPTH_BIAS_CLAMP = 1 << 14;
227 /// Fill-mode `Line` in [`PolygonMode`](crate::PolygonMode) — wireframe
228 /// debug views. Absent on WebGPU and Metal-on-some-hardware.
229 const POLYGON_MODE_LINE = 1 << 15;
230 /// BC/DXT compressed texture formats are sampleable.
231 const TEXTURE_COMPRESSION_BC = 1 << 16;
232 /// Anisotropic sampling; [`Limits::max_sampler_anisotropy`] gives the
233 /// cap.
234 const SAMPLER_ANISOTROPY = 1 << 17;
235 /// Debug labels and markers reach the capture tool
236 /// (`VK_EXT_debug_utils`, PIX events, Metal debug groups). Without it
237 /// the encoder's label calls are accepted and dropped.
238 const DEBUG_MARKERS = 1 << 18;
239 /// GPU-side shader printf / validation messages are routed into `log`.
240 const SHADER_DEBUG_PRINTF = 1 << 19;
241 /// The device reports back when a present has actually completed, so a
242 /// frame loop can pace on the display instead of on a clock —
243 /// [`Device::wait_until_presented`](crate::Device::wait_until_presented).
244 ///
245 /// Named for the capability rather than for any one API's spelling of
246 /// it, because the three that have it do not agree on the shape: one
247 /// numbers each present and blocks on the number, one hands out a
248 /// waitable object with no number at all, and one only calls back once
249 /// a drawable has been shown. What they share is that the CPU can find
250 /// out, which is the whole of what this flag promises. Optional, and
251 /// deliberately **not** part of [`GPU_DRIVEN`](Self::GPU_DRIVEN): a
252 /// device without it renders exactly the same frames, it just cannot be
253 /// paced by them.
254 const PRESENT_FEEDBACK = 1 << 20;
255 /// The device can say what the display is **doing** with the frames we
256 /// present — fixed refresh, adaptive sync, or neither reported —
257 /// through [`Device::display_timing`](crate::Device::display_timing).
258 ///
259 /// Distinct from [`PRESENT_FEEDBACK`](Self::PRESENT_FEEDBACK), which
260 /// says only that a present *finished*. This one is about the display's
261 /// own cadence, which nothing else in the seam can observe: a
262 /// [`PresentMode`](crate::PresentMode) is a request, and a frame time
263 /// measured over a paced loop is the request coming back at you. Also
264 /// optional and also **not** part of [`GPU_DRIVEN`](Self::GPU_DRIVEN):
265 /// a device without it renders the same frames and simply cannot be
266 /// asked.
267 const PRESENT_TIMING = 1 << 21;
268 /// Mesh shaders: a compute-shaped stage that emits primitives straight
269 /// into the rasteriser, replacing the vertex-fetch and input-assembly
270 /// front end entirely. Vulkan `VK_EXT_mesh_shader`, DX12 mesh shader
271 /// tier 1, Metal mesh functions. Absent on WebGPU.
272 ///
273 /// The best [`GeometryPath`], because a meshlet cull can run in the
274 /// same dispatch that emits the geometry rather than writing indirect
275 /// arguments for a separate draw to read back.
276 const MESH_SHADER = 1 << 22;
277 /// The amplification stage in front of a mesh shader, which decides how
278 /// many mesh workgroups to launch. Vulkan's task shader, DX12's
279 /// amplification shader, Metal's object function.
280 ///
281 /// Reported separately from [`MESH_SHADER`](Self::MESH_SHADER) because
282 /// the two are separately optional: a mesh shader works on its own with
283 /// a workgroup count computed on the CPU or by an earlier dispatch, and
284 /// this stage is only what moves that decision into the same draw.
285 const TASK_SHADER = 1 << 23;
286 /// Inline ray queries from any shader stage — `RayQuery` in Slang,
287 /// `VK_KHR_ray_query`, DXR 1.1 inline ray tracing. Traversal happens
288 /// inside an otherwise ordinary fragment or compute shader, with no
289 /// separate hit or miss stage and no shader binding table.
290 ///
291 /// Half of what [`LightingPath::RayTraced`] needs; the rays still want
292 /// an [`ACCELERATION_STRUCTURE`](Self::ACCELERATION_STRUCTURE) to
293 /// traverse, which is why neither flag alone selects that path.
294 const RAY_QUERY = 1 << 24;
295 /// Ray generation, closest-hit, any-hit, intersection and miss shader
296 /// stages, dispatched as a pipeline of their own against a shader
297 /// binding table. Vulkan `VK_KHR_ray_tracing_pipeline`, DXR 1.0.
298 ///
299 /// Strictly more than [`RAY_QUERY`](Self::RAY_QUERY) and reported apart
300 /// from it: a device may offer inline queries without the pipeline
301 /// stages, and nothing in the engine's own lighting needs the stages.
302 const RAY_TRACING_PIPELINE = 1 << 25;
303 /// Bottom- and top-level acceleration structures can be built, refit
304 /// and traversed. Vulkan `VK_KHR_acceleration_structure`, DXR
305 /// BLAS/TLAS, Metal `MTLAccelerationStructure`.
306 ///
307 /// The other half of [`LightingPath::RayTraced`], and reported apart
308 /// from the two ray flags because it is the half that costs memory and
309 /// build time whether or not anything traces against it.
310 const ACCELERATION_STRUCTURE = 1 << 26;
311 /// A vertex shader can read **which draw of a multi-draw indirect
312 /// call** it belongs to — SPIR-V's `DrawIndex`, Vulkan 1.1
313 /// `shaderDrawParameters`. With
314 /// [`MULTI_DRAW_INDIRECT`](Self::MULTI_DRAW_INDIRECT) it is what lets
315 /// one call draw a range of buckets that each read their own data:
316 /// `crcbl-render`'s forward passes record a call per range rather than
317 /// a bind and a call per bucket where a device has both.
318 ///
319 /// **On a device with [`MESH_SHADER`](Self::MESH_SHADER) it covers the
320 /// task and mesh stages too**: SPIR-V declares `DrawIndex` there under
321 /// `MeshShadingEXT`, and a multi-draw `draw_mesh_tasks_indirect` hands
322 /// each draw's workgroups its index, so the mesh tail ranges on the
323 /// same flag.
324 ///
325 /// Vulkan only. WGSL, MSL and HLSL have no builtin for it — D3D12's
326 /// `ExecuteIndirect` and Metal's indirect draws carry no draw index to
327 /// a shader — so no other backend reports it. Optional and **not** part
328 /// of [`GPU_DRIVEN`](Self::GPU_DRIVEN): a device without it draws the
329 /// same frames with a call per bucket.
330 const DRAW_INDEX = 1 << 27;
331 /// The GPU's timestamp clock can be read from the CPU, in the
332 /// nanoseconds [`Device::query_results`](crate::Device::query_results)
333 /// reports a timestamp in, through
334 /// [`Device::gpu_clock`](crate::Device::gpu_clock): what puts a
335 /// profile's GPU passes on the CPU's timeline.
336 ///
337 /// D3D12's `GetClockCalibration`, Vulkan's
338 /// `VK_KHR_calibrated_timestamps` with the device time domain, Metal's
339 /// `sampleTimestamps:gpuTimestamp:`. Absent on WebGPU, which has no
340 /// call reading the GPU's clock. Optional and **not** part of
341 /// [`GPU_DRIVEN`](Self::GPU_DRIVEN): a device without it renders the
342 /// same frames, and its profiles keep the GPU on its own clock.
343 const GPU_CLOCK = 1 << 28;
344
345 /// The feature set the full GPU-driven path uses.
346 ///
347 /// A **named bundle**, not a tier and not a gate. A device holding all
348 /// of it can run one bindless descriptor array for every texture, GPU
349 /// pointers for per-draw data, and a single indirect-count call per
350 /// pass.
351 ///
352 /// Useful as an
353 /// [`optional_features`](crate::DeviceDesc::optional_features) bundle,
354 /// so a caller enables whatever of it the adapter turns out to have.
355 /// **Never a requirement of code that has to run on whatever device it
356 /// finds.** Demanding the whole set there is what topic 39 removed — it
357 /// refuses a device over one absent flag while it has the rest, which
358 /// is the opposite of degrading. What such a caller genuinely cannot
359 /// run without goes in
360 /// [`required_features`](crate::DeviceDesc::required_features) by name.
361 ///
362 /// A test that opens
363 /// [`NullInstance::gpu_driven`](crate::null::NullInstance::gpu_driven)
364 /// is the exception, and the reason the rule above names the caller it
365 /// binds rather than saying "never": that preset holds this bundle by
366 /// construction, so there is no hardware to refuse and the requirement
367 /// is a precondition — it asserts the preset asked for is the preset
368 /// that opened. It also grants it, since a null device is opened with
369 /// the adapter's features intersected against
370 /// `required_features | optional_features`. Move it to the optional
371 /// half and a preset that lost a flag opens as a lesser path with those
372 /// tests still green, which is the untested-fallback failure topic 39
373 /// names as its likeliest risk.
374 const GPU_DRIVEN = Self::DESCRIPTOR_INDEXING.bits()
375 | Self::BUFFER_DEVICE_ADDRESS.bits()
376 | Self::DRAW_INDIRECT_COUNT.bits()
377 | Self::MULTI_DRAW_INDIRECT.bits()
378 | Self::COMPUTE.bits()
379 | Self::TIMELINE_SEMAPHORE.bits();
380 }
381}
382
383/// Numeric device limits.
384///
385/// Most fields are a hard ceiling on **the one quantity each names**: a
386/// descriptor exceeding that quantity is a [`HalError`](crate::HalError), not
387/// undefined behaviour. Three are not ceilings at all, and each says so in its
388/// own line: the two `min_*_buffer_offset_alignment` fields are alignments a
389/// binding offset must be a multiple of, and
390/// [`optimal_buffer_copy_offset_alignment`](Self::optimal_buffer_copy_offset_alignment)
391/// is a preference — a copy ignoring it is slower and never refused. Fields are
392/// named after the thing they bound, not after any one API's spelling of it.
393///
394/// # These are not a set of independent budgets
395///
396/// A descriptor respecting *every* field may still be refused. Three of the
397/// backends here spend several of these quantities out of one budget this struct
398/// has no field for, so the reading where each ceiling can be taken up to at the
399/// same time as every other holds on Vulkan and on nothing else:
400///
401/// * **D3D12** — one root signature costs at most `D3D12_MAX_ROOT_COST` DWORDs
402/// *in total*, and the sets and the push-constant range both spend out of it:
403/// a descriptor table costs one DWORD, a dynamic-offset binding two (it
404/// becomes a root descriptor carrying a 64-bit address), and a push-constant
405/// range one per 32-bit value. `crcbl-dx12` reports
406/// [`max_push_constant_size`](Self::max_push_constant_size) as that entire
407/// budget in bytes — reachable only by a layout with no sets at all — and
408/// reports [`max_bind_groups`](Self::max_bind_groups) at
409/// [`minimum`](Self::minimum)'s floor rather than as a count D3D12 has,
410/// because whether that many sets fit depends on what they hold.
411/// * **Metal** — a push-constant block is lowered to an ordinary buffer
412/// argument, so it competes with every set's buffer bindings for the same
413/// per-stage argument table. A layout whose sets fill that table has nowhere
414/// to put a block, whatever `max_push_constant_size` says.
415/// * **WebGPU** — binding counts are capped **per shader stage**, which this
416/// struct has no field for at all. `crcbl-webgpu` opens its device asking for
417/// the adapter's own ceilings rather than the specification's defaults, since
418/// the defaults are below what the engine's own layouts bind and there is no
419/// field here a caller could have asked with; a layout still over what the
420/// adapter offers is refused by the browser.
421///
422/// # What a caller does about it
423///
424/// **Attempt the creation and handle the refusal.** Nothing here predicts it —
425/// the cost model is each backend's own, and there is no field to pre-check
426/// against. A budget overrun, as opposed to a missing capability, arrives as
427/// [`HalError::InvalidDescriptor`](crate::HalError::InvalidDescriptor) from
428/// [`Device::create_pipeline_layout`](crate::Device::create_pipeline_layout)
429/// with the arithmetic in the message, so a caller holding a smaller fallback
430/// layout tries that one and a caller without one reports what it was told.
431/// `crcbl-webgpu` is the exception on *where* it arrives rather than on what it
432/// says: its `create_pipeline_layout` encodes onto a command stream and returns
433/// before a browser has seen the layout, so every refusal on that backend
434/// surfaces through [`Device::take_error`](crate::Device::take_error).
435#[derive(Clone, Copy, Debug, PartialEq)]
436pub struct Limits {
437 /// Largest width/height of a 2D image.
438 pub max_image_2d: u32,
439 /// Largest edge of a 3D image.
440 pub max_image_3d: u32,
441 /// Largest layer count of an array image.
442 pub max_image_array_layers: u32,
443 /// Largest bindable range of a storage buffer, in bytes.
444 pub max_storage_buffer_range: u64,
445 /// Largest bindable range of a uniform buffer, in bytes.
446 pub max_uniform_buffer_range: u64,
447 /// Bind groups (descriptor sets) bindable simultaneously.
448 ///
449 /// Not jointly satisfiable with
450 /// [`max_push_constant_size`](Self::max_push_constant_size) on every
451 /// backend — see the type's own docs.
452 pub max_bind_groups: u32,
453 /// Descriptors in one bindless array. `0` when
454 /// [`Features::DESCRIPTOR_INDEXING`] is absent.
455 pub max_bindless_descriptors: u32,
456 /// Push-constant bytes. `0` when [`Features::PUSH_CONSTANTS`] is absent.
457 ///
458 /// Not jointly satisfiable with
459 /// [`max_bind_groups`](Self::max_bind_groups) on every backend — see the
460 /// type's own docs. On D3D12 it is the whole root signature's budget, and on
461 /// Metal a block needs an argument-table entry the sets have not taken.
462 pub max_push_constant_size: u32,
463 /// Colour attachments in one render pass.
464 pub max_color_attachments: u32,
465 /// Highest sample count usable for a multisampled image or pipeline.
466 ///
467 /// Always a power of two in `1..=64`: a sample count is a *mask* in every
468 /// API underneath, so `3` is not "three samples", it is `TYPE_1 | TYPE_2`.
469 /// Backends reject a request that is not a power of two, or that exceeds
470 /// this, with [`HalError::InvalidDescriptor`](crate::HalError::InvalidDescriptor)
471 /// — which is the error [`Device::create_image`](crate::Device::create_image)
472 /// documents and which had nowhere to be expressed before this field.
473 pub max_sample_count: u32,
474 /// Draws one [`draw_indirect_count`](crate::CommandEncoder::draw_indirect_count)
475 /// may emit.
476 pub max_draw_indirect_count: u32,
477 /// Per-dimension workgroup size limit for compute dispatches.
478 pub max_compute_workgroup_size: [u32; 3],
479 /// Total invocations in one compute workgroup.
480 pub max_compute_invocations_per_workgroup: u32,
481 /// Per-dimension workgroup *count* limit for
482 /// [`dispatch`](crate::CommandEncoder::dispatch).
483 pub max_compute_workgroups_per_dimension: u32,
484 /// Required alignment for a uniform buffer binding offset.
485 pub min_uniform_buffer_offset_alignment: u64,
486 /// Required alignment for a storage buffer binding offset.
487 pub min_storage_buffer_offset_alignment: u64,
488 /// Preferred alignment for buffer↔image copy offsets.
489 pub optimal_buffer_copy_offset_alignment: u64,
490 /// Maximum anisotropy in [`SamplerDesc`](crate::SamplerDesc).
491 pub max_sampler_anisotropy: f32,
492}
493
494impl Limits {
495 /// The floor every backend must clear.
496 ///
497 /// Chosen to sit at or below WebGPU's guaranteed `downlevel` limits, so a
498 /// renderer written against these numbers runs on the weakest device the
499 /// engine targets. It is a *contract*, not a description of any real
500 /// device — [`NullInstance::portable`](crate::null::NullInstance::portable)
501 /// reports exactly this.
502 #[must_use]
503 pub const fn minimum() -> Self {
504 Self {
505 max_image_2d: 8192,
506 max_image_3d: 2048,
507 max_image_array_layers: 256,
508 max_storage_buffer_range: 128 << 20,
509 max_uniform_buffer_range: 64 << 10,
510 max_bind_groups: 4,
511 max_bindless_descriptors: 0,
512 max_push_constant_size: 0,
513 max_color_attachments: 4,
514 // WebGPU's downlevel floor: 1x and 4x, and nothing above.
515 max_sample_count: 4,
516 max_draw_indirect_count: 1,
517 max_compute_workgroup_size: [256, 256, 64],
518 max_compute_invocations_per_workgroup: 256,
519 max_compute_workgroups_per_dimension: 65535,
520 min_uniform_buffer_offset_alignment: 256,
521 min_storage_buffer_offset_alignment: 256,
522 optimal_buffer_copy_offset_alignment: 256,
523 max_sampler_anisotropy: 1.0,
524 }
525 }
526
527 /// A representative desktop device with headroom on every axis.
528 ///
529 /// Used by [`NullInstance::gpu_driven`](crate::null::NullInstance::gpu_driven)
530 /// and by tests that need plausible ceilings. Not a promise about any
531 /// specific GPU.
532 #[must_use]
533 pub const fn desktop() -> Self {
534 Self {
535 max_image_2d: 16384,
536 max_image_3d: 2048,
537 max_image_array_layers: 2048,
538 max_storage_buffer_range: u32::MAX as u64,
539 max_uniform_buffer_range: 64 << 10,
540 max_bind_groups: 8,
541 max_bindless_descriptors: 500_000,
542 max_push_constant_size: 128,
543 max_color_attachments: 8,
544 max_sample_count: 8,
545 max_draw_indirect_count: 1 << 20,
546 max_compute_workgroup_size: [1024, 1024, 64],
547 max_compute_invocations_per_workgroup: 1024,
548 max_compute_workgroups_per_dimension: 65535,
549 min_uniform_buffer_offset_alignment: 64,
550 min_storage_buffer_offset_alignment: 16,
551 optimal_buffer_copy_offset_alignment: 4,
552 max_sampler_anisotropy: 16.0,
553 }
554 }
555}
556
557/// How the renderer gets geometry in front of the rasteriser.
558///
559/// One shader-permutation axis and one golden-image axis, declared best-first
560/// and resolved downward: every value draws the same meshlets out of the same
561/// pools, and only the submission tail differs.
562#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
563pub enum GeometryPath {
564 /// A mesh shader emits primitives directly, so the meshlet cull and the
565 /// geometry it survives live in one dispatch.
566 MeshShader,
567 /// Indirect draws whose *count* is itself read from a GPU buffer, so the
568 /// CPU never learns how many draws a pass emits.
569 IndirectCount,
570 /// Indirect draws with a CPU-known count: one argument per batch, each
571 /// batch's instance count still decided on the GPU. The floor, and what
572 /// WebGPU gets.
573 IndirectPerBatch,
574}
575
576impl GeometryPath {
577 /// The features this selector reads, and the only ones it may read.
578 ///
579 /// Stated as data because [`downgrades`] has to answer "which selector did
580 /// this absence move", and a second hand-written table would drift from
581 /// [`from_features`](Self::from_features) the first time an axis gains a
582 /// flag. `selector_inputs_are_the_only_features_a_selector_reads` pins the
583 /// two together.
584 pub const INPUTS: Features = Features::MESH_SHADER.union(Features::DRAW_INDIRECT_COUNT);
585
586 /// The best path `features` can run.
587 #[must_use]
588 pub const fn from_features(features: Features) -> Self {
589 if features.contains(Features::MESH_SHADER) {
590 Self::MeshShader
591 } else if features.contains(Features::DRAW_INDIRECT_COUNT) {
592 Self::IndirectCount
593 } else {
594 Self::IndirectPerBatch
595 }
596 }
597}
598
599/// How the renderer addresses textures and per-draw data from a shader.
600///
601/// The data-layout axis: it decides what a material index *means* in shader
602/// source, which is why it is a permutation rather than a branch.
603#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
604pub enum BindingModel {
605 /// One runtime-sized descriptor array holding every texture, indexed by a
606 /// number that travels in the instance data.
607 Bindless,
608 /// Fixed-size texture arrays, bound a page at a time, with draws sorted so
609 /// one page serves a run of them.
610 ArrayPages,
611}
612
613impl BindingModel {
614 /// The features this selector reads — see [`GeometryPath::INPUTS`].
615 pub const INPUTS: Features = Features::DESCRIPTOR_INDEXING;
616
617 /// The best model `features` can run.
618 #[must_use]
619 pub const fn from_features(features: Features) -> Self {
620 if features.contains(Features::DESCRIPTOR_INDEXING) {
621 Self::Bindless
622 } else {
623 Self::ArrayPages
624 }
625 }
626}
627
628/// How the renderer resolves indirect lighting, shadows and reflections.
629///
630/// The raster path exists on every device and is what the browser and Apple
631/// targets get; see topic 39's worked example for why that is a capability
632/// answer and not a platform branch.
633#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
634pub enum LightingPath {
635 /// Inline ray queries traced against an acceleration structure.
636 RayTraced,
637 /// Shadow maps, screen-space reflections and a probe-based ambient term.
638 Rasterised,
639}
640
641impl LightingPath {
642 /// The features this selector reads — see [`GeometryPath::INPUTS`].
643 pub const INPUTS: Features = Features::RAY_QUERY.union(Features::ACCELERATION_STRUCTURE);
644
645 /// The best path `features` can run.
646 ///
647 /// Ray tracing needs **both** halves: a device reporting only one of
648 /// [`Features::RAY_QUERY`] and [`Features::ACCELERATION_STRUCTURE`] has
649 /// nothing to trace, or nothing to trace with, and rasterises.
650 #[must_use]
651 pub const fn from_features(features: Features) -> Self {
652 if features.contains(Features::RAY_QUERY.union(Features::ACCELERATION_STRUCTURE)) {
653 Self::RayTraced
654 } else {
655 Self::Rasterised
656 }
657 }
658}
659
660/// Everything the renderer needs to know about a device's abilities.
661#[derive(Clone, Copy, Debug, PartialEq)]
662pub struct DeviceCaps {
663 /// Optional capabilities present.
664 pub features: Features,
665 /// Numeric ceilings.
666 pub limits: Limits,
667}
668
669impl DeviceCaps {
670 /// Default [`GeometryPath`] selected from the capability ceiling.
671 ///
672 /// [`crate::Device::preferred_geometry_path`] may recommend a cheaper
673 /// supported path when the highest-ranked capability is emulated.
674 ///
675 /// Derived rather than stored, here and for the other two selectors: a
676 /// backend cannot claim a path while missing what that path is built on —
677 /// the one lie that would silently produce a renderer taking the bindless
678 /// path on a device without bindless.
679 #[must_use]
680 pub const fn geometry_path(&self) -> GeometryPath {
681 GeometryPath::from_features(self.features)
682 }
683
684 /// Which [`BindingModel`] this device selects.
685 #[must_use]
686 pub const fn binding_model(&self) -> BindingModel {
687 BindingModel::from_features(self.features)
688 }
689
690 /// Which [`LightingPath`] this device selects.
691 #[must_use]
692 pub const fn lighting_path(&self) -> LightingPath {
693 LightingPath::from_features(self.features)
694 }
695
696 /// Which of `required` this device is missing — empty if it satisfies them.
697 ///
698 /// The shape `Instance::create_device`
699 /// uses to build [`HalError::UnsupportedFeatures`](crate::HalError::UnsupportedFeatures),
700 /// so the error names the gap instead of saying "unsupported".
701 #[must_use]
702 pub fn missing(&self, required: Features) -> Features {
703 required.difference(self.features)
704 }
705
706 /// Whether this device satisfies `required`.
707 #[must_use]
708 pub fn supports(&self, required: Features) -> bool {
709 self.features.contains(required)
710 }
711}
712
713/// Which derived selector an absent feature moved, and the value it moved it to.
714///
715/// Only the flags the three selectors are derived from have one. A device that
716/// declines a timestamp query or a debug marker has still downgraded — the
717/// caller asked and did not get — but nothing about which path the renderer
718/// compiles changed, and [`Downgrade::selected`] says so by being `None` rather
719/// than by naming a path that was never in question.
720#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
721pub enum SelectedPath {
722 /// A [`GeometryPath`], from [`GeometryPath::INPUTS`].
723 Geometry(GeometryPath),
724 /// A [`BindingModel`], from [`BindingModel::INPUTS`].
725 Binding(BindingModel),
726 /// A [`LightingPath`], from [`LightingPath::INPUTS`].
727 Lighting(LightingPath),
728}
729
730impl fmt::Display for SelectedPath {
731 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732 match self {
733 Self::Geometry(path) => write!(f, "geometry {path:?}"),
734 Self::Binding(model) => write!(f, "binding {model:?}"),
735 Self::Lighting(path) => write!(f, "lighting {path:?}"),
736 }
737 }
738}
739
740/// One optional feature a device was asked for and did not grant.
741#[derive(Clone, Copy, Debug, PartialEq, Eq)]
742pub struct Downgrade {
743 /// The absent feature — always exactly one flag.
744 pub feature: Features,
745 /// How the flag is spelled in source, e.g. `"MESH_SHADER"`. Taken from the
746 /// flag table rather than written out, so it cannot disagree with the flag.
747 pub name: &'static str,
748 /// The selector this absence moved, or `None` when no selector reads it.
749 pub selected: Option<SelectedPath>,
750}
751
752impl fmt::Display for Downgrade {
753 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754 match self.selected {
755 Some(selected) => write!(f, "{} -> {selected}", self.name),
756 None => f.write_str(self.name),
757 }
758 }
759}
760
761/// Every optional feature a device declined, with the path each absence chose.
762///
763/// From [`downgrades`], and **empty when the device granted everything asked
764/// for**. That is the property worth having: topic 39 wants one line at device
765/// creation and no line at all when nothing degraded, so silence means no
766/// downgrade rather than meaning nobody looked.
767///
768/// [`Display`](fmt::Display) renders the whole set as one comma-separated
769/// clause — `MESH_SHADER -> geometry IndirectCount, TIMESTAMP_QUERY` — which is
770/// the log line's payload. It renders empty when the set is, so a caller must
771/// gate on [`is_empty`](Self::is_empty) rather than logging unconditionally.
772#[derive(Clone, Copy, Debug, PartialEq, Eq)]
773pub struct Downgrades {
774 absent: Features,
775 geometry: GeometryPath,
776 binding: BindingModel,
777 lighting: LightingPath,
778}
779
780impl Downgrades {
781 /// The absent features as one flag set. Empty means nothing degraded.
782 #[must_use]
783 pub const fn absent(&self) -> Features {
784 self.absent
785 }
786
787 /// Whether the device granted everything it was asked for.
788 #[must_use]
789 pub const fn is_empty(&self) -> bool {
790 self.absent.is_empty()
791 }
792
793 /// Each absent feature in flag-declaration order, with what it cost.
794 pub fn iter(&self) -> impl Iterator<Item = Downgrade> + '_ {
795 use bitflags::Flags;
796
797 Features::FLAGS
798 .iter()
799 // `GPU_DRIVEN` is a named union of other flags, not a bit of its
800 // own; reporting it would name the same absence twice.
801 .filter(|flag| flag.value().bits().is_power_of_two())
802 .filter(|flag| self.absent.contains(*flag.value()))
803 .map(|flag| Downgrade {
804 feature: *flag.value(),
805 name: flag.name(),
806 selected: self.selected_for(*flag.value()),
807 })
808 }
809
810 /// Which selector `feature`'s absence moved, from the selectors' own
811 /// declared inputs rather than from a table repeated here.
812 fn selected_for(&self, feature: Features) -> Option<SelectedPath> {
813 if GeometryPath::INPUTS.contains(feature) {
814 Some(SelectedPath::Geometry(self.geometry))
815 } else if BindingModel::INPUTS.contains(feature) {
816 Some(SelectedPath::Binding(self.binding))
817 } else if LightingPath::INPUTS.contains(feature) {
818 Some(SelectedPath::Lighting(self.lighting))
819 } else {
820 None
821 }
822 }
823}
824
825impl fmt::Display for Downgrades {
826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
827 for (index, downgrade) in self.iter().enumerate() {
828 if index > 0 {
829 f.write_str(", ")?;
830 }
831 write!(f, "{downgrade}")?;
832 }
833 Ok(())
834 }
835}
836
837/// What `granted` did not deliver of the optional features `requested`.
838///
839/// Topic 39: *"Every downgrade is logged once, at device creation, naming the
840/// feature and the path it selected."* This is that line's content, computed
841/// away from the call site so it can be checked without a device — the call
842/// site's only job is to log the result when it is not
843/// [`empty`](Downgrades::is_empty).
844///
845/// `requested` is the **optional** set and nothing else. A missing *required*
846/// feature is not a downgrade: it is
847/// [`HalError::UnsupportedFeatures`](crate::HalError::UnsupportedFeatures) and
848/// there is no device to describe.
849///
850/// ```
851/// use crcbl_hal::{DeviceCaps, Features, Limits, downgrades};
852///
853/// let webgpu_shaped = DeviceCaps {
854/// features: Features::COMPUTE,
855/// limits: Limits::minimum(),
856/// };
857/// let report = downgrades(Features::COMPUTE | Features::DESCRIPTOR_INDEXING, &webgpu_shaped);
858/// assert_eq!(report.to_string(), "DESCRIPTOR_INDEXING -> binding ArrayPages");
859///
860/// let asked_for_what_it_has = downgrades(Features::COMPUTE, &webgpu_shaped);
861/// assert!(asked_for_what_it_has.is_empty());
862/// ```
863#[must_use]
864pub fn downgrades(requested: Features, granted: &DeviceCaps) -> Downgrades {
865 Downgrades {
866 absent: granted.missing(requested),
867 geometry: granted.geometry_path(),
868 binding: granted.binding_model(),
869 lighting: granted.lighting_path(),
870 }
871}
872
873#[cfg(test)]
874mod tests {
875 use super::*;
876 use crate::HalError;
877
878 /// A device with mesh shaders and no GPU-side draw count must still take
879 /// the mesh path. The natural way to write the mapping wrong is to test the
880 /// cheaper flag first, or to require both, and either produces a device
881 /// that has the best path available and does not use it.
882 #[test]
883 fn mesh_shading_wins_without_a_draw_indirect_count() {
884 let mesh_only = GeometryPath::from_features(Features::MESH_SHADER);
885 assert_eq!(mesh_only, GeometryPath::MeshShader);
886 assert_eq!(
887 GeometryPath::from_features(Features::MESH_SHADER | Features::DRAW_INDIRECT_COUNT),
888 mesh_only,
889 "a draw count must not displace the mesh path"
890 );
891 assert_eq!(
892 GeometryPath::from_features(Features::DRAW_INDIRECT_COUNT),
893 GeometryPath::IndirectCount,
894 "the count alone is the middle path, not the floor"
895 );
896 }
897
898 /// Ray-traced lighting needs a structure to trace *and* a way to trace it.
899 /// Written as a truth table because the mistake is an `or`, which reads
900 /// identically and lets a device select a path it cannot execute.
901 #[test]
902 fn ray_traced_lighting_needs_both_halves() {
903 for (features, expected) in [
904 (Features::empty(), LightingPath::Rasterised),
905 (Features::RAY_QUERY, LightingPath::Rasterised),
906 (Features::ACCELERATION_STRUCTURE, LightingPath::Rasterised),
907 (
908 Features::RAY_TRACING_PIPELINE | Features::ACCELERATION_STRUCTURE,
909 LightingPath::Rasterised,
910 ),
911 (
912 Features::RAY_QUERY | Features::ACCELERATION_STRUCTURE,
913 LightingPath::RayTraced,
914 ),
915 ] {
916 assert_eq!(
917 LightingPath::from_features(features),
918 expected,
919 "{features:?}"
920 );
921 }
922 }
923
924 /// The null-device case: a backend reporting nothing at all must still
925 /// select a runnable path on every axis, because there is no fourth answer
926 /// and no `Option` for the renderer to handle.
927 #[test]
928 fn an_empty_feature_set_lands_on_the_floor_of_every_selector() {
929 let caps = DeviceCaps {
930 features: Features::empty(),
931 limits: Limits::minimum(),
932 };
933 assert_eq!(caps.geometry_path(), GeometryPath::IndirectPerBatch);
934 assert_eq!(caps.binding_model(), BindingModel::ArrayPages);
935 assert_eq!(caps.lighting_path(), LightingPath::Rasterised);
936 }
937
938 /// The accessors must read the device's own features and nothing else — a
939 /// selector wired to a constant would satisfy every assertion above.
940 #[test]
941 fn the_accessors_follow_the_devices_features() {
942 let caps = DeviceCaps {
943 features: Features::MESH_SHADER
944 | Features::DESCRIPTOR_INDEXING
945 | Features::RAY_QUERY
946 | Features::ACCELERATION_STRUCTURE,
947 limits: Limits::desktop(),
948 };
949 assert_eq!(caps.geometry_path(), GeometryPath::MeshShader);
950 assert_eq!(caps.binding_model(), BindingModel::Bindless);
951 assert_eq!(caps.lighting_path(), LightingPath::RayTraced);
952 }
953
954 /// Topic 39's monotonicity rule: **no capability's arrival may select a
955 /// path that needs more than the one it replaced.** Ranked by a table
956 /// written out here rather than by an `Ord` derived from declaration order,
957 /// which would make the assertion circular with the thing it checks.
958 #[test]
959 fn adding_a_feature_never_selects_a_path_that_needs_more() {
960 const AXES: [Features; 5] = [
961 Features::MESH_SHADER,
962 Features::DRAW_INDIRECT_COUNT,
963 Features::DESCRIPTOR_INDEXING,
964 Features::RAY_QUERY,
965 Features::ACCELERATION_STRUCTURE,
966 ];
967
968 fn rank(features: Features) -> [u8; 3] {
969 [
970 match GeometryPath::from_features(features) {
971 GeometryPath::IndirectPerBatch => 0,
972 GeometryPath::IndirectCount => 1,
973 GeometryPath::MeshShader => 2,
974 },
975 match BindingModel::from_features(features) {
976 BindingModel::ArrayPages => 0,
977 BindingModel::Bindless => 1,
978 },
979 match LightingPath::from_features(features) {
980 LightingPath::Rasterised => 0,
981 LightingPath::RayTraced => 1,
982 },
983 ]
984 }
985
986 for subset in 0..(1u32 << AXES.len()) {
987 let base = AXES
988 .iter()
989 .enumerate()
990 .filter(|(bit, _)| subset & (1 << bit) != 0)
991 .fold(Features::empty(), |acc, (_, axis)| acc.union(*axis));
992 let before = rank(base);
993 for axis in AXES {
994 let after = rank(base.union(axis));
995 assert!(
996 after.iter().zip(&before).all(|(now, then)| now >= then),
997 "gaining {axis:?} on top of {base:?} went backwards: \
998 {before:?} -> {after:?}"
999 );
1000 }
1001 }
1002 }
1003
1004 #[test]
1005 fn gpu_driven_is_exactly_the_documented_bundle() {
1006 // Guards the flag list against silent growth. Named exhaustively, and
1007 // checked for equality rather than containment: a feature added to
1008 // `GPU_DRIVEN` without a doc update is the thing this catches, and a
1009 // `contains` list of a subset never would.
1010 let documented = Features::DESCRIPTOR_INDEXING
1011 | Features::BUFFER_DEVICE_ADDRESS
1012 | Features::DRAW_INDIRECT_COUNT
1013 | Features::MULTI_DRAW_INDIRECT
1014 | Features::COMPUTE
1015 | Features::TIMELINE_SEMAPHORE;
1016 assert_eq!(Features::GPU_DRIVEN, documented);
1017 // Push constants are NOT in the bundle: WebGPU lacks them, but so do
1018 // some otherwise fully GPU-driven configurations, and the renderer must
1019 // have a uniform-buffer path regardless.
1020 assert!(!Features::GPU_DRIVEN.contains(Features::PUSH_CONSTANTS));
1021 // Neither present capability is in it, for the same reason as each
1022 // other: a device without them renders identical frames and only loses
1023 // the ability to be *asked* about the display.
1024 assert!(!Features::GPU_DRIVEN.contains(Features::PRESENT_FEEDBACK));
1025 assert!(!Features::GPU_DRIVEN.contains(Features::PRESENT_TIMING));
1026 // Nor is anything the selectors branch on beyond the draw count: mesh
1027 // shading and ray tracing are their own axes, and folding them in here
1028 // would make the bundle a tier again.
1029 assert!(!Features::GPU_DRIVEN.contains(Features::MESH_SHADER));
1030 assert!(!Features::GPU_DRIVEN.contains(Features::RAY_QUERY));
1031 assert!(!Features::GPU_DRIVEN.contains(Features::ACCELERATION_STRUCTURE));
1032 // Nor the draw index: three of the four backends cannot have it, and a
1033 // bundle three backends cannot hold would make them all report it
1034 // missing.
1035 assert!(!Features::GPU_DRIVEN.contains(Features::DRAW_INDEX));
1036 }
1037
1038 #[test]
1039 fn missing_names_the_gap() {
1040 let caps = DeviceCaps {
1041 features: Features::COMPUTE | Features::TIMELINE_SEMAPHORE,
1042 limits: Limits::minimum(),
1043 };
1044 let missing = caps.missing(Features::GPU_DRIVEN);
1045 assert!(missing.contains(Features::DESCRIPTOR_INDEXING));
1046 assert!(missing.contains(Features::BUFFER_DEVICE_ADDRESS));
1047 assert!(!missing.contains(Features::COMPUTE));
1048 assert!(!caps.supports(Features::GPU_DRIVEN));
1049 assert!(caps.supports(Features::COMPUTE));
1050 assert!(caps.missing(Features::COMPUTE).is_empty());
1051 }
1052
1053 /// Strictly below, not merely "not above". The regression worth guarding is
1054 /// the desktop preset being pasted into `minimum()`, and a table of `<=`
1055 /// passes on two byte-identical presets while the name says otherwise.
1056 #[test]
1057 fn minimum_limits_are_below_desktop_limits() {
1058 let min = Limits::minimum();
1059 let desktop = Limits::desktop();
1060 assert!(min.max_image_2d < desktop.max_image_2d);
1061 assert!(min.max_image_array_layers < desktop.max_image_array_layers);
1062 assert!(min.max_storage_buffer_range < desktop.max_storage_buffer_range);
1063 assert!(min.max_bind_groups < desktop.max_bind_groups);
1064 assert!(min.max_bindless_descriptors < desktop.max_bindless_descriptors);
1065 assert!(min.max_push_constant_size < desktop.max_push_constant_size);
1066 assert!(min.max_color_attachments < desktop.max_color_attachments);
1067 assert!(min.max_sample_count < desktop.max_sample_count);
1068 assert!(min.max_draw_indirect_count < desktop.max_draw_indirect_count);
1069 assert!(min.max_compute_workgroup_size[0] < desktop.max_compute_workgroup_size[0]);
1070 assert!(min.max_compute_workgroup_size[1] < desktop.max_compute_workgroup_size[1]);
1071 assert!(
1072 min.max_compute_invocations_per_workgroup
1073 < desktop.max_compute_invocations_per_workgroup
1074 );
1075 assert!(min.max_sampler_anisotropy < desktop.max_sampler_anisotropy);
1076
1077 // The fields the two presets legitimately agree on. Listed rather than
1078 // omitted, so "the floor already matches a desktop device here" is a
1079 // stated fact instead of a gap in the table above.
1080 assert!(min.max_image_3d <= desktop.max_image_3d);
1081 assert!(min.max_uniform_buffer_range <= desktop.max_uniform_buffer_range);
1082 assert!(min.max_compute_workgroup_size[2] <= desktop.max_compute_workgroup_size[2]);
1083 assert!(
1084 min.max_compute_workgroups_per_dimension
1085 <= desktop.max_compute_workgroups_per_dimension
1086 );
1087
1088 // A sample count is a bit in a mask underneath, so a preset reporting a
1089 // non-power-of-two ceiling would make every backend's check nonsense.
1090 for limits in [min, desktop] {
1091 assert!(limits.max_sample_count.is_power_of_two());
1092 assert!(limits.max_sample_count <= 64);
1093 }
1094 // Alignment limits run the other way: the floor is the *coarser* one,
1095 // and strictly so for the same reason.
1096 assert!(
1097 min.min_uniform_buffer_offset_alignment > desktop.min_uniform_buffer_offset_alignment
1098 );
1099 assert!(
1100 min.min_storage_buffer_offset_alignment > desktop.min_storage_buffer_offset_alignment
1101 );
1102 assert!(
1103 min.optimal_buffer_copy_offset_alignment > desktop.optimal_buffer_copy_offset_alignment
1104 );
1105 }
1106
1107 /// Every flag is a hand-written `1 << N`, and nothing checked the shifts
1108 /// were distinct. A repeated shift makes [`Features::contains`] vacuously
1109 /// true for the shadowed flag — it is never absent, so no test that asks
1110 /// "is X missing" can ever see it.
1111 ///
1112 /// The count comes from the flag table rather than a literal, so the check
1113 /// grows with the enum instead of needing an edit that would not happen.
1114 #[test]
1115 fn every_feature_owns_a_distinct_bit() {
1116 use bitflags::Flags;
1117
1118 // `GPU_DRIVEN` is a named union of other flags, not a bit of its own.
1119 let single_bit: Vec<&'static str> = Features::FLAGS
1120 .iter()
1121 .filter(|flag| flag.value().bits().is_power_of_two())
1122 .map(bitflags::Flag::name)
1123 .collect();
1124 assert_eq!(
1125 Features::all().bits().count_ones() as usize,
1126 single_bit.len(),
1127 "two of {single_bit:?} share a bit"
1128 );
1129 }
1130
1131 /// Every optional feature must be individually observable: `missing` names
1132 /// exactly it, and a device without it refuses it.
1133 ///
1134 /// Driven off the flag table, because a hand-written list structurally
1135 /// cannot keep up — nine flags had no mention in any test at all when this
1136 /// was written, including the two the queue selection keys off.
1137 #[test]
1138 fn every_feature_is_reported_one_at_a_time() {
1139 use bitflags::Flags;
1140
1141 for flag in Features::FLAGS {
1142 let feature = *flag.value();
1143 if !feature.bits().is_power_of_two() {
1144 continue;
1145 }
1146 let name = flag.name();
1147 let without = DeviceCaps {
1148 features: Features::all().difference(feature),
1149 limits: Limits::desktop(),
1150 };
1151 assert_eq!(without.missing(feature), feature, "{name}");
1152 assert!(!without.supports(feature), "{name}");
1153
1154 let only = DeviceCaps {
1155 features: feature,
1156 limits: Limits::minimum(),
1157 };
1158 assert!(only.supports(feature), "{name}");
1159 assert!(only.missing(feature).is_empty(), "{name}");
1160 assert!(
1161 HalError::UnsupportedFeatures {
1162 missing: without.missing(feature)
1163 }
1164 .to_string()
1165 .contains(name),
1166 "the error a backend owes must name {name}"
1167 );
1168 }
1169 }
1170
1171 #[test]
1172 fn minimum_limits_report_no_bindless_or_push_constants() {
1173 let min = Limits::minimum();
1174 assert_eq!(min.max_bindless_descriptors, 0);
1175 assert_eq!(min.max_push_constant_size, 0);
1176 assert_eq!(
1177 min.max_draw_indirect_count, 1,
1178 "the floor emits one draw per indirect call"
1179 );
1180 }
1181
1182 /// The mapping [`Downgrades::selected_for`] reads must be the whole of what
1183 /// a selector reads, or the log line attributes an absence to a path that
1184 /// did not move — and, worse, stays silent about the one that did.
1185 ///
1186 /// Checked by exhaustion rather than by inspection: every flag outside a
1187 /// selector's `INPUTS` is toggled against every subset of the flags inside
1188 /// it, and the selector's answer must not budge.
1189 #[test]
1190 fn selector_inputs_are_the_only_features_a_selector_reads() {
1191 use bitflags::Flags;
1192
1193 let single_bits: Vec<Features> = Features::FLAGS
1194 .iter()
1195 .map(|flag| *flag.value())
1196 .filter(|feature| feature.bits().is_power_of_two())
1197 .collect();
1198
1199 // One function per selector, each returning a rank so the three can be
1200 // compared through one code path.
1201 type Select = fn(Features) -> u8;
1202 let selectors: [(Features, Select); 3] = [
1203 (GeometryPath::INPUTS, |features| {
1204 GeometryPath::from_features(features) as u8
1205 }),
1206 (BindingModel::INPUTS, |features| {
1207 BindingModel::from_features(features) as u8
1208 }),
1209 (LightingPath::INPUTS, |features| {
1210 LightingPath::from_features(features) as u8
1211 }),
1212 ];
1213
1214 for (inputs, select) in selectors {
1215 let members: Vec<Features> = single_bits
1216 .iter()
1217 .copied()
1218 .filter(|feature| inputs.contains(*feature))
1219 .collect();
1220 assert!(
1221 !members.is_empty(),
1222 "a selector reading nothing would pass this vacuously"
1223 );
1224
1225 for subset in 0..(1u32 << members.len()) {
1226 let base = members
1227 .iter()
1228 .enumerate()
1229 .filter(|(bit, _)| subset & (1 << bit) != 0)
1230 .fold(Features::empty(), |acc, (_, feature)| acc.union(*feature));
1231 let expected = select(base);
1232 for other in &single_bits {
1233 if inputs.contains(*other) {
1234 continue;
1235 }
1236 assert_eq!(
1237 select(base.union(*other)),
1238 expected,
1239 "{other:?} moved a selector that does not list it in INPUTS"
1240 );
1241 }
1242 }
1243
1244 // The other half: each input must be *able* to move it, or it is
1245 // listed in `INPUTS` and read by nothing.
1246 for member in &members {
1247 assert!(
1248 (0..(1u32 << members.len())).any(|subset| {
1249 let base = members
1250 .iter()
1251 .enumerate()
1252 .filter(|(bit, _)| subset & (1 << bit) != 0)
1253 .fold(Features::empty(), |acc, (_, feature)| acc.union(*feature));
1254 select(base.union(*member)) != select(base.difference(*member))
1255 }),
1256 "{member:?} is listed in INPUTS but changes nothing"
1257 );
1258 }
1259 }
1260 }
1261
1262 /// **Silence is the property.** A device that granted everything asked for
1263 /// must produce nothing to log, and the empty rendering is what the call
1264 /// site's `is_empty` guard stands in for.
1265 #[test]
1266 fn a_device_that_granted_everything_reports_no_downgrade() {
1267 let caps = DeviceCaps {
1268 features: Features::all(),
1269 limits: Limits::desktop(),
1270 };
1271 for requested in [
1272 Features::empty(),
1273 Features::COMPUTE,
1274 Features::GPU_DRIVEN,
1275 Features::all(),
1276 ] {
1277 let report = downgrades(requested, &caps);
1278 assert!(report.is_empty(), "{requested:?}");
1279 assert!(report.absent().is_empty(), "{requested:?}");
1280 assert_eq!(report.iter().count(), 0, "{requested:?}");
1281 assert_eq!(report.to_string(), "", "{requested:?}");
1282 }
1283 }
1284
1285 /// One absent feature names *that* feature and the selector it moved —
1286 /// which is the whole of what topic 39 asks the line to say.
1287 ///
1288 /// Driven off the selectors' own inputs so every axis is covered, and the
1289 /// expected value is computed from the device rather than written out, so
1290 /// the assertion is about the wiring rather than about three literals.
1291 #[test]
1292 fn one_absent_feature_names_itself_and_the_path_it_moved() {
1293 for (feature, name, expected) in [
1294 (
1295 Features::MESH_SHADER,
1296 "MESH_SHADER",
1297 SelectedPath::Geometry(GeometryPath::IndirectCount),
1298 ),
1299 (
1300 Features::DRAW_INDIRECT_COUNT,
1301 "DRAW_INDIRECT_COUNT",
1302 SelectedPath::Geometry(GeometryPath::MeshShader),
1303 ),
1304 (
1305 Features::DESCRIPTOR_INDEXING,
1306 "DESCRIPTOR_INDEXING",
1307 SelectedPath::Binding(BindingModel::ArrayPages),
1308 ),
1309 (
1310 Features::RAY_QUERY,
1311 "RAY_QUERY",
1312 SelectedPath::Lighting(LightingPath::Rasterised),
1313 ),
1314 (
1315 Features::ACCELERATION_STRUCTURE,
1316 "ACCELERATION_STRUCTURE",
1317 SelectedPath::Lighting(LightingPath::Rasterised),
1318 ),
1319 ] {
1320 let caps = DeviceCaps {
1321 features: Features::all().difference(feature),
1322 limits: Limits::desktop(),
1323 };
1324 let report = downgrades(Features::all(), &caps);
1325 assert!(!report.is_empty(), "{name}");
1326 assert_eq!(report.absent(), feature, "{name}");
1327
1328 let entries: Vec<Downgrade> = report.iter().collect();
1329 assert_eq!(entries.len(), 1, "{name}");
1330 assert_eq!(entries[0].feature, feature, "{name}");
1331 assert_eq!(entries[0].name, name);
1332 assert_eq!(entries[0].selected, Some(expected), "{name}");
1333
1334 let line = report.to_string();
1335 assert!(line.starts_with(name), "{line}");
1336 assert!(line.contains(&expected.to_string()), "{line}");
1337 }
1338 }
1339
1340 /// A feature no selector is derived from is still a downgrade — the caller
1341 /// asked and did not get — but it must not claim to have moved a path.
1342 #[test]
1343 fn an_absence_no_selector_reads_names_no_path() {
1344 let caps = DeviceCaps {
1345 features: Features::all().difference(Features::TIMESTAMP_QUERY),
1346 limits: Limits::desktop(),
1347 };
1348 let report = downgrades(Features::all(), &caps);
1349 let entries: Vec<Downgrade> = report.iter().collect();
1350 assert_eq!(entries.len(), 1);
1351 assert_eq!(entries[0].selected, None);
1352 assert_eq!(report.to_string(), "TIMESTAMP_QUERY");
1353 }
1354
1355 /// Several absences must *all* be named. The failure this guards is a line
1356 /// that reports the first gap and stops, which reads like a complete
1357 /// account and is not.
1358 #[test]
1359 fn every_absent_feature_is_named() {
1360 // The browser's shape: compute and nothing else, asked for the full
1361 // GPU-driven bundle plus the two selector axes above it.
1362 let caps = DeviceCaps {
1363 features: Features::COMPUTE | Features::TIMELINE_SEMAPHORE,
1364 limits: Limits::minimum(),
1365 };
1366 let requested = Features::GPU_DRIVEN
1367 | Features::MESH_SHADER
1368 | Features::RAY_QUERY
1369 | Features::ACCELERATION_STRUCTURE
1370 | Features::TIMESTAMP_QUERY;
1371 let report = downgrades(requested, &caps);
1372
1373 let named: Vec<&'static str> = report.iter().map(|downgrade| downgrade.name).collect();
1374 assert_eq!(
1375 named,
1376 [
1377 "DESCRIPTOR_INDEXING",
1378 "BUFFER_DEVICE_ADDRESS",
1379 "DRAW_INDIRECT_COUNT",
1380 "MULTI_DRAW_INDIRECT",
1381 "TIMESTAMP_QUERY",
1382 "MESH_SHADER",
1383 "RAY_QUERY",
1384 "ACCELERATION_STRUCTURE",
1385 ],
1386 "in flag-declaration order, and `GPU_DRIVEN` itself never named"
1387 );
1388
1389 let line = report.to_string();
1390 for name in &named {
1391 assert!(line.contains(name), "{line} omits {name}");
1392 }
1393 assert!(line.contains("binding ArrayPages"), "{line}");
1394 assert!(line.contains("geometry IndirectPerBatch"), "{line}");
1395 assert!(line.contains("lighting Rasterised"), "{line}");
1396
1397 // What the device *did* grant is never named, and neither is anything
1398 // nobody asked for: the line is about the gap, not about the device.
1399 assert!(!line.contains("COMPUTE"), "{line}");
1400 assert!(!line.contains("TIMELINE_SEMAPHORE"), "{line}");
1401 assert!(!line.contains("PRESENT_FEEDBACK"), "{line}");
1402 }
1403
1404 #[test]
1405 fn backend_kind_displays_lowercase() {
1406 assert_eq!(BackendKind::Vulkan.to_string(), "vulkan");
1407 assert_eq!(BackendKind::Null.to_string(), "null");
1408 assert_eq!(BackendKind::WebGpu.to_string(), "webgpu");
1409 // Exhaustive on purpose: a variant added without a name of its own
1410 // would otherwise share one silently. This mattered most while a `Wgpu`
1411 // variant sat beside `WebGpu` — two backends both reaching WebGPU in a
1412 // browser, where an `as_str` arm copied from its neighbour would have
1413 // made a log line unable to say which one drew. That crate is gone, and
1414 // the check is kept because the hazard is about copied arms rather than
1415 // about those two names.
1416 let every = [
1417 BackendKind::Vulkan,
1418 BackendKind::WebGpu,
1419 BackendKind::Metal,
1420 BackendKind::Dx12,
1421 BackendKind::Null,
1422 ];
1423 let names: std::collections::HashSet<String> =
1424 every.iter().map(ToString::to_string).collect();
1425 assert_eq!(names.len(), every.len(), "two backend kinds share a name");
1426 }
1427}