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::{BakeLight, 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 /// EV.3 — baked point lights ([`BakeLight`], grid-local voxel
447 /// coords) consumed by [`BakeMode::PointLights`]: [`Grid::bake`]
448 /// and [`Grid::bake_bbox`] write each light's Lambertian pool
449 /// into the brightness bytes, so incremental carve relights keep
450 /// their glow. Authoring state only — editing this list does
451 /// **not** rebake by itself (call [`Grid::bake`] after) and it is
452 /// not carried through snapshots (the baked bytes are; re-set the
453 /// list after a load if you keep editing). Ignored by the other
454 /// bake modes and by the dynamic `LightRig`.
455 pub bake_lights: Vec<BakeLight>,
456 /// Per-chunk edit version counter (S7.2). Each user edit
457 /// through [`Self::set_voxel`] / [`Self::set_rect`] /
458 /// [`Self::set_sphere`] bumps the counter for every chunk it
459 /// actually wrote to. [`Self::ensure_chunk_generated`] does
460 /// NOT bump — a freshly generated chunk has no edits and
461 /// reads as version 0.
462 ///
463 /// Wired up here so the S7.3 async dispatch can detect "an
464 /// edit happened while a chunk was being generated in the
465 /// background" and discard the now-stale result: each
466 /// background task captures the dispatch-time version and
467 /// only installs its result iff the current version still
468 /// matches.
469 ///
470 /// Missing entries read as `0` via [`Self::chunk_version`].
471 /// Evictions in [`Scene::pump_streaming_sync`] drop the
472 /// corresponding entry so the map stays bounded.
473 ///
474 /// QE.3b — private: every mutation goes through
475 /// [`Self::bump_chunk_version`] / [`Self::bump_chunk_version_bbox`]
476 /// / the crate-internal tracking helpers, so the
477 /// version/extent/counter triple can never desync. Read via
478 /// [`Self::chunk_version`] / [`Self::chunk_versions`].
479 chunk_versions: HashMap<IVec3, u64>,
480 /// In-flight background generation tasks (S7.3).
481 ///
482 /// Populated by [`Scene::pump_streaming`] when it dispatches a
483 /// generator call onto the streaming rayon pool, drained when
484 /// the corresponding `ChunkResult` is received and processed
485 /// (either installed or discarded). The set is consulted to
486 /// avoid re-dispatching the same chunk while a previous task
487 /// is still running.
488 ///
489 /// Stays empty when only the synchronous
490 /// [`Scene::pump_streaming_sync`] is used — that path generates
491 /// inline on the calling thread.
492 pub pending_gen: HashSet<IVec3>,
493 /// Cross-frame DDA brick-occupancy cache (Substage DDA.7 perf).
494 /// Keyed by `(chunk, mip)` + the chunk's edit version, so a static
495 /// chunk's brick map is built once and reused every frame. Skipped
496 /// entirely on the voxlap render path. Not serialised.
497 pub dda_brick_cache: roxlap_core::BrickCache,
498 /// PF.12 — per-chunk change extent accumulated since a consumer
499 /// last [`Self::take_chunk_dirty`]'d it: the partial-refresh /
500 /// incremental-remip companion to [`Self::chunk_versions`]. Bounded
501 /// by the chunk count (one merged entry per chunk). Not serialised.
502 chunk_dirty: HashMap<IVec3, DirtyExtent>,
503 /// PF.13 (H9) — monotonic counter bumped by EVERY chunk-set /
504 /// chunk-content mutation (edits, installs, evictions). Per-frame
505 /// consumers (the GPU dirty poll, the brick-cache sweep) compare it
506 /// against their last-seen value and skip their O(all chunks) scans
507 /// outright on quiet frames. Not serialised.
508 mutations: u64,
509 /// PF.13 (H9) — `(mutation counter, requested mip, effective mip)`
510 /// of the last [`Self::ensure_dda_bricks`] sweep; a matching pair
511 /// skips the whole per-chunk ensure + retain pass.
512 last_bricks: Option<(u64, u32, u32)>,
513}
514
515/// PF.12 — how much of a chunk changed since a consumer last synced it.
516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
517pub enum DirtyExtent {
518 /// Unknown / whole-chunk change (installs, wholesale replaces,
519 /// extent-less [`Grid::bump_chunk_version`] calls).
520 Full,
521 /// Inclusive CHUNK-LOCAL voxel bbox covering every change.
522 Bbox(IVec3, IVec3),
523}
524
525impl Grid {
526 /// New empty grid at the given transform — no chunks populated,
527 /// `render_sky = true`, LOD thresholds default to
528 /// [`LodThresholds::always_near`], no billboard cache.
529 #[must_use]
530 pub fn new(transform: GridTransform) -> Self {
531 Self {
532 transform,
533 chunks: HashMap::new(),
534 render_sky: true,
535 mip_levels_override: None,
536 lod_thresholds: LodThresholds::always_near(),
537 billboards: None,
538 generator: None,
539 name: None,
540 store: None,
541 stream_radius: StreamRadius::DISABLED,
542 bake_lights: Vec::new(),
543 chunk_versions: HashMap::new(),
544 pending_gen: HashSet::new(),
545 dda_brick_cache: roxlap_core::BrickCache::new(),
546 chunk_dirty: HashMap::new(),
547 mutations: 0,
548 last_bricks: None,
549 }
550 }
551
552 /// Ensure the DDA brick cache holds current mip-`requested_mip`
553 /// occupancy maps for every populated chunk, rebuilding only chunks
554 /// whose edit version changed (Substage DDA.7). Clamps the mip to a
555 /// level every chunk has built (so coarse rendering never holes) and
556 /// returns that effective mip. Evicts cache entries for chunks no
557 /// longer present. Call once per frame before the DDA render.
558 pub fn ensure_dda_bricks(&mut self, requested_mip: u32) -> u32 {
559 // Split-borrow disjoint fields so the cache mutates while the
560 // chunks + versions are read.
561 // PF.13 (H9) — quiet frame at the same requested mip ⇒ nothing
562 // in the cache can be stale: skip the whole O(chunks) sweep.
563 if let Some((counter, req, eff)) = self.last_bricks {
564 if counter == self.mutations && req == requested_mip {
565 return eff;
566 }
567 }
568 let mutations = self.mutations;
569 let Self {
570 chunks,
571 chunk_versions,
572 dda_brick_cache,
573 ..
574 } = self;
575 // Effective uniform mip: min built mip across chunks, capped.
576 let mut mip = requested_mip;
577 if requested_mip > 0 {
578 for vxl in chunks.values() {
579 mip = mip.min(vxl.mip_count().saturating_sub(1));
580 }
581 }
582 for (idx, vxl) in chunks.iter() {
583 let version = chunk_versions.get(idx).copied().unwrap_or(0);
584 let view = roxlap_core::GridView::from_single_vxl(vxl);
585 dda_brick_cache.ensure([idx.x, idx.y, idx.z], mip, version, &view);
586 }
587 dda_brick_cache.retain_chunks(|c| chunks.contains_key(&IVec3::new(c[0], c[1], c[2])));
588 self.last_bricks = Some((mutations, requested_mip, mip));
589 mip
590 }
591
592 /// Current per-chunk edit version (S7.2). Returns `0` for any
593 /// chunk that hasn't been edited yet (including absent chunks
594 /// and chunks materialised only via
595 /// [`Self::ensure_chunk_generated`]).
596 ///
597 /// Used by S7.3's async generation dispatch to detect "edit
598 /// happened while we were generating" — the dispatcher
599 /// snapshots this value, the background task carries it, and
600 /// the result is discarded on install if the live counter has
601 /// since moved.
602 #[must_use]
603 pub fn chunk_version(&self, chunk_idx: IVec3) -> u64 {
604 self.chunk_versions.get(&chunk_idx).copied().unwrap_or(0)
605 }
606
607 /// Bump the edit version of `chunk_idx` (S7.2). Saturating add
608 /// at `u64::MAX` — a chunk would need 10^11 edits per second
609 /// for ~5 years to wrap, so saturation is a defensive cap, not
610 /// a realistic concern.
611 ///
612 /// Called by the edit API ([`Self::set_voxel`] /
613 /// [`Self::set_rect`] / [`Self::set_sphere`]) after a chunk
614 /// has actually been written to. Pure no-op edit paths
615 /// (carving from an air chunk that doesn't exist yet) skip
616 /// the bump.
617 ///
618 /// Exposed as `pub` (vs the historical `pub(crate)`) so hosts
619 /// that mutate `grid.chunks` directly — e.g.
620 /// `roxlap-scene-demo`'s `StreamingBakeTracker` writing
621 /// lightmode-1 alphas via `apply_lighting_with_cache` — can
622 /// signal "this chunk's slab changed" to downstream consumers
623 /// like the GPU dirty-chunk poller.
624 pub fn bump_chunk_version(&mut self, chunk_idx: IVec3) {
625 let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
626 *entry = entry.saturating_add(1);
627 // PF.12 — no extent information ⇒ the whole chunk must be
628 // treated as changed by partial-refresh consumers.
629 self.chunk_dirty.insert(chunk_idx, DirtyExtent::Full);
630 self.mutations = self.mutations.wrapping_add(1);
631 }
632
633 /// PF.13 (H9) — the grid's monotonic mutation counter: bumped by
634 /// every chunk edit, install, and eviction. Per-frame consumers
635 /// snapshot it to skip their whole-grid scans on quiet frames.
636 #[must_use]
637 pub fn mutation_counter(&self) -> u64 {
638 self.mutations
639 }
640
641 /// PF.12 — [`Self::bump_chunk_version`] with the edit's CHUNK-LOCAL
642 /// voxel extent (inclusive), so partial-refresh consumers (the GPU
643 /// facade) and incremental re-mip know how little actually changed.
644 /// Extents accumulate (bbox union) until a consumer
645 /// [`Self::take_chunk_dirty`]s them; an extent-less bump upgrades
646 /// the entry to [`DirtyExtent::Full`].
647 pub fn bump_chunk_version_bbox(&mut self, chunk_idx: IVec3, lo: IVec3, hi: IVec3) {
648 let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
649 *entry = entry.saturating_add(1);
650 let merged = match self.chunk_dirty.get(&chunk_idx) {
651 Some(DirtyExtent::Full) => DirtyExtent::Full,
652 Some(DirtyExtent::Bbox(l, h)) => DirtyExtent::Bbox(l.min(lo), h.max(hi)),
653 None => DirtyExtent::Bbox(lo, hi),
654 };
655 self.chunk_dirty.insert(chunk_idx, merged);
656 self.mutations = self.mutations.wrapping_add(1);
657 }
658
659 /// PF.12 — take (and clear) the extent accumulated for `chunk_idx`
660 /// since the last take. `None` ⇒ no recorded change (a consumer that
661 /// still observed a version bump should treat that as
662 /// [`DirtyExtent::Full`] — e.g. a change recorded before the
663 /// consumer first synced the chunk).
664 pub fn take_chunk_dirty(&mut self, chunk_idx: IVec3) -> Option<DirtyExtent> {
665 self.chunk_dirty.remove(&chunk_idx)
666 }
667
668 /// The full per-chunk edit-version map (QE.3b — the read half of
669 /// the previously `pub` field). Consumers seeding a sync tracker
670 /// iterate this; per-chunk reads go through
671 /// [`Self::chunk_version`].
672 #[must_use]
673 pub fn chunk_versions(&self) -> &HashMap<IVec3, u64> {
674 &self.chunk_versions
675 }
676
677 /// QE.3b — record a chunk-**set** mutation (materialise / install /
678 /// evict) on the PF.13 quiet-frame counter. The single entry point
679 /// for the counter besides the version bumps above; per-frame
680 /// consumers compare [`Self::mutation_counter`] snapshots.
681 pub(crate) fn note_chunk_set_changed(&mut self) {
682 self.mutations = self.mutations.wrapping_add(1);
683 }
684
685 /// QE.3b — drop `chunk_idx`'s per-chunk tracking on eviction, so
686 /// both maps stay bounded by the live chunk count. (Also clears any
687 /// accumulated [`DirtyExtent`] — pre-QE.3b that entry leaked until
688 /// a consumer happened to take it.) A future re-stream of the same
689 /// index restarts at version 0.
690 pub(crate) fn forget_chunk_tracking(&mut self, chunk_idx: IVec3) {
691 self.chunk_versions.remove(&chunk_idx);
692 self.chunk_dirty.remove(&chunk_idx);
693 }
694
695 /// QE.3b — seat a restored per-chunk version verbatim (the
696 /// [`snapshot`] load path; not an edit, so no extent / counter
697 /// side-effects).
698 pub(crate) fn restore_chunk_version(&mut self, chunk_idx: IVec3, version: u64) {
699 self.chunk_versions.insert(chunk_idx, version);
700 }
701
702 /// Attach (or detach) the procedural generator used by
703 /// [`Self::ensure_chunk_generated`] (S7.0).
704 ///
705 /// Pass `Some(Arc::new(generator))` to enable on-demand chunk
706 /// generation; pass `None` to revert to the "absent stays
707 /// absent" behaviour. Replacing an existing generator drops the
708 /// previous `Arc` clone without touching already-materialised
709 /// chunks. Any background tasks dispatched by a prior
710 /// [`Scene::pump_streaming`] hold their own clones of the old
711 /// generator and finish naturally.
712 pub fn set_generator(&mut self, generator: Option<Arc<dyn ChunkGenerator>>) {
713 self.generator = generator;
714 }
715
716 /// Attach (or detach) the persistence store for edited streamed
717 /// chunks (QE.5a; see [`ChunkStore`]). Without one, evicting an
718 /// edited chunk **discards the edits** — the pre-QE.5 default.
719 pub fn set_chunk_store(&mut self, store: Option<Arc<dyn ChunkStore>>) {
720 self.store = store;
721 }
722
723 /// Materialise the chunk at `chunk_idx` by running [`Self::generator`]
724 /// if (a) the chunk is not already present and (b) a generator
725 /// is attached. Returns `true` iff a chunk was newly generated.
726 ///
727 /// No-ops in all other cases:
728 /// - chunk already present (caller edits / a previous
729 /// `ensure_chunk_generated` call already populated it),
730 /// - no generator attached (the chunk stays implicit-air per
731 /// the existing convention — does NOT fall through to
732 /// [`Self::ensure_chunk`]'s empty-chunk constructor).
733 ///
734 /// This is the synchronous S7.0 path; [`Scene::pump_streaming`]
735 /// is the async counterpart (generation + store loads on a
736 /// dedicated rayon pool).
737 ///
738 /// QE.5a: with a [`ChunkStore`] attached, a stored chunk is
739 /// installed (with its persisted edit version) **before** the
740 /// generator is consulted — including for indices the generator's
741 /// [`ChunkGenerator::should_generate`] declines, since edits can
742 /// materialise chunks the generator never would.
743 pub fn ensure_chunk_generated(&mut self, chunk_idx: IVec3) -> bool {
744 if self.chunks.contains_key(&chunk_idx) {
745 return false;
746 }
747 // QE.5a — persisted edits win over regeneration.
748 if let Some((vxl, version)) = self.store.as_ref().and_then(|store| store.load(chunk_idx)) {
749 self.chunks.insert(chunk_idx, vxl);
750 self.restore_chunk_version(chunk_idx, version);
751 self.note_chunk_set_changed();
752 self.billboards = None; // same invalidation as below
753 return true;
754 }
755 let Some(generator) = self.generator.as_ref() else {
756 return false;
757 };
758 // S7.6+: generator may decline specific indices (e.g. a
759 // single-z-layer generator skipping placeholder bedrock
760 // chunks at chz != 0). Respect the filter so we don't
761 // materialise an unwanted chunk.
762 if !generator.should_generate(chunk_idx) {
763 return false;
764 }
765 let chunk = generator.generate(chunk_idx);
766 self.chunks.insert(chunk_idx, chunk);
767 self.note_chunk_set_changed();
768 // S7.4: a fresh chunk grows the populated AABB → the
769 // bounding sphere shifts/expands → existing impostor
770 // projections become wrong. Match the eviction (S7.1) +
771 // edit (S6.2) invalidation contract and drop the cache.
772 // Next Far-tier render rebuilds lazily.
773 self.billboards = None;
774 true
775 }
776
777 /// Bounding-sphere radius of the populated chunk set in
778 /// grid-local space.
779 ///
780 /// Walks the sparse chunk map once, computes the chunk-index
781 /// AABB, converts to voxel-space half-extent, returns its
782 /// Euclidean length. Empty grid → `0.0`.
783 ///
784 /// Conservative — bounds the full chunk volume, not just its
785 /// populated voxels (a chunk containing one voxel still
786 /// contributes `CHUNK_SIZE_XY × CHUNK_SIZE_XY × CHUNK_SIZE_Z`
787 /// to the bbox). For LOD picking that's fine: an over-bound
788 /// sphere errs on the side of `Near`.
789 ///
790 /// Cost: `O(chunks.len())`; recomputed on every call. Callers
791 /// who need this every frame should memoize at the
792 /// [`Scene`]-level cache (added when S6.2 needs it).
793 #[must_use]
794 pub fn bounding_radius(&self) -> f64 {
795 if self.chunks.is_empty() {
796 return 0.0;
797 }
798 let mut min = IVec3::splat(i32::MAX);
799 let mut max = IVec3::splat(i32::MIN);
800 for &idx in self.chunks.keys() {
801 min = min.min(idx);
802 max = max.max(idx);
803 }
804 // Chunk-index bbox → voxel-space half-extent. `+1` on max
805 // converts inclusive chunk index to exclusive voxel upper
806 // bound (chunk `idx` covers voxels `[idx*size, (idx+1)*size)`).
807 let sx = f64::from(CHUNK_SIZE_XY);
808 let sz = f64::from(CHUNK_SIZE_Z);
809 let lo = DVec3::new(
810 f64::from(min.x) * sx,
811 f64::from(min.y) * sx,
812 f64::from(min.z) * sz,
813 );
814 let hi = DVec3::new(
815 f64::from(max.x + 1) * sx,
816 f64::from(max.y + 1) * sx,
817 f64::from(max.z + 1) * sz,
818 );
819 let half_extent = (hi - lo) * 0.5;
820 half_extent.length()
821 }
822
823 /// Pick this grid's LOD tier for the given world-space camera
824 /// position. Convenience wrapper around [`crate::select_lod`]
825 /// that pulls [`Self::lod_thresholds`] from the grid.
826 #[must_use]
827 pub fn select_lod(&self, camera_world_pos: DVec3) -> Lod {
828 select_lod(camera_world_pos, &self.transform, self.lod_thresholds)
829 }
830}
831
832/// Top-level scene container. Holds a flat collection of grids
833/// keyed by [`GridId`].
834///
835/// S2.0 only exposes registration / removal / lookup. Address math
836/// helpers (S2.x), edit API (S2.x), and rendering composition (S3)
837/// land in later sub-substages.
838#[derive(Debug, Default)]
839pub struct Scene {
840 grids: HashMap<GridId, Grid>,
841 next_grid_id: u32,
842 /// S7.3: per-scene streaming pool + result channel. Stored on
843 /// the `Scene` so `pump_streaming` can dispatch background
844 /// tasks and drain results across pump calls. `cfg`-gated out
845 /// on wasm32 where `pump_streaming` short-circuits to
846 /// `pump_streaming_sync` (no rayon pool there).
847 #[cfg(not(target_arch = "wasm32"))]
848 streaming: streaming::StreamingState,
849}
850
851impl Scene {
852 /// New empty scene — no grids.
853 #[must_use]
854 pub fn new() -> Self {
855 Self::default()
856 }
857
858 /// Number of grids currently registered.
859 #[must_use]
860 pub fn grid_count(&self) -> usize {
861 self.grids.len()
862 }
863
864 /// Register a new grid. Returns its fresh, unique [`GridId`].
865 pub fn add_grid(&mut self, transform: GridTransform) -> GridId {
866 let id = GridId(self.next_grid_id);
867 self.next_grid_id += 1;
868 self.grids.insert(id, Grid::new(transform));
869 id
870 }
871
872 /// Remove a grid by id. Returns the removed [`Grid`] (so the
873 /// caller can reclaim its chunks) or `None` if the id wasn't
874 /// registered. Removed ids are not reissued.
875 pub fn remove_grid(&mut self, id: GridId) -> Option<Grid> {
876 self.grids.remove(&id)
877 }
878
879 /// Borrow a registered grid.
880 #[must_use]
881 pub fn grid(&self, id: GridId) -> Option<&Grid> {
882 self.grids.get(&id)
883 }
884
885 /// Mutably borrow a registered grid.
886 pub fn grid_mut(&mut self, id: GridId) -> Option<&mut Grid> {
887 self.grids.get_mut(&id)
888 }
889
890 /// Iterator over all `(id, grid)` pairs in registration order
891 /// is **not** guaranteed — the underlying map is a `HashMap`.
892 /// Callers that need a stable order must sort by [`GridId`].
893 pub fn grids(&self) -> impl Iterator<Item = (GridId, &Grid)> {
894 self.grids.iter().map(|(id, g)| (*id, g))
895 }
896
897 /// Mutable iterator over all `(id, grid)` pairs. Yield order
898 /// is not guaranteed (HashMap-backed).
899 pub fn grids_mut(&mut self) -> impl Iterator<Item = (GridId, &mut Grid)> {
900 self.grids.iter_mut().map(|(id, g)| (*id, g))
901 }
902
903 /// Resolve a world-space surface hit to the owning grid + its
904 /// grid-local voxel — the picking back half. `ray_dir` is the view
905 /// direction the hit was found along (need not be normalised); the
906 /// point is nudged half a voxel along it, past the surface and into
907 /// the solid cell, before each grid's [`Grid::voxel_solid`] test.
908 /// Returns the first grid that is solid there (transform-correct
909 /// for rotated/translated grids), or `None` if none claims it.
910 ///
911 /// Backend-agnostic: pair with a renderer depth read to turn a
912 /// click into a voxel — `world = cam.pos + t · normalize(ray_dir)`,
913 /// then `resolve_voxel(world, ray_dir)`. `roxlap-render`'s
914 /// `SceneRenderer::pick` wires exactly that.
915 #[must_use]
916 pub fn resolve_voxel(&self, world: DVec3, ray_dir: DVec3) -> Option<(GridId, IVec3)> {
917 let len = ray_dir.length();
918 if len < 1e-9 {
919 return None;
920 }
921 let inside = world + ray_dir * (0.5 / len); // half a voxel inward
922 for (id, grid) in self.grids() {
923 let glp = addr::world_to_grid_local(inside, &grid.transform);
924 let v = addr::voxel_global(glp.chunk, glp.voxel);
925 if grid.voxel_solid(v) {
926 return Some((id, v));
927 }
928 }
929 None
930 }
931
932 /// Cast a world-space ray and return the nearest solid voxel hit
933 /// across all grids, or `None` if nothing solid lies within
934 /// `max_dist`. Renderer-independent (no depth buffer, no camera) —
935 /// the primitive for line-of-sight, projectiles, AI probing, and
936 /// off-screen / backend-agnostic picking.
937 ///
938 /// `dir` need not be normalised. Each grid's ray is transformed
939 /// into the grid's local frame (so rotated / translated grids are
940 /// handled exactly) and marched with a voxel DDA against
941 /// [`Grid::voxel_solid`]; the closest hit by world distance `t`
942 /// wins. The step budget is bounded by `max_dist`, so empty space
943 /// is safe but not free — a chunk-level skip is a future
944 /// optimisation if hot.
945 #[must_use]
946 pub fn raycast(&self, origin: DVec3, dir: DVec3, max_dist: f64) -> Option<RayHit> {
947 let len = dir.length();
948 if len < 1e-12 || max_dist <= 0.0 {
949 return None;
950 }
951 let dn = dir / len; // unit world direction → t is world distance
952 let mut best: Option<RayHit> = None;
953 for (id, grid) in self.grids() {
954 // World ray → grid-local: undo translation + rotation. The
955 // inverse rotation preserves length, so `t` stays in world
956 // units and is comparable across grids.
957 let inv = grid.transform.rotation.inverse();
958 let lo = inv * (origin - grid.transform.origin);
959 let ld = inv * dn;
960 if let Some((voxel, t)) = voxel_dda(grid, lo, ld, max_dist) {
961 if best.as_ref().is_none_or(|b| t < b.t) {
962 best = Some(RayHit {
963 grid: id,
964 voxel,
965 world: origin + dn * t,
966 t,
967 color: grid.voxel_color(voxel),
968 });
969 }
970 }
971 }
972 best
973 }
974
975 /// Configure the number of worker threads in the dedicated
976 /// streaming pool (S7.3).
977 ///
978 /// Lazily applied — the pool itself is constructed on the first
979 /// [`Self::pump_streaming`] call. If the pool was already built
980 /// (i.e. a previous `pump_streaming` already dispatched at
981 /// least one task), it gets dropped and rebuilt. Dropping the
982 /// old pool blocks until all of its in-flight tasks finish
983 /// (rayon's contract); any results those tasks sent are still
984 /// drained by the next `pump_streaming` because the channel
985 /// survives the rebuild.
986 ///
987 /// The streaming pool is separate from rayon's global pool
988 /// (which R12 multicore rendering uses), so chunk generation
989 /// doesn't compete with render threads. Sensible values are 1
990 /// to ~4 — generation work is CPU-bound but should leave most
991 /// of the box for everything else.
992 ///
993 /// On wasm32 this is a no-op (no rayon pool available);
994 /// `pump_streaming` runs synchronously there.
995 ///
996 /// # Panics
997 /// Panics on native if `n == 0` (zero-thread pools are not
998 /// supported; the scene crate's S7.1 helper already disallows
999 /// the equivalent for `StreamRadius::r_active < 0`).
1000 #[cfg(not(target_arch = "wasm32"))]
1001 pub fn set_streaming_threads(&mut self, n: usize) {
1002 self.streaming.set_thread_count(n);
1003 }
1004
1005 /// wasm32 no-op companion of [`Self::set_streaming_threads`].
1006 /// Lets cross-target code call this unconditionally.
1007 #[cfg(target_arch = "wasm32")]
1008 pub fn set_streaming_threads(&mut self, _n: usize) {
1009 // No streaming pool on wasm32 — see `pump_streaming` docs.
1010 }
1011
1012 /// Asynchronous streaming pump (S7.3).
1013 ///
1014 /// On native, dispatches missing-chunk generations onto a
1015 /// dedicated rayon pool, drains any results that arrived since
1016 /// the last pump, runs the eviction pass, and tracks in-flight
1017 /// tasks in each grid's [`Grid::pending_gen`] set. The drain
1018 /// uses the per-chunk version counter from S7.2 to discard
1019 /// results whose chunk was edited mid-generation.
1020 ///
1021 /// On wasm32 this short-circuits to [`Self::pump_streaming_sync`]
1022 /// — no thread pool is available there, but the same per-grid
1023 /// stream-in / evict semantics apply.
1024 ///
1025 /// Call once per frame from the render thread. Cheap when
1026 /// nothing changed (early-exit on disabled grids, try_recv
1027 /// loops empty fast).
1028 pub fn pump_streaming(&mut self, camera_world_pos: DVec3) {
1029 #[cfg(target_arch = "wasm32")]
1030 {
1031 self.pump_streaming_sync(camera_world_pos);
1032 }
1033 #[cfg(not(target_arch = "wasm32"))]
1034 {
1035 self.pump_streaming_native(camera_world_pos);
1036 }
1037 }
1038
1039 /// Native implementation of [`Self::pump_streaming`].
1040 #[cfg(not(target_arch = "wasm32"))]
1041 fn pump_streaming_native(&mut self, camera_world_pos: DVec3) {
1042 // 1. Drain inbox — install fresh results, drop stale.
1043 while let Ok(result) = self.streaming.rx.try_recv() {
1044 let Some(grid) = self.grids.get_mut(&result.grid_id) else {
1045 // Grid was removed while a generation task was
1046 // in-flight. Drop silently.
1047 continue;
1048 };
1049 // Clearing pending_gen here both for "result delivered"
1050 // and "we shouldn't try to re-dispatch this chunk just
1051 // because it's missing".
1052 let was_pending = grid.pending_gen.remove(&result.chunk_idx);
1053 if !was_pending {
1054 // Either the chunk was evicted (pending cleared in
1055 // the eviction pass below in some prior call), or a
1056 // duplicate result for an already-handled chunk.
1057 continue;
1058 }
1059 if grid.chunks.contains_key(&result.chunk_idx) {
1060 // Some other path (e.g. `ensure_chunk_generated`
1061 // sync helper, or a manual edit's `ensure_chunk`)
1062 // already populated the slot. Don't overwrite.
1063 continue;
1064 }
1065 if grid.chunk_version(result.chunk_idx) != result.version_at_dispatch {
1066 // S7.2 stale-result discard: chunk was edited mid-
1067 // generation.
1068 continue;
1069 }
1070 let Some(vxl) = result.vxl else {
1071 // QE.5a — nothing to install (store miss + generator
1072 // declined); the pending entry is already cleared.
1073 continue;
1074 };
1075 grid.chunks.insert(result.chunk_idx, vxl);
1076 if let Some(version) = result.restored_version {
1077 // QE.5a — a store-restored chunk keeps its persisted
1078 // edit version (consumers see it as edited content).
1079 grid.restore_chunk_version(result.chunk_idx, version);
1080 }
1081 grid.note_chunk_set_changed();
1082 // S7.4: same invalidation contract as the sync
1083 // `ensure_chunk_generated` path — installing a new
1084 // chunk can grow the bounding sphere, so the
1085 // billboard impostor cache must be rebuilt on next
1086 // Far entry. Lazy: only one cache wipe per drain
1087 // batch, the Far render rebuilds afterwards.
1088 grid.billboards = None;
1089 }
1090
1091 // 2. Per-grid: eviction first, then dispatch. Doing evict
1092 // before dispatch means a chunk that's just left
1093 // r_active doesn't get re-dispatched on the same pump.
1094 self.streaming.ensure_pool();
1095 // Disjoint sub-field borrows: pool/tx via `&self.streaming.*`,
1096 // grids via `&mut self.grids`. Hold both at once.
1097 let pool: &rayon::ThreadPool = self.streaming.pool.as_ref().expect("ensure_pool just ran");
1098 let tx_template = &self.streaming.tx;
1099 for (grid_id, grid) in &mut self.grids {
1100 evict_grid_chunks(grid, camera_world_pos);
1101 dispatch_grid_async(*grid_id, grid, camera_world_pos, pool, tx_template);
1102 }
1103 }
1104
1105 /// Synchronous streaming pump (S7.1).
1106 ///
1107 /// For each grid with a non-[`StreamRadius::DISABLED`] policy:
1108 /// 1. Project the world-space camera into grid-local coords
1109 /// (inverse rotation + origin subtract).
1110 /// 2. Stream in any chunk whose AABB-to-camera distance is
1111 /// `<= r_active`, calling [`Grid::ensure_chunk_generated`].
1112 /// No-ops gracefully if the grid has no generator attached
1113 /// (so callers can use the eviction half of streaming on a
1114 /// purely-edited grid).
1115 /// 3. Evict any chunk whose AABB-to-camera distance exceeds
1116 /// `r_evict` from the grid's chunk map. Eviction also
1117 /// clears the cached [`BillboardCache`] (the bounding sphere
1118 /// may shrink, invalidating impostor projections; the next
1119 /// Far-tier render rebuilds lazily).
1120 ///
1121 /// Both passes use the f64 grid-local position so rotation +
1122 /// non-axis-aligned grids stream and evict correctly. The
1123 /// generate path is blocking — S7.3 will move it to a
1124 /// background rayon pool with `pump_streaming` (non-blocking).
1125 /// Callers that want the async variant in S7.0/S7.1 stages
1126 /// should keep `r_active` small.
1127 pub fn pump_streaming_sync(&mut self, camera_world_pos: DVec3) {
1128 for grid in self.grids.values_mut() {
1129 pump_grid_streaming_sync(grid, camera_world_pos);
1130 }
1131 }
1132}
1133
1134/// S7.1 helper — drives one grid's synchronous streaming pass.
1135/// Stream-in pass uses [`Grid::ensure_chunk_generated`] (blocking
1136/// inline generation); eviction pass shared with the S7.3 async
1137/// path through [`evict_grid_chunks`].
1138fn pump_grid_streaming_sync(grid: &mut Grid, camera_world_pos: DVec3) {
1139 let radius = grid.stream_radius;
1140 if radius.is_disabled() {
1141 return;
1142 }
1143 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1144
1145 // --- Pass 1: stream in active chunks (sync) ---------------
1146 // QE.5a — a ChunkStore alone (no generator) still restores
1147 // persisted edited chunks.
1148 if radius.r_active > 0.0 && (grid.generator.is_some() || grid.store.is_some()) {
1149 for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
1150 grid.ensure_chunk_generated(idx);
1151 });
1152 }
1153
1154 // --- Pass 2: evict chunks past r_evict --------------------
1155 evict_grid_chunks_with_cam(grid, cam_local);
1156}
1157
1158/// Eviction pass shared by [`pump_grid_streaming_sync`] and the
1159/// S7.3 async path. Public-ish so the async driver can call it
1160/// before dispatching to avoid generating chunks that are about
1161/// to be evicted. `cfg`-gated to native: on wasm32 the only
1162/// caller (`pump_streaming_native`) doesn't compile, so this
1163/// helper would warn as dead code.
1164#[cfg(not(target_arch = "wasm32"))]
1165fn evict_grid_chunks(grid: &mut Grid, camera_world_pos: DVec3) {
1166 let radius = grid.stream_radius;
1167 if radius.is_disabled() {
1168 return;
1169 }
1170 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1171 evict_grid_chunks_with_cam(grid, cam_local);
1172}
1173
1174/// Eviction inner — assumes `cam_local` is already computed (the
1175/// dispatcher and sync pump both have it on hand).
1176fn evict_grid_chunks_with_cam(grid: &mut Grid, cam_local: DVec3) {
1177 let radius = grid.stream_radius;
1178 if !radius.r_evict.is_finite() {
1179 return;
1180 }
1181 let r_sq = radius.r_evict * radius.r_evict;
1182 let to_evict: Vec<IVec3> = grid
1183 .chunks
1184 .keys()
1185 .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
1186 .copied()
1187 .collect();
1188 // S7.3: also evict pending in-flight tasks past r_evict so the
1189 // drain pass doesn't install a chunk that's no longer wanted.
1190 // We don't have a way to cancel the rayon task, but we can
1191 // drop the pending_gen entry so the result is dropped on
1192 // arrival.
1193 let to_evict_pending: Vec<IVec3> = grid
1194 .pending_gen
1195 .iter()
1196 .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
1197 .copied()
1198 .collect();
1199 if to_evict.is_empty() && to_evict_pending.is_empty() {
1200 return;
1201 }
1202 for idx in &to_evict {
1203 // QE.5a — an edited chunk (version != 0) is handed to the
1204 // ChunkStore before it drops, so the edits survive evict +
1205 // re-stream. Pristine generator output (version 0) is
1206 // regenerable and skips the store.
1207 if let Some(store) = grid.store.as_ref() {
1208 let version = grid.chunk_version(*idx);
1209 if version != 0 {
1210 if let Some(vxl) = grid.chunks.get(idx) {
1211 store.store(*idx, vxl, version);
1212 }
1213 }
1214 }
1215 grid.chunks.remove(idx);
1216 grid.note_chunk_set_changed();
1217 // S7.2/QE.3b: drop the chunk's version + dirty-extent tracking
1218 // so both maps stay bounded. A future re-stream of the same idx
1219 // restarts at 0 — that's fine because any in-flight gen-result
1220 // tagged with the pre-eviction version is unreachable (no chunk
1221 // to install onto) and gets discarded by the new "version
1222 // still 0" check anyway. (A stored edited chunk re-enters with
1223 // its persisted version via the QE.5a load path instead.)
1224 grid.forget_chunk_tracking(*idx);
1225 // S7.3: drop pending entry for the same chunk too. If a
1226 // background task is still running, its result will be
1227 // dropped on arrival (was_pending = false).
1228 grid.pending_gen.remove(idx);
1229 }
1230 for idx in &to_evict_pending {
1231 grid.pending_gen.remove(idx);
1232 }
1233 if !to_evict.is_empty() {
1234 // Bounding sphere can shrink → impostor projections would
1235 // be wrong on next Far render. Clear lazily; the next
1236 // Far-tier pass repopulates via BillboardCache::build.
1237 grid.billboards = None;
1238 }
1239}
1240
1241/// Walk every chunk index whose AABB falls within `r_active` of
1242/// `cam_local` and invoke `f` on it. Shared between the S7.1 sync
1243/// stream-in and the S7.3 async dispatch.
1244fn for_each_chunk_in_radius<F>(cam_local: DVec3, r_active: f64, mut f: F)
1245where
1246 F: FnMut(IVec3),
1247{
1248 let r_sq = r_active * r_active;
1249 let sxy = f64::from(CHUNK_SIZE_XY);
1250 let sz = f64::from(CHUNK_SIZE_Z);
1251 // Half-extent in chunk units; ceil to be conservative so any
1252 // chunk whose AABB clips the radius gets considered. `+1`
1253 // covers the half-open chunk-AABB upper edge plus the case
1254 // where the camera sits exactly on a chunk boundary and the
1255 // closest chunk is one index off.
1256 #[allow(clippy::cast_possible_truncation)]
1257 let r_chunks_xy = (r_active / sxy).ceil() as i32 + 1;
1258 #[allow(clippy::cast_possible_truncation)]
1259 let r_chunks_z = (r_active / sz).ceil() as i32 + 1;
1260 #[allow(clippy::cast_possible_truncation)]
1261 let cx_chunk = (cam_local.x / sxy).floor() as i32;
1262 #[allow(clippy::cast_possible_truncation)]
1263 let cy_chunk = (cam_local.y / sxy).floor() as i32;
1264 #[allow(clippy::cast_possible_truncation)]
1265 let cz_chunk = (cam_local.z / sz).floor() as i32;
1266 for chz in (cz_chunk - r_chunks_z)..=(cz_chunk + r_chunks_z) {
1267 for chy in (cy_chunk - r_chunks_xy)..=(cy_chunk + r_chunks_xy) {
1268 for chx in (cx_chunk - r_chunks_xy)..=(cx_chunk + r_chunks_xy) {
1269 let idx = IVec3::new(chx, chy, chz);
1270 if streaming::chunk_aabb_dist_sq(cam_local, idx) <= r_sq {
1271 f(idx);
1272 }
1273 }
1274 }
1275 }
1276}
1277
1278/// S7.3 async dispatch — schedule generation for every chunk in
1279/// `r_active` that's not already present and not already in
1280/// flight. Each dispatch clones the grid's generator `Arc` and a
1281/// sender clone, then spawns the closure on the streaming rayon
1282/// pool. The closure does the generate + send; the main thread
1283/// drains results on the next pump.
1284#[cfg(not(target_arch = "wasm32"))]
1285fn dispatch_grid_async(
1286 grid_id: GridId,
1287 grid: &mut Grid,
1288 camera_world_pos: DVec3,
1289 pool: &rayon::ThreadPool,
1290 tx: &crossbeam_channel::Sender<streaming::ChunkResult>,
1291) {
1292 let radius = grid.stream_radius;
1293 if radius.is_disabled() || radius.r_active <= 0.0 {
1294 return;
1295 }
1296 // QE.5a — a ChunkStore alone (no generator) still restores
1297 // persisted edited chunks on the background pool.
1298 let generator = grid.generator.as_ref().map(Arc::clone);
1299 let store = grid.store.as_ref().map(Arc::clone);
1300 if generator.is_none() && store.is_none() {
1301 return;
1302 }
1303 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
1304 for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
1305 if grid.chunks.contains_key(&idx) {
1306 return; // already present
1307 }
1308 if grid.pending_gen.contains(&idx) {
1309 return; // already in flight
1310 }
1311 // S7.6+: respect the generator's per-chunk filter — same
1312 // contract as `Grid::ensure_chunk_generated` (sync helper).
1313 // Lets a generator decline to materialise specific indices
1314 // (e.g. `HillsChunkGenerator` skipping placeholder bedrock
1315 // chunks at chz != 0 so the camera-above-grid path doesn't
1316 // create chz < 0 entries that would shift `origin_chunk_z`
1317 // and trigger the S4B.6.j cross-chunk look-down bug).
1318 // QE.5a — with a store attached the chunk is still
1319 // dispatched: a persisted edit wins over the decline (edits
1320 // can materialise chunks the generator never would); the
1321 // background task falls back to "nothing" on a store miss.
1322 let declined = !generator.as_ref().is_some_and(|g| g.should_generate(idx));
1323 if declined && store.is_none() {
1324 return;
1325 }
1326 grid.pending_gen.insert(idx);
1327 let version_at_dispatch = grid.chunk_version(idx);
1328 let tx_clone = tx.clone();
1329 let gen_clone = generator.clone();
1330 let store_clone = store.clone();
1331 pool.spawn(move || {
1332 // QE.5a — persisted edits win over regeneration; the
1333 // store load runs here on the pool so blocking IO never
1334 // stalls the render thread.
1335 let (vxl, restored_version) = match store_clone.as_ref().and_then(|s| s.load(idx)) {
1336 Some((vxl, version)) => (Some(vxl), Some(version)),
1337 None if declined => (None, None),
1338 None => (gen_clone.map(|g| g.generate(idx)), None),
1339 };
1340 // Send is non-blocking on unbounded channel; if the
1341 // receiver was dropped (Scene drop), the send fails
1342 // silently — that's fine.
1343 let _ = tx_clone.send(streaming::ChunkResult {
1344 grid_id,
1345 chunk_idx: idx,
1346 version_at_dispatch,
1347 vxl,
1348 restored_version,
1349 });
1350 });
1351 });
1352}
1353
1354#[cfg(test)]
1355mod tests {
1356 use super::*;
1357
1358 #[test]
1359 fn empty_scene_has_no_grids() {
1360 let scene = Scene::new();
1361 assert_eq!(scene.grid_count(), 0);
1362 assert!(scene.grids().next().is_none());
1363 }
1364
1365 #[test]
1366 fn raycast_hits_axis_aligned_voxel() {
1367 let mut scene = Scene::new();
1368 let id = scene.add_grid(GridTransform::identity());
1369 scene
1370 .grid_mut(id)
1371 .unwrap()
1372 .set_voxel(IVec3::new(5, 5, 10), Some(VoxColor(0x80_aa_bb_cc)));
1373
1374 // Straight down the +z column through (5,5): hits z=10 at t≈10.
1375 let hit = scene
1376 .raycast(DVec3::new(5.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1377 .expect("ray hits the voxel");
1378 assert_eq!(hit.grid, id);
1379 assert_eq!(hit.voxel, IVec3::new(5, 5, 10));
1380 assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1381 assert!(hit.color.is_some(), "textured voxel has a colour");
1382
1383 // A column with no voxel misses.
1384 assert!(
1385 scene
1386 .raycast(DVec3::new(0.5, 0.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1387 .is_none(),
1388 "empty column → no hit",
1389 );
1390 }
1391
1392 #[test]
1393 fn raycast_respects_grid_transform() {
1394 // A translated grid: the hit voxel is reported in GRID-LOCAL
1395 // coords, and the world hit point is back in world space — so a
1396 // host gets the true voxel regardless of where the grid sits.
1397 let mut scene = Scene::new();
1398 let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1399 scene
1400 .grid_mut(id)
1401 .unwrap()
1402 .set_voxel(IVec3::new(5, 5, 10), Some(VoxColor(0x80_11_22_33)));
1403
1404 let hit = scene
1405 .raycast(DVec3::new(105.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1406 .expect("ray hits the translated voxel");
1407 assert_eq!(hit.voxel, IVec3::new(5, 5, 10), "grid-local voxel");
1408 assert!((hit.world.x - 105.5).abs() < 1e-6, "world x preserved");
1409 assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1410 }
1411
1412 #[test]
1413 fn raycast_picks_nearest_grid() {
1414 // Two grids with a voxel each along the same world column; the
1415 // raycast must return the closer one.
1416 let mut scene = Scene::new();
1417 let near = scene.add_grid(GridTransform::identity());
1418 let far = scene.add_grid(GridTransform::identity());
1419 scene
1420 .grid_mut(near)
1421 .unwrap()
1422 .set_voxel(IVec3::new(1, 1, 20), Some(VoxColor(0x80_00_ff_00)));
1423 scene
1424 .grid_mut(far)
1425 .unwrap()
1426 .set_voxel(IVec3::new(1, 1, 40), Some(VoxColor(0x80_ff_00_00)));
1427
1428 let hit = scene
1429 .raycast(DVec3::new(1.5, 1.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1430 .expect("hits the nearer voxel");
1431 assert_eq!(hit.grid, near);
1432 assert_eq!(hit.voxel, IVec3::new(1, 1, 20));
1433 }
1434
1435 #[test]
1436 fn add_grid_returns_fresh_ids() {
1437 let mut scene = Scene::new();
1438 let a = scene.add_grid(GridTransform::identity());
1439 let b = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1440 assert_ne!(a, b);
1441 assert_eq!(a.raw(), 0);
1442 assert_eq!(b.raw(), 1);
1443 assert_eq!(scene.grid_count(), 2);
1444 }
1445
1446 #[test]
1447 fn grid_lookup_round_trips() {
1448 let mut scene = Scene::new();
1449 let id = scene.add_grid(GridTransform::at(DVec3::new(10.0, 20.0, 30.0)));
1450 let g = scene.grid(id).expect("grid registered");
1451 assert_eq!(g.transform.origin, DVec3::new(10.0, 20.0, 30.0));
1452 assert_eq!(g.transform.rotation, DQuat::IDENTITY);
1453 assert!(g.chunks.is_empty());
1454 }
1455
1456 #[test]
1457 fn remove_grid_drops_it_from_scene() {
1458 let mut scene = Scene::new();
1459 let id = scene.add_grid(GridTransform::identity());
1460 let removed = scene.remove_grid(id);
1461 assert!(removed.is_some());
1462 assert_eq!(scene.grid_count(), 0);
1463 assert!(scene.grid(id).is_none());
1464 // Re-adding does NOT reuse the dropped id.
1465 let id2 = scene.add_grid(GridTransform::identity());
1466 assert_ne!(id, id2);
1467 assert_eq!(id2.raw(), 1);
1468 }
1469
1470 #[test]
1471 fn remove_unknown_grid_is_none() {
1472 let mut scene = Scene::new();
1473 let bogus = GridId(999);
1474 assert!(scene.remove_grid(bogus).is_none());
1475 }
1476
1477 #[test]
1478 fn grid_mut_can_modify_transform() {
1479 let mut scene = Scene::new();
1480 let id = scene.add_grid(GridTransform::identity());
1481 scene.grid_mut(id).unwrap().transform.origin = DVec3::new(1.0, 2.0, 3.0);
1482 assert_eq!(
1483 scene.grid(id).unwrap().transform.origin,
1484 DVec3::new(1.0, 2.0, 3.0)
1485 );
1486 }
1487
1488 #[test]
1489 fn chunk_size_constants_match_plan() {
1490 // Plan locks these values; bumping either breaks the slab
1491 // byte format (Z) or the worst-case chunk footprint budget
1492 // (XY). Pin them so a future refactor that drifts them
1493 // shows up in CI.
1494 assert_eq!(CHUNK_SIZE_XY, 128);
1495 assert_eq!(CHUNK_SIZE_Z, 256);
1496 }
1497
1498 // ---- S6.0: bounding_radius + Grid::select_lod ----
1499
1500 #[test]
1501 fn new_grid_defaults_to_always_near_lod() {
1502 // Byte-identity contract for the staged S6 rollout: a
1503 // grid built through `new` must never trigger the Mid/Far
1504 // branches by accident, even when bounding_radius would
1505 // imply otherwise.
1506 let g = Grid::new(GridTransform::identity());
1507 assert_eq!(g.lod_thresholds.r_near, f64::INFINITY);
1508 assert_eq!(g.lod_thresholds.r_mid, f64::INFINITY);
1509 assert_eq!(g.select_lod(DVec3::new(1e9, 0.0, 0.0)), Lod::Near);
1510 }
1511
1512 #[test]
1513 fn bounding_radius_empty_grid_is_zero() {
1514 let g = Grid::new(GridTransform::identity());
1515 assert_eq!(g.bounding_radius(), 0.0);
1516 }
1517
1518 #[test]
1519 fn bounding_radius_single_chunk_at_origin() {
1520 // One chunk at (0, 0, 0): bbox is [0, 128) × [0, 128) × [0, 256).
1521 // Half-extent = (64, 64, 128); length = sqrt(64² + 64² + 128²)
1522 // = sqrt(4096 + 4096 + 16384) = sqrt(24576) ≈ 156.7747...
1523 let mut scene = Scene::new();
1524 let id = scene.add_grid(GridTransform::identity());
1525 let g = scene.grid_mut(id).unwrap();
1526 // Populate chunk (0, 0, 0) via the edit API.
1527 g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_88_88_88)));
1528 let r = g.bounding_radius();
1529 let expected = ((64.0_f64).powi(2) * 2.0 + (128.0_f64).powi(2)).sqrt();
1530 assert!(
1531 (r - expected).abs() < 1e-9,
1532 "bounding_radius={r} expected={expected}"
1533 );
1534 }
1535
1536 #[test]
1537 fn bounding_radius_grows_with_chunk_extent() {
1538 // Two chunks at (0,0,0) and (3,0,0): x extent is 4 chunks =
1539 // 512 voxels; y/z are 1 chunk each. Half-extent = (256, 64, 128);
1540 // length = sqrt(256² + 64² + 128²) = sqrt(65536+4096+16384)
1541 // = sqrt(86016) ≈ 293.2848.
1542 let mut scene = Scene::new();
1543 let id = scene.add_grid(GridTransform::identity());
1544 let g = scene.grid_mut(id).unwrap();
1545 // Stamp one voxel in chunk (0,0,0).
1546 g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_88_88_88)));
1547 // Stamp one voxel in chunk (3,0,0): grid-local x = 3*128 = 384.
1548 g.set_voxel(IVec3::new(384, 0, 0), Some(VoxColor(0x80_88_88_88)));
1549 assert_eq!(g.chunks.len(), 2);
1550 let r = g.bounding_radius();
1551 let expected = (256.0_f64.powi(2) + 64.0_f64.powi(2) + 128.0_f64.powi(2)).sqrt();
1552 assert!(
1553 (r - expected).abs() < 1e-9,
1554 "bounding_radius={r} expected={expected}"
1555 );
1556 }
1557
1558 #[test]
1559 fn grid_select_lod_respects_lod_thresholds_field() {
1560 // Set a non-default threshold and verify the helper picks
1561 // the right tier for known distances.
1562 let mut scene = Scene::new();
1563 let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1564 let g = scene.grid_mut(id).unwrap();
1565 g.lod_thresholds = LodThresholds {
1566 r_near: 50.0,
1567 r_mid: 200.0,
1568 ..LodThresholds::always_near()
1569 };
1570 // Camera 25 units from grid origin → Near.
1571 assert_eq!(g.select_lod(DVec3::new(125.0, 0.0, 0.0)), Lod::Near);
1572 // 100 units → Mid.
1573 assert_eq!(g.select_lod(DVec3::new(200.0, 0.0, 0.0)), Lod::Mid);
1574 // 500 units → Far.
1575 assert_eq!(g.select_lod(DVec3::new(600.0, 0.0, 0.0)), Lod::Far);
1576 }
1577}