Skip to main content

roxlap_scene/
snapshot.rs

1//! Serde-friendly snapshot of a [`Scene`].
2//!
3//! The live [`Scene`] holds [`Vxl`] chunks with allocator state
4//! ([`Vxl::vbit`] / [`Vxl::vbiti`]) that doesn't round-trip
5//! cleanly through serde — the post-edit slab pool is interior
6//! mutable and changes shape under voxalloc-driven scatter.
7//! [`SceneSnapshot`] is a flattened view: per-chunk bytes
8//! produced by [`roxlap_formats::vxl::serialize`], plus the grid
9//! transforms / ids the runtime tracks. It's a value type with
10//! plain serde derives — bincode / postcard / json / cbor all
11//! work.
12//!
13//! Use [`Scene::to_snapshot`] / [`Scene::from_snapshot`] to round
14//! trip. The deserialised scene is editable: each chunk goes back
15//! through [`Vxl::reserve_edit_capacity`] so subsequent
16//! `Grid::set_*` calls don't panic.
17//!
18//! [`Scene`]: crate::Scene
19//! [`Vxl`]: roxlap_formats::vxl::Vxl
20//! [`Vxl::vbit`]: roxlap_formats::vxl::Vxl::vbit
21//! [`Vxl::vbiti`]: roxlap_formats::vxl::Vxl::vbiti
22//! [`Vxl::reserve_edit_capacity`]: roxlap_formats::vxl::Vxl::reserve_edit_capacity
23
24use glam::IVec3;
25use roxlap_formats::vxl::{self, ParseError, Vxl};
26use serde::{Deserialize, Serialize};
27
28use crate::{Grid, GridId, GridTransform, LodThresholds, Scene, StreamRadius};
29
30/// Re-encode a [`Vxl`]'s mip-0 columns into a contiguous bytes
31/// blob that round-trips through [`vxl::parse`].
32///
33/// [`vxl::serialize`] writes the live `vxl.data` array verbatim,
34/// which breaks the round-trip after edits: post-`voxalloc`
35/// scatter, columns may live in the edit pool past the
36/// originally-contiguous prefix, and `vxl::parse` walks columns
37/// linearly from offset 0. This helper builds a temporary
38/// contiguous [`Vxl`] (column index order) and serialises that —
39/// the result is a layout `vxl::parse` accepts even after
40/// arbitrary `set_voxel` / `set_rect` / `set_sphere` edits.
41///
42/// Mip-1+ data isn't preserved (the renderer rebuilds it on
43/// demand). Snapshots are pre-mip; the receiver calls
44/// [`Vxl::generate_mips`] if it wants them.
45fn compact_serialize_chunk(vxl: &Vxl) -> Vec<u8> {
46    let n_cols = (vxl.vsid as usize) * (vxl.vsid as usize);
47    let mut data: Vec<u8> = Vec::new();
48    let mut column_offset: Vec<u32> = Vec::with_capacity(n_cols + 1);
49    for i in 0..n_cols {
50        column_offset.push(u32::try_from(data.len()).expect("offset fits in u32"));
51        data.extend_from_slice(vxl.column_data(i));
52    }
53    column_offset.push(u32::try_from(data.len()).expect("offset fits in u32"));
54
55    let compact = Vxl {
56        vsid: vxl.vsid,
57        ipo: vxl.ipo,
58        ist: vxl.ist,
59        ihe: vxl.ihe,
60        ifo: vxl.ifo,
61        data: data.into_boxed_slice(),
62        column_offset: column_offset.into_boxed_slice(),
63        mip_base_offsets: Box::new([0, n_cols + 1]),
64        vbit: Box::new([]),
65        vbiti: 0,
66    };
67    vxl::serialize(&compact)
68}
69
70/// Bytes of edit-pool headroom re-applied per chunk during
71/// [`Scene::from_snapshot`]. Matches the value chunk creation uses
72/// in [`crate::chunks`] so a snapshot round-trip leaves chunks
73/// equally edit-ready as freshly-created ones.
74const RESTORE_EDIT_HEADROOM_PER_COLUMN: usize = 256;
75
76/// Top-level scene snapshot — full state needed to reconstruct a
77/// [`Scene`] via [`Scene::from_snapshot`].
78///
79/// Grids serialised as a `Vec<(GridId, GridSnapshot)>` rather than
80/// a `HashMap` so the wire form is independent of `HashMap`'s
81/// non-deterministic iteration order — the same scene snapshot
82/// twice in a row produces byte-identical output.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct SceneSnapshot {
85    /// Next id [`Scene::add_grid`] will hand out. Preserved across
86    /// snapshot round-trips so removed-id non-reuse holds.
87    pub next_grid_id: u32,
88    /// All registered grids paired with their ids.
89    pub grids: Vec<(GridId, GridSnapshot)>,
90}
91
92/// One grid's snapshot: transform + flattened chunks + the grid's
93/// runtime configuration (QE.5b — pre-QE.5 snapshots restored every
94/// config field to its default, so a loaded save silently lost
95/// `render_sky` / LOD / streaming settings).
96///
97/// The `generator` and `store` hooks are host code and cannot be
98/// serialised — rebind them after [`Scene::load_snapshot`], keyed on
99/// [`name`](Self::name).
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct GridSnapshot {
102    /// The grid's world placement (position + rotation).
103    pub transform: GridTransform,
104    /// Chunks as `(chunk_idx, vxl_bytes)`. `vxl_bytes` is
105    /// [`roxlap_formats::vxl::serialize`] output — re-parseable
106    /// via [`roxlap_formats::vxl::parse`].
107    pub chunks: Vec<(IVec3, Vec<u8>)>,
108    /// S7.2: per-chunk edit version counters, sorted by chunk
109    /// index. Chunks absent from this list restore as version 0 —
110    /// the same as a freshly generated or pre-S7.2 snapshot.
111    /// (`#[serde(default)]` covers self-describing formats; the
112    /// wire-format compatibility story is the QE.5b envelope
113    /// version in [`Scene::save_snapshot`].)
114    #[serde(default)]
115    pub chunk_versions: Vec<(IVec3, u64)>,
116    /// QE.5b — the grid's host-assigned rebind tag ([`crate::Grid::name`]).
117    #[serde(default)]
118    pub name: Option<String>,
119    /// QE.5b — [`crate::Grid::render_sky`].
120    #[serde(default = "default_render_sky")]
121    pub render_sky: bool,
122    /// QE.5b — [`crate::Grid::mip_levels_override`].
123    #[serde(default)]
124    pub mip_levels_override: Option<u32>,
125    /// QE.5b — [`crate::Grid::lod_thresholds`].
126    #[serde(default = "LodThresholds::always_near")]
127    pub lod_thresholds: LodThresholds,
128    /// QE.5b — [`crate::Grid::stream_radius`].
129    #[serde(default)]
130    pub stream_radius: StreamRadius,
131    /// SC.snap (v2) — the grid's [`GridTransform::voxel_world_size`]. Stored
132    /// as a sibling field (not inside the transform, whose wire form stays
133    /// frozen with `#[serde(skip)]`). The `#[serde(default)]` covers
134    /// self-describing formats; the bincode positional gap between v1 and v2
135    /// is handled by the private `GridSnapshotV1` shadow shape + the version
136    /// dispatch in [`Scene::load_snapshot`]. v1 blobs restore this at `1.0`.
137    #[serde(default = "one_f64")]
138    pub voxel_world_size: f64,
139}
140
141/// `voxel_world_size`'s default (`1.0`) for `#[serde(default)]` on
142/// self-describing formats — an unscaled grid.
143fn one_f64() -> f64 {
144    1.0
145}
146
147/// SC.snap — the **frozen v1** wire shape of [`SceneSnapshot`], used only to
148/// deserialize version-1 blobs (which predate the persisted scale). bincode
149/// is positional, so this must mirror v1's fields exactly — it has NO
150/// `voxel_world_size` (grids restore at `1.0` via [`From`]).
151#[derive(Deserialize)]
152struct SceneSnapshotV1 {
153    next_grid_id: u32,
154    grids: Vec<(GridId, GridSnapshotV1)>,
155}
156
157/// SC.snap — the frozen v1 [`GridSnapshot`] shape (no `voxel_world_size`).
158/// The field list + `#[serde(default)]`s must byte-match what v1
159/// `save_snapshot` wrote (the checked-in fixture is the gate).
160#[derive(Deserialize)]
161struct GridSnapshotV1 {
162    transform: GridTransform,
163    chunks: Vec<(IVec3, Vec<u8>)>,
164    #[serde(default)]
165    chunk_versions: Vec<(IVec3, u64)>,
166    #[serde(default)]
167    name: Option<String>,
168    #[serde(default = "default_render_sky")]
169    render_sky: bool,
170    #[serde(default)]
171    mip_levels_override: Option<u32>,
172    #[serde(default = "LodThresholds::always_near")]
173    lod_thresholds: LodThresholds,
174    #[serde(default)]
175    stream_radius: StreamRadius,
176}
177
178impl From<SceneSnapshotV1> for SceneSnapshot {
179    fn from(v1: SceneSnapshotV1) -> Self {
180        Self {
181            next_grid_id: v1.next_grid_id,
182            grids: v1.grids.into_iter().map(|(id, g)| (id, g.into())).collect(),
183        }
184    }
185}
186
187impl From<GridSnapshotV1> for GridSnapshot {
188    fn from(g: GridSnapshotV1) -> Self {
189        Self {
190            transform: g.transform,
191            chunks: g.chunks,
192            chunk_versions: g.chunk_versions,
193            name: g.name,
194            render_sky: g.render_sky,
195            mip_levels_override: g.mip_levels_override,
196            lod_thresholds: g.lod_thresholds,
197            stream_radius: g.stream_radius,
198            // v1 predates persisted scale — an unscaled grid.
199            voxel_world_size: 1.0,
200        }
201    }
202}
203
204/// `render_sky`'s [`crate::Grid::new`] default, for
205/// `#[serde(default)]` on self-describing formats.
206fn default_render_sky() -> bool {
207    true
208}
209
210/// Errors from [`Scene::from_snapshot`]. Wraps the per-chunk
211/// [`ParseError`] with a tag identifying which grid + chunk
212/// failed.
213#[derive(Debug)]
214pub enum FromSnapshotError {
215    /// One chunk's bytes failed to round-trip through
216    /// [`roxlap_formats::vxl::parse`].
217    ChunkParse {
218        /// The grid whose chunk failed to parse.
219        grid: GridId,
220        /// The failing chunk's index within `grid`.
221        chunk: IVec3,
222        /// The underlying `.vxl` parse failure.
223        source: ParseError,
224    },
225}
226
227impl std::fmt::Display for FromSnapshotError {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        match self {
230            Self::ChunkParse {
231                grid,
232                chunk,
233                source,
234            } => {
235                write!(
236                    f,
237                    "scene snapshot: grid {} chunk {chunk:?} parse failed: {source:?}",
238                    grid.raw()
239                )
240            }
241        }
242    }
243}
244
245impl std::error::Error for FromSnapshotError {}
246
247impl Scene {
248    /// Capture the scene's full state as a serde-friendly value.
249    /// Each chunk is encoded via
250    /// [`roxlap_formats::vxl::serialize`]; the rest is plain field
251    /// data.
252    ///
253    /// Grid iteration order in the produced snapshot is sorted by
254    /// [`GridId`] so two snapshots of the same scene produce
255    /// byte-identical output (the live `HashMap` iteration order
256    /// would be non-deterministic).
257    #[must_use]
258    pub fn to_snapshot(&self) -> SceneSnapshot {
259        let mut grid_ids: Vec<GridId> = self.grids.keys().copied().collect();
260        grid_ids.sort_unstable();
261
262        let mut grids = Vec::with_capacity(grid_ids.len());
263        for id in grid_ids {
264            let grid = &self.grids[&id];
265            let mut chunk_addrs: Vec<IVec3> = grid.chunks.keys().copied().collect();
266            chunk_addrs.sort_unstable_by_key(|a| (a.x, a.y, a.z));
267            let chunks = chunk_addrs
268                .into_iter()
269                .map(|addr| (addr, compact_serialize_chunk(&grid.chunks[&addr])))
270                .collect();
271            // S7.2: emit chunk_versions sorted by chunk idx so the
272            // snapshot bytes stay deterministic (HashMap iter order
273            // is not). Zero entries are dropped on the assumption
274            // "missing == 0" — the snapshot stays compact for grids
275            // whose live counters are dense in 1+.
276            let mut version_addrs: Vec<IVec3> = grid
277                .chunk_versions
278                .iter()
279                .filter_map(|(a, v)| if *v != 0 { Some(*a) } else { None })
280                .collect();
281            version_addrs.sort_unstable_by_key(|a| (a.x, a.y, a.z));
282            let chunk_versions = version_addrs
283                .into_iter()
284                .map(|addr| (addr, grid.chunk_versions[&addr]))
285                .collect();
286            grids.push((
287                id,
288                GridSnapshot {
289                    transform: grid.transform,
290                    chunks,
291                    chunk_versions,
292                    name: grid.name.clone(),
293                    render_sky: grid.render_sky,
294                    mip_levels_override: grid.mip_levels_override,
295                    lod_thresholds: grid.lod_thresholds,
296                    stream_radius: grid.stream_radius,
297                    // SC.snap — persist the grid's scale (transform's own wire
298                    // form omits it via #[serde(skip)]).
299                    voxel_world_size: grid.transform.voxel_world_size,
300                },
301            ));
302        }
303        SceneSnapshot {
304            next_grid_id: self.next_grid_id,
305            grids,
306        }
307    }
308
309    /// Restore a [`Scene`] from a snapshot. Each chunk's bytes are
310    /// re-parsed via [`roxlap_formats::vxl::parse`] and re-armed
311    /// for edits via [`roxlap_formats::vxl::Vxl::reserve_edit_capacity`].
312    ///
313    /// # Errors
314    ///
315    /// Returns [`FromSnapshotError::ChunkParse`] tagged with the
316    /// owning grid + chunk index if any chunk's bytes fail to
317    /// parse. The partial scene is dropped — restoration is
318    /// all-or-nothing.
319    pub fn from_snapshot(snap: &SceneSnapshot) -> Result<Self, FromSnapshotError> {
320        let mut scene = Self::new();
321        scene.next_grid_id = snap.next_grid_id;
322        for (id, gsnap) in &snap.grids {
323            // SC.snap — `transform`'s wire form omits `voxel_world_size`
324            // (`#[serde(skip)]`); the persisted value rides in the sibling
325            // `gsnap.voxel_world_size`. Fold it back into the transform.
326            // Guard untrusted bytes to a sane range: not just ≤0 / non-finite
327            // (which break the marcher — GPU `chunk_dim = 0` → NaN) but also
328            // subnormal-near-zero (1e-300 > 0 yet `vsid · 1e-300 ≈ 0`) and
329            // absurdly-huge finite values. `[1e-6, 1e6]` spans any sane
330            // planet↔grain ratio with margin; out-of-range → fall back to 1.0.
331            let mut transform = gsnap.transform;
332            let vws = gsnap.voxel_world_size;
333            transform.voxel_world_size = if vws.is_finite() && (1e-6..=1e6).contains(&vws) {
334                vws
335            } else {
336                log::warn!(
337                    "load_snapshot: grid {id:?} has out-of-range \
338                         voxel_world_size {vws} — restoring at 1.0"
339                );
340                1.0
341            };
342            let mut grid = Grid::new(transform);
343            for (addr, bytes) in &gsnap.chunks {
344                let mut vxl =
345                    vxl::parse(bytes).map_err(|source| FromSnapshotError::ChunkParse {
346                        grid: *id,
347                        chunk: *addr,
348                        source,
349                    })?;
350                let n_cols = (vxl.vsid as usize) * (vxl.vsid as usize);
351                vxl.reserve_edit_capacity(n_cols * RESTORE_EDIT_HEADROOM_PER_COLUMN);
352                grid.chunks.insert(*addr, vxl);
353                grid.note_chunk_set_changed();
354            }
355            // S7.2: restore per-chunk versions. Pre-S7.2 snapshots
356            // carry an empty Vec (via #[serde(default)]) → no
357            // bumps applied, every chunk reads as version 0.
358            for (addr, ver) in &gsnap.chunk_versions {
359                grid.restore_chunk_version(*addr, *ver);
360            }
361            // QE.5b — restore the grid's runtime configuration (the
362            // `generator` / `store` hooks are host code: rebind them
363            // after loading, keyed on `name`).
364            grid.name.clone_from(&gsnap.name);
365            grid.render_sky = gsnap.render_sky;
366            grid.mip_levels_override = gsnap.mip_levels_override;
367            grid.lod_thresholds = gsnap.lod_thresholds;
368            grid.stream_radius = gsnap.stream_radius;
369            scene.grids.insert(*id, grid);
370        }
371        Ok(scene)
372    }
373}
374
375/// The QE.5b wire envelope's magic — identifies a byte blob as a
376/// roxlap scene snapshot before any deserialisation runs.
377pub const SNAPSHOT_MAGIC: [u8; 4] = *b"RXSS";
378
379/// Current snapshot wire version. Bumped whenever the
380/// [`SceneSnapshot`] payload shape changes in a way `#[serde(default)]`
381/// trailing fields can't cover; [`Scene::load_snapshot`] dispatches on
382/// it, so an old save either loads correctly or fails with
383/// [`SnapshotLoadError::UnsupportedVersion`] — never a silent misparse
384/// (the pre-QE.5 failure mode of bare positional bincode).
385///
386/// SC.snap — **v2** persists per-grid `voxel_world_size`. bincode is
387/// strictly positional, so the trailing `voxel_world_size` field on
388/// [`GridSnapshot`] would make a v1 blob short-read ("unexpected end of
389/// file") — hence the version bump. [`Scene::load_snapshot`] dispatches:
390/// v2 blobs decode [`GridSnapshot`] directly; v1 blobs decode the frozen
391/// private `GridSnapshotV1` shadow shape (which lacks the field) and restore
392/// at `voxel_world_size = 1.0`. `GridTransform`'s own wire form stays frozen
393/// (`#[serde(skip)]` on the field) in BOTH versions — the persisted scale
394/// is a sibling field on the snapshot, not inside the transform — so the
395/// forever-loadable v1 fixture keeps loading unchanged.
396pub const SNAPSHOT_VERSION: u32 = 2;
397
398/// Errors from [`Scene::load_snapshot`].
399#[derive(Debug)]
400pub enum SnapshotLoadError {
401    /// The bytes don't start with [`SNAPSHOT_MAGIC`] — not a roxlap
402    /// snapshot (or a pre-QE.5 bare-bincode save; see the
403    /// [`Scene::load_snapshot`] migration note).
404    BadMagic,
405    /// A snapshot from a newer (or unknown) wire version.
406    UnsupportedVersion(u32),
407    /// The payload failed to decode (truncated / corrupted bytes).
408    Decode(String),
409    /// The payload decoded but a chunk failed to restore.
410    Restore(FromSnapshotError),
411}
412
413impl std::fmt::Display for SnapshotLoadError {
414    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
415        match self {
416            Self::BadMagic => write!(f, "not a roxlap scene snapshot (bad magic)"),
417            Self::UnsupportedVersion(v) => {
418                write!(
419                    f,
420                    "unsupported snapshot version {v} (this build reads <= {SNAPSHOT_VERSION})"
421                )
422            }
423            Self::Decode(msg) => write!(f, "snapshot payload decode failed: {msg}"),
424            Self::Restore(e) => write!(f, "snapshot restore failed: {e}"),
425        }
426    }
427}
428
429impl std::error::Error for SnapshotLoadError {
430    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
431        match self {
432            Self::Restore(e) => Some(e),
433            _ => None,
434        }
435    }
436}
437
438impl Scene {
439    /// Serialise the scene to the versioned snapshot **wire format**
440    /// (QE.5b): [`SNAPSHOT_MAGIC`] + little-endian
441    /// [`SNAPSHOT_VERSION`] + a bincode [`SceneSnapshot`] payload.
442    /// This is the save-file API — a blob written today stays
443    /// loadable by future engine versions ([`Self::load_snapshot`]
444    /// dispatches on the version), which bare serde values can't
445    /// promise under positional codecs.
446    ///
447    /// Hosts that want a different payload codec (JSON for debugging,
448    /// postcard for size) can still serialise
449    /// [`Self::to_snapshot`]'s value themselves — and then own their
450    /// format's evolution story.
451    #[must_use]
452    pub fn save_snapshot(&self) -> Vec<u8> {
453        // SC.snap — v2 persists per-grid `voxel_world_size` (see
454        // [`SNAPSHOT_VERSION`]); no scale is lost across a round-trip.
455        let mut out = Vec::with_capacity(64);
456        out.extend_from_slice(&SNAPSHOT_MAGIC);
457        out.extend_from_slice(&SNAPSHOT_VERSION.to_le_bytes());
458        bincode::serialize_into(&mut out, &self.to_snapshot())
459            .expect("bincode into Vec<u8> cannot fail");
460        out
461    }
462
463    /// Load a scene from [`Self::save_snapshot`] bytes, dispatching
464    /// on the embedded wire version.
465    ///
466    /// Migration note: saves written **before** QE.5b (bare bincode
467    /// of a [`SceneSnapshot`], no envelope) fail with
468    /// [`SnapshotLoadError::BadMagic`]; decode those with the engine
469    /// version that wrote them and re-save.
470    ///
471    /// # Errors
472    /// [`SnapshotLoadError`] — bad magic, unknown version, corrupted
473    /// payload, or a failing chunk restore.
474    pub fn load_snapshot(bytes: &[u8]) -> Result<Self, SnapshotLoadError> {
475        let (Some(magic), Some(version)) = (bytes.get(..4), bytes.get(4..8)) else {
476            return Err(SnapshotLoadError::BadMagic);
477        };
478        if magic != SNAPSHOT_MAGIC {
479            return Err(SnapshotLoadError::BadMagic);
480        }
481        let version = u32::from_le_bytes(version.try_into().expect("4-byte slice"));
482        let payload = &bytes[8..];
483        // SC.snap — dispatch on the wire version. v1 blobs decode the frozen
484        // `SceneSnapshotV1` shadow shape (no persisted scale → 1.0); v2 blobs
485        // decode `SceneSnapshot` directly. Both funnel through `from_snapshot`.
486        let snap: SceneSnapshot = match version {
487            1 => bincode::deserialize::<SceneSnapshotV1>(payload)
488                .map_err(|e| SnapshotLoadError::Decode(e.to_string()))?
489                .into(),
490            2 => bincode::deserialize(payload)
491                .map_err(|e| SnapshotLoadError::Decode(e.to_string()))?,
492            v => return Err(SnapshotLoadError::UnsupportedVersion(v)),
493        };
494        Self::from_snapshot(&snap).map_err(SnapshotLoadError::Restore)
495    }
496}
497
498#[cfg(test)]
499#[allow(clippy::cast_possible_wrap, clippy::type_complexity)]
500mod tests {
501    use super::*;
502    use crate::chunks::tests::voxel_is_solid;
503    use crate::CHUNK_SIZE_XY;
504    use glam::DVec3;
505    use roxlap_formats::color::VoxColor;
506
507    impl GridId {
508        pub(crate) fn from_raw_for_test(raw: u32) -> Self {
509            Self(raw)
510        }
511    }
512
513    #[test]
514    fn sc_snap_scaled_grid_survives_round_trip() {
515        // SC.snap — v2 persists per-grid voxel_world_size. A vws=0.25 grid must
516        // restore at 0.25, not the pre-SC.snap 1.0 (transform's own wire form
517        // still omits it via #[serde(skip)] — the value rides the sibling
518        // GridSnapshot field).
519        let mut scene = Scene::new();
520        let id = scene.add_grid(GridTransform::at_scale(DVec3::new(5.0, -3.0, 0.0), 0.25));
521        scene
522            .grid_mut(id)
523            .unwrap()
524            .set_voxel(IVec3::new(1, 2, 100), Some(VoxColor(0x8011_2233)));
525
526        let bytes = scene.save_snapshot();
527        assert_eq!(&bytes[4..8], &2u32.to_le_bytes(), "expected v2 wire");
528        let restored = Scene::load_snapshot(&bytes).expect("round trip");
529
530        let (_, g) = restored.grids().next().expect("one grid");
531        assert!(
532            (g.transform.voxel_world_size - 0.25).abs() < 1e-12,
533            "scale must survive: got {}",
534            g.transform.voxel_world_size
535        );
536        assert_eq!(g.transform.origin, DVec3::new(5.0, -3.0, 0.0));
537        assert!(g.voxel_solid(IVec3::new(1, 2, 100)));
538    }
539
540    #[test]
541    fn sc_snap_out_of_range_scale_restores_at_one() {
542        // The load-side guard rejects corrupt/absurd persisted scale — not
543        // just ≤0 / non-finite but subnormal-near-zero and huge finite values,
544        // any of which collapse the marcher's chunk_dim toward 0 (→ NaN on
545        // GPU). All fall back to 1.0.
546        for bad in [0.0, -2.0, f64::NAN, f64::INFINITY, 1e-300, 1e300] {
547            let snap = SceneSnapshot {
548                next_grid_id: 1,
549                grids: vec![(
550                    GridId::from_raw_for_test(0),
551                    GridSnapshot {
552                        transform: GridTransform::identity(),
553                        chunks: vec![],
554                        chunk_versions: vec![],
555                        name: None,
556                        render_sky: true,
557                        mip_levels_override: None,
558                        lod_thresholds: LodThresholds::always_near(),
559                        stream_radius: StreamRadius::default(),
560                        voxel_world_size: bad,
561                    },
562                )],
563            };
564            let scene = Scene::from_snapshot(&snap).expect("restore");
565            let (_, g) = scene.grids().next().expect("one grid");
566            assert_eq!(
567                g.transform.voxel_world_size, 1.0,
568                "out-of-range vws {bad} must restore at 1.0"
569            );
570        }
571        // A sane extreme within [1e-6, 1e6] is preserved verbatim.
572        let ok = SceneSnapshot {
573            next_grid_id: 1,
574            grids: vec![(
575                GridId::from_raw_for_test(0),
576                GridSnapshot {
577                    transform: GridTransform::identity(),
578                    chunks: vec![],
579                    chunk_versions: vec![],
580                    name: None,
581                    render_sky: true,
582                    mip_levels_override: None,
583                    lod_thresholds: LodThresholds::always_near(),
584                    stream_radius: StreamRadius::default(),
585                    voxel_world_size: 1000.0,
586                },
587            )],
588        };
589        let scene = Scene::from_snapshot(&ok).expect("restore");
590        assert_eq!(
591            scene.grids().next().unwrap().1.transform.voxel_world_size,
592            1000.0
593        );
594    }
595
596    /// A 2-grid scene with ~100 chunks total — the validation
597    /// criterion in PORTING-SCENE.md S2. Builds a deterministic
598    /// pattern (one voxel per chunk, colour derived from chunk
599    /// index) so the round-trip can verify each chunk byte-by-byte
600    /// without relying on edit ordering.
601    fn build_two_grid_scene() -> (Scene, Vec<(GridId, IVec3, u32, u32, u32, VoxColor)>) {
602        // Returns (scene, expected_voxels) where each expected entry
603        // is (grid, chunk_idx, voxel_x, voxel_y, voxel_z, color) for
604        // post-restore verification.
605        let mut scene = Scene::new();
606        let g0 = scene.add_grid(GridTransform::at(DVec3::new(0.0, 0.0, 0.0)));
607        let g1 = scene.add_grid(GridTransform::at(DVec3::new(1000.0, 0.0, 0.0)));
608        let mut expected = Vec::new();
609        // Grid 0: 5×5×2 = 50 chunks across (chx, chy, chz) ∈
610        // ([0..5], [0..5], [0..2]). One voxel per chunk at local
611        // (5, 6, 7) with chunk-derived colour.
612        for chz in 0..2 {
613            for chy in 0..5 {
614                for chx in 0..5 {
615                    let chunk_idx = IVec3::new(chx, chy, chz);
616                    #[allow(clippy::cast_sign_loss)]
617                    let color = VoxColor(
618                        0x80_00_00_00 | ((chx as u32) << 16) | ((chy as u32) << 8) | (chz as u32),
619                    );
620                    let global_voxel = chunk_idx
621                        * IVec3::new(
622                            CHUNK_SIZE_XY as i32,
623                            CHUNK_SIZE_XY as i32,
624                            crate::CHUNK_SIZE_Z as i32,
625                        )
626                        + IVec3::new(5, 6, 7);
627                    scene
628                        .grid_mut(g0)
629                        .unwrap()
630                        .set_voxel(global_voxel, Some(color));
631                    expected.push((g0, chunk_idx, 5, 6, 7, color));
632                }
633            }
634        }
635        // Grid 1: 5×5×2 = 50 chunks, similar pattern but offset
636        // colour space + different voxel coord.
637        for chz in 0..2 {
638            for chy in 0..5 {
639                for chx in 0..5 {
640                    let chunk_idx = IVec3::new(chx, chy, chz);
641                    #[allow(clippy::cast_sign_loss)]
642                    let color = VoxColor(
643                        0x80_ff_00_00 | ((chx as u32) << 16) | ((chy as u32) << 8) | (chz as u32),
644                    );
645                    let global_voxel = chunk_idx
646                        * IVec3::new(
647                            CHUNK_SIZE_XY as i32,
648                            CHUNK_SIZE_XY as i32,
649                            crate::CHUNK_SIZE_Z as i32,
650                        )
651                        + IVec3::new(10, 11, 12);
652                    scene
653                        .grid_mut(g1)
654                        .unwrap()
655                        .set_voxel(global_voxel, Some(color));
656                    expected.push((g1, chunk_idx, 10, 11, 12, color));
657                }
658            }
659        }
660        (scene, expected)
661    }
662
663    fn assert_voxels_match(scene: &Scene, expected: &[(GridId, IVec3, u32, u32, u32, VoxColor)]) {
664        for &(grid_id, chunk_idx, vx, vy, vz, _color) in expected {
665            let grid = scene.grid(grid_id).expect("grid present");
666            let chunk = grid.chunk(chunk_idx).expect("chunk present");
667            assert!(
668                voxel_is_solid(chunk, vx, vy, vz),
669                "voxel ({vx},{vy},{vz}) in grid={} chunk={chunk_idx:?} not solid post-restore",
670                grid_id.raw()
671            );
672        }
673    }
674
675    #[test]
676    fn snapshot_round_trip_preserves_two_grid_100_chunk_scene() {
677        let (scene, expected) = build_two_grid_scene();
678        assert_eq!(scene.grid_count(), 2);
679        let total_chunks: usize = scene.grids().map(|(_, g)| g.chunks.len()).sum();
680        assert_eq!(total_chunks, 100, "test setup should produce 100 chunks");
681
682        // Round-trip via in-memory bincode.
683        let snap = scene.to_snapshot();
684        let bytes = bincode::serialize(&snap).expect("bincode serialize");
685        let snap_back: SceneSnapshot = bincode::deserialize(&bytes).expect("bincode deserialize");
686        let restored = Scene::from_snapshot(&snap_back).expect("restore");
687
688        // Same shape.
689        assert_eq!(restored.grid_count(), 2);
690        let total_restored: usize = restored.grids().map(|(_, g)| g.chunks.len()).sum();
691        assert_eq!(total_restored, 100);
692
693        // Same voxels.
694        assert_voxels_match(&restored, &expected);
695    }
696
697    #[test]
698    fn snapshot_preserves_next_grid_id_and_transforms() {
699        let mut scene = Scene::new();
700        let g0 = scene.add_grid(GridTransform::at(DVec3::new(10.0, 20.0, 30.0)));
701        let _g1 = scene.add_grid(GridTransform::at(DVec3::new(40.0, 50.0, 60.0)));
702        scene.remove_grid(g0); // bumps the gap
703        let _g2 = scene.add_grid(GridTransform::at(DVec3::new(70.0, 80.0, 90.0)));
704        // next_grid_id should be 3 now (g0=0, g1=1, g2=2).
705        let snap = scene.to_snapshot();
706        assert_eq!(snap.next_grid_id, 3);
707
708        let restored = Scene::from_snapshot(&snap).expect("restore");
709        assert_eq!(restored.grid_count(), 2);
710        // A new grid added to the restored scene should get id 3,
711        // not reuse the dropped id 0.
712        let mut restored_mut = restored;
713        let new_id = restored_mut.add_grid(GridTransform::identity());
714        assert_eq!(new_id.raw(), 3);
715    }
716
717    #[test]
718    fn restored_scene_is_editable() {
719        // The "/ mutate" half of "round-trip serialize / deserialize
720        // / mutate" — verify that a restored scene's chunks have
721        // edit capacity reserved so subsequent `set_voxel` doesn't
722        // panic.
723        let (scene, _) = build_two_grid_scene();
724        let snap = scene.to_snapshot();
725        let mut restored = Scene::from_snapshot(&snap).expect("restore");
726
727        let g0 = GridId::from_raw_for_test(0);
728        let new_voxel = IVec3::new(50, 51, 52);
729        restored
730            .grid_mut(g0)
731            .expect("grid 0 present")
732            .set_voxel(new_voxel, Some(VoxColor(0x80_de_ad_be)));
733        let chunk = restored
734            .grid(g0)
735            .unwrap()
736            .chunk(IVec3::ZERO)
737            .expect("chunk created");
738        assert!(voxel_is_solid(chunk, 50, 51, 52));
739    }
740
741    // ---- S7.2: chunk_versions round-trip ----
742
743    #[test]
744    fn snapshot_round_trip_preserves_chunk_versions() {
745        // Build a scene whose chunk_versions are non-trivial (multi-
746        // edit on the same chunk + edits across multiple chunks),
747        // round-trip, and verify every version survives.
748        let mut scene = Scene::new();
749        let id = scene.add_grid(GridTransform::identity());
750        let g = scene.grid_mut(id).unwrap();
751        // Three edits on chunk (0,0,0) → version 3.
752        g.set_voxel(IVec3::new(0, 0, 0), Some(VoxColor(0x80_aa_bb_cc)));
753        g.set_voxel(IVec3::new(1, 1, 1), Some(VoxColor(0x80_dd_ee_ff)));
754        g.set_voxel(IVec3::new(2, 2, 2), Some(VoxColor(0x80_11_22_33)));
755        // One edit on chunk (1,0,0) → version 1.
756        g.set_voxel(IVec3::new(128, 0, 0), Some(VoxColor(0x80_44_55_66)));
757        assert_eq!(g.chunk_version(IVec3::ZERO), 3);
758        assert_eq!(g.chunk_version(IVec3::new(1, 0, 0)), 1);
759
760        let snap = scene.to_snapshot();
761        let bytes = bincode::serialize(&snap).expect("bincode serialize");
762        let snap_back: SceneSnapshot = bincode::deserialize(&bytes).expect("bincode deserialize");
763        let restored = Scene::from_snapshot(&snap_back).expect("restore");
764
765        let g = restored.grid(id).expect("grid present");
766        assert_eq!(g.chunk_version(IVec3::ZERO), 3);
767        assert_eq!(g.chunk_version(IVec3::new(1, 0, 0)), 1);
768        assert_eq!(g.chunk_versions.len(), 2);
769    }
770
771    #[test]
772    fn snapshot_chunk_versions_zero_entries_are_dropped_from_wire() {
773        // Implementation detail worth pinning: we don't waste bytes
774        // on chunks whose live counter is 0 (== absent semantically).
775        let mut scene = Scene::new();
776        let id = scene.add_grid(GridTransform::identity());
777        let g = scene.grid_mut(id).unwrap();
778        // Manually inject a zero entry — we don't have a public API
779        // to do this; reach into chunk_versions to verify the
780        // serialise-side filter behaves.
781        g.chunk_versions.insert(IVec3::ZERO, 0);
782        let snap = scene.to_snapshot();
783        let g_snap = &snap.grids[0].1;
784        assert!(g_snap.chunk_versions.is_empty(), "zero entries dropped");
785    }
786
787    #[test]
788    fn snapshot_is_deterministic() {
789        let (scene, _) = build_two_grid_scene();
790        let s1 = bincode::serialize(&scene.to_snapshot()).unwrap();
791        let s2 = bincode::serialize(&scene.to_snapshot()).unwrap();
792        assert_eq!(s1, s2, "snapshot bytes should be deterministic");
793    }
794}