Skip to main content

roxlap_scene/
lib.rs

1//! roxlap scene-graph layer — many independent chunked voxel
2//! grids in a single 3D scene.
3//!
4//! New to roxlap? **[The roxlap book](https://ncrashed.github.io/roxlap/)**
5//! is the guide — its scene-graph chapter walks this crate end to end;
6//! this page is the API reference.
7//!
8//! This crate is the layer **above** the per-chunk renderer
9//! (`roxlap-core`): a [`Scene`] holds a sparse set of [`Grid`]s, each
10//! with its own f64 world position + arbitrary 3D rotation
11//! ([`GridTransform`]). Around that core sit:
12//!
13//! - [`addr`] — world ↔ grid-local ↔ chunk + voxel-in-chunk
14//!   decomposition, the canonical f64↔i32 boundary helpers;
15//! - [`chunks`] — sparse chunk storage with on-demand materialisation,
16//!   plus the [`Grid`] edit API ([`Grid::set_voxel`],
17//!   [`Grid::set_rect`], [`Grid::set_sphere`], …) which decomposes
18//!   multi-chunk operations and delegates to [`roxlap_formats::edit`];
19//! - [`render`] — multi-grid raycast composition for the CPU renderer;
20//! - [`snapshot`] — save/load: the versioned wire format
21//!   ([`Scene::save_snapshot`] / [`Scene::load_snapshot`], QE.5b)
22//!   plus the underlying serde-friendly [`snapshot::SceneSnapshot`]
23//!   value (chunks encode via [`roxlap_formats::vxl::serialize`] /
24//!   [`parse`]);
25//! - [`streaming`] — chunk streaming + procedural generation
26//!   ([`streaming::ChunkGenerator`], radius-driven install/evict,
27//!   async generation on a rayon pool) and persistence for edited
28//!   chunks ([`streaming::ChunkStore`], QE.5a);
29//! - [`lod`] / [`billboard`] / [`occluder`] — far-LOD billboards and
30//!   render culling helpers;
31//! - world queries — [`Scene::raycast`], [`Scene::resolve_voxel`],
32//!   [`Grid::voxel_solid`] / [`Grid::voxel_color`].
33//!
34//! `docs/porting/PORTING-SCENE.md` in the repository records the
35//! original substage roadmap (S1..S7, all landed).
36//!
37//! [`parse`]: roxlap_formats::vxl::parse
38
39pub mod addr;
40pub mod billboard;
41pub mod cavegen;
42/// Character controller (stage CC) — a walking body over the scene;
43/// see `docs/porting/PORTING-CONTROLLER.md`.
44pub mod character;
45pub mod chunks;
46/// Collision query layer (stage CC) — box-vs-voxel overlap over a
47/// scene; see `docs/porting/PORTING-CONTROLLER.md`.
48pub mod collide;
49pub mod edit;
50pub mod lod;
51pub mod occluder;
52pub mod render;
53pub mod snapshot;
54pub mod streaming;
55
56use std::collections::{HashMap, HashSet};
57use std::sync::Arc;
58
59use glam::{DQuat, DVec3, IVec3, UVec3};
60use roxlap_formats::vxl::Vxl;
61use serde::{Deserialize, Serialize};
62
63pub use addr::{grid_local_to_world, voxel_global, voxel_split, world_to_grid_local, GridLocalPos};
64pub use billboard::{canonical_viewpoints, BillboardCache, BillboardSnapshot};
65pub use character::{CharacterBody, CharacterDef, MoveMode, WalkInput};
66pub use chunks::BakeMode;
67pub use collide::{box_overlaps_solid, grid_box_overlaps_solid, point_overlaps_solid, Solidity};
68pub use edit::SpanOp;
69pub use lod::{select_lod, Lod, LodThresholds};
70pub use roxlap_core::AoParams;
71pub use roxlap_formats::color::{OverlayColor, Rgb, VoxColor};
72pub use streaming::{ChunkGenerator, ChunkStore, StreamRadius};
73
74/// XY size of one chunk in voxels. The plan locks 128 — keeps
75/// chunks compact (~2 MB worst-case dense-slab footprint inside
76/// each `Vxl`) and divides cleanly into voxlap's 2048 reference
77/// world size.
78pub const CHUNK_SIZE_XY: u32 = 128;
79
80/// Z size of one chunk in voxels. Locked at 256 to preserve
81/// voxlap's existing slab byte format unchanged inside each chunk
82/// — the per-chunk renderer doesn't need to know it's living
83/// inside a scene-graph.
84pub const CHUNK_SIZE_Z: u32 = 256;
85
86/// Stable identifier for a grid registered in a [`Scene`]. Issued
87/// by [`Scene::add_grid`]; persists across edits but a removed
88/// grid's id is not reissued.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
90pub struct GridId(u32);
91
92impl GridId {
93    /// The integer wire form. Useful for serde / debug output.
94    #[must_use]
95    pub const fn raw(self) -> u32 {
96        self.0
97    }
98}
99
100/// A solid-voxel hit from [`Scene::raycast`].
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub struct RayHit {
103    /// The grid the ray hit.
104    pub grid: GridId,
105    /// Grid-local integer voxel coordinate of the hit cell.
106    pub voxel: IVec3,
107    /// World-space hit point (`origin + t · normalize(dir)`).
108    pub world: DVec3,
109    /// World distance from the ray origin to the hit.
110    pub t: f64,
111    /// Packed colour of the hit voxel, or `None` if it's an untextured
112    /// (bedrock / interior) cell. See [`Grid::voxel_color`].
113    pub color: Option<VoxColor>,
114}
115
116/// Ray/AABB slab intersection in f64 (`[lo, hi)` box). Returns the
117/// entry/exit ray parameters, or `None` on a miss. PF.6 helper for the
118/// raycast pre-clip + absent-chunk exit.
119fn ray_box(o: DVec3, d: DVec3, blo: DVec3, bhi: DVec3) -> Option<(f64, f64)> {
120    let mut tmin = f64::NEG_INFINITY;
121    let mut tmax = f64::INFINITY;
122    for a in 0..3 {
123        if d[a].abs() < 1e-12 {
124            if o[a] < blo[a] || o[a] > bhi[a] {
125                return None;
126            }
127        } else {
128            let inv = 1.0 / d[a];
129            let (t0, t1) = ((blo[a] - o[a]) * inv, (bhi[a] - o[a]) * inv);
130            tmin = tmin.max(t0.min(t1));
131            tmax = tmax.min(t0.max(t1));
132            if tmin > tmax {
133                return None;
134            }
135        }
136    }
137    Some((tmin, tmax))
138}
139
140/// The populated chunk extent of `grid` as a grid-local voxel-space AABB
141/// `[lo, hi)`, or `None` for an empty grid. O(chunks) HashMap key walk —
142/// fine for per-call raycast use.
143fn grid_voxel_aabb_f64(grid: &Grid) -> Option<(DVec3, DVec3)> {
144    let mut min = IVec3::splat(i32::MAX);
145    let mut max = IVec3::splat(i32::MIN);
146    let mut any = false;
147    for idx in grid.chunks.keys() {
148        any = true;
149        min = min.min(*idx);
150        max = max.max(*idx);
151    }
152    if !any {
153        return None;
154    }
155    let (cs_xy, cs_z) = (
156        i64::from(CHUNK_SIZE_XY as i32),
157        i64::from(CHUNK_SIZE_Z as i32),
158    );
159    #[allow(clippy::cast_precision_loss)]
160    let v = |i: IVec3, add: i64| {
161        DVec3::new(
162            ((i64::from(i.x) + add) * cs_xy) as f64,
163            ((i64::from(i.y) + add) * cs_xy) as f64,
164            ((i64::from(i.z) + add) * cs_z) as f64,
165        )
166    };
167    Some((v(min, 0), v(max, 1)))
168}
169
170/// Voxel DDA (Amanatides-Woo) in a grid's local space. `lo` / `ld` are
171/// the ray origin + unit direction already transformed into grid-local
172/// coords. Returns the first [`Grid::voxel_solid`] cell and its world-
173/// equal distance `t`, or `None` past `max_t`.
174///
175/// PF.6 — three upgrades over the naive from-origin march:
176/// - the ray is pre-clipped to the grid's populated chunk AABB (a miss
177///   costs one slab test; a distant grid is marched AT the box, not from
178///   the origin);
179/// - chunk lookups go through the chunk-cached [`SolidSampler`]-style
180///   probe (one HashMap hit per chunk crossing) and the solid test walks
181///   the slab chain in place (no per-step allocation);
182/// - a voxel in an absent (all-air) chunk fast-forwards the march to
183///   that chunk's exit face instead of stepping its up-to-128 voxels.
184#[allow(clippy::cast_possible_truncation)]
185fn voxel_dda(grid: &Grid, lo: DVec3, ld: DVec3, max_t: f64) -> Option<(IVec3, f64)> {
186    // Clip to the populated chunk AABB: everything outside is air.
187    let (blo, bhi) = grid_voxel_aabb_f64(grid)?;
188    let (t0, t1) = ray_box(lo, ld, blo, bhi)?;
189    let t_enter = t0.max(0.0);
190    let t_exit = t1.min(max_t);
191    if t_enter > t_exit {
192        return None;
193    }
194
195    let step = IVec3::new(
196        i32::from(ld.x > 0.0) - i32::from(ld.x < 0.0),
197        i32::from(ld.y > 0.0) - i32::from(ld.y < 0.0),
198        i32::from(ld.z > 0.0) - i32::from(ld.z < 0.0),
199    );
200    // Distance to advance one whole voxel along each axis (∞ if parallel).
201    let inv_abs = |d: f64| {
202        if d == 0.0 {
203            f64::INFINITY
204        } else {
205            (1.0 / d).abs()
206        }
207    };
208    let t_delta = DVec3::new(inv_abs(ld.x), inv_abs(ld.y), inv_abs(ld.z));
209    // Absolute-`t` of the next voxel boundary from cell `p`, per axis
210    // (also the re-seed after an absent-chunk jump).
211    let seed_t_max = |p: IVec3| -> DVec3 {
212        let axis = |pa: i32, oa: f64, da: f64| -> f64 {
213            if da > 0.0 {
214                (f64::from(pa) + 1.0 - oa) / da
215            } else if da < 0.0 {
216                (f64::from(pa) - oa) / da
217            } else {
218                f64::INFINITY
219            }
220        };
221        DVec3::new(
222            axis(p.x, lo.x, ld.x),
223            axis(p.y, lo.y, ld.y),
224            axis(p.z, lo.z, ld.z),
225        )
226    };
227
228    // Start at the AABB entry (t stays measured from the true origin;
229    // t_enter == 0 ⇒ the original from-origin start, bit-identical).
230    let start = lo + ld * t_enter;
231    let mut p = IVec3::new(
232        start.x.floor() as i32,
233        start.y.floor() as i32,
234        start.z.floor() as i32,
235    );
236    let mut t_max = seed_t_max(p);
237    let mut t_curr = t_enter;
238    let mut sampler = grid.solid_sampler();
239
240    #[allow(clippy::cast_sign_loss)]
241    let max_steps = (max_t * 3.0) as u64 + 8;
242    let (cs_xy, cs_z) = (
243        f64::from(CHUNK_SIZE_XY as i32),
244        f64::from(CHUNK_SIZE_Z as i32),
245    );
246    for _ in 0..max_steps {
247        let (chunk_idx, in_chunk) = voxel_split(p);
248        if let Some(vxl) = sampler.chunk_at(chunk_idx) {
249            if chunks::vxl_voxel_solid(vxl, in_chunk.x, in_chunk.y, in_chunk.z) {
250                return Some((p, t_curr));
251            }
252            // Advance across the nearest voxel boundary.
253            let t = if t_max.x <= t_max.y && t_max.x <= t_max.z {
254                p.x += step.x;
255                let t = t_max.x;
256                t_max.x += t_delta.x;
257                t
258            } else if t_max.y <= t_max.z {
259                p.y += step.y;
260                let t = t_max.y;
261                t_max.y += t_delta.y;
262                t
263            } else {
264                p.z += step.z;
265                let t = t_max.z;
266                t_max.z += t_delta.z;
267                t
268            };
269            if t > t_exit {
270                return None;
271            }
272            t_curr = t;
273        } else {
274            // Absent chunk ⇒ guaranteed air: jump to its exit face.
275            let clo = DVec3::new(
276                f64::from(chunk_idx.x) * cs_xy,
277                f64::from(chunk_idx.y) * cs_xy,
278                f64::from(chunk_idx.z) * cs_z,
279            );
280            let chi = clo + DVec3::new(cs_xy, cs_xy, cs_z);
281            let exit = match ray_box(lo, ld, clo, chi) {
282                // Nudge past the face so the floor lands in the next chunk.
283                Some((_, t1)) => t1.max(t_curr) + 1e-4,
284                None => return None, // degenerate (shouldn't happen: p is inside)
285            };
286            if exit > t_exit {
287                return None;
288            }
289            let q = lo + ld * exit;
290            p = IVec3::new(q.x.floor() as i32, q.y.floor() as i32, q.z.floor() as i32);
291            t_max = seed_t_max(p);
292            t_curr = exit;
293        }
294    }
295    None
296}
297
298/// f64 world placement of one grid: position + orientation.
299///
300/// `origin` is the grid's local-space origin in world coords —
301/// chunk `(0, 0, 0)`'s `(0, 0, 0)` voxel maps to
302/// `origin + rotation * vec3(0, 0, 0)` (i.e. just `origin`).
303/// Voxel size is fixed at 1 world unit / voxel for v1.
304#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
305pub struct GridTransform {
306    /// The grid's local-space origin, in world coordinates.
307    pub origin: DVec3,
308    /// The grid's orientation about `origin`.
309    pub rotation: DQuat,
310}
311
312impl GridTransform {
313    /// Identity transform at world origin. Useful as a default for
314    /// the first grid added to an otherwise empty scene.
315    #[must_use]
316    pub fn identity() -> Self {
317        Self {
318            origin: DVec3::ZERO,
319            rotation: DQuat::IDENTITY,
320        }
321    }
322
323    /// Axis-aligned grid placed at `origin` with no rotation.
324    #[must_use]
325    pub fn at(origin: DVec3) -> Self {
326        Self {
327            origin,
328            rotation: DQuat::IDENTITY,
329        }
330    }
331}
332
333impl Default for GridTransform {
334    fn default() -> Self {
335        Self::identity()
336    }
337}
338
339/// Address of one voxel inside a scene: which grid it belongs to,
340/// which chunk within that grid, and the voxel's offset inside
341/// that chunk.
342///
343/// `chunk` is signed (`IVec3`) because chunks are centred on the
344/// grid's local origin and may extend in either direction. `voxel`
345/// is unsigned and must satisfy
346/// `(voxel.x, voxel.y) < CHUNK_SIZE_XY` and `voxel.z < CHUNK_SIZE_Z`.
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
348pub struct GridAddr {
349    /// The owning grid.
350    pub grid: GridId,
351    /// Signed chunk index within the grid.
352    pub chunk: IVec3,
353    /// Voxel offset inside `chunk` (see the bounds above).
354    pub voxel: UVec3,
355}
356
357/// One independent voxel grid in a scene. Holds its world placement
358/// and a sparse map of populated chunks. Empty chunk slots are
359/// implicit air and skipped during rendering / raycasts.
360///
361/// Each chunk is internally a [`Vxl`] with `vsid = CHUNK_SIZE_XY`
362/// — the existing per-chunk renderer (opticast + grouscan +
363/// sprites + lighting in `roxlap-core`) runs on each chunk
364/// unchanged. Vertical worlds are built by stacking chunks along
365/// grid-local `+z`.
366#[derive(Debug)]
367pub struct Grid {
368    /// World placement (origin + rotation).
369    pub transform: GridTransform,
370    /// Sparse chunk storage keyed by `(chx, chy, chz)` chunk
371    /// coordinates. A missing entry means the chunk is fully air.
372    pub chunks: HashMap<IVec3, Vxl>,
373    /// Whether sky pixels rendered for this grid should be
374    /// composited into the final framebuffer. `true` is the
375    /// historical "grid owns its own sky" behaviour: ray misses
376    /// inside this grid's frustum paint sky_color into the temp
377    /// buffer. Set `false` for grids that are a foreground object
378    /// (e.g. a ship) — the sky is owned by a single "world" grid
379    /// (the ground) and other grids should not contribute sky
380    /// pixels, otherwise their grid-local-frame sky lookup
381    /// rotates with the grid and visibly fights the world's sky
382    /// during compose. See [`crate::render::render_scene_composed`]
383    /// for the masking implementation.
384    pub render_sky: bool,
385    /// Override [`roxlap_core::opticast::OpticastSettings::mip_levels`]
386    /// for this grid. `None` ⇒ use the caller's value. `Some(n)`
387    /// ⇒ cap at `n` (clamped to `[1, settings.mip_levels]`). Use
388    /// to disable multi-mip on a per-grid basis — small grids
389    /// (rotating ships, billboards) don't benefit from deep mips
390    /// and CAN trigger the
391    /// `[[project_axis_aligned_mip_beams]]`-style cf-cancellation
392    /// artifact when near-axis-aligned rays hit the rotated grid.
393    /// `Some(1)` = mip-0 only, byte-stable to single-mip.
394    pub mip_levels_override: Option<u32>,
395    /// World-distance thresholds for per-grid LOD tier selection
396    /// (S6.0). Defaults to [`LodThresholds::always_near`], so a
397    /// freshly-constructed grid always renders at full voxel (the
398    /// S5-and-earlier byte-stable behaviour). S6.1 plugs `Mid` into
399    /// the existing multi-mip path; S6.3 plugs `Far` into the
400    /// billboard impostor cache. See [`crate::lod`].
401    pub lod_thresholds: LodThresholds,
402    /// Lazy [`BillboardCache`] for the `Lod::Far` tier (S6.2).
403    /// `None` until the first time S6.3's render dispatch needs
404    /// it; populated then via [`BillboardCache::build`] and
405    /// cleared by edits ([`Self::set_voxel`] / [`Self::set_rect`]
406    /// / [`Self::set_sphere`]) to force a rebuild on next Far use.
407    /// Callers may also force-invalidate via direct assignment.
408    pub billboards: Option<BillboardCache>,
409    /// Optional procedural generator (S7.0). When set,
410    /// [`Self::ensure_chunk_generated`] uses it to materialise
411    /// chunks that are still absent from [`Self::chunks`].
412    ///
413    /// Streaming layers (S7.1+) walk the active radius around the
414    /// camera and call `ensure_chunk_generated` for missing chunks;
415    /// later stages dispatch this onto a background rayon pool. The
416    /// trait bound is `Send + Sync` (needed for S7.3 async
417    /// dispatch) + `Debug` (needed so [`Grid`] keeps deriving
418    /// `Debug`).
419    ///
420    /// `None` is the default — a grid without a generator behaves
421    /// exactly like the pre-S7 grids: absent chunks stay absent.
422    ///
423    /// `Arc` (not `Box`) so S7.3's async dispatch can clone the
424    /// generator into background rayon tasks without moving it out
425    /// of the grid. Trait bound `Send + Sync` (required at S7.0)
426    /// already makes `Arc<dyn ChunkGenerator>` `Send + Sync`.
427    pub generator: Option<Arc<dyn ChunkGenerator>>,
428    /// QE.5b - optional host-assigned tag, carried through snapshots.
429    /// Grid ids are runtime-opaque, so a save/load cycle gives hosts
430    /// nothing to rebind their own per-grid data (generators, stores,
431    /// gameplay state) against; a stable name closes that gap. Not
432    /// interpreted by the engine.
433    pub name: Option<String>,
434    /// QE.5a - optional persistence for edited streamed chunks: the
435    /// eviction pass hands every `chunk_version != 0` chunk to
436    /// [`ChunkStore::store`] before dropping it, and stream-in asks
437    /// [`ChunkStore::load`] before running the generator. `None` (the
438    /// default) keeps the pre-QE.5 behaviour: evicting an edited
439    /// chunk discards the edits.
440    pub store: Option<Arc<dyn ChunkStore>>,
441    /// Streaming activity / eviction radii used by
442    /// [`Scene::pump_streaming_sync`] (S7.1). Defaults to
443    /// [`StreamRadius::DISABLED`] so existing grids see no change
444    /// in behaviour until the caller opts in.
445    pub stream_radius: StreamRadius,
446    /// Per-chunk edit version counter (S7.2). Each user edit
447    /// through [`Self::set_voxel`] / [`Self::set_rect`] /
448    /// [`Self::set_sphere`] bumps the counter for every chunk it
449    /// actually wrote to. [`Self::ensure_chunk_generated`] does
450    /// NOT bump — a freshly generated chunk has no edits and
451    /// reads as version 0.
452    ///
453    /// Wired up here so the S7.3 async dispatch can detect "an
454    /// edit happened while a chunk was being generated in the
455    /// background" and discard the now-stale result: each
456    /// background task captures the dispatch-time version and
457    /// only installs its result iff the current version still
458    /// matches.
459    ///
460    /// Missing entries read as `0` via [`Self::chunk_version`].
461    /// Evictions in [`Scene::pump_streaming_sync`] drop the
462    /// corresponding entry so the map stays bounded.
463    ///
464    /// QE.3b — private: every mutation goes through
465    /// [`Self::bump_chunk_version`] / [`Self::bump_chunk_version_bbox`]
466    /// / the crate-internal tracking helpers, so the
467    /// version/extent/counter triple can never desync. Read via
468    /// [`Self::chunk_version`] / [`Self::chunk_versions`].
469    chunk_versions: HashMap<IVec3, u64>,
470    /// In-flight background generation tasks (S7.3).
471    ///
472    /// Populated by [`Scene::pump_streaming`] when it dispatches a
473    /// generator call onto the streaming rayon pool, drained when
474    /// the corresponding `ChunkResult` is received and processed
475    /// (either installed or discarded). The set is consulted to
476    /// avoid re-dispatching the same chunk while a previous task
477    /// is still running.
478    ///
479    /// Stays empty when only the synchronous
480    /// [`Scene::pump_streaming_sync`] is used — that path generates
481    /// inline on the calling thread.
482    pub pending_gen: HashSet<IVec3>,
483    /// Cross-frame DDA brick-occupancy cache (Substage DDA.7 perf).
484    /// Keyed by `(chunk, mip)` + the chunk's edit version, so a static
485    /// chunk's brick map is built once and reused every frame. Skipped
486    /// entirely on the voxlap render path. Not serialised.
487    pub dda_brick_cache: roxlap_core::BrickCache,
488    /// PF.12 — per-chunk change extent accumulated since a consumer
489    /// last [`Self::take_chunk_dirty`]'d it: the partial-refresh /
490    /// incremental-remip companion to [`Self::chunk_versions`]. Bounded
491    /// by the chunk count (one merged entry per chunk). Not serialised.
492    chunk_dirty: HashMap<IVec3, DirtyExtent>,
493    /// PF.13 (H9) — monotonic counter bumped by EVERY chunk-set /
494    /// chunk-content mutation (edits, installs, evictions). Per-frame
495    /// consumers (the GPU dirty poll, the brick-cache sweep) compare it
496    /// against their last-seen value and skip their O(all chunks) scans
497    /// outright on quiet frames. Not serialised.
498    mutations: u64,
499    /// PF.13 (H9) — `(mutation counter, requested mip, effective mip)`
500    /// of the last [`Self::ensure_dda_bricks`] sweep; a matching pair
501    /// skips the whole per-chunk ensure + retain pass.
502    last_bricks: Option<(u64, u32, u32)>,
503}
504
505/// PF.12 — how much of a chunk changed since a consumer last synced it.
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
507pub enum DirtyExtent {
508    /// Unknown / whole-chunk change (installs, wholesale replaces,
509    /// extent-less [`Grid::bump_chunk_version`] calls).
510    Full,
511    /// Inclusive CHUNK-LOCAL voxel bbox covering every change.
512    Bbox(IVec3, IVec3),
513}
514
515impl Grid {
516    /// New empty grid at the given transform — no chunks populated,
517    /// `render_sky = true`, LOD thresholds default to
518    /// [`LodThresholds::always_near`], no billboard cache.
519    #[must_use]
520    pub fn new(transform: GridTransform) -> Self {
521        Self {
522            transform,
523            chunks: HashMap::new(),
524            render_sky: true,
525            mip_levels_override: None,
526            lod_thresholds: LodThresholds::always_near(),
527            billboards: None,
528            generator: None,
529            name: None,
530            store: None,
531            stream_radius: StreamRadius::DISABLED,
532            chunk_versions: HashMap::new(),
533            pending_gen: HashSet::new(),
534            dda_brick_cache: roxlap_core::BrickCache::new(),
535            chunk_dirty: HashMap::new(),
536            mutations: 0,
537            last_bricks: None,
538        }
539    }
540
541    /// Ensure the DDA brick cache holds current mip-`requested_mip`
542    /// occupancy maps for every populated chunk, rebuilding only chunks
543    /// whose edit version changed (Substage DDA.7). Clamps the mip to a
544    /// level every chunk has built (so coarse rendering never holes) and
545    /// returns that effective mip. Evicts cache entries for chunks no
546    /// longer present. Call once per frame before the DDA render.
547    pub fn ensure_dda_bricks(&mut self, requested_mip: u32) -> u32 {
548        // Split-borrow disjoint fields so the cache mutates while the
549        // chunks + versions are read.
550        // PF.13 (H9) — quiet frame at the same requested mip ⇒ nothing
551        // in the cache can be stale: skip the whole O(chunks) sweep.
552        if let Some((counter, req, eff)) = self.last_bricks {
553            if counter == self.mutations && req == requested_mip {
554                return eff;
555            }
556        }
557        let mutations = self.mutations;
558        let Self {
559            chunks,
560            chunk_versions,
561            dda_brick_cache,
562            ..
563        } = self;
564        // Effective uniform mip: min built mip across chunks, capped.
565        let mut mip = requested_mip;
566        if requested_mip > 0 {
567            for vxl in chunks.values() {
568                mip = mip.min(vxl.mip_count().saturating_sub(1));
569            }
570        }
571        for (idx, vxl) in chunks.iter() {
572            let version = chunk_versions.get(idx).copied().unwrap_or(0);
573            let view = roxlap_core::GridView::from_single_vxl(vxl);
574            dda_brick_cache.ensure([idx.x, idx.y, idx.z], mip, version, &view);
575        }
576        dda_brick_cache.retain_chunks(|c| chunks.contains_key(&IVec3::new(c[0], c[1], c[2])));
577        self.last_bricks = Some((mutations, requested_mip, mip));
578        mip
579    }
580
581    /// Current per-chunk edit version (S7.2). Returns `0` for any
582    /// chunk that hasn't been edited yet (including absent chunks
583    /// and chunks materialised only via
584    /// [`Self::ensure_chunk_generated`]).
585    ///
586    /// Used by S7.3's async generation dispatch to detect "edit
587    /// happened while we were generating" — the dispatcher
588    /// snapshots this value, the background task carries it, and
589    /// the result is discarded on install if the live counter has
590    /// since moved.
591    #[must_use]
592    pub fn chunk_version(&self, chunk_idx: IVec3) -> u64 {
593        self.chunk_versions.get(&chunk_idx).copied().unwrap_or(0)
594    }
595
596    /// Bump the edit version of `chunk_idx` (S7.2). Saturating add
597    /// at `u64::MAX` — a chunk would need 10^11 edits per second
598    /// for ~5 years to wrap, so saturation is a defensive cap, not
599    /// a realistic concern.
600    ///
601    /// Called by the edit API ([`Self::set_voxel`] /
602    /// [`Self::set_rect`] / [`Self::set_sphere`]) after a chunk
603    /// has actually been written to. Pure no-op edit paths
604    /// (carving from an air chunk that doesn't exist yet) skip
605    /// the bump.
606    ///
607    /// Exposed as `pub` (vs the historical `pub(crate)`) so hosts
608    /// that mutate `grid.chunks` directly — e.g.
609    /// `roxlap-scene-demo`'s `StreamingBakeTracker` writing
610    /// lightmode-1 alphas via `apply_lighting_with_cache` — can
611    /// signal "this chunk's slab changed" to downstream consumers
612    /// like the GPU dirty-chunk poller.
613    pub fn bump_chunk_version(&mut self, chunk_idx: IVec3) {
614        let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
615        *entry = entry.saturating_add(1);
616        // PF.12 — no extent information ⇒ the whole chunk must be
617        // treated as changed by partial-refresh consumers.
618        self.chunk_dirty.insert(chunk_idx, DirtyExtent::Full);
619        self.mutations = self.mutations.wrapping_add(1);
620    }
621
622    /// PF.13 (H9) — the grid's monotonic mutation counter: bumped by
623    /// every chunk edit, install, and eviction. Per-frame consumers
624    /// snapshot it to skip their whole-grid scans on quiet frames.
625    #[must_use]
626    pub fn mutation_counter(&self) -> u64 {
627        self.mutations
628    }
629
630    /// PF.12 — [`Self::bump_chunk_version`] with the edit's CHUNK-LOCAL
631    /// voxel extent (inclusive), so partial-refresh consumers (the GPU
632    /// facade) and incremental re-mip know how little actually changed.
633    /// Extents accumulate (bbox union) until a consumer
634    /// [`Self::take_chunk_dirty`]s them; an extent-less bump upgrades
635    /// the entry to [`DirtyExtent::Full`].
636    pub fn bump_chunk_version_bbox(&mut self, chunk_idx: IVec3, lo: IVec3, hi: IVec3) {
637        let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
638        *entry = entry.saturating_add(1);
639        let merged = match self.chunk_dirty.get(&chunk_idx) {
640            Some(DirtyExtent::Full) => DirtyExtent::Full,
641            Some(DirtyExtent::Bbox(l, h)) => DirtyExtent::Bbox(l.min(lo), h.max(hi)),
642            None => DirtyExtent::Bbox(lo, hi),
643        };
644        self.chunk_dirty.insert(chunk_idx, merged);
645        self.mutations = self.mutations.wrapping_add(1);
646    }
647
648    /// PF.12 — take (and clear) the extent accumulated for `chunk_idx`
649    /// since the last take. `None` ⇒ no recorded change (a consumer that
650    /// still observed a version bump should treat that as
651    /// [`DirtyExtent::Full`] — e.g. a change recorded before the
652    /// consumer first synced the chunk).
653    pub fn take_chunk_dirty(&mut self, chunk_idx: IVec3) -> Option<DirtyExtent> {
654        self.chunk_dirty.remove(&chunk_idx)
655    }
656
657    /// The full per-chunk edit-version map (QE.3b — the read half of
658    /// the previously `pub` field). Consumers seeding a sync tracker
659    /// iterate this; per-chunk reads go through
660    /// [`Self::chunk_version`].
661    #[must_use]
662    pub fn chunk_versions(&self) -> &HashMap<IVec3, u64> {
663        &self.chunk_versions
664    }
665
666    /// QE.3b — record a chunk-**set** mutation (materialise / install /
667    /// evict) on the PF.13 quiet-frame counter. The single entry point
668    /// for the counter besides the version bumps above; per-frame
669    /// consumers compare [`Self::mutation_counter`] snapshots.
670    pub(crate) fn note_chunk_set_changed(&mut self) {
671        self.mutations = self.mutations.wrapping_add(1);
672    }
673
674    /// QE.3b — drop `chunk_idx`'s per-chunk tracking on eviction, so
675    /// both maps stay bounded by the live chunk count. (Also clears any
676    /// accumulated [`DirtyExtent`] — pre-QE.3b that entry leaked until
677    /// a consumer happened to take it.) A future re-stream of the same
678    /// index restarts at version 0.
679    pub(crate) fn forget_chunk_tracking(&mut self, chunk_idx: IVec3) {
680        self.chunk_versions.remove(&chunk_idx);
681        self.chunk_dirty.remove(&chunk_idx);
682    }
683
684    /// QE.3b — seat a restored per-chunk version verbatim (the
685    /// [`snapshot`] load path; not an edit, so no extent / counter
686    /// side-effects).
687    pub(crate) fn restore_chunk_version(&mut self, chunk_idx: IVec3, version: u64) {
688        self.chunk_versions.insert(chunk_idx, version);
689    }
690
691    /// Attach (or detach) the procedural generator used by
692    /// [`Self::ensure_chunk_generated`] (S7.0).
693    ///
694    /// Pass `Some(Arc::new(generator))` to enable on-demand chunk
695    /// generation; pass `None` to revert to the "absent stays
696    /// absent" behaviour. Replacing an existing generator drops the
697    /// previous `Arc` clone without touching already-materialised
698    /// chunks. Any background tasks dispatched by a prior
699    /// [`Scene::pump_streaming`] hold their own clones of the old
700    /// generator and finish naturally.
701    pub fn set_generator(&mut self, generator: Option<Arc<dyn ChunkGenerator>>) {
702        self.generator = generator;
703    }
704
705    /// Attach (or detach) the persistence store for edited streamed
706    /// chunks (QE.5a; see [`ChunkStore`]). Without one, evicting an
707    /// edited chunk **discards the edits** — the pre-QE.5 default.
708    pub fn set_chunk_store(&mut self, store: Option<Arc<dyn ChunkStore>>) {
709        self.store = store;
710    }
711
712    /// Materialise the chunk at `chunk_idx` by running [`Self::generator`]
713    /// if (a) the chunk is not already present and (b) a generator
714    /// is attached. Returns `true` iff a chunk was newly generated.
715    ///
716    /// No-ops in all other cases:
717    /// - chunk already present (caller edits / a previous
718    ///   `ensure_chunk_generated` call already populated it),
719    /// - no generator attached (the chunk stays implicit-air per
720    ///   the existing convention — does NOT fall through to
721    ///   [`Self::ensure_chunk`]'s empty-chunk constructor).
722    ///
723    /// This is the synchronous S7.0 path; [`Scene::pump_streaming`]
724    /// is the async counterpart (generation + store loads on a
725    /// dedicated rayon pool).
726    ///
727    /// QE.5a: with a [`ChunkStore`] attached, a stored chunk is
728    /// installed (with its persisted edit version) **before** the
729    /// generator is consulted — including for indices the generator's
730    /// [`ChunkGenerator::should_generate`] declines, since edits can
731    /// materialise chunks the generator never would.
732    pub fn ensure_chunk_generated(&mut self, chunk_idx: IVec3) -> bool {
733        if self.chunks.contains_key(&chunk_idx) {
734            return false;
735        }
736        // QE.5a — persisted edits win over regeneration.
737        if let Some((vxl, version)) = self.store.as_ref().and_then(|store| store.load(chunk_idx)) {
738            self.chunks.insert(chunk_idx, vxl);
739            self.restore_chunk_version(chunk_idx, version);
740            self.note_chunk_set_changed();
741            self.billboards = None; // same invalidation as below
742            return true;
743        }
744        let Some(generator) = self.generator.as_ref() else {
745            return false;
746        };
747        // S7.6+: generator may decline specific indices (e.g. a
748        // single-z-layer generator skipping placeholder bedrock
749        // chunks at chz != 0). Respect the filter so we don't
750        // materialise an unwanted chunk.
751        if !generator.should_generate(chunk_idx) {
752            return false;
753        }
754        let chunk = generator.generate(chunk_idx);
755        self.chunks.insert(chunk_idx, chunk);
756        self.note_chunk_set_changed();
757        // S7.4: a fresh chunk grows the populated AABB → the
758        // bounding sphere shifts/expands → existing impostor
759        // projections become wrong. Match the eviction (S7.1) +
760        // edit (S6.2) invalidation contract and drop the cache.
761        // Next Far-tier render rebuilds lazily.
762        self.billboards = None;
763        true
764    }
765
766    /// Bounding-sphere radius of the populated chunk set in
767    /// grid-local space.
768    ///
769    /// Walks the sparse chunk map once, computes the chunk-index
770    /// AABB, converts to voxel-space half-extent, returns its
771    /// Euclidean length. Empty grid → `0.0`.
772    ///
773    /// Conservative — bounds the full chunk volume, not just its
774    /// populated voxels (a chunk containing one voxel still
775    /// contributes `CHUNK_SIZE_XY × CHUNK_SIZE_XY × CHUNK_SIZE_Z`
776    /// to the bbox). For LOD picking that's fine: an over-bound
777    /// sphere errs on the side of `Near`.
778    ///
779    /// Cost: `O(chunks.len())`; recomputed on every call. Callers
780    /// who need this every frame should memoize at the
781    /// [`Scene`]-level cache (added when S6.2 needs it).
782    #[must_use]
783    pub fn bounding_radius(&self) -> f64 {
784        if self.chunks.is_empty() {
785            return 0.0;
786        }
787        let mut min = IVec3::splat(i32::MAX);
788        let mut max = IVec3::splat(i32::MIN);
789        for &idx in self.chunks.keys() {
790            min = min.min(idx);
791            max = max.max(idx);
792        }
793        // Chunk-index bbox → voxel-space half-extent. `+1` on max
794        // converts inclusive chunk index to exclusive voxel upper
795        // bound (chunk `idx` covers voxels `[idx*size, (idx+1)*size)`).
796        let sx = f64::from(CHUNK_SIZE_XY);
797        let sz = f64::from(CHUNK_SIZE_Z);
798        let lo = DVec3::new(
799            f64::from(min.x) * sx,
800            f64::from(min.y) * sx,
801            f64::from(min.z) * sz,
802        );
803        let hi = DVec3::new(
804            f64::from(max.x + 1) * sx,
805            f64::from(max.y + 1) * sx,
806            f64::from(max.z + 1) * sz,
807        );
808        let half_extent = (hi - lo) * 0.5;
809        half_extent.length()
810    }
811
812    /// Pick this grid's LOD tier for the given world-space camera
813    /// position. Convenience wrapper around [`crate::select_lod`]
814    /// that pulls [`Self::lod_thresholds`] from the grid.
815    #[must_use]
816    pub fn select_lod(&self, camera_world_pos: DVec3) -> Lod {
817        select_lod(camera_world_pos, &self.transform, self.lod_thresholds)
818    }
819}
820
821/// Top-level scene container. Holds a flat collection of grids
822/// keyed by [`GridId`].
823///
824/// S2.0 only exposes registration / removal / lookup. Address math
825/// helpers (S2.x), edit API (S2.x), and rendering composition (S3)
826/// land in later sub-substages.
827#[derive(Debug, Default)]
828pub struct Scene {
829    grids: HashMap<GridId, Grid>,
830    next_grid_id: u32,
831    /// S7.3: per-scene streaming pool + result channel. Stored on
832    /// the `Scene` so `pump_streaming` can dispatch background
833    /// tasks and drain results across pump calls. `cfg`-gated out
834    /// on wasm32 where `pump_streaming` short-circuits to
835    /// `pump_streaming_sync` (no rayon pool there).
836    #[cfg(not(target_arch = "wasm32"))]
837    streaming: streaming::StreamingState,
838}
839
840impl Scene {
841    /// New empty scene — no grids.
842    #[must_use]
843    pub fn new() -> Self {
844        Self::default()
845    }
846
847    /// Number of grids currently registered.
848    #[must_use]
849    pub fn grid_count(&self) -> usize {
850        self.grids.len()
851    }
852
853    /// Register a new grid. Returns its fresh, unique [`GridId`].
854    pub fn add_grid(&mut self, transform: GridTransform) -> GridId {
855        let id = GridId(self.next_grid_id);
856        self.next_grid_id += 1;
857        self.grids.insert(id, Grid::new(transform));
858        id
859    }
860
861    /// Remove a grid by id. Returns the removed [`Grid`] (so the
862    /// caller can reclaim its chunks) or `None` if the id wasn't
863    /// registered. Removed ids are not reissued.
864    pub fn remove_grid(&mut self, id: GridId) -> Option<Grid> {
865        self.grids.remove(&id)
866    }
867
868    /// Borrow a registered grid.
869    #[must_use]
870    pub fn grid(&self, id: GridId) -> Option<&Grid> {
871        self.grids.get(&id)
872    }
873
874    /// Mutably borrow a registered grid.
875    pub fn grid_mut(&mut self, id: GridId) -> Option<&mut Grid> {
876        self.grids.get_mut(&id)
877    }
878
879    /// Iterator over all `(id, grid)` pairs in registration order
880    /// is **not** guaranteed — the underlying map is a `HashMap`.
881    /// Callers that need a stable order must sort by [`GridId`].
882    pub fn grids(&self) -> impl Iterator<Item = (GridId, &Grid)> {
883        self.grids.iter().map(|(id, g)| (*id, g))
884    }
885
886    /// Mutable iterator over all `(id, grid)` pairs. Yield order
887    /// is not guaranteed (HashMap-backed).
888    pub fn grids_mut(&mut self) -> impl Iterator<Item = (GridId, &mut Grid)> {
889        self.grids.iter_mut().map(|(id, g)| (*id, g))
890    }
891
892    /// Resolve a world-space surface hit to the owning grid + its
893    /// grid-local voxel — the picking back half. `ray_dir` is the view
894    /// direction the hit was found along (need not be normalised); the
895    /// point is nudged half a voxel along it, past the surface and into
896    /// the solid cell, before each grid's [`Grid::voxel_solid`] test.
897    /// Returns the first grid that is solid there (transform-correct
898    /// for rotated/translated grids), or `None` if none claims it.
899    ///
900    /// Backend-agnostic: pair with a renderer depth read to turn a
901    /// click into a voxel — `world = cam.pos + t · normalize(ray_dir)`,
902    /// then `resolve_voxel(world, ray_dir)`. `roxlap-render`'s
903    /// `SceneRenderer::pick` wires exactly that.
904    #[must_use]
905    pub fn resolve_voxel(&self, world: DVec3, ray_dir: DVec3) -> Option<(GridId, IVec3)> {
906        let len = ray_dir.length();
907        if len < 1e-9 {
908            return None;
909        }
910        let inside = world + ray_dir * (0.5 / len); // half a voxel inward
911        for (id, grid) in self.grids() {
912            let glp = addr::world_to_grid_local(inside, &grid.transform);
913            let v = addr::voxel_global(glp.chunk, glp.voxel);
914            if grid.voxel_solid(v) {
915                return Some((id, v));
916            }
917        }
918        None
919    }
920
921    /// Cast a world-space ray and return the nearest solid voxel hit
922    /// across all grids, or `None` if nothing solid lies within
923    /// `max_dist`. Renderer-independent (no depth buffer, no camera) —
924    /// the primitive for line-of-sight, projectiles, AI probing, and
925    /// off-screen / backend-agnostic picking.
926    ///
927    /// `dir` need not be normalised. Each grid's ray is transformed
928    /// into the grid's local frame (so rotated / translated grids are
929    /// handled exactly) and marched with a voxel DDA against
930    /// [`Grid::voxel_solid`]; the closest hit by world distance `t`
931    /// wins. The step budget is bounded by `max_dist`, so empty space
932    /// is safe but not free — a chunk-level skip is a future
933    /// optimisation if hot.
934    #[must_use]
935    pub fn raycast(&self, origin: DVec3, dir: DVec3, max_dist: f64) -> Option<RayHit> {
936        let len = dir.length();
937        if len < 1e-12 || max_dist <= 0.0 {
938            return None;
939        }
940        let dn = dir / len; // unit world direction → t is world distance
941        let mut best: Option<RayHit> = None;
942        for (id, grid) in self.grids() {
943            // World ray → grid-local: undo translation + rotation. The
944            // inverse rotation preserves length, so `t` stays in world
945            // units and is comparable across grids.
946            let inv = grid.transform.rotation.inverse();
947            let lo = inv * (origin - grid.transform.origin);
948            let ld = inv * dn;
949            if let Some((voxel, t)) = voxel_dda(grid, lo, ld, max_dist) {
950                if best.as_ref().map_or(true, |b| t < b.t) {
951                    best = Some(RayHit {
952                        grid: id,
953                        voxel,
954                        world: origin + dn * t,
955                        t,
956                        color: grid.voxel_color(voxel),
957                    });
958                }
959            }
960        }
961        best
962    }
963
964    /// Configure the number of worker threads in the dedicated
965    /// streaming pool (S7.3).
966    ///
967    /// Lazily applied — the pool itself is constructed on the first
968    /// [`Self::pump_streaming`] call. If the pool was already built
969    /// (i.e. a previous `pump_streaming` already dispatched at
970    /// least one task), it gets dropped and rebuilt. Dropping the
971    /// old pool blocks until all of its in-flight tasks finish
972    /// (rayon's contract); any results those tasks sent are still
973    /// drained by the next `pump_streaming` because the channel
974    /// survives the rebuild.
975    ///
976    /// The streaming pool is separate from rayon's global pool
977    /// (which R12 multicore rendering uses), so chunk generation
978    /// doesn't compete with render threads. Sensible values are 1
979    /// to ~4 — generation work is CPU-bound but should leave most
980    /// of the box for everything else.
981    ///
982    /// On wasm32 this is a no-op (no rayon pool available);
983    /// `pump_streaming` runs synchronously there.
984    ///
985    /// # Panics
986    /// Panics on native if `n == 0` (zero-thread pools are not
987    /// supported; the scene crate's S7.1 helper already disallows
988    /// the equivalent for `StreamRadius::r_active < 0`).
989    #[cfg(not(target_arch = "wasm32"))]
990    pub fn set_streaming_threads(&mut self, n: usize) {
991        self.streaming.set_thread_count(n);
992    }
993
994    /// wasm32 no-op companion of [`Self::set_streaming_threads`].
995    /// Lets cross-target code call this unconditionally.
996    #[cfg(target_arch = "wasm32")]
997    pub fn set_streaming_threads(&mut self, _n: usize) {
998        // No streaming pool on wasm32 — see `pump_streaming` docs.
999    }
1000
1001    /// Asynchronous streaming pump (S7.3).
1002    ///
1003    /// On native, dispatches missing-chunk generations onto a
1004    /// dedicated rayon pool, drains any results that arrived since
1005    /// the last pump, runs the eviction pass, and tracks in-flight
1006    /// tasks in each grid's [`Grid::pending_gen`] set. The drain
1007    /// uses the per-chunk version counter from S7.2 to discard
1008    /// results whose chunk was edited mid-generation.
1009    ///
1010    /// On wasm32 this short-circuits to [`Self::pump_streaming_sync`]
1011    /// — no thread pool is available there, but the same per-grid
1012    /// stream-in / evict semantics apply.
1013    ///
1014    /// Call once per frame from the render thread. Cheap when
1015    /// nothing changed (early-exit on disabled grids, try_recv
1016    /// loops empty fast).
1017    pub fn pump_streaming(&mut self, camera_world_pos: DVec3) {
1018        #[cfg(target_arch = "wasm32")]
1019        {
1020            self.pump_streaming_sync(camera_world_pos);
1021        }
1022        #[cfg(not(target_arch = "wasm32"))]
1023        {
1024            self.pump_streaming_native(camera_world_pos);
1025        }
1026    }
1027
1028    /// Native implementation of [`Self::pump_streaming`].
1029    #[cfg(not(target_arch = "wasm32"))]
1030    fn pump_streaming_native(&mut self, camera_world_pos: DVec3) {
1031        // 1. Drain inbox — install fresh results, drop stale.
1032        while let Ok(result) = self.streaming.rx.try_recv() {
1033            let Some(grid) = self.grids.get_mut(&result.grid_id) else {
1034                // Grid was removed while a generation task was
1035                // in-flight. Drop silently.
1036                continue;
1037            };
1038            // Clearing pending_gen here both for "result delivered"
1039            // and "we shouldn't try to re-dispatch this chunk just
1040            // because it's missing".
1041            let was_pending = grid.pending_gen.remove(&result.chunk_idx);
1042            if !was_pending {
1043                // Either the chunk was evicted (pending cleared in
1044                // the eviction pass below in some prior call), or a
1045                // duplicate result for an already-handled chunk.
1046                continue;
1047            }
1048            if grid.chunks.contains_key(&result.chunk_idx) {
1049                // Some other path (e.g. `ensure_chunk_generated`
1050                // sync helper, or a manual edit's `ensure_chunk`)
1051                // already populated the slot. Don't overwrite.
1052                continue;
1053            }
1054            if grid.chunk_version(result.chunk_idx) != result.version_at_dispatch {
1055                // S7.2 stale-result discard: chunk was edited mid-
1056                // generation.
1057                continue;
1058            }
1059            let Some(vxl) = result.vxl else {
1060                // QE.5a — nothing to install (store miss + generator
1061                // declined); the pending entry is already cleared.
1062                continue;
1063            };
1064            grid.chunks.insert(result.chunk_idx, vxl);
1065            if let Some(version) = result.restored_version {
1066                // QE.5a — a store-restored chunk keeps its persisted
1067                // edit version (consumers see it as edited content).
1068                grid.restore_chunk_version(result.chunk_idx, version);
1069            }
1070            grid.note_chunk_set_changed();
1071            // S7.4: same invalidation contract as the sync
1072            // `ensure_chunk_generated` path — installing a new
1073            // chunk can grow the bounding sphere, so the
1074            // billboard impostor cache must be rebuilt on next
1075            // Far entry. Lazy: only one cache wipe per drain
1076            // batch, the Far render rebuilds afterwards.
1077            grid.billboards = None;
1078        }
1079
1080        // 2. Per-grid: eviction first, then dispatch. Doing evict
1081        //    before dispatch means a chunk that's just left
1082        //    r_active doesn't get re-dispatched on the same pump.
1083        self.streaming.ensure_pool();
1084        // Disjoint sub-field borrows: pool/tx via `&self.streaming.*`,
1085        // grids via `&mut self.grids`. Hold both at once.
1086        let pool: &rayon::ThreadPool = self.streaming.pool.as_ref().expect("ensure_pool just ran");
1087        let tx_template = &self.streaming.tx;
1088        for (grid_id, grid) in &mut self.grids {
1089            evict_grid_chunks(grid, camera_world_pos);
1090            dispatch_grid_async(*grid_id, grid, camera_world_pos, pool, tx_template);
1091        }
1092    }
1093
1094    /// Synchronous streaming pump (S7.1).
1095    ///
1096    /// For each grid with a non-[`StreamRadius::DISABLED`] policy:
1097    /// 1. Project the world-space camera into grid-local coords
1098    ///    (inverse rotation + origin subtract).
1099    /// 2. Stream in any chunk whose AABB-to-camera distance is
1100    ///    `<= r_active`, calling [`Grid::ensure_chunk_generated`].
1101    ///    No-ops gracefully if the grid has no generator attached
1102    ///    (so callers can use the eviction half of streaming on a
1103    ///    purely-edited grid).
1104    /// 3. Evict any chunk whose AABB-to-camera distance exceeds
1105    ///    `r_evict` from the grid's chunk map. Eviction also
1106    ///    clears the cached [`BillboardCache`] (the bounding sphere
1107    ///    may shrink, invalidating impostor projections; the next
1108    ///    Far-tier render rebuilds lazily).
1109    ///
1110    /// Both passes use the f64 grid-local position so rotation +
1111    /// non-axis-aligned grids stream and evict correctly. The
1112    /// generate path is blocking — S7.3 will move it to a
1113    /// background rayon pool with `pump_streaming` (non-blocking).
1114    /// Callers that want the async variant in S7.0/S7.1 stages
1115    /// should keep `r_active` small.
1116    pub fn pump_streaming_sync(&mut self, camera_world_pos: DVec3) {
1117        for grid in self.grids.values_mut() {
1118            pump_grid_streaming_sync(grid, camera_world_pos);
1119        }
1120    }
1121}
1122
1123/// S7.1 helper — drives one grid's synchronous streaming pass.
1124/// Stream-in pass uses [`Grid::ensure_chunk_generated`] (blocking
1125/// inline generation); eviction pass shared with the S7.3 async
1126/// path through [`evict_grid_chunks`].
1127fn pump_grid_streaming_sync(grid: &mut Grid, camera_world_pos: DVec3) {
1128    let radius = grid.stream_radius;
1129    if radius.is_disabled() {
1130        return;
1131    }
1132    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1133
1134    // --- Pass 1: stream in active chunks (sync) ---------------
1135    // QE.5a — a ChunkStore alone (no generator) still restores
1136    // persisted edited chunks.
1137    if radius.r_active > 0.0 && (grid.generator.is_some() || grid.store.is_some()) {
1138        for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
1139            grid.ensure_chunk_generated(idx);
1140        });
1141    }
1142
1143    // --- Pass 2: evict chunks past r_evict --------------------
1144    evict_grid_chunks_with_cam(grid, cam_local);
1145}
1146
1147/// Eviction pass shared by [`pump_grid_streaming_sync`] and the
1148/// S7.3 async path. Public-ish so the async driver can call it
1149/// before dispatching to avoid generating chunks that are about
1150/// to be evicted. `cfg`-gated to native: on wasm32 the only
1151/// caller (`pump_streaming_native`) doesn't compile, so this
1152/// helper would warn as dead code.
1153#[cfg(not(target_arch = "wasm32"))]
1154fn evict_grid_chunks(grid: &mut Grid, camera_world_pos: DVec3) {
1155    let radius = grid.stream_radius;
1156    if radius.is_disabled() {
1157        return;
1158    }
1159    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1160    evict_grid_chunks_with_cam(grid, cam_local);
1161}
1162
1163/// Eviction inner — assumes `cam_local` is already computed (the
1164/// dispatcher and sync pump both have it on hand).
1165fn evict_grid_chunks_with_cam(grid: &mut Grid, cam_local: DVec3) {
1166    let radius = grid.stream_radius;
1167    if !radius.r_evict.is_finite() {
1168        return;
1169    }
1170    let r_sq = radius.r_evict * radius.r_evict;
1171    let to_evict: Vec<IVec3> = grid
1172        .chunks
1173        .keys()
1174        .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
1175        .copied()
1176        .collect();
1177    // S7.3: also evict pending in-flight tasks past r_evict so the
1178    // drain pass doesn't install a chunk that's no longer wanted.
1179    // We don't have a way to cancel the rayon task, but we can
1180    // drop the pending_gen entry so the result is dropped on
1181    // arrival.
1182    let to_evict_pending: Vec<IVec3> = grid
1183        .pending_gen
1184        .iter()
1185        .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
1186        .copied()
1187        .collect();
1188    if to_evict.is_empty() && to_evict_pending.is_empty() {
1189        return;
1190    }
1191    for idx in &to_evict {
1192        // QE.5a — an edited chunk (version != 0) is handed to the
1193        // ChunkStore before it drops, so the edits survive evict +
1194        // re-stream. Pristine generator output (version 0) is
1195        // regenerable and skips the store.
1196        if let Some(store) = grid.store.as_ref() {
1197            let version = grid.chunk_version(*idx);
1198            if version != 0 {
1199                if let Some(vxl) = grid.chunks.get(idx) {
1200                    store.store(*idx, vxl, version);
1201                }
1202            }
1203        }
1204        grid.chunks.remove(idx);
1205        grid.note_chunk_set_changed();
1206        // S7.2/QE.3b: drop the chunk's version + dirty-extent tracking
1207        // so both maps stay bounded. A future re-stream of the same idx
1208        // restarts at 0 — that's fine because any in-flight gen-result
1209        // tagged with the pre-eviction version is unreachable (no chunk
1210        // to install onto) and gets discarded by the new "version
1211        // still 0" check anyway. (A stored edited chunk re-enters with
1212        // its persisted version via the QE.5a load path instead.)
1213        grid.forget_chunk_tracking(*idx);
1214        // S7.3: drop pending entry for the same chunk too. If a
1215        // background task is still running, its result will be
1216        // dropped on arrival (was_pending = false).
1217        grid.pending_gen.remove(idx);
1218    }
1219    for idx in &to_evict_pending {
1220        grid.pending_gen.remove(idx);
1221    }
1222    if !to_evict.is_empty() {
1223        // Bounding sphere can shrink → impostor projections would
1224        // be wrong on next Far render. Clear lazily; the next
1225        // Far-tier pass repopulates via BillboardCache::build.
1226        grid.billboards = None;
1227    }
1228}
1229
1230/// Walk every chunk index whose AABB falls within `r_active` of
1231/// `cam_local` and invoke `f` on it. Shared between the S7.1 sync
1232/// stream-in and the S7.3 async dispatch.
1233fn for_each_chunk_in_radius<F>(cam_local: DVec3, r_active: f64, mut f: F)
1234where
1235    F: FnMut(IVec3),
1236{
1237    let r_sq = r_active * r_active;
1238    let sxy = f64::from(CHUNK_SIZE_XY);
1239    let sz = f64::from(CHUNK_SIZE_Z);
1240    // Half-extent in chunk units; ceil to be conservative so any
1241    // chunk whose AABB clips the radius gets considered. `+1`
1242    // covers the half-open chunk-AABB upper edge plus the case
1243    // where the camera sits exactly on a chunk boundary and the
1244    // closest chunk is one index off.
1245    #[allow(clippy::cast_possible_truncation)]
1246    let r_chunks_xy = (r_active / sxy).ceil() as i32 + 1;
1247    #[allow(clippy::cast_possible_truncation)]
1248    let r_chunks_z = (r_active / sz).ceil() as i32 + 1;
1249    #[allow(clippy::cast_possible_truncation)]
1250    let cx_chunk = (cam_local.x / sxy).floor() as i32;
1251    #[allow(clippy::cast_possible_truncation)]
1252    let cy_chunk = (cam_local.y / sxy).floor() as i32;
1253    #[allow(clippy::cast_possible_truncation)]
1254    let cz_chunk = (cam_local.z / sz).floor() as i32;
1255    for chz in (cz_chunk - r_chunks_z)..=(cz_chunk + r_chunks_z) {
1256        for chy in (cy_chunk - r_chunks_xy)..=(cy_chunk + r_chunks_xy) {
1257            for chx in (cx_chunk - r_chunks_xy)..=(cx_chunk + r_chunks_xy) {
1258                let idx = IVec3::new(chx, chy, chz);
1259                if streaming::chunk_aabb_dist_sq(cam_local, idx) <= r_sq {
1260                    f(idx);
1261                }
1262            }
1263        }
1264    }
1265}
1266
1267/// S7.3 async dispatch — schedule generation for every chunk in
1268/// `r_active` that's not already present and not already in
1269/// flight. Each dispatch clones the grid's generator `Arc` and a
1270/// sender clone, then spawns the closure on the streaming rayon
1271/// pool. The closure does the generate + send; the main thread
1272/// drains results on the next pump.
1273#[cfg(not(target_arch = "wasm32"))]
1274fn dispatch_grid_async(
1275    grid_id: GridId,
1276    grid: &mut Grid,
1277    camera_world_pos: DVec3,
1278    pool: &rayon::ThreadPool,
1279    tx: &crossbeam_channel::Sender<streaming::ChunkResult>,
1280) {
1281    let radius = grid.stream_radius;
1282    if radius.is_disabled() || radius.r_active <= 0.0 {
1283        return;
1284    }
1285    // QE.5a — a ChunkStore alone (no generator) still restores
1286    // persisted edited chunks on the background pool.
1287    let generator = grid.generator.as_ref().map(Arc::clone);
1288    let store = grid.store.as_ref().map(Arc::clone);
1289    if generator.is_none() && store.is_none() {
1290        return;
1291    }
1292    let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1293    for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
1294        if grid.chunks.contains_key(&idx) {
1295            return; // already present
1296        }
1297        if grid.pending_gen.contains(&idx) {
1298            return; // already in flight
1299        }
1300        // S7.6+: respect the generator's per-chunk filter — same
1301        // contract as `Grid::ensure_chunk_generated` (sync helper).
1302        // Lets a generator decline to materialise specific indices
1303        // (e.g. `HillsChunkGenerator` skipping placeholder bedrock
1304        // chunks at chz != 0 so the camera-above-grid path doesn't
1305        // create chz < 0 entries that would shift `origin_chunk_z`
1306        // and trigger the S4B.6.j cross-chunk look-down bug).
1307        // QE.5a — with a store attached the chunk is still
1308        // dispatched: a persisted edit wins over the decline (edits
1309        // can materialise chunks the generator never would); the
1310        // background task falls back to "nothing" on a store miss.
1311        let declined = !generator.as_ref().is_some_and(|g| g.should_generate(idx));
1312        if declined && store.is_none() {
1313            return;
1314        }
1315        grid.pending_gen.insert(idx);
1316        let version_at_dispatch = grid.chunk_version(idx);
1317        let tx_clone = tx.clone();
1318        let gen_clone = generator.clone();
1319        let store_clone = store.clone();
1320        pool.spawn(move || {
1321            // QE.5a — persisted edits win over regeneration; the
1322            // store load runs here on the pool so blocking IO never
1323            // stalls the render thread.
1324            let (vxl, restored_version) = match store_clone.as_ref().and_then(|s| s.load(idx)) {
1325                Some((vxl, version)) => (Some(vxl), Some(version)),
1326                None if declined => (None, None),
1327                None => (gen_clone.map(|g| g.generate(idx)), None),
1328            };
1329            // Send is non-blocking on unbounded channel; if the
1330            // receiver was dropped (Scene drop), the send fails
1331            // silently — that's fine.
1332            let _ = tx_clone.send(streaming::ChunkResult {
1333                grid_id,
1334                chunk_idx: idx,
1335                version_at_dispatch,
1336                vxl,
1337                restored_version,
1338            });
1339        });
1340    });
1341}
1342
1343#[cfg(test)]
1344mod tests {
1345    use super::*;
1346
1347    #[test]
1348    fn empty_scene_has_no_grids() {
1349        let scene = Scene::new();
1350        assert_eq!(scene.grid_count(), 0);
1351        assert!(scene.grids().next().is_none());
1352    }
1353
1354    #[test]
1355    fn raycast_hits_axis_aligned_voxel() {
1356        let mut scene = Scene::new();
1357        let id = scene.add_grid(GridTransform::identity());
1358        scene
1359            .grid_mut(id)
1360            .unwrap()
1361            .set_voxel(IVec3::new(5, 5, 10), Some(VoxColor(0x80_aa_bb_cc)));
1362
1363        // Straight down the +z column through (5,5): hits z=10 at t≈10.
1364        let hit = scene
1365            .raycast(DVec3::new(5.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1366            .expect("ray hits the voxel");
1367        assert_eq!(hit.grid, id);
1368        assert_eq!(hit.voxel, IVec3::new(5, 5, 10));
1369        assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1370        assert!(hit.color.is_some(), "textured voxel has a colour");
1371
1372        // A column with no voxel misses.
1373        assert!(
1374            scene
1375                .raycast(DVec3::new(0.5, 0.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1376                .is_none(),
1377            "empty column → no hit",
1378        );
1379    }
1380
1381    #[test]
1382    fn raycast_respects_grid_transform() {
1383        // A translated grid: the hit voxel is reported in GRID-LOCAL
1384        // coords, and the world hit point is back in world space — so a
1385        // host gets the true voxel regardless of where the grid sits.
1386        let mut scene = Scene::new();
1387        let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1388        scene
1389            .grid_mut(id)
1390            .unwrap()
1391            .set_voxel(IVec3::new(5, 5, 10), Some(VoxColor(0x80_11_22_33)));
1392
1393        let hit = scene
1394            .raycast(DVec3::new(105.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1395            .expect("ray hits the translated voxel");
1396        assert_eq!(hit.voxel, IVec3::new(5, 5, 10), "grid-local voxel");
1397        assert!((hit.world.x - 105.5).abs() < 1e-6, "world x preserved");
1398        assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1399    }
1400
1401    #[test]
1402    fn raycast_picks_nearest_grid() {
1403        // Two grids with a voxel each along the same world column; the
1404        // raycast must return the closer one.
1405        let mut scene = Scene::new();
1406        let near = scene.add_grid(GridTransform::identity());
1407        let far = scene.add_grid(GridTransform::identity());
1408        scene
1409            .grid_mut(near)
1410            .unwrap()
1411            .set_voxel(IVec3::new(1, 1, 20), Some(VoxColor(0x80_00_ff_00)));
1412        scene
1413            .grid_mut(far)
1414            .unwrap()
1415            .set_voxel(IVec3::new(1, 1, 40), Some(VoxColor(0x80_ff_00_00)));
1416
1417        let hit = scene
1418            .raycast(DVec3::new(1.5, 1.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1419            .expect("hits the nearer voxel");
1420        assert_eq!(hit.grid, near);
1421        assert_eq!(hit.voxel, IVec3::new(1, 1, 20));
1422    }
1423
1424    #[test]
1425    fn add_grid_returns_fresh_ids() {
1426        let mut scene = Scene::new();
1427        let a = scene.add_grid(GridTransform::identity());
1428        let b = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1429        assert_ne!(a, b);
1430        assert_eq!(a.raw(), 0);
1431        assert_eq!(b.raw(), 1);
1432        assert_eq!(scene.grid_count(), 2);
1433    }
1434
1435    #[test]
1436    fn grid_lookup_round_trips() {
1437        let mut scene = Scene::new();
1438        let id = scene.add_grid(GridTransform::at(DVec3::new(10.0, 20.0, 30.0)));
1439        let g = scene.grid(id).expect("grid registered");
1440        assert_eq!(g.transform.origin, DVec3::new(10.0, 20.0, 30.0));
1441        assert_eq!(g.transform.rotation, DQuat::IDENTITY);
1442        assert!(g.chunks.is_empty());
1443    }
1444
1445    #[test]
1446    fn remove_grid_drops_it_from_scene() {
1447        let mut scene = Scene::new();
1448        let id = scene.add_grid(GridTransform::identity());
1449        let removed = scene.remove_grid(id);
1450        assert!(removed.is_some());
1451        assert_eq!(scene.grid_count(), 0);
1452        assert!(scene.grid(id).is_none());
1453        // Re-adding does NOT reuse the dropped id.
1454        let id2 = scene.add_grid(GridTransform::identity());
1455        assert_ne!(id, id2);
1456        assert_eq!(id2.raw(), 1);
1457    }
1458
1459    #[test]
1460    fn remove_unknown_grid_is_none() {
1461        let mut scene = Scene::new();
1462        let bogus = GridId(999);
1463        assert!(scene.remove_grid(bogus).is_none());
1464    }
1465
1466    #[test]
1467    fn grid_mut_can_modify_transform() {
1468        let mut scene = Scene::new();
1469        let id = scene.add_grid(GridTransform::identity());
1470        scene.grid_mut(id).unwrap().transform.origin = DVec3::new(1.0, 2.0, 3.0);
1471        assert_eq!(
1472            scene.grid(id).unwrap().transform.origin,
1473            DVec3::new(1.0, 2.0, 3.0)
1474        );
1475    }
1476
1477    #[test]
1478    fn chunk_size_constants_match_plan() {
1479        // Plan locks these values; bumping either breaks the slab
1480        // byte format (Z) or the worst-case chunk footprint budget
1481        // (XY). Pin them so a future refactor that drifts them
1482        // shows up in CI.
1483        assert_eq!(CHUNK_SIZE_XY, 128);
1484        assert_eq!(CHUNK_SIZE_Z, 256);
1485    }
1486
1487    // ---- S6.0: bounding_radius + Grid::select_lod ----
1488
1489    #[test]
1490    fn new_grid_defaults_to_always_near_lod() {
1491        // Byte-identity contract for the staged S6 rollout: a
1492        // grid built through `new` must never trigger the Mid/Far
1493        // branches by accident, even when bounding_radius would
1494        // imply otherwise.
1495        let g = Grid::new(GridTransform::identity());
1496        assert_eq!(g.lod_thresholds.r_near, f64::INFINITY);
1497        assert_eq!(g.lod_thresholds.r_mid, f64::INFINITY);
1498        assert_eq!(g.select_lod(DVec3::new(1e9, 0.0, 0.0)), Lod::Near);
1499    }
1500
1501    #[test]
1502    fn bounding_radius_empty_grid_is_zero() {
1503        let g = Grid::new(GridTransform::identity());
1504        assert_eq!(g.bounding_radius(), 0.0);
1505    }
1506
1507    #[test]
1508    fn bounding_radius_single_chunk_at_origin() {
1509        // One chunk at (0, 0, 0): bbox is [0, 128) × [0, 128) × [0, 256).
1510        // Half-extent = (64, 64, 128); length = sqrt(64² + 64² + 128²)
1511        //   = sqrt(4096 + 4096 + 16384) = sqrt(24576) ≈ 156.7747...
1512        let mut scene = Scene::new();
1513        let id = scene.add_grid(GridTransform::identity());
1514        let g = scene.grid_mut(id).unwrap();
1515        // Populate chunk (0, 0, 0) via the edit API.
1516        g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_88_88_88)));
1517        let r = g.bounding_radius();
1518        let expected = ((64.0_f64).powi(2) * 2.0 + (128.0_f64).powi(2)).sqrt();
1519        assert!(
1520            (r - expected).abs() < 1e-9,
1521            "bounding_radius={r} expected={expected}"
1522        );
1523    }
1524
1525    #[test]
1526    fn bounding_radius_grows_with_chunk_extent() {
1527        // Two chunks at (0,0,0) and (3,0,0): x extent is 4 chunks =
1528        // 512 voxels; y/z are 1 chunk each. Half-extent = (256, 64, 128);
1529        // length = sqrt(256² + 64² + 128²) = sqrt(65536+4096+16384)
1530        //        = sqrt(86016) ≈ 293.2848.
1531        let mut scene = Scene::new();
1532        let id = scene.add_grid(GridTransform::identity());
1533        let g = scene.grid_mut(id).unwrap();
1534        // Stamp one voxel in chunk (0,0,0).
1535        g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_88_88_88)));
1536        // Stamp one voxel in chunk (3,0,0): grid-local x = 3*128 = 384.
1537        g.set_voxel(IVec3::new(384, 0, 0), Some(VoxColor(0x80_88_88_88)));
1538        assert_eq!(g.chunks.len(), 2);
1539        let r = g.bounding_radius();
1540        let expected = (256.0_f64.powi(2) + 64.0_f64.powi(2) + 128.0_f64.powi(2)).sqrt();
1541        assert!(
1542            (r - expected).abs() < 1e-9,
1543            "bounding_radius={r} expected={expected}"
1544        );
1545    }
1546
1547    #[test]
1548    fn grid_select_lod_respects_lod_thresholds_field() {
1549        // Set a non-default threshold and verify the helper picks
1550        // the right tier for known distances.
1551        let mut scene = Scene::new();
1552        let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1553        let g = scene.grid_mut(id).unwrap();
1554        g.lod_thresholds = LodThresholds {
1555            r_near: 50.0,
1556            r_mid: 200.0,
1557            ..LodThresholds::always_near()
1558        };
1559        // Camera 25 units from grid origin → Near.
1560        assert_eq!(g.select_lod(DVec3::new(125.0, 0.0, 0.0)), Lod::Near);
1561        // 100 units → Mid.
1562        assert_eq!(g.select_lod(DVec3::new(200.0, 0.0, 0.0)), Lod::Mid);
1563        // 500 units → Far.
1564        assert_eq!(g.select_lod(DVec3::new(600.0, 0.0, 0.0)), Lod::Far);
1565    }
1566}