roxlap_scene/lib.rs
1//! roxlap scene-graph layer — many independent chunked voxel
2//! grids in a single 3D scene.
3//!
4//! See `PORTING-SCENE.md` at the workspace root for the substage
5//! roadmap. This crate is the layer **above** voxlap's per-chunk
6//! renderer (`roxlap-core`): a [`Scene`] holds a sparse set of
7//! [`Grid`]s, each with its own f64 world position + arbitrary 3D
8//! rotation. Future stages will add per-grid raycast composition
9//! (S3), cross-chunk gline within a grid (S4), per-grid rotation
10//! (S5), far-LOD billboards / planet proxies (S6), and streaming +
11//! procedural generation (S7).
12//!
13//! S2.0 lands the **type skeleton + grid registration only**.
14//! S2.1 adds the [`addr`] module — world ↔ grid-local ↔ chunk +
15//! voxel-in-chunk decomposition, the canonical f64↔i32 boundary
16//! helper called out by risk R5 in `PORTING-SCENE.md`. S2.2 adds
17//! the [`chunks`] module (sparse storage with on-demand chunk
18//! allocation) and the [`Grid`] edit API ([`Grid::set_voxel`],
19//! [`Grid::set_rect`], [`Grid::set_sphere`]) which decompose
20//! multi-chunk operations and delegate to
21//! [`roxlap_formats::edit`]. S2.3 adds the [`snapshot`] module —
22//! a serde-friendly view of the scene that round-trips through
23//! `Serialize` + `Deserialize` (chunks encode via
24//! [`roxlap_formats::vxl::serialize`] / [`parse`]). Rendering
25//! composition is still owed (S3+).
26//!
27//! [`parse`]: roxlap_formats::vxl::parse
28
29pub mod addr;
30pub mod billboard;
31pub mod cavegen;
32pub mod chunks;
33pub mod edit;
34pub mod lod;
35pub mod render;
36pub mod snapshot;
37pub mod streaming;
38
39use std::collections::{HashMap, HashSet};
40use std::sync::Arc;
41
42use glam::{DQuat, DVec3, IVec3, UVec3};
43use roxlap_formats::vxl::Vxl;
44use serde::{Deserialize, Serialize};
45
46pub use addr::{grid_local_to_world, voxel_global, voxel_split, world_to_grid_local, GridLocalPos};
47pub use billboard::{canonical_viewpoints, BillboardCache, BillboardSnapshot};
48pub use edit::SpanOp;
49pub use lod::{select_lod, Lod, LodThresholds};
50pub use streaming::{ChunkGenerator, StreamRadius};
51
52/// XY size of one chunk in voxels. The plan locks 128 — keeps
53/// chunks compact (~2 MB worst-case dense-slab footprint inside
54/// each `Vxl`) and divides cleanly into voxlap's 2048 reference
55/// world size.
56pub const CHUNK_SIZE_XY: u32 = 128;
57
58/// Z size of one chunk in voxels. Locked at 256 to preserve
59/// voxlap's existing slab byte format unchanged inside each chunk
60/// — the per-chunk renderer doesn't need to know it's living
61/// inside a scene-graph.
62pub const CHUNK_SIZE_Z: u32 = 256;
63
64/// Stable identifier for a grid registered in a [`Scene`]. Issued
65/// by [`Scene::add_grid`]; persists across edits but a removed
66/// grid's id is not reissued.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
68pub struct GridId(u32);
69
70impl GridId {
71 /// The integer wire form. Useful for serde / debug output.
72 #[must_use]
73 pub const fn raw(self) -> u32 {
74 self.0
75 }
76}
77
78/// A solid-voxel hit from [`Scene::raycast`].
79#[derive(Debug, Clone, Copy, PartialEq)]
80pub struct RayHit {
81 /// The grid the ray hit.
82 pub grid: GridId,
83 /// Grid-local integer voxel coordinate of the hit cell.
84 pub voxel: IVec3,
85 /// World-space hit point (`origin + t · normalize(dir)`).
86 pub world: DVec3,
87 /// World distance from the ray origin to the hit.
88 pub t: f64,
89 /// Packed colour of the hit voxel, or `None` if it's an untextured
90 /// (bedrock / interior) cell. See [`Grid::voxel_color`].
91 pub color: Option<u32>,
92}
93
94/// Voxel DDA (Amanatides-Woo) in a grid's local space. `lo` / `ld` are
95/// the ray origin + unit direction already transformed into grid-local
96/// coords. Returns the first [`Grid::voxel_solid`] cell and its world-
97/// equal distance `t`, or `None` past `max_t`. The step budget is
98/// `~3·max_t` so a near-axis ray through empty space still terminates.
99fn voxel_dda(grid: &Grid, lo: DVec3, ld: DVec3, max_t: f64) -> Option<(IVec3, f64)> {
100 #[allow(clippy::cast_possible_truncation)]
101 let mut p = IVec3::new(
102 lo.x.floor() as i32,
103 lo.y.floor() as i32,
104 lo.z.floor() as i32,
105 );
106 if grid.voxel_solid(p) {
107 return Some((p, 0.0)); // origin already inside a solid voxel
108 }
109 let sign = |d: f64| -> i32 {
110 if d > 0.0 {
111 1
112 } else if d < 0.0 {
113 -1
114 } else {
115 0
116 }
117 };
118 let step = IVec3::new(sign(ld.x), sign(ld.y), sign(ld.z));
119 // Distance to advance one whole voxel along each axis (∞ if parallel).
120 let t_delta = DVec3::new(
121 if ld.x == 0.0 {
122 f64::INFINITY
123 } else {
124 (1.0 / ld.x).abs()
125 },
126 if ld.y == 0.0 {
127 f64::INFINITY
128 } else {
129 (1.0 / ld.y).abs()
130 },
131 if ld.z == 0.0 {
132 f64::INFINITY
133 } else {
134 (1.0 / ld.z).abs()
135 },
136 );
137 // Distance to the first voxel boundary on each axis.
138 let boundary = |o: f64, d: f64| -> f64 {
139 if d > 0.0 {
140 (o.floor() + 1.0 - o) / d
141 } else if d < 0.0 {
142 (o - o.floor()) / -d
143 } else {
144 f64::INFINITY
145 }
146 };
147 let mut t_max = DVec3::new(
148 boundary(lo.x, ld.x),
149 boundary(lo.y, ld.y),
150 boundary(lo.z, ld.z),
151 );
152 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
153 let max_steps = (max_t * 3.0) as u64 + 8;
154 for _ in 0..max_steps {
155 // Advance across the nearest voxel boundary.
156 let t = if t_max.x <= t_max.y && t_max.x <= t_max.z {
157 p.x += step.x;
158 let t = t_max.x;
159 t_max.x += t_delta.x;
160 t
161 } else if t_max.y <= t_max.z {
162 p.y += step.y;
163 let t = t_max.y;
164 t_max.y += t_delta.y;
165 t
166 } else {
167 p.z += step.z;
168 let t = t_max.z;
169 t_max.z += t_delta.z;
170 t
171 };
172 if t > max_t {
173 return None;
174 }
175 if grid.voxel_solid(p) {
176 return Some((p, t));
177 }
178 }
179 None
180}
181
182/// f64 world placement of one grid: position + orientation.
183///
184/// `origin` is the grid's local-space origin in world coords —
185/// chunk `(0, 0, 0)`'s `(0, 0, 0)` voxel maps to
186/// `origin + rotation * vec3(0, 0, 0)` (i.e. just `origin`).
187/// Voxel size is fixed at 1 world unit / voxel for v1.
188#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
189pub struct GridTransform {
190 pub origin: DVec3,
191 pub rotation: DQuat,
192}
193
194impl GridTransform {
195 /// Identity transform at world origin. Useful as a default for
196 /// the first grid added to an otherwise empty scene.
197 #[must_use]
198 pub fn identity() -> Self {
199 Self {
200 origin: DVec3::ZERO,
201 rotation: DQuat::IDENTITY,
202 }
203 }
204
205 /// Axis-aligned grid placed at `origin` with no rotation.
206 #[must_use]
207 pub fn at(origin: DVec3) -> Self {
208 Self {
209 origin,
210 rotation: DQuat::IDENTITY,
211 }
212 }
213}
214
215impl Default for GridTransform {
216 fn default() -> Self {
217 Self::identity()
218 }
219}
220
221/// Address of one voxel inside a scene: which grid it belongs to,
222/// which chunk within that grid, and the voxel's offset inside
223/// that chunk.
224///
225/// `chunk` is signed (`IVec3`) because chunks are centred on the
226/// grid's local origin and may extend in either direction. `voxel`
227/// is unsigned and must satisfy
228/// `(voxel.x, voxel.y) < CHUNK_SIZE_XY` and `voxel.z < CHUNK_SIZE_Z`.
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
230pub struct GridAddr {
231 pub grid: GridId,
232 pub chunk: IVec3,
233 pub voxel: UVec3,
234}
235
236/// One independent voxel grid in a scene. Holds its world placement
237/// and a sparse map of populated chunks. Empty chunk slots are
238/// implicit air and skipped during rendering / raycasts.
239///
240/// Each chunk is internally a [`Vxl`] with `vsid = CHUNK_SIZE_XY`
241/// — the existing per-chunk renderer (opticast + grouscan +
242/// sprites + lighting in `roxlap-core`) runs on each chunk
243/// unchanged. Vertical worlds are built by stacking chunks along
244/// grid-local `+z`.
245#[derive(Debug)]
246pub struct Grid {
247 /// World placement (origin + rotation).
248 pub transform: GridTransform,
249 /// Sparse chunk storage keyed by `(chx, chy, chz)` chunk
250 /// coordinates. A missing entry means the chunk is fully air.
251 pub chunks: HashMap<IVec3, Vxl>,
252 /// Whether sky pixels rendered for this grid should be
253 /// composited into the final framebuffer. `true` is the
254 /// historical "grid owns its own sky" behaviour: ray misses
255 /// inside this grid's frustum paint sky_color into the temp
256 /// buffer. Set `false` for grids that are a foreground object
257 /// (e.g. a ship) — the sky is owned by a single "world" grid
258 /// (the ground) and other grids should not contribute sky
259 /// pixels, otherwise their grid-local-frame sky lookup
260 /// rotates with the grid and visibly fights the world's sky
261 /// during compose. See [`crate::render::render_scene_composed`]
262 /// for the masking implementation.
263 pub render_sky: bool,
264 /// Override [`roxlap_core::opticast::OpticastSettings::mip_levels`]
265 /// for this grid. `None` ⇒ use the caller's value. `Some(n)`
266 /// ⇒ cap at `n` (clamped to `[1, settings.mip_levels]`). Use
267 /// to disable multi-mip on a per-grid basis — small grids
268 /// (rotating ships, billboards) don't benefit from deep mips
269 /// and CAN trigger the
270 /// `[[project_axis_aligned_mip_beams]]`-style cf-cancellation
271 /// artifact when near-axis-aligned rays hit the rotated grid.
272 /// `Some(1)` = mip-0 only, byte-stable to single-mip.
273 pub mip_levels_override: Option<u32>,
274 /// World-distance thresholds for per-grid LOD tier selection
275 /// (S6.0). Defaults to [`LodThresholds::always_near`], so a
276 /// freshly-constructed grid always renders at full voxel (the
277 /// S5-and-earlier byte-stable behaviour). S6.1 plugs `Mid` into
278 /// the existing multi-mip path; S6.3 plugs `Far` into the
279 /// billboard impostor cache. See [`crate::lod`].
280 pub lod_thresholds: LodThresholds,
281 /// Lazy [`BillboardCache`] for the `Lod::Far` tier (S6.2).
282 /// `None` until the first time S6.3's render dispatch needs
283 /// it; populated then via [`BillboardCache::build`] and
284 /// cleared by edits ([`Self::set_voxel`] / [`Self::set_rect`]
285 /// / [`Self::set_sphere`]) to force a rebuild on next Far use.
286 /// Callers may also force-invalidate via direct assignment.
287 pub billboards: Option<BillboardCache>,
288 /// Optional procedural generator (S7.0). When set,
289 /// [`Self::ensure_chunk_generated`] uses it to materialise
290 /// chunks that are still absent from [`Self::chunks`].
291 ///
292 /// Streaming layers (S7.1+) walk the active radius around the
293 /// camera and call `ensure_chunk_generated` for missing chunks;
294 /// later stages dispatch this onto a background rayon pool. The
295 /// trait bound is `Send + Sync` (needed for S7.3 async
296 /// dispatch) + `Debug` (needed so [`Grid`] keeps deriving
297 /// `Debug`).
298 ///
299 /// `None` is the default — a grid without a generator behaves
300 /// exactly like the pre-S7 grids: absent chunks stay absent.
301 ///
302 /// `Arc` (not `Box`) so S7.3's async dispatch can clone the
303 /// generator into background rayon tasks without moving it out
304 /// of the grid. Trait bound `Send + Sync` (required at S7.0)
305 /// already makes `Arc<dyn ChunkGenerator>` `Send + Sync`.
306 pub generator: Option<Arc<dyn ChunkGenerator>>,
307 /// Streaming activity / eviction radii used by
308 /// [`Scene::pump_streaming_sync`] (S7.1). Defaults to
309 /// [`StreamRadius::DISABLED`] so existing grids see no change
310 /// in behaviour until the caller opts in.
311 pub stream_radius: StreamRadius,
312 /// Per-chunk edit version counter (S7.2). Each user edit
313 /// through [`Self::set_voxel`] / [`Self::set_rect`] /
314 /// [`Self::set_sphere`] bumps the counter for every chunk it
315 /// actually wrote to. [`Self::ensure_chunk_generated`] does
316 /// NOT bump — a freshly generated chunk has no edits and
317 /// reads as version 0.
318 ///
319 /// Wired up here so the S7.3 async dispatch can detect "an
320 /// edit happened while a chunk was being generated in the
321 /// background" and discard the now-stale result: each
322 /// background task captures the dispatch-time version and
323 /// only installs its result iff the current version still
324 /// matches.
325 ///
326 /// Missing entries read as `0` via [`Self::chunk_version`].
327 /// Evictions in [`Scene::pump_streaming_sync`] drop the
328 /// corresponding entry so the map stays bounded.
329 pub chunk_versions: HashMap<IVec3, u64>,
330 /// In-flight background generation tasks (S7.3).
331 ///
332 /// Populated by [`Scene::pump_streaming`] when it dispatches a
333 /// generator call onto the streaming rayon pool, drained when
334 /// the corresponding [`ChunkResult`] is received and processed
335 /// (either installed or discarded). The set is consulted to
336 /// avoid re-dispatching the same chunk while a previous task
337 /// is still running.
338 ///
339 /// Stays empty when only the synchronous
340 /// [`Scene::pump_streaming_sync`] is used — that path generates
341 /// inline on the calling thread.
342 ///
343 /// [`ChunkResult`]: streaming::ChunkResult
344 pub pending_gen: HashSet<IVec3>,
345}
346
347impl Grid {
348 /// New empty grid at the given transform — no chunks populated,
349 /// `render_sky = true`, LOD thresholds default to
350 /// [`LodThresholds::always_near`], no billboard cache.
351 #[must_use]
352 pub fn new(transform: GridTransform) -> Self {
353 Self {
354 transform,
355 chunks: HashMap::new(),
356 render_sky: true,
357 mip_levels_override: None,
358 lod_thresholds: LodThresholds::always_near(),
359 billboards: None,
360 generator: None,
361 stream_radius: StreamRadius::DISABLED,
362 chunk_versions: HashMap::new(),
363 pending_gen: HashSet::new(),
364 }
365 }
366
367 /// Current per-chunk edit version (S7.2). Returns `0` for any
368 /// chunk that hasn't been edited yet (including absent chunks
369 /// and chunks materialised only via
370 /// [`Self::ensure_chunk_generated`]).
371 ///
372 /// Used by S7.3's async generation dispatch to detect "edit
373 /// happened while we were generating" — the dispatcher
374 /// snapshots this value, the background task carries it, and
375 /// the result is discarded on install if the live counter has
376 /// since moved.
377 #[must_use]
378 pub fn chunk_version(&self, chunk_idx: IVec3) -> u64 {
379 self.chunk_versions.get(&chunk_idx).copied().unwrap_or(0)
380 }
381
382 /// Bump the edit version of `chunk_idx` (S7.2). Saturating add
383 /// at `u64::MAX` — a chunk would need 10^11 edits per second
384 /// for ~5 years to wrap, so saturation is a defensive cap, not
385 /// a realistic concern.
386 ///
387 /// Called by the edit API ([`Self::set_voxel`] /
388 /// [`Self::set_rect`] / [`Self::set_sphere`]) after a chunk
389 /// has actually been written to. Pure no-op edit paths
390 /// (carving from an air chunk that doesn't exist yet) skip
391 /// the bump.
392 ///
393 /// Exposed as `pub` (vs the historical `pub(crate)`) so hosts
394 /// that mutate `grid.chunks` directly — e.g.
395 /// `roxlap-scene-demo`'s `StreamingBakeTracker` writing
396 /// lightmode-1 alphas via `apply_lighting_with_cache` — can
397 /// signal "this chunk's slab changed" to downstream consumers
398 /// like the GPU dirty-chunk poller.
399 pub fn bump_chunk_version(&mut self, chunk_idx: IVec3) {
400 let entry = self.chunk_versions.entry(chunk_idx).or_insert(0);
401 *entry = entry.saturating_add(1);
402 }
403
404 /// Attach (or detach) the procedural generator used by
405 /// [`Self::ensure_chunk_generated`] (S7.0).
406 ///
407 /// Pass `Some(Arc::new(generator))` to enable on-demand chunk
408 /// generation; pass `None` to revert to the "absent stays
409 /// absent" behaviour. Replacing an existing generator drops the
410 /// previous `Arc` clone without touching already-materialised
411 /// chunks. Any background tasks dispatched by a prior
412 /// [`Scene::pump_streaming`] hold their own clones of the old
413 /// generator and finish naturally.
414 pub fn set_generator(&mut self, generator: Option<Arc<dyn ChunkGenerator>>) {
415 self.generator = generator;
416 }
417
418 /// Materialise the chunk at `chunk_idx` by running [`Self::generator`]
419 /// if (a) the chunk is not already present and (b) a generator
420 /// is attached. Returns `true` iff a chunk was newly generated.
421 ///
422 /// No-ops in all other cases:
423 /// - chunk already present (caller edits / a previous
424 /// `ensure_chunk_generated` call already populated it),
425 /// - no generator attached (the chunk stays implicit-air per
426 /// the existing convention — does NOT fall through to
427 /// [`Self::ensure_chunk`]'s empty-chunk constructor).
428 ///
429 /// This is the synchronous S7.0 path. S7.3 will add an async
430 /// counterpart that dispatches the generator call to a
431 /// dedicated rayon pool and installs the result on the next
432 /// `pump_streaming` call.
433 pub fn ensure_chunk_generated(&mut self, chunk_idx: IVec3) -> bool {
434 if self.chunks.contains_key(&chunk_idx) {
435 return false;
436 }
437 let Some(generator) = self.generator.as_ref() else {
438 return false;
439 };
440 // S7.6+: generator may decline specific indices (e.g. a
441 // single-z-layer generator skipping placeholder bedrock
442 // chunks at chz != 0). Respect the filter so we don't
443 // materialise an unwanted chunk.
444 if !generator.should_generate(chunk_idx) {
445 return false;
446 }
447 let chunk = generator.generate(chunk_idx);
448 self.chunks.insert(chunk_idx, chunk);
449 // S7.4: a fresh chunk grows the populated AABB → the
450 // bounding sphere shifts/expands → existing impostor
451 // projections become wrong. Match the eviction (S7.1) +
452 // edit (S6.2) invalidation contract and drop the cache.
453 // Next Far-tier render rebuilds lazily.
454 self.billboards = None;
455 true
456 }
457
458 /// Bounding-sphere radius of the populated chunk set in
459 /// grid-local space.
460 ///
461 /// Walks the sparse chunk map once, computes the chunk-index
462 /// AABB, converts to voxel-space half-extent, returns its
463 /// Euclidean length. Empty grid → `0.0`.
464 ///
465 /// Conservative — bounds the full chunk volume, not just its
466 /// populated voxels (a chunk containing one voxel still
467 /// contributes `CHUNK_SIZE_XY × CHUNK_SIZE_XY × CHUNK_SIZE_Z`
468 /// to the bbox). For LOD picking that's fine: an over-bound
469 /// sphere errs on the side of `Near`.
470 ///
471 /// Cost: `O(chunks.len())`; recomputed on every call. Callers
472 /// who need this every frame should memoize at the
473 /// [`Scene`]-level cache (added when S6.2 needs it).
474 #[must_use]
475 pub fn bounding_radius(&self) -> f64 {
476 if self.chunks.is_empty() {
477 return 0.0;
478 }
479 let mut min = IVec3::splat(i32::MAX);
480 let mut max = IVec3::splat(i32::MIN);
481 for &idx in self.chunks.keys() {
482 min = min.min(idx);
483 max = max.max(idx);
484 }
485 // Chunk-index bbox → voxel-space half-extent. `+1` on max
486 // converts inclusive chunk index to exclusive voxel upper
487 // bound (chunk `idx` covers voxels `[idx*size, (idx+1)*size)`).
488 let sx = f64::from(CHUNK_SIZE_XY);
489 let sz = f64::from(CHUNK_SIZE_Z);
490 let lo = DVec3::new(
491 f64::from(min.x) * sx,
492 f64::from(min.y) * sx,
493 f64::from(min.z) * sz,
494 );
495 let hi = DVec3::new(
496 f64::from(max.x + 1) * sx,
497 f64::from(max.y + 1) * sx,
498 f64::from(max.z + 1) * sz,
499 );
500 let half_extent = (hi - lo) * 0.5;
501 half_extent.length()
502 }
503
504 /// Pick this grid's LOD tier for the given world-space camera
505 /// position. Convenience wrapper around [`crate::select_lod`]
506 /// that pulls [`Self::lod_thresholds`] from the grid.
507 #[must_use]
508 pub fn select_lod(&self, camera_world_pos: DVec3) -> Lod {
509 select_lod(camera_world_pos, &self.transform, self.lod_thresholds)
510 }
511}
512
513/// Top-level scene container. Holds a flat collection of grids
514/// keyed by [`GridId`].
515///
516/// S2.0 only exposes registration / removal / lookup. Address math
517/// helpers (S2.x), edit API (S2.x), and rendering composition (S3)
518/// land in later sub-substages.
519#[derive(Debug, Default)]
520pub struct Scene {
521 grids: HashMap<GridId, Grid>,
522 next_grid_id: u32,
523 /// S7.3: per-scene streaming pool + result channel. Stored on
524 /// the `Scene` so `pump_streaming` can dispatch background
525 /// tasks and drain results across pump calls. `cfg`-gated out
526 /// on wasm32 where `pump_streaming` short-circuits to
527 /// `pump_streaming_sync` (no rayon pool there).
528 #[cfg(not(target_arch = "wasm32"))]
529 streaming: streaming::StreamingState,
530}
531
532impl Scene {
533 /// New empty scene — no grids.
534 #[must_use]
535 pub fn new() -> Self {
536 Self::default()
537 }
538
539 /// Number of grids currently registered.
540 #[must_use]
541 pub fn grid_count(&self) -> usize {
542 self.grids.len()
543 }
544
545 /// Register a new grid. Returns its fresh, unique [`GridId`].
546 pub fn add_grid(&mut self, transform: GridTransform) -> GridId {
547 let id = GridId(self.next_grid_id);
548 self.next_grid_id += 1;
549 self.grids.insert(id, Grid::new(transform));
550 id
551 }
552
553 /// Remove a grid by id. Returns the removed [`Grid`] (so the
554 /// caller can reclaim its chunks) or `None` if the id wasn't
555 /// registered. Removed ids are not reissued.
556 pub fn remove_grid(&mut self, id: GridId) -> Option<Grid> {
557 self.grids.remove(&id)
558 }
559
560 /// Borrow a registered grid.
561 #[must_use]
562 pub fn grid(&self, id: GridId) -> Option<&Grid> {
563 self.grids.get(&id)
564 }
565
566 /// Mutably borrow a registered grid.
567 pub fn grid_mut(&mut self, id: GridId) -> Option<&mut Grid> {
568 self.grids.get_mut(&id)
569 }
570
571 /// Iterator over all `(id, grid)` pairs in registration order
572 /// is **not** guaranteed — the underlying map is a `HashMap`.
573 /// Callers that need a stable order must sort by [`GridId`].
574 pub fn grids(&self) -> impl Iterator<Item = (GridId, &Grid)> {
575 self.grids.iter().map(|(id, g)| (*id, g))
576 }
577
578 /// Mutable iterator over all `(id, grid)` pairs. Yield order
579 /// is not guaranteed (HashMap-backed).
580 pub fn grids_mut(&mut self) -> impl Iterator<Item = (GridId, &mut Grid)> {
581 self.grids.iter_mut().map(|(id, g)| (*id, g))
582 }
583
584 /// Resolve a world-space surface hit to the owning grid + its
585 /// grid-local voxel — the picking back half. `ray_dir` is the view
586 /// direction the hit was found along (need not be normalised); the
587 /// point is nudged half a voxel along it, past the surface and into
588 /// the solid cell, before each grid's [`Grid::voxel_solid`] test.
589 /// Returns the first grid that is solid there (transform-correct
590 /// for rotated/translated grids), or `None` if none claims it.
591 ///
592 /// Backend-agnostic: pair with a renderer depth read to turn a
593 /// click into a voxel — `world = cam.pos + t · normalize(ray_dir)`,
594 /// then `resolve_voxel(world, ray_dir)`. `roxlap-render`'s
595 /// `SceneRenderer::pick` wires exactly that.
596 #[must_use]
597 pub fn resolve_voxel(&self, world: DVec3, ray_dir: DVec3) -> Option<(GridId, IVec3)> {
598 let len = ray_dir.length();
599 if len < 1e-9 {
600 return None;
601 }
602 let inside = world + ray_dir * (0.5 / len); // half a voxel inward
603 for (id, grid) in self.grids() {
604 let glp = addr::world_to_grid_local(inside, &grid.transform);
605 let v = addr::voxel_global(glp.chunk, glp.voxel);
606 if grid.voxel_solid(v) {
607 return Some((id, v));
608 }
609 }
610 None
611 }
612
613 /// Cast a world-space ray and return the nearest solid voxel hit
614 /// across all grids, or `None` if nothing solid lies within
615 /// `max_dist`. Renderer-independent (no depth buffer, no camera) —
616 /// the primitive for line-of-sight, projectiles, AI probing, and
617 /// off-screen / backend-agnostic picking.
618 ///
619 /// `dir` need not be normalised. Each grid's ray is transformed
620 /// into the grid's local frame (so rotated / translated grids are
621 /// handled exactly) and marched with a voxel DDA against
622 /// [`Grid::voxel_solid`]; the closest hit by world distance `t`
623 /// wins. The step budget is bounded by `max_dist`, so empty space
624 /// is safe but not free — a chunk-level skip is a future
625 /// optimisation if hot.
626 #[must_use]
627 pub fn raycast(&self, origin: DVec3, dir: DVec3, max_dist: f64) -> Option<RayHit> {
628 let len = dir.length();
629 if len < 1e-12 || max_dist <= 0.0 {
630 return None;
631 }
632 let dn = dir / len; // unit world direction → t is world distance
633 let mut best: Option<RayHit> = None;
634 for (id, grid) in self.grids() {
635 // World ray → grid-local: undo translation + rotation. The
636 // inverse rotation preserves length, so `t` stays in world
637 // units and is comparable across grids.
638 let inv = grid.transform.rotation.inverse();
639 let lo = inv * (origin - grid.transform.origin);
640 let ld = inv * dn;
641 if let Some((voxel, t)) = voxel_dda(grid, lo, ld, max_dist) {
642 if best.as_ref().map_or(true, |b| t < b.t) {
643 best = Some(RayHit {
644 grid: id,
645 voxel,
646 world: origin + dn * t,
647 t,
648 color: grid.voxel_color(voxel),
649 });
650 }
651 }
652 }
653 best
654 }
655
656 /// Configure the number of worker threads in the dedicated
657 /// streaming pool (S7.3).
658 ///
659 /// Lazily applied — the pool itself is constructed on the first
660 /// [`Self::pump_streaming`] call. If the pool was already built
661 /// (i.e. a previous `pump_streaming` already dispatched at
662 /// least one task), it gets dropped and rebuilt. Dropping the
663 /// old pool blocks until all of its in-flight tasks finish
664 /// (rayon's contract); any results those tasks sent are still
665 /// drained by the next `pump_streaming` because the channel
666 /// survives the rebuild.
667 ///
668 /// The streaming pool is separate from rayon's global pool
669 /// (which R12 multicore rendering uses), so chunk generation
670 /// doesn't compete with render threads. Sensible values are 1
671 /// to ~4 — generation work is CPU-bound but should leave most
672 /// of the box for everything else.
673 ///
674 /// On wasm32 this is a no-op (no rayon pool available);
675 /// `pump_streaming` runs synchronously there.
676 ///
677 /// # Panics
678 /// Panics on native if `n == 0` (zero-thread pools are not
679 /// supported; the scene crate's S7.1 helper already disallows
680 /// the equivalent for `StreamRadius::r_active < 0`).
681 #[cfg(not(target_arch = "wasm32"))]
682 pub fn set_streaming_threads(&mut self, n: usize) {
683 self.streaming.set_thread_count(n);
684 }
685
686 /// wasm32 no-op companion of [`Self::set_streaming_threads`].
687 /// Lets cross-target code call this unconditionally.
688 #[cfg(target_arch = "wasm32")]
689 pub fn set_streaming_threads(&mut self, _n: usize) {
690 // No streaming pool on wasm32 — see `pump_streaming` docs.
691 }
692
693 /// Asynchronous streaming pump (S7.3).
694 ///
695 /// On native, dispatches missing-chunk generations onto a
696 /// dedicated rayon pool, drains any results that arrived since
697 /// the last pump, runs the eviction pass, and tracks in-flight
698 /// tasks in each grid's [`Grid::pending_gen`] set. The drain
699 /// uses the per-chunk version counter from S7.2 to discard
700 /// results whose chunk was edited mid-generation.
701 ///
702 /// On wasm32 this short-circuits to [`Self::pump_streaming_sync`]
703 /// — no thread pool is available there, but the same per-grid
704 /// stream-in / evict semantics apply.
705 ///
706 /// Call once per frame from the render thread. Cheap when
707 /// nothing changed (early-exit on disabled grids, try_recv
708 /// loops empty fast).
709 pub fn pump_streaming(&mut self, camera_world_pos: DVec3) {
710 #[cfg(target_arch = "wasm32")]
711 {
712 self.pump_streaming_sync(camera_world_pos);
713 }
714 #[cfg(not(target_arch = "wasm32"))]
715 {
716 self.pump_streaming_native(camera_world_pos);
717 }
718 }
719
720 /// Native implementation of [`Self::pump_streaming`].
721 #[cfg(not(target_arch = "wasm32"))]
722 fn pump_streaming_native(&mut self, camera_world_pos: DVec3) {
723 // 1. Drain inbox — install fresh results, drop stale.
724 while let Ok(result) = self.streaming.rx.try_recv() {
725 let Some(grid) = self.grids.get_mut(&result.grid_id) else {
726 // Grid was removed while a generation task was
727 // in-flight. Drop silently.
728 continue;
729 };
730 // Clearing pending_gen here both for "result delivered"
731 // and "we shouldn't try to re-dispatch this chunk just
732 // because it's missing".
733 let was_pending = grid.pending_gen.remove(&result.chunk_idx);
734 if !was_pending {
735 // Either the chunk was evicted (pending cleared in
736 // the eviction pass below in some prior call), or a
737 // duplicate result for an already-handled chunk.
738 continue;
739 }
740 if grid.chunks.contains_key(&result.chunk_idx) {
741 // Some other path (e.g. `ensure_chunk_generated`
742 // sync helper, or a manual edit's `ensure_chunk`)
743 // already populated the slot. Don't overwrite.
744 continue;
745 }
746 if grid.chunk_version(result.chunk_idx) != result.version_at_dispatch {
747 // S7.2 stale-result discard: chunk was edited mid-
748 // generation.
749 continue;
750 }
751 grid.chunks.insert(result.chunk_idx, result.vxl);
752 // S7.4: same invalidation contract as the sync
753 // `ensure_chunk_generated` path — installing a new
754 // chunk can grow the bounding sphere, so the
755 // billboard impostor cache must be rebuilt on next
756 // Far entry. Lazy: only one cache wipe per drain
757 // batch, the Far render rebuilds afterwards.
758 grid.billboards = None;
759 }
760
761 // 2. Per-grid: eviction first, then dispatch. Doing evict
762 // before dispatch means a chunk that's just left
763 // r_active doesn't get re-dispatched on the same pump.
764 self.streaming.ensure_pool();
765 // Disjoint sub-field borrows: pool/tx via `&self.streaming.*`,
766 // grids via `&mut self.grids`. Hold both at once.
767 let pool: &rayon::ThreadPool = self.streaming.pool.as_ref().expect("ensure_pool just ran");
768 let tx_template = &self.streaming.tx;
769 for (grid_id, grid) in &mut self.grids {
770 evict_grid_chunks(grid, camera_world_pos);
771 dispatch_grid_async(*grid_id, grid, camera_world_pos, pool, tx_template);
772 }
773 }
774
775 /// Synchronous streaming pump (S7.1).
776 ///
777 /// For each grid with a non-[`StreamRadius::DISABLED`] policy:
778 /// 1. Project the world-space camera into grid-local coords
779 /// (inverse rotation + origin subtract).
780 /// 2. Stream in any chunk whose AABB-to-camera distance is
781 /// `<= r_active`, calling [`Grid::ensure_chunk_generated`].
782 /// No-ops gracefully if the grid has no generator attached
783 /// (so callers can use the eviction half of streaming on a
784 /// purely-edited grid).
785 /// 3. Evict any chunk whose AABB-to-camera distance exceeds
786 /// `r_evict` from the grid's chunk map. Eviction also
787 /// clears the cached [`BillboardCache`] (the bounding sphere
788 /// may shrink, invalidating impostor projections; the next
789 /// Far-tier render rebuilds lazily).
790 ///
791 /// Both passes use the f64 grid-local position so rotation +
792 /// non-axis-aligned grids stream and evict correctly. The
793 /// generate path is blocking — S7.3 will move it to a
794 /// background rayon pool with `pump_streaming` (non-blocking).
795 /// Callers that want the async variant in S7.0/S7.1 stages
796 /// should keep `r_active` small.
797 pub fn pump_streaming_sync(&mut self, camera_world_pos: DVec3) {
798 for grid in self.grids.values_mut() {
799 pump_grid_streaming_sync(grid, camera_world_pos);
800 }
801 }
802}
803
804/// S7.1 helper — drives one grid's synchronous streaming pass.
805/// Stream-in pass uses [`Grid::ensure_chunk_generated`] (blocking
806/// inline generation); eviction pass shared with the S7.3 async
807/// path through [`evict_grid_chunks`].
808fn pump_grid_streaming_sync(grid: &mut Grid, camera_world_pos: DVec3) {
809 let radius = grid.stream_radius;
810 if radius.is_disabled() {
811 return;
812 }
813 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
814
815 // --- Pass 1: stream in active chunks (sync) ---------------
816 if radius.r_active > 0.0 && grid.generator.is_some() {
817 for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
818 grid.ensure_chunk_generated(idx);
819 });
820 }
821
822 // --- Pass 2: evict chunks past r_evict --------------------
823 evict_grid_chunks_with_cam(grid, cam_local);
824}
825
826/// Eviction pass shared by [`pump_grid_streaming_sync`] and the
827/// S7.3 async path. Public-ish so the async driver can call it
828/// before dispatching to avoid generating chunks that are about
829/// to be evicted. `cfg`-gated to native: on wasm32 the only
830/// caller (`pump_streaming_native`) doesn't compile, so this
831/// helper would warn as dead code.
832#[cfg(not(target_arch = "wasm32"))]
833fn evict_grid_chunks(grid: &mut Grid, camera_world_pos: DVec3) {
834 let radius = grid.stream_radius;
835 if radius.is_disabled() {
836 return;
837 }
838 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
839 evict_grid_chunks_with_cam(grid, cam_local);
840}
841
842/// Eviction inner — assumes `cam_local` is already computed (the
843/// dispatcher and sync pump both have it on hand).
844fn evict_grid_chunks_with_cam(grid: &mut Grid, cam_local: DVec3) {
845 let radius = grid.stream_radius;
846 if !radius.r_evict.is_finite() {
847 return;
848 }
849 let r_sq = radius.r_evict * radius.r_evict;
850 let to_evict: Vec<IVec3> = grid
851 .chunks
852 .keys()
853 .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
854 .copied()
855 .collect();
856 // S7.3: also evict pending in-flight tasks past r_evict so the
857 // drain pass doesn't install a chunk that's no longer wanted.
858 // We don't have a way to cancel the rayon task, but we can
859 // drop the pending_gen entry so the result is dropped on
860 // arrival.
861 let to_evict_pending: Vec<IVec3> = grid
862 .pending_gen
863 .iter()
864 .filter(|&&idx| streaming::chunk_aabb_dist_sq(cam_local, idx) > r_sq)
865 .copied()
866 .collect();
867 if to_evict.is_empty() && to_evict_pending.is_empty() {
868 return;
869 }
870 for idx in &to_evict {
871 grid.chunks.remove(idx);
872 // S7.2: keep chunk_versions in sync with chunks so the
873 // map stays bounded. A future re-stream of the same idx
874 // restarts at 0 — that's fine because any in-flight
875 // gen-result tagged with the pre-eviction version is
876 // unreachable (no chunk to install onto) and gets
877 // discarded by the new "version still 0" check anyway.
878 grid.chunk_versions.remove(idx);
879 // S7.3: drop pending entry for the same chunk too. If a
880 // background task is still running, its result will be
881 // dropped on arrival (was_pending = false).
882 grid.pending_gen.remove(idx);
883 }
884 for idx in &to_evict_pending {
885 grid.pending_gen.remove(idx);
886 }
887 if !to_evict.is_empty() {
888 // Bounding sphere can shrink → impostor projections would
889 // be wrong on next Far render. Clear lazily; the next
890 // Far-tier pass repopulates via BillboardCache::build.
891 grid.billboards = None;
892 }
893}
894
895/// Walk every chunk index whose AABB falls within `r_active` of
896/// `cam_local` and invoke `f` on it. Shared between the S7.1 sync
897/// stream-in and the S7.3 async dispatch.
898fn for_each_chunk_in_radius<F>(cam_local: DVec3, r_active: f64, mut f: F)
899where
900 F: FnMut(IVec3),
901{
902 let r_sq = r_active * r_active;
903 let sxy = f64::from(CHUNK_SIZE_XY);
904 let sz = f64::from(CHUNK_SIZE_Z);
905 // Half-extent in chunk units; ceil to be conservative so any
906 // chunk whose AABB clips the radius gets considered. `+1`
907 // covers the half-open chunk-AABB upper edge plus the case
908 // where the camera sits exactly on a chunk boundary and the
909 // closest chunk is one index off.
910 #[allow(clippy::cast_possible_truncation)]
911 let r_chunks_xy = (r_active / sxy).ceil() as i32 + 1;
912 #[allow(clippy::cast_possible_truncation)]
913 let r_chunks_z = (r_active / sz).ceil() as i32 + 1;
914 #[allow(clippy::cast_possible_truncation)]
915 let cx_chunk = (cam_local.x / sxy).floor() as i32;
916 #[allow(clippy::cast_possible_truncation)]
917 let cy_chunk = (cam_local.y / sxy).floor() as i32;
918 #[allow(clippy::cast_possible_truncation)]
919 let cz_chunk = (cam_local.z / sz).floor() as i32;
920 for chz in (cz_chunk - r_chunks_z)..=(cz_chunk + r_chunks_z) {
921 for chy in (cy_chunk - r_chunks_xy)..=(cy_chunk + r_chunks_xy) {
922 for chx in (cx_chunk - r_chunks_xy)..=(cx_chunk + r_chunks_xy) {
923 let idx = IVec3::new(chx, chy, chz);
924 if streaming::chunk_aabb_dist_sq(cam_local, idx) <= r_sq {
925 f(idx);
926 }
927 }
928 }
929 }
930}
931
932/// S7.3 async dispatch — schedule generation for every chunk in
933/// `r_active` that's not already present and not already in
934/// flight. Each dispatch clones the grid's generator `Arc` and a
935/// sender clone, then spawns the closure on the streaming rayon
936/// pool. The closure does the generate + send; the main thread
937/// drains results on the next pump.
938#[cfg(not(target_arch = "wasm32"))]
939fn dispatch_grid_async(
940 grid_id: GridId,
941 grid: &mut Grid,
942 camera_world_pos: DVec3,
943 pool: &rayon::ThreadPool,
944 tx: &crossbeam_channel::Sender<streaming::ChunkResult>,
945) {
946 let radius = grid.stream_radius;
947 if radius.is_disabled() || radius.r_active <= 0.0 {
948 return;
949 }
950 let Some(generator) = grid.generator.as_ref().map(Arc::clone) else {
951 return;
952 };
953 let cam_local = streaming::world_to_grid_local_pos(camera_world_pos, &grid.transform);
954 for_each_chunk_in_radius(cam_local, radius.r_active, |idx| {
955 if grid.chunks.contains_key(&idx) {
956 return; // already present
957 }
958 if grid.pending_gen.contains(&idx) {
959 return; // already in flight
960 }
961 // S7.6+: respect the generator's per-chunk filter — same
962 // contract as `Grid::ensure_chunk_generated` (sync helper).
963 // Lets a generator decline to materialise specific indices
964 // (e.g. `HillsChunkGenerator` skipping placeholder bedrock
965 // chunks at chz != 0 so the camera-above-grid path doesn't
966 // create chz < 0 entries that would shift `origin_chunk_z`
967 // and trigger the S4B.6.j cross-chunk look-down bug).
968 if !generator.should_generate(idx) {
969 return;
970 }
971 grid.pending_gen.insert(idx);
972 let version_at_dispatch = grid.chunk_version(idx);
973 let tx_clone = tx.clone();
974 let gen_clone = Arc::clone(&generator);
975 pool.spawn(move || {
976 let vxl = gen_clone.generate(idx);
977 // Send is non-blocking on unbounded channel; if the
978 // receiver was dropped (Scene drop), the send fails
979 // silently — that's fine.
980 let _ = tx_clone.send(streaming::ChunkResult {
981 grid_id,
982 chunk_idx: idx,
983 version_at_dispatch,
984 vxl,
985 });
986 });
987 });
988}
989
990#[cfg(test)]
991mod tests {
992 use super::*;
993
994 #[test]
995 fn empty_scene_has_no_grids() {
996 let scene = Scene::new();
997 assert_eq!(scene.grid_count(), 0);
998 assert!(scene.grids().next().is_none());
999 }
1000
1001 #[test]
1002 fn raycast_hits_axis_aligned_voxel() {
1003 let mut scene = Scene::new();
1004 let id = scene.add_grid(GridTransform::identity());
1005 scene
1006 .grid_mut(id)
1007 .unwrap()
1008 .set_voxel(IVec3::new(5, 5, 10), Some(0x80_aa_bb_cc));
1009
1010 // Straight down the +z column through (5,5): hits z=10 at t≈10.
1011 let hit = scene
1012 .raycast(DVec3::new(5.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1013 .expect("ray hits the voxel");
1014 assert_eq!(hit.grid, id);
1015 assert_eq!(hit.voxel, IVec3::new(5, 5, 10));
1016 assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1017 assert!(hit.color.is_some(), "textured voxel has a colour");
1018
1019 // A column with no voxel misses.
1020 assert!(
1021 scene
1022 .raycast(DVec3::new(0.5, 0.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1023 .is_none(),
1024 "empty column → no hit",
1025 );
1026 }
1027
1028 #[test]
1029 fn raycast_respects_grid_transform() {
1030 // A translated grid: the hit voxel is reported in GRID-LOCAL
1031 // coords, and the world hit point is back in world space — so a
1032 // host gets the true voxel regardless of where the grid sits.
1033 let mut scene = Scene::new();
1034 let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1035 scene
1036 .grid_mut(id)
1037 .unwrap()
1038 .set_voxel(IVec3::new(5, 5, 10), Some(0x80_11_22_33));
1039
1040 let hit = scene
1041 .raycast(DVec3::new(105.5, 5.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1042 .expect("ray hits the translated voxel");
1043 assert_eq!(hit.voxel, IVec3::new(5, 5, 10), "grid-local voxel");
1044 assert!((hit.world.x - 105.5).abs() < 1e-6, "world x preserved");
1045 assert!((hit.t - 10.0).abs() < 1e-6, "t≈10, got {}", hit.t);
1046 }
1047
1048 #[test]
1049 fn raycast_picks_nearest_grid() {
1050 // Two grids with a voxel each along the same world column; the
1051 // raycast must return the closer one.
1052 let mut scene = Scene::new();
1053 let near = scene.add_grid(GridTransform::identity());
1054 let far = scene.add_grid(GridTransform::identity());
1055 scene
1056 .grid_mut(near)
1057 .unwrap()
1058 .set_voxel(IVec3::new(1, 1, 20), Some(0x80_00_ff_00));
1059 scene
1060 .grid_mut(far)
1061 .unwrap()
1062 .set_voxel(IVec3::new(1, 1, 40), Some(0x80_ff_00_00));
1063
1064 let hit = scene
1065 .raycast(DVec3::new(1.5, 1.5, 0.0), DVec3::new(0.0, 0.0, 1.0), 64.0)
1066 .expect("hits the nearer voxel");
1067 assert_eq!(hit.grid, near);
1068 assert_eq!(hit.voxel, IVec3::new(1, 1, 20));
1069 }
1070
1071 #[test]
1072 fn add_grid_returns_fresh_ids() {
1073 let mut scene = Scene::new();
1074 let a = scene.add_grid(GridTransform::identity());
1075 let b = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1076 assert_ne!(a, b);
1077 assert_eq!(a.raw(), 0);
1078 assert_eq!(b.raw(), 1);
1079 assert_eq!(scene.grid_count(), 2);
1080 }
1081
1082 #[test]
1083 fn grid_lookup_round_trips() {
1084 let mut scene = Scene::new();
1085 let id = scene.add_grid(GridTransform::at(DVec3::new(10.0, 20.0, 30.0)));
1086 let g = scene.grid(id).expect("grid registered");
1087 assert_eq!(g.transform.origin, DVec3::new(10.0, 20.0, 30.0));
1088 assert_eq!(g.transform.rotation, DQuat::IDENTITY);
1089 assert!(g.chunks.is_empty());
1090 }
1091
1092 #[test]
1093 fn remove_grid_drops_it_from_scene() {
1094 let mut scene = Scene::new();
1095 let id = scene.add_grid(GridTransform::identity());
1096 let removed = scene.remove_grid(id);
1097 assert!(removed.is_some());
1098 assert_eq!(scene.grid_count(), 0);
1099 assert!(scene.grid(id).is_none());
1100 // Re-adding does NOT reuse the dropped id.
1101 let id2 = scene.add_grid(GridTransform::identity());
1102 assert_ne!(id, id2);
1103 assert_eq!(id2.raw(), 1);
1104 }
1105
1106 #[test]
1107 fn remove_unknown_grid_is_none() {
1108 let mut scene = Scene::new();
1109 let bogus = GridId(999);
1110 assert!(scene.remove_grid(bogus).is_none());
1111 }
1112
1113 #[test]
1114 fn grid_mut_can_modify_transform() {
1115 let mut scene = Scene::new();
1116 let id = scene.add_grid(GridTransform::identity());
1117 scene.grid_mut(id).unwrap().transform.origin = DVec3::new(1.0, 2.0, 3.0);
1118 assert_eq!(
1119 scene.grid(id).unwrap().transform.origin,
1120 DVec3::new(1.0, 2.0, 3.0)
1121 );
1122 }
1123
1124 #[test]
1125 fn chunk_size_constants_match_plan() {
1126 // Plan locks these values; bumping either breaks the slab
1127 // byte format (Z) or the worst-case chunk footprint budget
1128 // (XY). Pin them so a future refactor that drifts them
1129 // shows up in CI.
1130 assert_eq!(CHUNK_SIZE_XY, 128);
1131 assert_eq!(CHUNK_SIZE_Z, 256);
1132 }
1133
1134 // ---- S6.0: bounding_radius + Grid::select_lod ----
1135
1136 #[test]
1137 fn new_grid_defaults_to_always_near_lod() {
1138 // Byte-identity contract for the staged S6 rollout: a
1139 // grid built through `new` must never trigger the Mid/Far
1140 // branches by accident, even when bounding_radius would
1141 // imply otherwise.
1142 let g = Grid::new(GridTransform::identity());
1143 assert_eq!(g.lod_thresholds.r_near, f64::INFINITY);
1144 assert_eq!(g.lod_thresholds.r_mid, f64::INFINITY);
1145 assert_eq!(g.select_lod(DVec3::new(1e9, 0.0, 0.0)), Lod::Near);
1146 }
1147
1148 #[test]
1149 fn bounding_radius_empty_grid_is_zero() {
1150 let g = Grid::new(GridTransform::identity());
1151 assert_eq!(g.bounding_radius(), 0.0);
1152 }
1153
1154 #[test]
1155 fn bounding_radius_single_chunk_at_origin() {
1156 // One chunk at (0, 0, 0): bbox is [0, 128) × [0, 128) × [0, 256).
1157 // Half-extent = (64, 64, 128); length = sqrt(64² + 64² + 128²)
1158 // = sqrt(4096 + 4096 + 16384) = sqrt(24576) ≈ 156.7747...
1159 let mut scene = Scene::new();
1160 let id = scene.add_grid(GridTransform::identity());
1161 let g = scene.grid_mut(id).unwrap();
1162 // Populate chunk (0, 0, 0) via the edit API.
1163 g.set_voxel(IVec3::new(0, 0, 0), Some(0x80_88_88_88));
1164 let r = g.bounding_radius();
1165 let expected = ((64.0_f64).powi(2) * 2.0 + (128.0_f64).powi(2)).sqrt();
1166 assert!(
1167 (r - expected).abs() < 1e-9,
1168 "bounding_radius={r} expected={expected}"
1169 );
1170 }
1171
1172 #[test]
1173 fn bounding_radius_grows_with_chunk_extent() {
1174 // Two chunks at (0,0,0) and (3,0,0): x extent is 4 chunks =
1175 // 512 voxels; y/z are 1 chunk each. Half-extent = (256, 64, 128);
1176 // length = sqrt(256² + 64² + 128²) = sqrt(65536+4096+16384)
1177 // = sqrt(86016) ≈ 293.2848.
1178 let mut scene = Scene::new();
1179 let id = scene.add_grid(GridTransform::identity());
1180 let g = scene.grid_mut(id).unwrap();
1181 // Stamp one voxel in chunk (0,0,0).
1182 g.set_voxel(IVec3::new(0, 0, 0), Some(0x80_88_88_88));
1183 // Stamp one voxel in chunk (3,0,0): grid-local x = 3*128 = 384.
1184 g.set_voxel(IVec3::new(384, 0, 0), Some(0x80_88_88_88));
1185 assert_eq!(g.chunks.len(), 2);
1186 let r = g.bounding_radius();
1187 let expected = (256.0_f64.powi(2) + 64.0_f64.powi(2) + 128.0_f64.powi(2)).sqrt();
1188 assert!(
1189 (r - expected).abs() < 1e-9,
1190 "bounding_radius={r} expected={expected}"
1191 );
1192 }
1193
1194 #[test]
1195 fn grid_select_lod_respects_lod_thresholds_field() {
1196 // Set a non-default threshold and verify the helper picks
1197 // the right tier for known distances.
1198 let mut scene = Scene::new();
1199 let id = scene.add_grid(GridTransform::at(DVec3::new(100.0, 0.0, 0.0)));
1200 let g = scene.grid_mut(id).unwrap();
1201 g.lod_thresholds = LodThresholds {
1202 r_near: 50.0,
1203 r_mid: 200.0,
1204 ..LodThresholds::always_near()
1205 };
1206 // Camera 25 units from grid origin → Near.
1207 assert_eq!(g.select_lod(DVec3::new(125.0, 0.0, 0.0)), Lod::Near);
1208 // 100 units → Mid.
1209 assert_eq!(g.select_lod(DVec3::new(200.0, 0.0, 0.0)), Lod::Mid);
1210 // 500 units → Far.
1211 assert_eq!(g.select_lod(DVec3::new(600.0, 0.0, 0.0)), Lod::Far);
1212 }
1213}