Skip to main content

crcbl_render/
debug_draw.rs

1//! The debug draw layer: an immediate-mode buffer of world-space line segments,
2//! drawn pre-tonemap in HDR.
3//!
4//! ```text
5//! any system ──line/aabb/sphere/frustum──▶ DebugDraw's segment buffer
6//!                                                │ begin_frame: upload + clear
7//!                                                ▼
8//!                          scene colour ──▶ debug-draw ──▶ scene colour
9//!                                                ▲
10//!                                  scene depth (tested, never written)
11//! ```
12//!
13//! The UI's debug item 5 (`docs/notes/tooling.md`) is what this is, and
14//! topic 43's foundations block is where it was
15//! scheduled: the layer the four owed views —
16//! topic 45's cascade overlay and atlas view,
17//! topic 25's cluster bounds and the light list's
18//! reach — are drawn through.
19//!
20//! **World-anchored text is not here**, and it is not deferred silently: text
21//! needs a glyph atlas and a rasteriser seam, `crcbl_ui::text::FontAtlas` and
22//! [`crate::ui_pass`] already own one between them, and folding a second
23//! consumer of it into this module would double the diff and put a screen-space
24//! pass and a world-space one in one file. `docs/backlog.md` carries what the
25//! slice needs. Everything this module offers is geometry.
26//!
27//! # Immediate mode, on [`crate::ui_pass`]'s shape
28//!
29//! A system appends during the frame; the buffer is uploaded and **cleared** by
30//! the [`ForwardRenderer::begin_frame`](crate::ForwardRenderer::begin_frame)
31//! that opens the next one, so a segment survives exactly the frame it was
32//! appended in and nothing has to be un-appended. That is the same ring the UI
33//! draw list rides — one host-visible buffer per frame in flight, grown by
34//! doubling, and a count committed only after the upload succeeded.
35//!
36//! # Pre-tonemap, in HDR
37//!
38//! `docs/plan/18-render-features.md`'s interaction rule fixed this before the
39//! layer existed: "Debug overlays (debug draw, gizmos) render pre-tonemap in HDR
40//! (they're in the world) except UI-space panels." So a colour appended here is
41//! linear radiance and is exposed and tonemapped like geometry — which is what
42//! makes a debug line read as *being in the scene* rather than painted over it,
43//! and it is the opposite of [`crate::grid`]'s decision, whose own header says
44//! why reference chrome goes the other way.
45//!
46//! [`crate::forward`] is what puts the pass in the frame, and it lands
47//! immediately before the tonemap: after the reflection composite, the bloom
48//! chain and the auto-exposure histogram, so a debug line neither reflects in a
49//! surface, blooms, nor moves the exposure the scene is metered at, and before
50//! the tonemap, so it is exposed with everything else.
51//!
52//! # Nothing is drawn until something asks for it
53//!
54//! [`r_debug_draw`] is off by default and a frame that appended no segment
55//! records **no pass at all** — no pipeline, no buffer, no barrier — which is
56//! what makes every golden image in the workspace identical to the one it was
57//! blessed as. The pipeline itself is built lazily, on the first frame that has
58//! both, so a renderer nobody draws through never pays for it either.
59
60use crcbl_hal::{
61    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
62    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BlendState, BufferDesc,
63    BufferHandle, BufferUsage, ColorTargetState, ColorWrites, CompareOp, DepthBias,
64    DepthStencilState, Device, GraphicsPipelineDesc, GraphicsPipelineHandle, HalError, LoadOp,
65    MemoryLocation, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PrimitiveState,
66    PrimitiveTopology, ShaderEntry, ShaderModuleDesc, ShaderStages, StoreOp,
67    check_portable_storage_buffers,
68};
69use crcbl_shaders::{DEBUG_DRAW, Stage};
70use glam::{Mat4, Vec3, Vec4Swizzles};
71
72use crate::graph::{ImageId, RenderGraph};
73
74crcbl_console::convar! {
75    /// Draw the debug-draw layer's segments over the scene, pre-tonemap.
76    pub static r_debug_draw: bool = false;
77}
78
79/// How many segments each of a sphere's three great circles is drawn with.
80///
81/// Twenty-four puts a vertex every fifteen degrees, which is where a circle
82/// stops reading as a polygon at the sizes a debug sphere is looked at — a
83/// light's reach or a cluster's bounding sphere, drawn against geometry rather
84/// than on its own. It is also what fixes a sphere's cost:
85/// [`DebugDraw::sphere`] appends three times this many segments.
86pub const SPHERE_SEGMENTS: usize = 24;
87
88/// The eight corners of a box, in the order [`BOX_EDGES`] indexes them.
89///
90/// Bit 0 is the x end, bit 1 the y end and bit 2 the z end, so corner `i` takes
91/// the maximum on an axis exactly where that axis's bit is set. Written as a
92/// rule rather than a table because both callers derive their corners from it —
93/// an axis-aligned box from its two extremes, a frustum from the unit cube of
94/// normalised device coordinates.
95const fn corner_signs(corner: usize) -> [bool; 3] {
96    [corner & 1 != 0, corner & 2 != 0, corner & 4 != 0]
97}
98
99/// A box's twelve edges, as pairs of [`corner_signs`] indices.
100///
101/// Four along each axis, which is what makes the list exhaustive: two corners
102/// share an edge exactly when their indices differ in one bit.
103const BOX_EDGES: [(usize, usize); 12] = [
104    (0, 1),
105    (2, 3),
106    (4, 5),
107    (6, 7),
108    (0, 2),
109    (1, 3),
110    (4, 6),
111    (5, 7),
112    (0, 4),
113    (1, 5),
114    (2, 6),
115    (3, 7),
116];
117
118/// One endpoint of one segment, matching `debug_draw.slang`'s `DebugVertex`.
119///
120/// `position.w` is unused — the vertex stage supplies the homogeneous one — and
121/// `color` is linear RGBA, written into the HDR scene target.
122#[repr(C)]
123#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
124pub struct DebugVertex {
125    /// The endpoint in world space, with an unused `w`.
126    pub position: [f32; 4],
127    /// Linear RGBA, alpha-blended over the scene.
128    pub color: [f32; 4],
129}
130
131/// Bytes of `debug_draw.slang`'s constant block: one `float4x4`.
132const CONSTANTS_SIZE: u64 = 64;
133
134/// Starting size of each frame's segment buffer, in bytes.
135const INITIAL_RING_BYTES: u64 = 4096;
136
137/// The size a ring buffer grows to when `needed` bytes no longer fit.
138///
139/// Doubling rather than fitting exactly, on [`crate::ui_pass`]'s terms: a system
140/// that appends a few more segments each frame reallocates a handful of times
141/// rather than every frame.
142fn grown(needed: u64) -> u64 {
143    needed
144        .max(INITIAL_RING_BYTES)
145        .next_power_of_two()
146        .next_multiple_of(256)
147}
148
149/// The eight world-space corners of the view volume `view_proj` projects, or
150/// [`None`] where that volume has no finite corners.
151///
152/// **The [`None`] arm is the engine's own camera**, and it is why this is an
153/// [`Option`] rather than a comment telling callers what not to pass. A
154/// [`Projection::Perspective`](crate::Projection) here is an *infinite*
155/// reversed-Z projection — its far plane is degenerate on purpose, which
156/// [`crate::cull::Frustum::from_view_projection`] also carries — so the corners
157/// at the far end of normalised device coordinates unproject to infinity, and a
158/// caller that drew them would append segments with no finite endpoint and see
159/// nothing rather than an error. The finite views are the ones the owed overlays
160/// are about: a cascade's orthographic box and a spot light's finite
161/// perspective.
162#[must_use]
163pub fn frustum_corners(view_proj: Mat4) -> Option<[Vec3; 8]> {
164    let inverse = view_proj.inverse();
165    let mut corners = [Vec3::ZERO; 8];
166    for (corner, out) in corners.iter_mut().enumerate() {
167        let [x, y, z] = corner_signs(corner);
168        let ndc = glam::Vec4::new(
169            if x { 1.0 } else { -1.0 },
170            if y { 1.0 } else { -1.0 },
171            // The engine's clip space is reversed-Z over `0.0..=1.0`, so the
172            // `z` bit picks the near plane rather than a symmetric extreme.
173            if z { 1.0 } else { 0.0 },
174            1.0,
175        );
176        let clip = inverse * ndc;
177        // One predicate, not two: a `w` of zero divides to an infinity and a
178        // `w` of zero over a zero numerator to a NaN, and neither is finite —
179        // so a separate `w == 0.0` arm would be a branch nothing can reach that
180        // this one does not.
181        *out = clip.xyz() / clip.w;
182        if !out.is_finite() {
183            return None;
184        }
185    }
186    Some(corners)
187}
188
189/// The immediate-mode buffer every system appends to, and the pass that draws
190/// it.
191///
192/// Built by [`ForwardRenderer`](crate::ForwardRenderer), which owns one and
193/// hands it out through
194/// [`debug_draw`](crate::ForwardRenderer::debug_draw); appending is all a system
195/// ever does with it.
196#[derive(Debug, Default)]
197pub struct DebugDraw {
198    /// This frame's segments, two entries per line, cleared by
199    /// [`begin_frame`](Self::begin_frame).
200    vertices: Vec<DebugVertex>,
201    /// The pipeline and the rings, built on the first frame that has something
202    /// to draw. [`None`] on a renderer nobody has drawn a segment through, which
203    /// is what makes the layer cost nothing at all until it is used.
204    gpu: Option<Gpu>,
205}
206
207/// Everything the pass owns once there has been a frame worth building it for.
208#[derive(Debug)]
209struct Gpu {
210    layout: BindGroupLayoutHandle,
211    pipeline_layout: PipelineLayoutHandle,
212    pipeline: GraphicsPipelineHandle,
213    /// `[frame]`: the segment buffer, host-visible and rewritten each frame.
214    buffers: Vec<BufferHandle>,
215    /// `[frame]`: how many **bytes** the buffer above holds.
216    capacity: Vec<u64>,
217    /// `[frame]`: the constant block, one per frame in flight for the frame
218    /// uniforms' reason exactly.
219    uniforms: Vec<BufferHandle>,
220    /// `[frame]`: the group naming the two buffers above.
221    groups: Vec<BindGroupHandle>,
222    /// `[frame]`: how many vertices the last [`DebugDraw::begin_frame`] on that
223    /// slot uploaded. Zero is what makes [`DebugDraw::add_pass`] record nothing.
224    counts: Vec<usize>,
225}
226
227impl DebugDraw {
228    /// Whether the console has the layer switched on.
229    ///
230    /// The read half of [`r_debug_draw`], for a system deciding whether to build
231    /// its overlay at all: appending while it is off is harmless — the buffer is
232    /// cleared and never uploaded — but a system whose geometry costs something
233    /// to compute wants to know before it computes it.
234    #[must_use]
235    pub fn enabled() -> bool {
236        r_debug_draw.get_bool()
237    }
238
239    /// Appends one world-space segment.
240    ///
241    /// Every other primitive here is written in terms of this one.
242    pub fn line(&mut self, from: Vec3, to: Vec3, color: [f32; 4]) {
243        self.vertices.push(DebugVertex {
244            position: [from.x, from.y, from.z, 1.0],
245            color,
246        });
247        self.vertices.push(DebugVertex {
248            position: [to.x, to.y, to.z, 1.0],
249            color,
250        });
251    }
252
253    /// Appends the twelve edges of the axis-aligned box spanning `min..=max`.
254    pub fn aabb(&mut self, min: Vec3, max: Vec3, color: [f32; 4]) {
255        let mut corners = [Vec3::ZERO; 8];
256        for (corner, out) in corners.iter_mut().enumerate() {
257            let [x, y, z] = corner_signs(corner);
258            *out = Vec3::new(
259                if x { max.x } else { min.x },
260                if y { max.y } else { min.y },
261                if z { max.z } else { min.z },
262            );
263        }
264        self.box_edges(&corners, color);
265    }
266
267    /// Appends the twelve edges of the view volume `view_proj` projects.
268    ///
269    /// **A view volume with no finite corners appends nothing and says so**, on
270    /// [`frustum_corners`]'s terms — which is the engine's own camera, whose
271    /// far plane is at infinity. A caller that wants to handle that itself calls
272    /// [`frustum_corners`] and [`box_edges`](Self::box_edges).
273    pub fn frustum(&mut self, view_proj: Mat4, color: [f32; 4]) {
274        let Some(corners) = frustum_corners(view_proj) else {
275            crcbl_core::log::error!(
276                "debug draw: a frustum whose corners are not finite was not drawn; an infinite \
277                 reversed-Z projection has no far plane to draw"
278            );
279            return;
280        };
281        self.box_edges(&corners, color);
282    }
283
284    /// Appends the twelve edges joining eight corners in [`frustum_corners`]'
285    /// order.
286    ///
287    /// What [`aabb`](Self::aabb) and [`frustum`](Self::frustum) share: a box and
288    /// a view volume differ in where their corners come from and in nothing
289    /// else.
290    pub fn box_edges(&mut self, corners: &[Vec3; 8], color: [f32; 4]) {
291        for (from, to) in BOX_EDGES {
292            self.line(corners[from], corners[to], color);
293        }
294    }
295
296    /// Appends three great circles of `radius` about `centre`, one in each
297    /// coordinate plane, each of [`SPHERE_SEGMENTS`] segments.
298    ///
299    /// Three circles rather than a mesh of latitudes and longitudes: what a
300    /// debug sphere has to show is where a radius reaches, and three rings show
301    /// it from any angle without filling the frame with lines.
302    pub fn sphere(&mut self, centre: Vec3, radius: f32, color: [f32; 4]) {
303        for plane in 0..3 {
304            let mut previous = None;
305            for step in 0..=SPHERE_SEGMENTS {
306                let angle = std::f32::consts::TAU * (step % SPHERE_SEGMENTS) as f32
307                    / SPHERE_SEGMENTS as f32;
308                let (sin, cos) = angle.sin_cos();
309                let offset = match plane {
310                    0 => Vec3::new(cos, sin, 0.0),
311                    1 => Vec3::new(0.0, cos, sin),
312                    _ => Vec3::new(sin, 0.0, cos),
313                };
314                let point = centre + offset * radius;
315                if let Some(previous) = previous {
316                    self.line(previous, point, color);
317                }
318                previous = Some(point);
319            }
320        }
321    }
322
323    /// How many segments have been appended since the renderer last opened a
324    /// frame.
325    ///
326    /// The observable a check asking "did this system draw anything" wants, and
327    /// what says a primitive helper appended the edges it claims to.
328    #[must_use]
329    pub fn segments(&self) -> usize {
330        self.vertices.len() / 2
331    }
332
333    /// Uploads this frame's segments and clears the buffer.
334    ///
335    /// `frames` is how many frames the renderer keeps in flight, and it sizes
336    /// the rings the first time there is anything to build them for.
337    ///
338    /// **Uploads nothing while [`r_debug_draw`] is off**, and nothing on a frame
339    /// with no segment in it: the slot's count goes to zero, which is what makes
340    /// [`add_pass`](Self::add_pass) record no pass. The CPU buffer is cleared
341    /// either way, so a segment lives exactly the frame it was appended in.
342    ///
343    /// # Errors
344    ///
345    /// [`HalError`] if the pipeline, a ring buffer or a write was refused.
346    /// Nothing is left half-built: a failed first build releases what it
347    /// created and the layer stays unbuilt.
348    pub(crate) fn begin_frame(
349        &mut self,
350        device: &dyn Device,
351        frames: usize,
352        frame: usize,
353        view_proj: Mat4,
354    ) -> Result<(), HalError> {
355        let drawing = Self::enabled() && !self.vertices.is_empty();
356        if !drawing {
357            self.vertices.clear();
358            if let Some(gpu) = self.gpu.as_mut() {
359                gpu.counts[frame] = 0;
360            }
361            return Ok(());
362        }
363        let gpu = match self.gpu.as_mut() {
364            Some(gpu) => gpu,
365            None => self.gpu.insert(Gpu::new(device, frames)?),
366        };
367        gpu.upload(device, frame, &self.vertices, view_proj)?;
368        self.vertices.clear();
369        Ok(())
370    }
371
372    /// Whether the slot `frame` has anything for [`add_pass`](Self::add_pass) to
373    /// record.
374    pub(crate) fn records_pass(&self, frame: usize) -> bool {
375        self.gpu.as_ref().is_some_and(|gpu| gpu.counts[frame] != 0)
376    }
377
378    /// Adds the pass that draws this frame's segments over `target`, tested
379    /// against `depth`.
380    ///
381    /// Records **nothing** where the slot uploaded no segment, which is the
382    /// whole of the layer's off switch — see the module docs.
383    pub(crate) fn add_pass<'a>(
384        &'a self,
385        graph: &mut RenderGraph<'a>,
386        frame: usize,
387        target: ImageId,
388        depth: ImageId,
389    ) {
390        let Some(gpu) = self.gpu.as_ref().filter(|gpu| gpu.counts[frame] != 0) else {
391            return;
392        };
393        let pipeline = gpu.pipeline;
394        let pipeline_layout = gpu.pipeline_layout;
395        let group = gpu.groups[frame];
396        let count = gpu.counts[frame] as u32;
397
398        graph
399            .add_render_pass("debug-draw")
400            // Loaded and stored: the segments composite over the frame the
401            // scene passes drew, in the HDR values they wrote.
402            .color(target, LoadOp::Load, StoreOp::Store, Default::default())
403            // Read-only, on [`crate::grid`]'s terms: attached so the hardware
404            // depth test runs, declared this way so the graph moves it to a
405            // depth-read state rather than one that would let this pass write
406            // it.
407            .depth_read(depth)
408            .execute(move |ctx| {
409                let encoder = ctx.encoder();
410                encoder.bind_graphics_pipeline(pipeline);
411                encoder.bind_group(0, group, &[], pipeline_layout);
412                encoder.draw(0..count, 0..1);
413            });
414    }
415
416    /// The most passes this layer adds to one frame.
417    ///
418    /// The most rather than the count: a frame with nothing appended adds none.
419    /// What a caller sizing [`PassTimers`](crate::timing::PassTimers) adds up.
420    ///
421    /// [`ForwardRenderer::add_passes`](crate::ForwardRenderer::add_passes) is
422    /// what records it.
423    pub const MAX_PASSES: u32 = 1;
424
425    /// Releases everything, in dependency order. The device must be idle.
426    ///
427    /// A layer nobody drew through has nothing to release.
428    pub(crate) fn destroy(self, device: &dyn Device) {
429        if let Some(gpu) = self.gpu {
430            gpu.destroy(device);
431        }
432    }
433}
434
435impl Gpu {
436    /// Builds the pipeline and one ring per frame in flight.
437    fn new(device: &dyn Device, frames: usize) -> Result<Self, HalError> {
438        let mut rollback = Rollback::default();
439        match Self::build(device, frames, &mut rollback) {
440            Ok(gpu) => Ok(gpu),
441            Err(error) => {
442                rollback.run(device);
443                Err(error)
444            }
445        }
446    }
447
448    /// The body of [`Gpu::new`], recording what it has created into `rollback`
449    /// as it goes.
450    fn build(
451        device: &dyn Device,
452        frames: usize,
453        rollback: &mut Rollback,
454    ) -> Result<Self, HalError> {
455        // Both `VERTEX`, and declared in binding order — see
456        // `crcbl_shaders::declaration_order`, and [`crate::ui_pass`], whose
457        // storage buffer and constant block sit at the same two stages.
458        let entries = [
459            BindGroupLayoutEntry {
460                binding: 0,
461                visibility: ShaderStages::VERTEX,
462                kind: BindingKind::StorageBuffer {
463                    read_only: true,
464                    dynamic: false,
465                    stride: size_of::<DebugVertex>() as u32,
466                },
467                count: 1,
468                flags: BindingFlags::empty(),
469            },
470            BindGroupLayoutEntry {
471                binding: 1,
472                visibility: ShaderStages::VERTEX,
473                kind: BindingKind::UniformBuffer { dynamic: false },
474                count: 1,
475                flags: BindingFlags::empty(),
476            },
477        ];
478        let desc = BindGroupLayoutDesc {
479            label: Some("debug draw"),
480            entries: &entries,
481        };
482        check_portable_storage_buffers(Some("debug draw"), &[&desc])?;
483        let layout = device.create_bind_group_layout(&desc)?;
484        rollback.bind_group_layouts.push(layout);
485
486        let set_layouts = [layout];
487        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
488            label: Some("debug draw"),
489            bind_group_layouts: &set_layouts,
490            // No range at all, for [`crate::ui_pass`]'s reason: the block
491            // arrives through the bind group so there is one code path on every
492            // backend, including the one with no push constants.
493            push_constants: None,
494        })?;
495        rollback.pipeline_layouts.push(pipeline_layout);
496
497        let mut buffers = Vec::with_capacity(frames);
498        let mut capacity = Vec::with_capacity(frames);
499        let mut uniforms = Vec::with_capacity(frames);
500        let mut groups = Vec::with_capacity(frames);
501        for _ in 0..frames {
502            let segments = device.create_buffer(&BufferDesc {
503                label: Some("debug draw segments"),
504                size: INITIAL_RING_BYTES,
505                usage: BufferUsage::STORAGE,
506                memory: MemoryLocation::HostUpload,
507            })?;
508            rollback.buffers.push(segments);
509            let block = device.create_buffer(&BufferDesc {
510                label: Some("debug draw camera"),
511                size: CONSTANTS_SIZE,
512                usage: BufferUsage::UNIFORM,
513                memory: MemoryLocation::HostUpload,
514            })?;
515            rollback.buffers.push(block);
516            let group = device.create_bind_group(&BindGroupDesc {
517                label: Some("debug draw frame"),
518                layout,
519                entries: &frame_entries(segments, block),
520                variable_count: None,
521            })?;
522            rollback.bind_groups.push(group);
523            buffers.push(segments);
524            capacity.push(INITIAL_RING_BYTES);
525            uniforms.push(block);
526            groups.push(group);
527        }
528
529        // Entry points resolved before the module exists, for
530        // [`crate::ui_pass`]'s reason: a manifest that disagreed with the
531        // artifact would otherwise fail inside the descriptor literal, with the
532        // module already created and nothing holding it.
533        let vertex = entry(Stage::Vertex)?;
534        let fragment = entry(Stage::Fragment)?;
535        let module = device.create_shader_module(&ShaderModuleDesc {
536            label: Some(DEBUG_DRAW.source()),
537            spirv: DEBUG_DRAW.spirv(),
538            wgsl: DEBUG_DRAW.wgsl(),
539            msl: DEBUG_DRAW.msl(),
540            // A container per entry point, for the reason [`crate::forward`]'s
541            // mesh module gives.
542            dxil: &DEBUG_DRAW.dxil_containers(),
543        })?;
544        let targets = [ColorTargetState {
545            format: crate::forward::SCENE_COLOR_FORMAT,
546            // Straight alpha, as [`crate::ui_pass`] composites: the shader emits
547            // the colour it was appended with and the blender weighs it.
548            blend: Some(BlendState::alpha()),
549            write_mask: ColorWrites::ALL,
550        }];
551        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
552            label: Some("debug draw"),
553            layout: pipeline_layout,
554            vertex: ShaderEntry {
555                module,
556                entry_point: vertex,
557            },
558            fragment: Some(ShaderEntry {
559                module,
560                entry_point: fragment,
561            }),
562            primitive: PrimitiveState {
563                // Two consecutive vertices are one segment, which is what every
564                // primitive in this module is decomposed into.
565                topology: PrimitiveTopology::LineList,
566                ..PrimitiveState::default()
567            },
568            depth_stencil: Some(DepthStencilState {
569                format: crate::forward::SCENE_DEPTH_FORMAT,
570                // **Tested, never written**, on [`crate::grid`]'s terms: an
571                // overlay is occluded by the geometry in front of it and must
572                // not occlude anything drawn after it.
573                depth_write: false,
574                // `Greater` under this engine's reversed-Z, so a segment exactly
575                // on a surface the scene already drew loses to it.
576                depth_compare: CompareOp::Greater,
577                stencil: None,
578                bias: DepthBias::default(),
579            }),
580            multisample: MultisampleState::default(),
581            color_targets: &targets,
582        });
583        device.destroy_shader_module(module);
584        let pipeline = pipeline?;
585        rollback.pipelines.push(pipeline);
586
587        Ok(Self {
588            layout,
589            pipeline_layout,
590            pipeline,
591            buffers,
592            capacity,
593            uniforms,
594            groups,
595            counts: vec![0; frames],
596        })
597    }
598
599    /// Writes `vertices` and the camera into slot `frame`, growing the ring
600    /// where this frame no longer fits.
601    fn upload(
602        &mut self,
603        device: &dyn Device,
604        frame: usize,
605        vertices: &[DebugVertex],
606        view_proj: Mat4,
607    ) -> Result<(), HalError> {
608        let needed = std::mem::size_of_val(vertices) as u64;
609        if needed > self.capacity[frame] {
610            let size = grown(needed);
611            // Create before destroying, on [`crate::ui_pass`]'s terms: a
612            // creation that fails must not leave a destroyed handle in the
613            // struct for `destroy` to hand back to the device a second time.
614            let fresh = device.create_buffer(&BufferDesc {
615                label: Some("debug draw segments"),
616                size,
617                usage: BufferUsage::STORAGE,
618                memory: MemoryLocation::HostUpload,
619            })?;
620            device.destroy_buffer(std::mem::replace(&mut self.buffers[frame], fresh));
621            self.capacity[frame] = size;
622            let group = device.create_bind_group(&BindGroupDesc {
623                label: Some("debug draw frame"),
624                layout: self.layout,
625                entries: &frame_entries(self.buffers[frame], self.uniforms[frame]),
626                variable_count: None,
627            })?;
628            device.destroy_bind_group(std::mem::replace(&mut self.groups[frame], group));
629        }
630        device.write_buffer(self.buffers[frame], 0, bytemuck::cast_slice(vertices))?;
631        device.write_buffer(
632            self.uniforms[frame],
633            0,
634            bytemuck::cast_slice(&view_proj.to_cols_array()),
635        )?;
636        // Committed only after both writes succeeded, on [`crate::ui_pass`]'s
637        // terms: a count ahead of its bytes is a vertex stage reading past what
638        // was written.
639        self.counts[frame] = vertices.len();
640        Ok(())
641    }
642
643    /// Releases everything, in dependency order.
644    fn destroy(self, device: &dyn Device) {
645        for group in self.groups {
646            device.destroy_bind_group(group);
647        }
648        for buffer in self.buffers {
649            device.destroy_buffer(buffer);
650        }
651        for buffer in self.uniforms {
652            device.destroy_buffer(buffer);
653        }
654        device.destroy_graphics_pipeline(self.pipeline);
655        device.destroy_pipeline_layout(self.pipeline_layout);
656        device.destroy_bind_group_layout(self.layout);
657    }
658}
659
660/// The two entries every frame's group names.
661fn frame_entries(segments: BufferHandle, block: BufferHandle) -> [BindGroupEntry; 2] {
662    [
663        BindGroupEntry {
664            binding: 0,
665            array_index: 0,
666            resource: BindingResource::whole_buffer(segments),
667        },
668        BindGroupEntry {
669            binding: 1,
670            array_index: 0,
671            resource: BindingResource::whole_buffer(block),
672        },
673    ]
674}
675
676/// `debug_draw.slang`'s entry point for `stage`.
677fn entry(stage: Stage) -> Result<&'static str, HalError> {
678    DEBUG_DRAW.entry_point(stage).ok_or_else(|| {
679        HalError::ShaderCompilation(format!(
680            "debug_draw.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V \
681             and its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would \
682             fix"
683        ))
684    })
685}
686
687/// What a partly-built [`Gpu`] has to give back.
688///
689/// [`Gpu::build`] creates a handful of objects with `?` between them and the
690/// seam's `destroy_*` is explicit, so a failure half way through would otherwise
691/// leak everything created before it. [`crate::grid`] carries the same shape for
692/// the same reason.
693#[derive(Default)]
694struct Rollback {
695    buffers: Vec<BufferHandle>,
696    bind_groups: Vec<BindGroupHandle>,
697    bind_group_layouts: Vec<BindGroupLayoutHandle>,
698    pipeline_layouts: Vec<PipelineLayoutHandle>,
699    pipelines: Vec<GraphicsPipelineHandle>,
700}
701
702impl Rollback {
703    /// Releases everything recorded, in dependency order.
704    fn run(self, device: &dyn Device) {
705        for group in self.bind_groups {
706            device.destroy_bind_group(group);
707        }
708        for buffer in self.buffers {
709            device.destroy_buffer(buffer);
710        }
711        for pipeline in self.pipelines {
712            device.destroy_graphics_pipeline(pipeline);
713        }
714        for layout in self.pipeline_layouts {
715            device.destroy_pipeline_layout(layout);
716        }
717        for layout in self.bind_group_layouts {
718            device.destroy_bind_group_layout(layout);
719        }
720    }
721}
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726    use std::collections::BTreeSet;
727
728    /// Eight corners no two of which are near each other, so a position in the
729    /// appended buffer identifies the corner it came from.
730    fn marked_corners() -> [Vec3; 8] {
731        let mut corners = [Vec3::ZERO; 8];
732        for (corner, out) in corners.iter_mut().enumerate() {
733            let [x, y, z] = corner_signs(corner);
734            *out = Vec3::new(
735                if x { 10.0 } else { -10.0 },
736                if y { 20.0 } else { -20.0 },
737                if z { 30.0 } else { -30.0 },
738            );
739        }
740        corners
741    }
742
743    /// Every appended segment as the pair of `corners` indices it joins, lowest
744    /// first.
745    ///
746    /// Panics rather than skipping when an endpoint is not one of `corners`: a
747    /// segment this could not place is the failure the caller is asking about,
748    /// and dropping it would make the set look right by being smaller.
749    fn joined(draw: &DebugDraw, corners: &[Vec3; 8]) -> BTreeSet<(usize, usize)> {
750        let index = |vertex: &DebugVertex| {
751            let at = Vec3::new(vertex.position[0], vertex.position[1], vertex.position[2]);
752            corners
753                .iter()
754                .position(|corner| (*corner - at).length() < 1.0e-4)
755                .unwrap_or_else(|| panic!("{at:?} is not one of the corners"))
756        };
757        draw.vertices
758            .as_chunks::<2>()
759            .0
760            .iter()
761            .map(|pair| {
762                let (from, to) = (index(&pair[0]), index(&pair[1]));
763                (from.min(to), from.max(to))
764            })
765            .collect()
766    }
767
768    /// The four corners of the face of a box that takes `end` on `axis`, and the
769    /// four edges around it.
770    fn face_edges(axis: usize, end: bool) -> BTreeSet<(usize, usize)> {
771        let on_face: Vec<usize> = (0..8)
772            .filter(|corner| corner_signs(*corner)[axis] == end)
773            .collect();
774        let mut edges = BTreeSet::new();
775        for &from in &on_face {
776            for &to in &on_face {
777                // One bit apart is one edge; the two corners diagonally across
778                // the face differ in two.
779                if from < to && (from ^ to).count_ones() == 1 {
780                    edges.insert((from, to));
781                }
782            }
783        }
784        edges
785    }
786
787    /// **A line is its two endpoints, in the colour it was appended with.**
788    #[test]
789    fn a_line_is_two_endpoints_in_the_colour_it_was_appended_with() {
790        let mut draw = DebugDraw::default();
791        draw.line(
792            Vec3::new(1.0, 2.0, 3.0),
793            Vec3::new(4.0, 5.0, 6.0),
794            [0.25, 0.5, 0.75, 1.0],
795        );
796        assert_eq!(draw.segments(), 1);
797        assert_eq!(draw.vertices[0].position, [1.0, 2.0, 3.0, 1.0]);
798        assert_eq!(draw.vertices[1].position, [4.0, 5.0, 6.0, 1.0]);
799        for vertex in &draw.vertices {
800            assert_eq!(vertex.color, [0.25, 0.5, 0.75, 1.0]);
801        }
802    }
803
804    /// **A box is twelve edges, and they are exactly the pairs of corners that
805    /// differ on one axis** — so the six faces are all closed.
806    ///
807    /// Twelve *and* which twelve: a helper that appended the same edge twice, or
808    /// joined the two corners of a diagonal, would satisfy a count.
809    #[test]
810    fn a_box_is_the_twelve_edges_that_close_its_six_faces() {
811        let corners = marked_corners();
812        let mut draw = DebugDraw::default();
813        draw.box_edges(&corners, [1.0; 4]);
814
815        assert_eq!(draw.segments(), BOX_EDGES.len());
816        let drawn = joined(&draw, &corners);
817        assert_eq!(
818            drawn.len(),
819            BOX_EDGES.len(),
820            "an edge was appended twice: {drawn:?}"
821        );
822        for axis in 0..3 {
823            for end in [false, true] {
824                let face = face_edges(axis, end);
825                assert_eq!(face.len(), 4, "a face of a box has four edges");
826                assert!(
827                    face.is_subset(&drawn),
828                    "the face at axis {axis} end {end} is not closed: {face:?} against {drawn:?}"
829                );
830            }
831        }
832    }
833
834    /// **An axis-aligned box's corners are its two extremes in every
835    /// combination**, which is what makes [`DebugDraw::aabb`] the box a caller
836    /// asked for rather than one of the right shape somewhere else.
837    #[test]
838    fn an_aabb_spans_the_two_extremes_it_was_given() {
839        let (min, max) = (Vec3::new(-1.0, 2.0, -3.0), Vec3::new(4.0, 5.0, 6.0));
840        let mut draw = DebugDraw::default();
841        draw.aabb(min, max, [1.0; 4]);
842        assert_eq!(draw.segments(), BOX_EDGES.len());
843        for vertex in &draw.vertices {
844            let at = Vec3::new(vertex.position[0], vertex.position[1], vertex.position[2]);
845            for axis in 0..3 {
846                assert!(
847                    at[axis] == min[axis] || at[axis] == max[axis],
848                    "{at:?} is off the box spanning {min:?}..={max:?}"
849                );
850            }
851        }
852        assert!(
853            draw.vertices
854                .iter()
855                .any(|vertex| vertex.position[0] == min.x),
856            "no endpoint reached the low x face"
857        );
858        assert!(
859            draw.vertices
860                .iter()
861                .any(|vertex| vertex.position[0] == max.x),
862            "no endpoint reached the high x face"
863        );
864    }
865
866    /// **A frustum is the world-space box its view-projection maps onto
867    /// normalised device coordinates**, corner for corner.
868    ///
869    /// The matrix here is a scale and a translate chosen so the answer is
870    /// arithmetic rather than a second implementation of the unprojection: the
871    /// world box `[-2,2] × [-3,3] × [1,5]` maps onto `x,y ∈ [-1,1]` and the
872    /// engine's reversed-Z `z ∈ [0,1]`, with the near plane — `z = 1` — at
873    /// `world z = 1`.
874    #[test]
875    fn a_frustum_is_the_world_box_its_view_projection_maps_onto_clip_space() {
876        let view_proj = Mat4::from_translation(Vec3::new(0.0, 0.0, 1.25))
877            * Mat4::from_scale(Vec3::new(0.5, 1.0 / 3.0, -0.25));
878        let corners = frustum_corners(view_proj).expect("a finite view volume has corners");
879        for (corner, at) in corners.iter().enumerate() {
880            let [x, y, z] = corner_signs(corner);
881            let expected = Vec3::new(
882                if x { 2.0 } else { -2.0 },
883                if y { 3.0 } else { -3.0 },
884                // The `z` bit is the near plane under reversed-Z, which this
885                // matrix puts at `world z = 1`; the far end is at `5`.
886                if z { 1.0 } else { 5.0 },
887            );
888            assert!(
889                (*at - expected).length() < 1.0e-4,
890                "corner {corner} came back at {at:?} rather than {expected:?}"
891            );
892        }
893
894        let mut draw = DebugDraw::default();
895        draw.frustum(view_proj, [1.0; 4]);
896        assert_eq!(draw.segments(), BOX_EDGES.len());
897        let drawn = joined(&draw, &corners);
898        for axis in 0..3 {
899            for end in [false, true] {
900                assert!(
901                    face_edges(axis, end).is_subset(&drawn),
902                    "the frustum's face at axis {axis} end {end} is not closed"
903                );
904            }
905        }
906    }
907
908    /// **The engine's own camera has no drawable frustum, and it is refused
909    /// rather than drawn.**
910    ///
911    /// [`crate::Projection`]'s perspective is an infinite reversed-Z one — its
912    /// far plane is degenerate on purpose — so the far corners unproject to
913    /// infinity. A caller that appended them would see nothing and have nothing
914    /// to read.
915    #[test]
916    fn a_view_volume_with_no_finite_corners_is_refused() {
917        let camera = crate::Camera::default();
918        let view_proj = camera.view_projection(16.0 / 9.0);
919        assert!(
920            frustum_corners(view_proj).is_none(),
921            "an infinite reversed-Z projection has no far corners to draw"
922        );
923
924        let mut draw = DebugDraw::default();
925        draw.frustum(view_proj, [1.0; 4]);
926        assert_eq!(
927            draw.segments(),
928            0,
929            "a frustum with no finite corners must append nothing"
930        );
931    }
932
933    /// **A sphere is three closed great circles at the radius it was given.**
934    ///
935    /// Every endpoint at the radius is the claim a segment count cannot make: a
936    /// helper that stepped the angle wrongly, or scaled one ring, draws the
937    /// right number of segments in the wrong place.
938    #[test]
939    fn a_sphere_is_three_closed_great_circles_at_its_radius() {
940        let (centre, radius) = (Vec3::new(1.0, -2.0, 3.0), 4.0);
941        let mut draw = DebugDraw::default();
942        draw.sphere(centre, radius, [1.0; 4]);
943        assert_eq!(draw.segments(), 3 * SPHERE_SEGMENTS);
944        for vertex in &draw.vertices {
945            let at = Vec3::new(vertex.position[0], vertex.position[1], vertex.position[2]);
946            assert!(
947                ((at - centre).length() - radius).abs() < 1.0e-3,
948                "{at:?} is {} from the centre, not {radius}",
949                (at - centre).length()
950            );
951        }
952        // Each ring closes: its last endpoint is its first. Written as a
953        // per-ring check rather than over the whole buffer, because three rings
954        // that all ended where the *first* one started would satisfy anything
955        // looser.
956        for ring in 0..3 {
957            let first = ring * SPHERE_SEGMENTS * 2;
958            let last = first + SPHERE_SEGMENTS * 2 - 1;
959            assert_eq!(
960                draw.vertices[first].position, draw.vertices[last].position,
961                "ring {ring} does not close"
962            );
963        }
964    }
965}