Skip to main content

roxlap_gpu/
scene.rs

1//! GPU.5 — multi-grid scene upload + shared storage layout.
2//!
3//! Concatenates every chunk of every grid into one set of storage
4//! buffers + a per-grid offsets table. Each grid keeps its own
5//! `vsid`, `chunks_dims`, `origin_chunk`, and runtime transform;
6//! the shader iterates grids 0..grid_count, transforms the world
7//! camera into each grid's local frame, runs that grid's outer-DDA
8//! over chunks, and tracks the closest hit across all grids.
9//!
10//! Why concatenate rather than one bind group per grid? wgpu's
11//! `MAX_BIND_GROUPS` default is 4; demos with 10+ grids
12//! (`roxlap-scene-demo` has ground + ship + 10 marker pillars =
13//! 12) need a single bind-group layout that scales.
14
15#![allow(
16    clippy::cast_sign_loss,
17    clippy::cast_lossless,
18    clippy::cast_possible_truncation,
19    clippy::cast_possible_wrap,
20    clippy::doc_markdown,
21    clippy::missing_panics_doc,
22    clippy::needless_range_loop,
23    clippy::pub_underscore_fields
24)]
25
26use bytemuck::Zeroable;
27use wgpu::util::DeviceExt;
28
29use crate::decompress::{gpu_mip_count, occ_words_per_column_for_mip, ChunkUpload};
30use crate::grid::GridUpload;
31
32/// GPU.11 — max mip levels the per-slot layout reserves room for in
33/// [`GridStaticMeta`]'s relative-offset tables. Matches
34/// [`crate::decompress::GPU_MAX_MIPS`]; the shader's `array<u32, N>`
35/// must use the same N.
36pub const MAX_GPU_MIPS: usize = 6;
37
38/// GPU.11 — per-slot occupancy/color-offset strides + per-mip
39/// within-slot relative offsets for a grid of side `vsid`. All
40/// chunks of a grid share these (uniform mip count by
41/// [`gpu_mip_count`]). `colors` keep their fixed
42/// [`COLORS_PER_CHUNK_WORDS`] stride; each mip's colours are
43/// concatenated within that block and indexed by the chunk's own
44/// (absolute) `color_offsets`.
45#[derive(Debug, Clone, Copy)]
46pub struct MipLayout {
47    /// Number of mip levels stored per slot = [`gpu_mip_count`]`(vsid)`,
48    /// always `1..=`[`MAX_GPU_MIPS`].
49    pub mip_count: u32,
50    /// Occupancy u32 words per chunk slot, summed over all mips — each
51    /// mip stores its textured **and** solid bitmap back-to-back, so
52    /// this is `Σ 2·(vsid>>m)²·occ_words_per_column_for_mip(m)`.
53    pub occ_words_per_slot: u32,
54    /// `color_offsets` u32 words per chunk slot, summed over all mips
55    /// (`Σ (vsid>>m)² + 1` — each mip keeps its own `cols + 1` prefix
56    /// table).
57    pub offsets_words_per_slot: u32,
58    /// Within-slot u32 offset where mip `m`'s occupancy starts.
59    pub mip_occ_rel: [u32; MAX_GPU_MIPS],
60    /// Within-slot u32 offset where mip `m`'s color_offsets start.
61    pub mip_coff_rel: [u32; MAX_GPU_MIPS],
62}
63
64impl MipLayout {
65    /// Compute the per-slot layout for a grid whose chunks are
66    /// `vsid × vsid × CHUNK_Z` voxels. Deterministic in `vsid`, so the
67    /// upload, [`GpuSceneResident::refresh_chunk`], and the shader all
68    /// derive identical strides independently.
69    #[must_use]
70    pub fn for_vsid(vsid: u32) -> Self {
71        let mip_count = gpu_mip_count(vsid);
72        let mut mip_occ_rel = [0u32; MAX_GPU_MIPS];
73        let mut mip_coff_rel = [0u32; MAX_GPU_MIPS];
74        let mut occ_acc = 0u32;
75        let mut coff_acc = 0u32;
76        for m in 0..mip_count {
77            mip_occ_rel[m as usize] = occ_acc;
78            mip_coff_rel[m as usize] = coff_acc;
79            let vsid_m = vsid >> m;
80            let cols = vsid_m * vsid_m;
81            // Each mip stores TWO bitmaps back-to-back: the textured
82            // occupancy then the solid occupancy (cliff-face fix). The
83            // shader reads solid at `tex_base + cols*occ_words_per_col`.
84            occ_acc += 2 * cols * occ_words_per_column_for_mip(m);
85            coff_acc += cols + 1;
86        }
87        Self {
88            mip_count,
89            occ_words_per_slot: occ_acc,
90            offsets_words_per_slot: coff_acc,
91            mip_occ_rel,
92            mip_coff_rel,
93        }
94    }
95}
96
97/// Per-chunk colour-slot stride, in u32 words (256 KiB). Each
98/// chunk's colour data lives at `meta_idx * COLORS_PER_CHUNK_WORDS`
99/// within its grid's colours range. Fixed-stride layout means
100/// every slot — present or absent at upload time — has the same
101/// capacity, so [`GpuSceneResident::refresh_chunk`] can always
102/// write new colour data into the slot when a chunk arrives via
103/// streaming or is re-baked.
104///
105/// 65536 u32s = 256 KiB. Scene-demo's densest ground-hills chunks
106/// run ~36 k colour entries (~144 KiB) — multiple textured voxels
107/// per column at slopes/cliffs; 256 KiB gives ~1.8× headroom.
108/// Memory cost on the demo's 32×32×1 static grid: 1024 slots ×
109/// 256 KiB = 256 MiB colours (~830 MiB resident scene total).
110/// Chunks past the cap truncate with a stderr warn; GPU.7
111/// sliding-window storage removes the cap entirely.
112pub const COLORS_PER_CHUNK_WORDS: u32 = 65536;
113
114/// Number of separate storage bindings the concatenated occupancy
115/// buffer is split ("paged") across. A single storage binding may
116/// not exceed the device's `max_storage_buffer_binding_size` — on
117/// strict drivers that's a hard 128 MiB (lavapipe), which the
118/// streaming demo's occupancy already reaches. Splitting into pages
119/// keeps every binding under the limit while preserving a single
120/// global word index in the shader (each page is a whole number of
121/// chunk slots, so no slot ever straddles a page boundary).
122///
123/// On GPUs with multi-GiB binding limits (NVK, native Vulkan) the
124/// whole buffer fits in page 0, the other bindings get a 1-word
125/// dummy, and the shader's page select is a single perfectly-
126/// predicted uniform branch → zero hot-loop cost. 4 pages covers
127/// 512 MiB of occupancy even on a 128 MiB-per-binding device.
128pub const MAX_OCC_PAGES: usize = 4;
129
130/// Per-grid runtime transform — voxlap-style (world → grid-local).
131/// `rotation` is column-major and encodes the inverse rotation
132/// applied to the world camera basis before passing it to that
133/// grid's marcher. Identity for the ground; non-trivial for the
134/// rotating ship.
135#[derive(Debug, Clone, Copy)]
136pub struct GridRuntimeTransform {
137    /// Grid-local position of the world origin = `-rotation⁻¹ ·
138    /// grid.position` for a `GridTransform { position, rotation }`.
139    /// The host computes this once per frame.
140    pub grid_origin_world: [f64; 3],
141    /// 3×3 inverse rotation (column-major).
142    pub world_to_grid_rotation: [[f32; 3]; 3],
143}
144
145impl Default for GridRuntimeTransform {
146    fn default() -> Self {
147        Self {
148            grid_origin_world: [0.0, 0.0, 0.0],
149            world_to_grid_rotation: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
150        }
151    }
152}
153
154/// CPU-side aggregation of every grid in a scene. Built once at
155/// startup; per-grid transforms are recomputed each frame and
156/// passed to `render_scene` separately.
157pub struct SceneUpload {
158    /// One [`GridUpload`] per scene grid, in the order the shader
159    /// iterates them; index = the `scene_idx` handed to
160    /// [`GpuSceneResident::refresh_chunk`] / `evict_chunk` and the
161    /// per-grid camera slot.
162    pub grids: Vec<GridUpload>,
163}
164
165impl SceneUpload {
166    /// Number of grids, saturated into `u32` (the type the shader's
167    /// `grid_count` uniform uses).
168    #[must_use]
169    pub fn grid_count(&self) -> u32 {
170        u32::try_from(self.grids.len()).unwrap_or(u32::MAX)
171    }
172}
173
174/// Per-grid static metadata: offsets into the concatenated storage
175/// buffers + the grid's slot-pool dimensions. Uploaded once.
176///
177/// GPU.7 changes: `chunks_dims` and `origin_chunk` were dropped.
178/// The shader uses modular slot indexing
179/// (`chunk_idx & (pool_dims - 1)`) and verifies slot identity via
180/// `slot_chunk_idx[slot]`, so the upload-time bbox is no longer
181/// relevant to the shader.
182#[repr(C)]
183#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable, Debug)]
184pub struct GridStaticMeta {
185    /// `occupancy` u32-word offset where this grid's data starts.
186    pub occupancy_offset: u32,
187    /// `all_color_offsets` (binding 2) u32-word offset where this
188    /// grid's per-slot colour-offset tables start; slot `meta_id`'s
189    /// window is `offsets_words_per_slot` words from
190    /// `color_offsets_offset + meta_id * offsets_words_per_slot`.
191    pub color_offsets_offset: u32,
192    /// `all_colors` (binding 3) u32-word offset where this grid's
193    /// packed voxel colours start (per-slot blocks of the grid's
194    /// colour stride).
195    pub colors_offset: u32,
196    /// `all_chunk_colors_base` (binding 4) u32-word offset of this
197    /// grid's per-slot table mapping `meta_id` → the slot's colour
198    /// base (in words, relative to `colors_offset`).
199    pub chunk_colors_base_offset: u32,
200    /// `all_chunk_occupancy` (binding 5) u32-word offset of this
201    /// grid's chunk-occupancy bitmap: bit `slot_idx & 31` of word
202    /// `slot_idx >> 5` is set iff the slot holds a non-empty chunk —
203    /// the outer DDA's whole-chunk skip test.
204    pub chunk_occupancy_offset: u32,
205    /// New in GPU.7: u32-word offset where this grid's
206    /// `slot_chunk_idx` array starts (one `vec3<i32>` per slot,
207    /// i.e. 3 u32 words each, plus 1 padding word for std430).
208    pub slot_chunk_idx_offset: u32,
209    /// Chunk XY extent in voxels (typically 128); the chunk's Z extent
210    /// is the fixed `CHUNK_Z = 256`.
211    pub vsid: u32,
212    /// Slot count in the modular pool
213    /// (`pool_dims.x · pool_dims.y · pool_dims.z`).
214    pub total_slots: u32,
215    /// GPU.7 slot-pool dimensions (each a power of 2). Chunk
216    /// `(chx, chy, chz)` lives in slot
217    /// `(chx & (pool_dims.x - 1), chy & …, chz & …)`.
218    pub pool_dims: [u32; 3],
219    /// std430 padding; always 0.
220    pub _pad0: u32,
221    /// GPU.11 — per-slot occupancy stride (sum over all mips).
222    /// `meta_id`'s occupancy slab starts at
223    /// `occupancy_offset + meta_id * occ_words_per_slot`.
224    pub occ_words_per_slot: u32,
225    /// GPU.11 — per-slot color_offsets stride (sum over all mips).
226    pub offsets_words_per_slot: u32,
227    /// GPU.11 — number of mip levels stored per slot.
228    pub mip_count: u32,
229    /// std430 padding; always 0.
230    pub _pad1: u32,
231    /// GPU.11 — within-slot u32 offset where mip `m`'s occupancy
232    /// starts. `mip_occ_rel[0] == 0` so mip-0 reads are unchanged.
233    pub mip_occ_rel: [u32; MAX_GPU_MIPS],
234    /// GPU.11 — within-slot u32 offset where mip `m`'s color_offsets
235    /// start. `mip_coff_rel[0] == 0`.
236    pub mip_coff_rel: [u32; MAX_GPU_MIPS],
237    /// GPU.13.0 — occupied chunk-AABB (inclusive) in chunk-index space.
238    /// The outer DDA stops once `p_chunk` passes this box along the
239    /// ray's travel direction (no resident chunk can lie ahead). An
240    /// empty grid uses the inverted sentinel (`aabb_min = i32::MAX`,
241    /// `aabb_max = i32::MIN`) so every ray early-outs immediately.
242    /// Maintained live: [`GpuSceneResident::refresh_chunk`] /
243    /// [`GpuSceneResident::evict_chunk`] recompute + re-upload it.
244    pub aabb_min: [i32; 3],
245    /// std430 `vec3<i32>` padding; always 0.
246    pub _pad2: i32,
247    /// Inclusive upper corner of the occupied chunk-AABB (chunk-index
248    /// space); `i32::MIN` sentinel when the grid holds no chunks. See
249    /// [`Self::aabb_min`].
250    pub aabb_max: [i32; 3],
251    /// std430 `vec3<i32>` padding; always 0.
252    pub _pad3: i32,
253}
254
255/// Sentinel chunk_idx written into empty slot_chunk_idx entries.
256/// Real chunk indices never use `i32::MIN`, so the shader can
257/// distinguish empty slots from collisions via a single equality
258/// check.
259pub const SLOT_EMPTY_SENTINEL: [i32; 3] = [i32::MIN, i32::MIN, i32::MIN];
260
261/// GPU-resident storage for an entire scene's grids.
262pub struct GpuSceneResident {
263    /// Number of grids uploaded (= `SceneUpload::grid_count()`); the
264    /// shader's grid loop bound and the length of [`Self::static_meta`].
265    pub grid_count: u32,
266    /// Concatenated per-slot occupancy, split into up to
267    /// [`MAX_OCC_PAGES`] storage bindings so no single binding
268    /// exceeds the device's `max_storage_buffer_binding_size`. The
269    /// vec is always exactly `MAX_OCC_PAGES` long — pages past
270    /// `occupancy_num_pages` are 1-word dummies kept only so the
271    /// bind group has a buffer for every layout entry. Page p holds
272    /// the global word range `[p*occupancy_page_words,
273    /// (p+1)*occupancy_page_words)`; `occupancy_page_words` is a
274    /// whole number of chunk slots so no slot straddles a boundary.
275    pub occupancy_pages: Vec<wgpu::Buffer>,
276    /// Words per occupancy page (a multiple of `occ_words_per_slot`).
277    pub occupancy_page_words: u32,
278    /// Number of real (non-dummy) pages in `occupancy_pages`.
279    pub occupancy_num_pages: u32,
280    /// Binding 2 — concatenated per-slot `color_offsets` prefix tables
281    /// (all grids, all mips). Grid `g`'s region starts at
282    /// `static_meta[g].color_offsets_offset` words.
283    pub all_color_offsets: wgpu::Buffer,
284    /// Binding 3 — concatenated packed voxel colours (all grids).
285    /// Each word is the voxlap wire format the shader unpacks: blue in
286    /// bits 0-7, green 8-15, red 16-23, and a **brightness** byte (not
287    /// alpha) in bits 24-31 with `0x80` = neutral.
288    pub all_colors: wgpu::Buffer,
289    /// Binding 4 — per-slot colour base table: word `meta_id` of grid
290    /// `g`'s region holds the slot's colour start (in words, relative
291    /// to `static_meta[g].colors_offset`) = `meta_id × colour stride`.
292    pub all_chunk_colors_base: wgpu::Buffer,
293    /// Binding 5 — per-grid chunk-occupancy bitmaps (one bit per pool
294    /// slot: set iff the slot holds a non-empty chunk). The outer DDA
295    /// tests it to skip whole 128×128×256 chunks per step.
296    pub all_chunk_occupancy: wgpu::Buffer,
297    /// GPU.7 — per-slot chunk_idx for identity verification in the
298    /// shader. Stored as `vec3<i32>` with std430 16-byte stride
299    /// (each entry is `[i32; 4]` on the host: x, y, z, _pad).
300    pub all_slot_chunk_idx: wgpu::Buffer,
301    /// Binding 6 — the [`GridStaticMeta`] array, one element per grid.
302    /// Mostly upload-time constant; the live chunk-AABB fields are
303    /// patched in place on `refresh_chunk` / `evict_chunk`.
304    pub grid_static_meta: wgpu::Buffer,
305    /// Total bytes allocated across all the resident storage buffers,
306    /// for VRAM accounting (see [`Self::resident_bytes`]).
307    pub total_bytes: u64,
308    /// Cached static metadata for the host's frame-loop work.
309    pub static_meta: Vec<GridStaticMeta>,
310    /// CPU shadow of the per-grid chunk-occupancy bitmap. Each entry
311    /// is the u32 word at `chunk_occupancy_offset + (mi >> 5)`.
312    /// `refresh_chunk` / `evict_chunk` flip the right bit + write
313    /// the affected word back to the GPU.
314    pub(crate) chunk_occupancy_shadow: Vec<Vec<u32>>,
315    /// CPU shadow of `slot_chunk_idx`. Indexed `[scene_idx][slot]`
316    /// → `[i32; 4]` (vec3 + pad). Host uses this to detect "slot is
317    /// holding a different chunk than expected" + as the eviction
318    /// origin.
319    pub(crate) slot_chunk_idx_shadow: Vec<Vec<[i32; 4]>>,
320    /// Per-grid colour stride in u32 words (the adaptive
321    /// [`COLORS_PER_CHUNK_WORDS`]-or-larger value chosen at upload to
322    /// fit the grid's densest chunk). `refresh_chunk` reads it so a
323    /// streamed re-upload addresses colours with the same stride the
324    /// initial upload used.
325    pub(crate) colors_stride_shadow: Vec<u32>,
326    /// PF.12.c — CPU mirror of each installed slot's per-mip
327    /// `color_offsets` tables (`offsets_words_per_slot` words, the exact
328    /// content of the GPU window). [`Self::refresh_chunk_partial`] reads
329    /// it to (a) place a dirty column's colours at the resident offset
330    /// and (b) verify the column's colour COUNT is unchanged — a count
331    /// change reflows the packed colour block and forces the full-path
332    /// fallback. ~87 KB per 128² chunk; dropped on evict.
333    pub(crate) color_offsets_shadow: Vec<std::collections::HashMap<usize, Vec<u32>>>,
334}
335
336impl GpuSceneResident {
337    /// Pack + upload `info`. Each grid is uploaded as a contiguous
338    /// slab inside the shared storage buffers; per-grid offsets
339    /// live in `grid_static_meta`. The grid count is bounded only by
340    /// the device's storage-buffer limits (per-grid cameras + metadata
341    /// are runtime-sized storage arrays, not a fixed shader array).
342    pub fn upload(device: &wgpu::Device, info: &SceneUpload) -> Self {
343        let grid_count = info.grid_count();
344
345        let mut all_occupancy: Vec<u32> = Vec::new();
346        let mut all_color_offsets: Vec<u32> = Vec::new();
347        let mut all_colors: Vec<u32> = Vec::new();
348        let mut all_chunk_colors_base: Vec<u32> = Vec::new();
349        let mut all_chunk_occupancy: Vec<u32> = Vec::new();
350        let mut all_slot_chunk_idx: Vec<i32> = Vec::new();
351        let mut static_meta: Vec<GridStaticMeta> = Vec::with_capacity(info.grids.len());
352        let mut chunk_occupancy_shadow: Vec<Vec<u32>> = Vec::with_capacity(info.grids.len());
353        let mut slot_chunk_idx_shadow: Vec<Vec<[i32; 4]>> = Vec::with_capacity(info.grids.len());
354        let mut color_offsets_shadow: Vec<std::collections::HashMap<usize, Vec<u32>>> =
355            Vec::with_capacity(info.grids.len());
356        // Per-grid colour stride (words/slot) — adaptive to the grid's
357        // densest chunk (see the in-loop derivation). `refresh_chunk`
358        // reads it back so streamed re-uploads use the same stride.
359        let mut grid_colors_strides: Vec<u32> = Vec::with_capacity(info.grids.len());
360
361        for grid in &info.grids {
362            let vsid = grid.vsid;
363            // GPU.11 — per-slot strides span the whole mip ladder.
364            let layout = MipLayout::for_vsid(vsid);
365            let occ_words_per_slot = layout.occ_words_per_slot as usize;
366            let offsets_words_per_slot = layout.offsets_words_per_slot as usize;
367            // Per-slot colour stride. The fixed-stride layout gives every
368            // slot — present or not — the same capacity, so streaming /
369            // re-bake can write a fresh chunk's colours into any slot.
370            // [`COLORS_PER_CHUNK_WORDS`] is sized for sparse terrain
371            // chunks (~36 k colours); a *fully dense* chunk (the cave
372            // demo's single 128×128×256 chunk carries ~207 k colours
373            // across its mip ladder) needs more, or its colours truncate
374            // and the chunk's high-`y` columns render black. Grow the
375            // stride to the grid's densest chunk, floored at the default
376            // so denser chunks that stream in later still fit the common
377            // case. Per-grid: a sparse grid keeps the small stride; only
378            // a grid that actually holds dense chunks pays for the
379            // bigger one.
380            let max_chunk_colors = grid
381                .chunks
382                .iter()
383                .map(|(_, c)| c.mips.iter().map(|m| m.colors.len()).sum::<usize>())
384                .max()
385                .unwrap_or(0);
386            let colors_stride = (COLORS_PER_CHUNK_WORDS as usize).max(max_chunk_colors);
387            grid_colors_strides.push(colors_stride as u32);
388
389            // Validate pool_dims are powers of 2 — required for the
390            // shader's `chunk_idx & (pool_dims - 1)` modular slot
391            // indexing.
392            assert!(
393                grid.pool_dims[0].is_power_of_two()
394                    && grid.pool_dims[1].is_power_of_two()
395                    && grid.pool_dims[2].is_power_of_two(),
396                "scene grid: pool_dims {:?} must all be powers of 2",
397                grid.pool_dims,
398            );
399            let pool_x = grid.pool_dims[0] as usize;
400            let pool_y = grid.pool_dims[1] as usize;
401            let pool_z = grid.pool_dims[2] as usize;
402            let total_slots = pool_x * pool_y * pool_z;
403
404            let mut grid_occupancy = vec![0u32; total_slots * occ_words_per_slot];
405            let mut grid_color_offsets = vec![0u32; total_slots * offsets_words_per_slot];
406            let mut grid_colors = vec![0u32; total_slots * colors_stride];
407            let mut grid_chunk_colors_base = vec![0u32; total_slots];
408            for i in 0..total_slots {
409                grid_chunk_colors_base[i] = (i * colors_stride) as u32;
410            }
411            let mut grid_chunk_occupancy = vec![0u32; total_slots.div_ceil(32)];
412            // slot_chunk_idx: vec3<i32> per slot, std430 stride = 16
413            // bytes (4 u32 words: x, y, z, _pad). Initialise every
414            // slot to the empty sentinel; populated slots overwrite
415            // with the actual chunk_idx below.
416            let mut grid_offsets_shadow: std::collections::HashMap<usize, Vec<u32>> =
417                std::collections::HashMap::new();
418            let mut grid_slot_chunk_idx: Vec<[i32; 4]> = Vec::with_capacity(total_slots);
419            for _ in 0..total_slots {
420                grid_slot_chunk_idx.push([
421                    SLOT_EMPTY_SENTINEL[0],
422                    SLOT_EMPTY_SENTINEL[1],
423                    SLOT_EMPTY_SENTINEL[2],
424                    0,
425                ]);
426            }
427
428            let mask_x = (grid.pool_dims[0] - 1) as i32;
429            let mask_y = (grid.pool_dims[1] - 1) as i32;
430            let mask_z = (grid.pool_dims[2] - 1) as i32;
431            let chunks_per_layer = pool_x * pool_y;
432
433            for (chunk_idx, chunk) in &grid.chunks {
434                assert_eq!(chunk.vsid, vsid, "scene grid: chunk vsid mismatch");
435                let sx = (chunk_idx[0] & mask_x) as usize;
436                let sy = (chunk_idx[1] & mask_y) as usize;
437                let sz = (chunk_idx[2] & mask_z) as usize;
438                let slot_idx = sx + sy * pool_x + sz * chunks_per_layer;
439
440                // GPU.11 — write each mip at its within-slot offset.
441                // occupancy + color_offsets land in per-mip sub-blocks
442                // (mip-0 first, so its data is byte-identical to the
443                // pre-mip layout); colours of every mip concatenate
444                // into the slot's fixed COLORS_PER_CHUNK_WORDS block in
445                // level order, indexed by each chunk's own absolute
446                // `color_offsets`.
447                let occ_start = slot_idx * occ_words_per_slot;
448                let off_start = slot_idx * offsets_words_per_slot;
449                let col_start = slot_idx * colors_stride;
450                let mut color_cursor = 0usize;
451                for (m, mip) in chunk.mips.iter().enumerate() {
452                    let occ_dst = occ_start + layout.mip_occ_rel[m] as usize;
453                    grid_occupancy[occ_dst..occ_dst + mip.occupancy.len()]
454                        .copy_from_slice(&mip.occupancy);
455                    // Solid bitmap immediately follows the textured one.
456                    let solid_dst = occ_dst + mip.occupancy.len();
457                    grid_occupancy[solid_dst..solid_dst + mip.solid_occupancy.len()]
458                        .copy_from_slice(&mip.solid_occupancy);
459                    let coff_dst = off_start + layout.mip_coff_rel[m] as usize;
460                    grid_color_offsets[coff_dst..coff_dst + mip.color_offsets.len()]
461                        .copy_from_slice(&mip.color_offsets);
462
463                    let remaining = colors_stride.saturating_sub(color_cursor);
464                    let n = mip.colors.len().min(remaining);
465                    if n < mip.colors.len() {
466                        eprintln!(
467                            "roxlap-gpu SceneUpload: scene grid chunk {chunk_idx:?} mip {m} \
468                             colours overflow COLORS_PER_CHUNK_WORDS ({colors_stride}); \
469                             truncating",
470                        );
471                    }
472                    grid_colors[col_start + color_cursor..col_start + color_cursor + n]
473                        .copy_from_slice(&mip.colors[..n]);
474                    color_cursor += n;
475                }
476
477                if !chunk.mips[0].colors.is_empty() {
478                    grid_chunk_occupancy[slot_idx >> 5] |= 1u32 << (slot_idx & 31);
479                }
480                grid_slot_chunk_idx[slot_idx] = [chunk_idx[0], chunk_idx[1], chunk_idx[2], 0];
481                // PF.12.c — mirror the slot's color_offsets window.
482                grid_offsets_shadow.insert(
483                    slot_idx,
484                    grid_color_offsets[off_start..off_start + offsets_words_per_slot].to_vec(),
485                );
486            }
487
488            // Slot_chunk_idx storage offset: each entry is 4 u32
489            // words (vec3 padded to 16 bytes in std430).
490            let slot_chunk_idx_offset = u32::try_from(all_slot_chunk_idx.len()).expect("fits");
491            // GPU.13.0 — occupied chunk-AABB for the outer-DDA early-out.
492            let (aabb_min, aabb_max) = aabb_of_slots(&grid_slot_chunk_idx);
493            let meta = GridStaticMeta {
494                occupancy_offset: u32::try_from(all_occupancy.len()).expect("fits"),
495                color_offsets_offset: u32::try_from(all_color_offsets.len()).expect("fits"),
496                colors_offset: u32::try_from(all_colors.len()).expect("fits"),
497                chunk_colors_base_offset: u32::try_from(all_chunk_colors_base.len()).expect("fits"),
498                chunk_occupancy_offset: u32::try_from(all_chunk_occupancy.len()).expect("fits"),
499                slot_chunk_idx_offset,
500                vsid,
501                total_slots: total_slots as u32,
502                pool_dims: grid.pool_dims,
503                _pad0: 0,
504                occ_words_per_slot: layout.occ_words_per_slot,
505                offsets_words_per_slot: layout.offsets_words_per_slot,
506                mip_count: layout.mip_count,
507                _pad1: 0,
508                mip_occ_rel: layout.mip_occ_rel,
509                mip_coff_rel: layout.mip_coff_rel,
510                aabb_min,
511                _pad2: 0,
512                aabb_max,
513                _pad3: 0,
514            };
515
516            chunk_occupancy_shadow.push(grid_chunk_occupancy.clone());
517            slot_chunk_idx_shadow.push(grid_slot_chunk_idx.clone());
518            color_offsets_shadow.push(grid_offsets_shadow);
519
520            all_occupancy.extend_from_slice(&grid_occupancy);
521            all_color_offsets.extend_from_slice(&grid_color_offsets);
522            all_colors.extend_from_slice(&grid_colors);
523            all_chunk_colors_base.extend_from_slice(&grid_chunk_colors_base);
524            all_chunk_occupancy.extend_from_slice(&grid_chunk_occupancy);
525            for entry in &grid_slot_chunk_idx {
526                all_slot_chunk_idx.extend_from_slice(entry);
527            }
528            static_meta.push(meta);
529        }
530
531        // Pad an empty scene's storage buffers — wgpu rejects
532        // zero-size storage bindings.
533        if all_occupancy.is_empty() {
534            all_occupancy.push(0);
535        }
536        if all_color_offsets.is_empty() {
537            all_color_offsets.push(0);
538        }
539        if all_colors.is_empty() {
540            all_colors.push(0);
541        }
542        if all_chunk_colors_base.is_empty() {
543            all_chunk_colors_base.push(0);
544        }
545        if all_chunk_occupancy.is_empty() {
546            all_chunk_occupancy.push(0);
547        }
548        if all_slot_chunk_idx.is_empty() {
549            // 4 zeros = single padded vec3<i32>. wgpu rejects
550            // zero-sized storage bindings.
551            all_slot_chunk_idx.extend_from_slice(&[0; 4]);
552        }
553        if static_meta.is_empty() {
554            static_meta.push(GridStaticMeta::zeroed());
555        }
556
557        let occupancy_bytes = (all_occupancy.len() * 4) as u64;
558        let color_offsets_bytes = (all_color_offsets.len() * 4) as u64;
559        let colors_bytes = (all_colors.len() * 4) as u64;
560        let chunk_colors_base_bytes = (all_chunk_colors_base.len() * 4) as u64;
561        let chunk_occupancy_bytes = (all_chunk_occupancy.len() * 4) as u64;
562        let slot_chunk_idx_bytes = (all_slot_chunk_idx.len() * 4) as u64;
563        let static_meta_bytes = (static_meta.len() * std::mem::size_of::<GridStaticMeta>()) as u64;
564        let total_bytes = occupancy_bytes
565            + color_offsets_bytes
566            + colors_bytes
567            + chunk_colors_base_bytes
568            + chunk_occupancy_bytes
569            + slot_chunk_idx_bytes
570            + static_meta_bytes;
571
572        // Split the concatenated occupancy across storage pages so no
573        // single binding exceeds the device limit. Page size is a
574        // whole number of chunk slots (slot-aligned) so no per-slot
575        // refresh write ever straddles two pages.
576        // GPU.11 — page alignment is now the whole-ladder per-slot
577        // occupancy stride so a slot (all its mips) never straddles a
578        // page boundary.
579        let slot_align_words = info
580            .grids
581            .iter()
582            .map(|g| u64::from(MipLayout::for_vsid(g.vsid).occ_words_per_slot))
583            .max()
584            .unwrap_or(1)
585            .max(1);
586        let (occupancy_pages, occupancy_page_words, occupancy_num_pages) =
587            split_occupancy_pages(device, &all_occupancy, slot_align_words);
588        let all_color_offsets =
589            create_storage(device, "roxlap-gpu scene.color_offsets", &all_color_offsets);
590        let all_colors = create_storage(device, "roxlap-gpu scene.colors", &all_colors);
591        let all_chunk_colors_base = create_storage(
592            device,
593            "roxlap-gpu scene.chunk_colors_base",
594            &all_chunk_colors_base,
595        );
596        let all_chunk_occupancy = create_storage(
597            device,
598            "roxlap-gpu scene.chunk_occupancy",
599            &all_chunk_occupancy,
600        );
601        // GPU.7 slot identity verification buffer. i32 storage.
602        let all_slot_chunk_idx_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
603            label: Some("roxlap-gpu scene.slot_chunk_idx"),
604            contents: bytemuck::cast_slice(&all_slot_chunk_idx),
605            usage: wgpu::BufferUsages::STORAGE
606                | wgpu::BufferUsages::COPY_DST
607                | wgpu::BufferUsages::COPY_SRC,
608        });
609        let grid_static_meta = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
610            label: Some("roxlap-gpu scene.grid_static_meta"),
611            contents: bytemuck::cast_slice(&static_meta),
612            // GPU.13.0 — COPY_DST so the live chunk-AABB can be patched
613            // into a grid's meta on refresh_chunk / evict_chunk.
614            usage: wgpu::BufferUsages::STORAGE
615                | wgpu::BufferUsages::COPY_DST
616                | wgpu::BufferUsages::COPY_SRC,
617        });
618
619        Self {
620            grid_count,
621            occupancy_pages,
622            occupancy_page_words,
623            occupancy_num_pages,
624            all_color_offsets,
625            all_colors,
626            all_chunk_colors_base,
627            all_chunk_occupancy,
628            all_slot_chunk_idx: all_slot_chunk_idx_buf,
629            grid_static_meta,
630            total_bytes,
631            static_meta,
632            chunk_occupancy_shadow,
633            slot_chunk_idx_shadow,
634            color_offsets_shadow,
635            colors_stride_shadow: grid_colors_strides,
636        }
637    }
638
639    /// GPU memory held by the scene's storage buffers, in bytes —
640    /// [`Self::total_bytes`] as computed at upload time (in-place
641    /// refreshes never change it).
642    pub fn resident_bytes(&self) -> u64 {
643        self.total_bytes
644    }
645
646    /// Install or refresh a chunk in its modular pool slot. GPU.7
647    /// generalises GPU.6's in-place refresh: any chunk_idx maps to
648    /// a slot via `chunk_idx & (pool_dims - 1)`. The previous
649    /// occupant (if a different chunk) is silently replaced — the
650    /// host is responsible for guaranteeing that the pool is sized
651    /// large enough that two simultaneously-resident chunks never
652    /// collide on the same slot.
653    pub fn refresh_chunk(
654        &mut self,
655        queue: &wgpu::Queue,
656        scene_idx: usize,
657        chunk_idx: [i32; 3],
658        chunk: &ChunkUpload,
659    ) -> RefreshOutcome {
660        let Some(meta) = self.static_meta.get(scene_idx).copied() else {
661            return RefreshOutcome::SceneIdxOob;
662        };
663        let slot_idx = modular_slot_idx(chunk_idx, meta.pool_dims);
664
665        // GPU.11 — the per-slot strides span the full mip ladder; the
666        // resident's layout was built from the same `MipLayout`.
667        let layout = MipLayout::for_vsid(meta.vsid);
668        let occ_words_per_slot = layout.occ_words_per_slot as usize;
669        let offsets_words_per_slot = layout.offsets_words_per_slot as usize;
670        // Same adaptive stride the initial upload chose for this grid.
671        let colors_stride = self
672            .colors_stride_shadow
673            .get(scene_idx)
674            .map_or(COLORS_PER_CHUNK_WORDS as usize, |&s| s as usize);
675
676        assert_eq!(
677            chunk.mips.len() as u32,
678            layout.mip_count,
679            "refresh_chunk: mip count mismatch (chunk {} vs grid {})",
680            chunk.mips.len(),
681            layout.mip_count,
682        );
683
684        // ---- occupancy ----
685        // Route each mip's write to its page. Page size is slot-
686        // aligned (see `split_occupancy_pages`) so the whole slot's
687        // occupancy ladder lands in a single page.
688        let slot_occ_base = meta.occupancy_offset as usize + slot_idx * occ_words_per_slot;
689        let page_words = self.occupancy_page_words as usize;
690        let page = slot_occ_base / page_words;
691        let slot_local_word = slot_occ_base % page_words;
692        debug_assert!(
693            slot_local_word + occ_words_per_slot <= page_words,
694            "occupancy slot straddles a page boundary — page size not slot-aligned",
695        );
696        let off_slot_base = meta.color_offsets_offset as usize + slot_idx * offsets_words_per_slot;
697        let col_slot_base = meta.colors_offset as usize + slot_idx * colors_stride;
698
699        let mut outcome = RefreshOutcome::Ok;
700        let mut color_cursor = 0usize;
701        for (m, mip) in chunk.mips.iter().enumerate() {
702            // occupancy (textured) then solid, back-to-back.
703            let local = slot_local_word + layout.mip_occ_rel[m] as usize;
704            queue.write_buffer(
705                &self.occupancy_pages[page],
706                (local * 4) as u64,
707                bytemuck::cast_slice(&mip.occupancy),
708            );
709            queue.write_buffer(
710                &self.occupancy_pages[page],
711                ((local + mip.occupancy.len()) * 4) as u64,
712                bytemuck::cast_slice(&mip.solid_occupancy),
713            );
714            // color_offsets
715            let coff = off_slot_base + layout.mip_coff_rel[m] as usize;
716            queue.write_buffer(
717                &self.all_color_offsets,
718                (coff * 4) as u64,
719                bytemuck::cast_slice(&mip.color_offsets),
720            );
721            // colours (concatenated per slot, truncate to stride)
722            let remaining = colors_stride.saturating_sub(color_cursor);
723            let n = mip.colors.len().min(remaining);
724            if n < mip.colors.len() {
725                eprintln!(
726                    "roxlap-gpu refresh_chunk: scene_idx={scene_idx} chunk_idx={chunk_idx:?} \
727                     mip {m} colours overflow stride {colors_stride}; truncating",
728                );
729                outcome = RefreshOutcome::ColorsTruncated;
730            }
731            if n > 0 {
732                queue.write_buffer(
733                    &self.all_colors,
734                    ((col_slot_base + color_cursor) * 4) as u64,
735                    bytemuck::cast_slice(&mip.colors[..n]),
736                );
737            }
738            color_cursor += n;
739        }
740
741        // ---- chunk_occupancy bit ----
742        self.set_chunk_occupancy_bit(
743            queue,
744            scene_idx,
745            &meta,
746            slot_idx,
747            !chunk.mips[0].colors.is_empty(),
748        );
749
750        // ---- slot_chunk_idx (identity for the shader) ----
751        self.set_slot_chunk_idx(queue, scene_idx, &meta, slot_idx, chunk_idx);
752
753        // ---- PF.12.c — mirror the slot's color_offsets window ----
754        // (`refresh_chunk_partial` verifies counts + places colours
755        // against it). Rebuilt exactly as the GPU windows were written.
756        let mut window = vec![0u32; offsets_words_per_slot];
757        for (m, mip) in chunk.mips.iter().enumerate() {
758            let coff = layout.mip_coff_rel[m] as usize;
759            window[coff..coff + mip.color_offsets.len()].copy_from_slice(&mip.color_offsets);
760        }
761        self.color_offsets_shadow[scene_idx].insert(slot_idx, window);
762
763        // ---- GPU.13.0 grid-AABB early-out box ----
764        self.sync_aabb(queue, scene_idx);
765
766        outcome
767    }
768
769    /// Evict a chunk's slot — clear its `chunk_occupancy` bit and
770    /// reset `slot_chunk_idx` to the empty sentinel. Used by the
771    /// host when a chunk disappears from the CPU-side `Grid::chunks`
772    /// (e.g. streaming eviction past `r_evict`).
773    ///
774    /// Returns `false` if `scene_idx` is past `grid_count` (no-op);
775    /// `true` otherwise.
776    /// PF.12.c — partial refresh: re-derive + re-upload ONLY the columns
777    /// inside the inclusive chunk-local mip-0 column rect `[x0..=x1] ×
778    /// [y0..=y1]` (pre-padded by the caller with the edit's ±1 adjacency
779    /// reach), for every mip. Requires the slot to already hold
780    /// `chunk_idx` with a mirrored offsets table, and every dirty
781    /// column's colour COUNT to be unchanged (a count change reflows the
782    /// packed colour block). Returns `false` — with **nothing written**
783    /// — when any precondition fails; the caller falls back to the full
784    /// [`Self::refresh_chunk`] path.
785    ///
786    /// The count-stable case is the streaming bake tracker's per-frame
787    /// path (brightness-byte rewrites) and recolour edits: those now
788    /// upload a few KB instead of decompressing + rewriting the whole
789    /// ~1–2 MB chunk ladder.
790    #[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
791    pub fn refresh_chunk_partial(
792        &mut self,
793        queue: &wgpu::Queue,
794        scene_idx: usize,
795        chunk_idx: [i32; 3],
796        vxl: &roxlap_formats::vxl::Vxl,
797        x0: i32,
798        y0: i32,
799        x1: i32,
800        y1: i32,
801    ) -> bool {
802        let Some(meta) = self.static_meta.get(scene_idx).copied() else {
803            return false;
804        };
805        let layout = MipLayout::for_vsid(meta.vsid);
806        if vxl.mip_count() < layout.mip_count {
807            return false;
808        }
809        let slot_idx = modular_slot_idx(chunk_idx, meta.pool_dims);
810        // The slot must currently hold THIS chunk (modular pools reuse
811        // slots; a partial write over another chunk's data = garbage).
812        let held = self.slot_chunk_idx_shadow[scene_idx][slot_idx];
813        if held[0] != chunk_idx[0] || held[1] != chunk_idx[1] || held[2] != chunk_idx[2] {
814            return false;
815        }
816        let Some(offs_shadow) = self.color_offsets_shadow[scene_idx].get(&slot_idx) else {
817            return false;
818        };
819        let colors_stride = self
820            .colors_stride_shadow
821            .get(scene_idx)
822            .map_or(COLORS_PER_CHUNK_WORDS as usize, |&s| s as usize);
823
824        // Phase 1 — recompute every dirty column per mip into row-run
825        // buffers (rows are contiguous in both the occupancy layout and
826        // the packed colour block), verifying colour counts. NOTHING is
827        // written until the whole extent verifies.
828        struct RowRun {
829            /// Textured-occupancy word offset within the slot.
830            occ_word: usize,
831            /// Solid block sits `block_words` after the textured one.
832            block_words: usize,
833            occ: Vec<u32>,
834            solid: Vec<u32>,
835            /// Colour word offset within the slot's colour block.
836            color_word: usize,
837            colors: Vec<u32>,
838        }
839        let mut runs: Vec<RowRun> = Vec::new();
840        for m in 0..layout.mip_count {
841            let vsid_m = (meta.vsid >> m).max(1) as i32;
842            let cz_m = crate::decompress::CHUNK_Z >> m;
843            let wpc = occ_words_per_column_for_mip(m) as usize;
844            let block_words = (vsid_m as usize) * (vsid_m as usize) * wpc;
845            let rx0 = (x0 >> m).clamp(0, vsid_m - 1);
846            let ry0 = (y0 >> m).clamp(0, vsid_m - 1);
847            let rx1 = (x1 >> m).clamp(0, vsid_m - 1);
848            let ry1 = (y1 >> m).clamp(0, vsid_m - 1);
849            let coff_base = layout.mip_coff_rel[m as usize] as usize;
850            for y in ry0..=ry1 {
851                let row_col0 = (y * vsid_m + rx0) as usize;
852                let n_cols = (rx1 - rx0 + 1) as usize;
853                let mut occ = vec![0u32; n_cols * wpc];
854                let mut solid = vec![0u32; n_cols * wpc];
855                let mut colors: Vec<u32> = Vec::new();
856                for i in 0..n_cols {
857                    let col_idx = row_col0 + i;
858                    let slab = vxl.column_data_for_mip(m, col_idx);
859                    let before = colors.len();
860                    // vsid=1 / (0,0) → the column scratch windows index
861                    // from word 0 of the per-column slices.
862                    crate::decompress::decompress_column(
863                        slab,
864                        0,
865                        0,
866                        1,
867                        cz_m,
868                        wpc as u32,
869                        &mut occ[i * wpc..(i + 1) * wpc],
870                        &mut solid[i * wpc..(i + 1) * wpc],
871                        &mut colors,
872                    );
873                    // Count stability vs the mirrored offsets table.
874                    let old_count = offs_shadow[coff_base + col_idx + 1]
875                        .saturating_sub(offs_shadow[coff_base + col_idx])
876                        as usize;
877                    if colors.len() - before != old_count {
878                        return false; // reflow → full path
879                    }
880                }
881                let color_word = offs_shadow[coff_base + row_col0] as usize;
882                if color_word + colors.len() > colors_stride {
883                    return false; // stride overflow → full path handles
884                }
885                runs.push(RowRun {
886                    occ_word: layout.mip_occ_rel[m as usize] as usize + row_col0 * wpc,
887                    block_words,
888                    occ,
889                    solid,
890                    color_word,
891                    colors,
892                });
893            }
894        }
895
896        // Phase 2 — verified: write the row runs.
897        let occ_words_per_slot = layout.occ_words_per_slot as usize;
898        let slot_occ_base = meta.occupancy_offset as usize + slot_idx * occ_words_per_slot;
899        let page_words = self.occupancy_page_words as usize;
900        let page = slot_occ_base / page_words;
901        let slot_local_word = slot_occ_base % page_words;
902        let col_slot_base = meta.colors_offset as usize + slot_idx * colors_stride;
903        for run in &runs {
904            let tex = slot_local_word + run.occ_word;
905            queue.write_buffer(
906                &self.occupancy_pages[page],
907                (tex * 4) as u64,
908                bytemuck::cast_slice(&run.occ),
909            );
910            queue.write_buffer(
911                &self.occupancy_pages[page],
912                ((tex + run.block_words) * 4) as u64,
913                bytemuck::cast_slice(&run.solid),
914            );
915            if !run.colors.is_empty() {
916                queue.write_buffer(
917                    &self.all_colors,
918                    ((col_slot_base + run.color_word) * 4) as u64,
919                    bytemuck::cast_slice(&run.colors),
920                );
921            }
922        }
923        // Counts unchanged ⇒ offsets, chunk-occupancy bit, AABB and the
924        // mirrors all stay valid untouched.
925        true
926    }
927
928    /// Evict `chunk_idx` from grid `scene_idx`: clear the slot's
929    /// chunk-occupancy bit, stamp [`SLOT_EMPTY_SENTINEL`] into its
930    /// `slot_chunk_idx` entry, and shrink the grid's chunk-AABB if the
931    /// box tightened. The bulk voxel data is left in place — the
932    /// cleared occupancy bit + sentinel already make the shader treat
933    /// the slot as empty. A no-op (returning `true`) when the slot
934    /// meanwhile holds a *different* chunk, so a stale evict can never
935    /// wipe a newer occupant. Returns `false` only for an out-of-range
936    /// `scene_idx`.
937    pub fn evict_chunk(
938        &mut self,
939        queue: &wgpu::Queue,
940        scene_idx: usize,
941        chunk_idx: [i32; 3],
942    ) -> bool {
943        let Some(meta) = self.static_meta.get(scene_idx).copied() else {
944            return false;
945        };
946        let slot_idx = modular_slot_idx(chunk_idx, meta.pool_dims);
947        // Only evict if this slot still claims to hold `chunk_idx`.
948        // Otherwise we'd be wiping out a different (newer) chunk
949        // that happens to share the slot.
950        let shadow_entry = self.slot_chunk_idx_shadow[scene_idx][slot_idx];
951        if shadow_entry[0] != chunk_idx[0]
952            || shadow_entry[1] != chunk_idx[1]
953            || shadow_entry[2] != chunk_idx[2]
954        {
955            return true;
956        }
957        self.set_chunk_occupancy_bit(queue, scene_idx, &meta, slot_idx, false);
958        self.set_slot_chunk_idx(queue, scene_idx, &meta, slot_idx, SLOT_EMPTY_SENTINEL);
959        // PF.12.c — drop the evicted slot's offsets mirror.
960        self.color_offsets_shadow[scene_idx].remove(&slot_idx);
961        // GPU.13.0 — eviction may shrink the occupied box; recompute.
962        self.sync_aabb(queue, scene_idx);
963        true
964    }
965
966    fn set_chunk_occupancy_bit(
967        &mut self,
968        queue: &wgpu::Queue,
969        scene_idx: usize,
970        meta: &GridStaticMeta,
971        slot_idx: usize,
972        new_bit: bool,
973    ) {
974        let word_idx = slot_idx >> 5;
975        let bit = slot_idx & 31;
976        let shadow = &mut self.chunk_occupancy_shadow[scene_idx][word_idx];
977        let was_bit = (*shadow >> bit) & 1 == 1;
978        if new_bit == was_bit {
979            return;
980        }
981        if new_bit {
982            *shadow |= 1u32 << bit;
983        } else {
984            *shadow &= !(1u32 << bit);
985        }
986        let global_word_idx = meta.chunk_occupancy_offset as usize + word_idx;
987        queue.write_buffer(
988            &self.all_chunk_occupancy,
989            (global_word_idx * 4) as u64,
990            bytemuck::bytes_of(shadow),
991        );
992    }
993
994    fn set_slot_chunk_idx(
995        &mut self,
996        queue: &wgpu::Queue,
997        scene_idx: usize,
998        meta: &GridStaticMeta,
999        slot_idx: usize,
1000        chunk_idx: [i32; 3],
1001    ) {
1002        let entry = [chunk_idx[0], chunk_idx[1], chunk_idx[2], 0];
1003        self.slot_chunk_idx_shadow[scene_idx][slot_idx] = entry;
1004        let global_word_idx = meta.slot_chunk_idx_offset as usize + slot_idx * 4;
1005        queue.write_buffer(
1006            &self.all_slot_chunk_idx,
1007            (global_word_idx * 4) as u64,
1008            bytemuck::cast_slice(&entry),
1009        );
1010    }
1011
1012    /// GPU.13.0 — recompute the grid's occupied chunk-AABB from its
1013    /// `slot_chunk_idx` shadow and, if it changed, patch the grid's
1014    /// [`GridStaticMeta`] on the GPU. Cheap: scans `total_slots`
1015    /// entries and writes 144 bytes only when the box actually moves
1016    /// (steady-state re-bakes leave it unchanged → no GPU write).
1017    /// Called after every install/eviction so streaming grids keep a
1018    /// tight, always-conservative early-out box.
1019    fn sync_aabb(&mut self, queue: &wgpu::Queue, scene_idx: usize) {
1020        let (aabb_min, aabb_max) = aabb_of_slots(&self.slot_chunk_idx_shadow[scene_idx]);
1021        let meta = &mut self.static_meta[scene_idx];
1022        if meta.aabb_min == aabb_min && meta.aabb_max == aabb_max {
1023            return;
1024        }
1025        meta.aabb_min = aabb_min;
1026        meta.aabb_max = aabb_max;
1027        let off = (scene_idx * std::mem::size_of::<GridStaticMeta>()) as u64;
1028        queue.write_buffer(&self.grid_static_meta, off, bytemuck::bytes_of(meta));
1029    }
1030}
1031
1032/// GPU.13.0 — inclusive chunk-AABB over a grid's `slot_chunk_idx`
1033/// shadow, skipping the [`SLOT_EMPTY_SENTINEL`] entries. Returns the
1034/// inverted sentinel box (`min = i32::MAX`, `max = i32::MIN`) when no
1035/// slot is occupied, which makes the shader's `aabb_passed` early-out
1036/// fire for every ray (an empty grid renders nothing).
1037fn aabb_of_slots(slots: &[[i32; 4]]) -> ([i32; 3], [i32; 3]) {
1038    let mut min = [i32::MAX; 3];
1039    let mut max = [i32::MIN; 3];
1040    for e in slots {
1041        if e[0] == SLOT_EMPTY_SENTINEL[0]
1042            && e[1] == SLOT_EMPTY_SENTINEL[1]
1043            && e[2] == SLOT_EMPTY_SENTINEL[2]
1044        {
1045            continue;
1046        }
1047        for k in 0..3 {
1048            if e[k] < min[k] {
1049                min[k] = e[k];
1050            }
1051            if e[k] > max[k] {
1052                max[k] = e[k];
1053            }
1054        }
1055    }
1056    (min, max)
1057}
1058
1059/// Modular slot index for `chunk_idx` given the grid's
1060/// power-of-2 `pool_dims`. Negative `chunk_idx` components map via
1061/// two's-complement bitwise AND, matching the shader's
1062/// `chunk_idx & (pool_dims - 1)`.
1063#[must_use]
1064pub fn modular_slot_idx(chunk_idx: [i32; 3], pool_dims: [u32; 3]) -> usize {
1065    let mask_x = (pool_dims[0] - 1) as i32;
1066    let mask_y = (pool_dims[1] - 1) as i32;
1067    let mask_z = (pool_dims[2] - 1) as i32;
1068    let sx = (chunk_idx[0] & mask_x) as usize;
1069    let sy = (chunk_idx[1] & mask_y) as usize;
1070    let sz = (chunk_idx[2] & mask_z) as usize;
1071    sx + sy * (pool_dims[0] as usize) + sz * (pool_dims[0] as usize) * (pool_dims[1] as usize)
1072}
1073
1074/// Outcome of `GpuSceneResident::refresh_chunk`. Most callers
1075/// can ignore the result; `ColorsTruncated` indicates the chunk's
1076/// colour data overflowed the per-slot stride and was clipped.
1077#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1078pub enum RefreshOutcome {
1079    /// The chunk was installed/refreshed in full — every mip's
1080    /// occupancy, offsets, and colours are resident.
1081    Ok,
1082    /// The chunk's colour count exceeded `COLORS_PER_CHUNK_WORDS`;
1083    /// the GPU sees the first `stride` colours. Bump
1084    /// `COLORS_PER_CHUNK_WORDS` for content that hits this.
1085    ColorsTruncated,
1086    /// Retained for ABI compatibility; the GPU.7 modular pool no
1087    /// longer rejects chunks by bbox.
1088    ChunkOutOfBbox,
1089    /// `scene_idx` is past `grid_count`. Programming error.
1090    SceneIdxOob,
1091}
1092
1093fn create_storage(device: &wgpu::Device, label: &str, data: &[u32]) -> wgpu::Buffer {
1094    // GPU.6: include COPY_DST so `refresh_chunk` can `queue.write_buffer`
1095    // into existing slots without rebuilding the resident.
1096    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
1097        label: Some(label),
1098        contents: bytemuck::cast_slice(data),
1099        usage: wgpu::BufferUsages::STORAGE
1100            | wgpu::BufferUsages::COPY_DST
1101            | wgpu::BufferUsages::COPY_SRC,
1102    })
1103}
1104
1105/// Split the concatenated occupancy words into up to
1106/// [`MAX_OCC_PAGES`] storage buffers, each no larger than the
1107/// device's `max_storage_buffer_binding_size`, then pad the page
1108/// list with 1-word dummy buffers so the returned vec is always
1109/// exactly `MAX_OCC_PAGES` long (one buffer per bind-group entry).
1110///
1111/// `slot_align_words` is the per-slot occupancy stride: page size is
1112/// rounded down to a multiple of it so no chunk slot — and therefore
1113/// no per-slot `refresh_chunk` write — straddles a page boundary.
1114/// Returns `(pages, page_words, num_pages)`.
1115fn split_occupancy_pages(
1116    device: &wgpu::Device,
1117    words: &[u32],
1118    slot_align_words: u64,
1119) -> (Vec<wgpu::Buffer>, u32, u32) {
1120    let total_words = words.len() as u64;
1121    // wgpu 29 widened `max_storage_buffer_binding_size` to `u64`.
1122    let limit_words = device.limits().max_storage_buffer_binding_size / 4;
1123    // Largest slot-aligned page that fits one binding (≥ 1 slot).
1124    let page_slots = (limit_words / slot_align_words).max(1);
1125    let mut page_words = page_slots.saturating_mul(slot_align_words);
1126    // A tiny scene (or the empty-scene 1-word pad) isn't slot-aligned;
1127    // cap the page at the data length so we don't allocate emptiness.
1128    page_words = page_words.min(total_words.max(1));
1129    let num_pages = total_words.div_ceil(page_words);
1130    assert!(
1131        num_pages as usize <= MAX_OCC_PAGES,
1132        "occupancy needs {num_pages} pages (>{MAX_OCC_PAGES}) at this device's \
1133         {limit_words}-word binding limit; shrink the streaming pool or raise MAX_OCC_PAGES",
1134    );
1135
1136    let mut pages: Vec<wgpu::Buffer> = Vec::with_capacity(MAX_OCC_PAGES);
1137    let page_words_usize = page_words as usize;
1138    for p in 0..num_pages as usize {
1139        let start = p * page_words_usize;
1140        let end = ((p + 1) * page_words_usize).min(words.len());
1141        pages.push(create_storage(
1142            device,
1143            &format!("roxlap-gpu scene.occupancy.page{p}"),
1144            &words[start..end],
1145        ));
1146    }
1147    // Dummy 1-word buffers for the unused bindings.
1148    while pages.len() < MAX_OCC_PAGES {
1149        pages.push(create_storage(
1150            device,
1151            "roxlap-gpu scene.occupancy.page_dummy",
1152            &[0u32],
1153        ));
1154    }
1155    (
1156        pages,
1157        u32::try_from(page_words).expect("page_words fits u32"),
1158        num_pages as u32,
1159    )
1160}
1161
1162#[cfg(test)]
1163mod tests {
1164    use super::*;
1165
1166    #[test]
1167    fn grid_static_meta_matches_wgsl_std430_size() {
1168        // scene_dda.wgsl's GridStaticMeta is read as
1169        // array<GridStaticMeta>; the std430 array stride must equal
1170        // the Rust size_of or wgpu rejects the binding.
1171        // Concretely: 8 u32 (32) + vec3+pad (16) + 4 u32 (16) +
1172        // 2*[u32;6] (48) = 112, then GPU.13.0 adds two vec3<i32>+pad
1173        // (aabb_min, aabb_max) = 32 → 144 bytes.
1174        assert_eq!(std::mem::size_of::<GridStaticMeta>(), 144);
1175        assert_eq!(std::mem::align_of::<GridStaticMeta>(), 4);
1176    }
1177
1178    #[test]
1179    fn mip_layout_offsets_accumulate() {
1180        // vsid=128 → 6 mips. Relative offsets are cumulative; mip-0
1181        // sits at 0 so mip-0 reads are byte-identical to pre-mip.
1182        let l = MipLayout::for_vsid(128);
1183        assert_eq!(l.mip_count, 6);
1184        assert_eq!(l.mip_occ_rel[0], 0);
1185        assert_eq!(l.mip_coff_rel[0], 0);
1186
1187        // Recompute the strides independently and compare. Each mip
1188        // stores TWO occupancy bitmaps (textured + solid) back-to-back.
1189        let mut occ = 0u32;
1190        let mut coff = 0u32;
1191        for m in 0..6u32 {
1192            assert_eq!(l.mip_occ_rel[m as usize], occ, "occ rel mip {m}");
1193            assert_eq!(l.mip_coff_rel[m as usize], coff, "coff rel mip {m}");
1194            let v = 128u32 >> m;
1195            occ += 2 * v * v * occ_words_per_column_for_mip(m);
1196            coff += v * v + 1;
1197        }
1198        assert_eq!(l.occ_words_per_slot, occ);
1199        assert_eq!(l.offsets_words_per_slot, coff);
1200
1201        // mip-0 occupancy stride is 2 × the historical vsid²·8 (tex +
1202        // solid bitmaps).
1203        assert_eq!(l.mip_occ_rel[1], 2 * 128 * 128 * 8);
1204        // The whole ladder is only ~1/7 larger than mip-0 alone
1205        // (geometric 1 + 1/8 + 1/64 + …) — here on the doubled base.
1206        assert!(l.occ_words_per_slot < 2 * 128 * 128 * 8 * 5 / 4);
1207    }
1208}