Skip to main content

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