dreamwell-engine 1.0.0

Dreamwell pure-logic engine library — transforms, hierarchy, canon pipeline, spatial math, hashing, tile rules, validation, waymark schema, material/lighting descriptors. No SpacetimeDB dependency.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
// game_object.rs — Portable, serializable game object and scene model.
//
// Like Unity's GameObject + MonoBehaviour pattern, adapted for Dreamwell's
// GPU-driven meshlet/particle/procedural rendering and ESCG (Event-Sourced
// Compute Graph) backend. Every object is an empty container that gains
// visual identity via MeshBinding and behavior via ComponentSlots.
//
// CODESPEC §2.3: Enums as tagged unions for MeshBinding, ComponentKind.
// CODESPEC §3.1: Scene stores objects contiguously for cache-friendly iteration.
// CODESPEC §0.1: All logic is pure — no RNG, no time, no I/O.

use serde::{Deserialize, Serialize};

/// Maximum scene objects per GameObjectScene. Prevents unbounded GPU buffer growth.
pub const MAX_SCENE_OBJECTS: usize = 65536;

/// Maximum components per GameObject.
pub const MAX_COMPONENTS_PER_OBJECT: usize = 32;

// ── Transform ──────────────────────────────────────────────────────────

/// 3D transform: position, rotation (quaternion), scale.
/// Column-major model matrix computed on demand via `to_matrix()`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Transform {
    pub position: [f32; 3],
    /// Quaternion `[x, y, z, w]`. Identity = `[0, 0, 0, 1]`.
    pub rotation: [f32; 4],
    pub scale: [f32; 3],
}

impl Default for Transform {
    fn default() -> Self {
        Self {
            position: [0.0; 3],
            rotation: [0.0, 0.0, 0.0, 1.0],
            scale: [1.0, 1.0, 1.0],
        }
    }
}

impl Transform {
    /// Compute the 4×4 column-major model matrix from TRS.
    pub fn to_matrix(&self) -> [f32; 16] {
        let [qx, qy, qz, qw] = self.rotation;
        let [sx, sy, sz] = self.scale;
        let [px, py, pz] = self.position;

        let x2 = qx + qx;
        let y2 = qy + qy;
        let z2 = qz + qz;
        let xx = qx * x2;
        let xy = qx * y2;
        let xz = qx * z2;
        let yy = qy * y2;
        let yz = qy * z2;
        let zz = qz * z2;
        let wx = qw * x2;
        let wy = qw * y2;
        let wz = qw * z2;

        [
            (1.0 - (yy + zz)) * sx,
            (xy + wz) * sx,
            (xz - wy) * sx,
            0.0,
            (xy - wz) * sy,
            (1.0 - (xx + zz)) * sy,
            (yz + wx) * sy,
            0.0,
            (xz + wy) * sz,
            (yz - wx) * sz,
            (1.0 - (xx + yy)) * sz,
            0.0,
            px,
            py,
            pz,
            1.0,
        ]
    }

    /// Validate: finite position, unit quaternion (±1%), positive finite scale.
    pub fn validate(&self) -> Result<(), String> {
        if self.position.iter().any(|p| !p.is_finite()) {
            return Err("transform_invalid_position:contains NaN or Inf".into());
        }
        let [qx, qy, qz, qw] = self.rotation;
        let len_sq = qx * qx + qy * qy + qz * qz + qw * qw;
        if !len_sq.is_finite() || (len_sq - 1.0).abs() > 0.01 {
            return Err(format!(
                "transform_invalid_rotation:quaternion length² {len_sq} not ≈1.0"
            ));
        }
        if self.scale.iter().any(|&s| s <= 0.0 || !s.is_finite()) {
            return Err("transform_invalid_scale:must be positive and finite".into());
        }
        Ok(())
    }
}

// ── Mesh binding ───────────────────────────────────────────────────────

/// Primitive mesh type. Maps 1:1 to `dreamwell_gpu::primitives::PrimitiveShape`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PrimitiveKind {
    Cube,
    Sphere,
    Cylinder,
    Cone,
    Plane,
    Torus,
    Capsule,
    Pyramid,
    Wedge,
}

impl PrimitiveKind {
    pub const ALL: &'static [PrimitiveKind] = &[
        Self::Cube,
        Self::Sphere,
        Self::Cylinder,
        Self::Cone,
        Self::Plane,
        Self::Torus,
        Self::Capsule,
        Self::Pyramid,
        Self::Wedge,
    ];

    pub fn name(self) -> &'static str {
        match self {
            Self::Cube => "Cube",
            Self::Sphere => "Sphere",
            Self::Cylinder => "Cylinder",
            Self::Cone => "Cone",
            Self::Plane => "Plane",
            Self::Torus => "Torus",
            Self::Capsule => "Capsule",
            Self::Pyramid => "Pyramid",
            Self::Wedge => "Wedge",
        }
    }
}

/// What mesh to render for this object.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub enum MeshBinding {
    /// No mesh — invisible container for components only.
    #[default]
    None,
    /// Built-in primitive with pre-computed meshlets. Color is RGBA linear.
    Primitive { kind: PrimitiveKind, color: [f32; 4] },
    /// Custom mesh referenced by asset key (resolved at load time).
    Custom { asset_key: String },
}

// ── Component system ───────────────────────────────────────────────────

/// Component kind — typed categories of attachable game logic.
/// Analogous to Unity MonoBehaviour categories, mapped to Dreamwell's
/// ESCG backend systems (physics compute, particles, Waymark scripts).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ComponentKind {
    /// Rigid-body physics (integrates with PhysicsGpu simulation).
    Physics,
    /// Collision shape (box, sphere, capsule, mesh).
    Collider,
    /// Waymark script — event-driven logic from content packs.
    /// Properties carry the pack-defined fields (like C# serialized fields).
    WaymarkScript,
    /// Audio source.
    Audio,
    /// Point, spot, or directional light.
    Light,
    /// Particle emitter (integrates with PhysicsGpu emitter pool).
    Particle,
    /// Camera override (when active, replaces scene camera).
    Camera,
    /// Trigger volume — fires ESCG events on enter/exit.
    Trigger,
    /// Animation controller (integrates with GpuTweenContext).
    Animation,
    /// DreamMatter particle attachment — dissolve/materialize particle effect.
    /// When attached, the GPU spawns particles from this object's mesh surface.
    /// Properties: emission_rate, lifetime, particle_count, effect_preset.
    DreamMatter,
    /// FBX animation source — skeletal animation from imported FBX binary.
    /// Properties: fbx_asset_key, clip_name, loop_mode, playback_speed.
    FbxAnimation,
    /// User-defined via Waymark content packs.
    Custom,
}

/// A single attached component with typed kind and Waymark-style property bag.
/// Properties are key-value pairs that the ESCG runtime evaluates per-tick.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentSlot {
    pub kind: ComponentKind,
    pub enabled: bool,
    /// Properties bag: Waymark script fields, physics params, emitter config, etc.
    /// Serialized as JSON for portability across editor / runtime / server.
    pub properties: serde_json::Value,
}

impl ComponentSlot {
    pub fn new(kind: ComponentKind) -> Self {
        Self {
            kind,
            enabled: true,
            properties: serde_json::Value::Object(serde_json::Map::new()),
        }
    }

    /// Set a named property. Bounded: max 256 properties per component.
    pub fn set_property(&mut self, key: &str, value: serde_json::Value) -> Result<(), String> {
        if let serde_json::Value::Object(ref mut map) = self.properties {
            if map.len() >= 256 && !map.contains_key(key) {
                return Err("component_property_limit:max 256 properties".into());
            }
            map.insert(key.to_string(), value);
            Ok(())
        } else {
            Err("component_properties_not_object:must be a JSON object".into())
        }
    }

    pub fn get_property(&self, key: &str) -> Option<&serde_json::Value> {
        self.properties.get(key)
    }
}

// ── GameObject ─────────────────────────────────────────────────────────

/// A game object — empty container that gains visual and behavioral identity
/// through `MeshBinding` and `ComponentSlot`s.
///
/// - `id`: deterministic u64, no UUIDs or RNG.
/// - `transform`: inline hot data, accessed every frame.
/// - `components`: bounded `Vec<ComponentSlot>` (max 32).
/// - Fully serializable for scene save/load and network replication.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GameObject {
    pub id: u64,
    pub name: String,
    pub transform: Transform,
    pub mesh: MeshBinding,
    pub visible: bool,
    pub parent_id: Option<u64>,
    pub components: Vec<ComponentSlot>,
    /// Property tags (e.g., "isFlammable", "isDestructible"). Drive physics
    /// heuristics, DreamMatter behavior, and event emission at runtime.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub property_tags: Vec<String>,
    /// Topology layer index (0=Universe, 9=Point). Determines which gameplay
    /// channel this object belongs to. GPU quantum culling uses this to render
    /// only the active layer's content.
    #[serde(default = "default_topology_layer")]
    pub topology_layer: u8,
}

fn default_topology_layer() -> u8 {
    9
}

impl GameObject {
    /// Create a new empty game object with default transform and no mesh.
    pub fn new(id: u64, name: String) -> Self {
        Self {
            id,
            name,
            transform: Transform::default(),
            mesh: MeshBinding::None,
            visible: true,
            parent_id: None,
            components: Vec::new(),
            property_tags: Vec::new(),
            topology_layer: 9,
        }
    }

    /// Create with a primitive mesh (default gray color).
    pub fn with_primitive(id: u64, name: String, kind: PrimitiveKind) -> Self {
        Self {
            mesh: MeshBinding::Primitive {
                kind,
                color: [0.7, 0.7, 0.7, 1.0],
            },
            ..Self::new(id, name)
        }
    }

    /// Attach a component. Returns error if `MAX_COMPONENTS_PER_OBJECT` exceeded.
    pub fn add_component(&mut self, slot: ComponentSlot) -> Result<(), String> {
        if self.components.len() >= MAX_COMPONENTS_PER_OBJECT {
            return Err(format!(
                "game_object_component_limit:max {MAX_COMPONENTS_PER_OBJECT} components"
            ));
        }
        self.components.push(slot);
        Ok(())
    }

    /// Remove the first component matching `kind`. Returns true if found.
    pub fn remove_component(&mut self, kind: ComponentKind) -> bool {
        if let Some(pos) = self.components.iter().position(|c| c.kind == kind) {
            self.components.swap_remove(pos);
            true
        } else {
            false
        }
    }

    pub fn get_component(&self, kind: ComponentKind) -> Option<&ComponentSlot> {
        self.components.iter().find(|c| c.kind == kind)
    }

    pub fn get_component_mut(&mut self, kind: ComponentKind) -> Option<&mut ComponentSlot> {
        self.components.iter_mut().find(|c| c.kind == kind)
    }

    /// Check whether this object has any component of the given kind.
    pub fn has_component(&self, kind: ComponentKind) -> bool {
        self.components.iter().any(|c| c.kind == kind)
    }

    /// Validate data integrity.
    pub fn validate(&self) -> Result<(), String> {
        self.transform.validate()?;
        if self.name.len() > 256 {
            return Err("game_object_name_too_long:max 256 chars".into());
        }
        if self.components.len() > MAX_COMPONENTS_PER_OBJECT {
            return Err(format!(
                "game_object_too_many_components:{} > {MAX_COMPONENTS_PER_OBJECT}",
                self.components.len()
            ));
        }
        Ok(())
    }
}

// ── GameObjectScene ────────────────────────────────────────────────────

/// A bounded scene of game objects with hierarchy support.
/// Serializable as JSON for `.wm` scene files, editor snapshots, and replication.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GameObjectScene {
    pub name: String,
    pub objects: Vec<GameObject>,
    next_id: u64,
}

impl GameObjectScene {
    pub fn new(name: String) -> Self {
        Self {
            name,
            objects: Vec::new(),
            next_id: 0,
        }
    }

    /// Spawn an empty game object. Returns its ID.
    pub fn spawn(&mut self, name: String) -> Result<u64, String> {
        if self.objects.len() >= MAX_SCENE_OBJECTS {
            return Err(format!("scene_object_limit:max {MAX_SCENE_OBJECTS}"));
        }
        let id = self.next_id;
        self.next_id = self.next_id.saturating_add(1);
        self.objects.push(GameObject::new(id, name));
        Ok(id)
    }

    /// Spawn a game object with a primitive mesh. Returns its ID.
    pub fn spawn_primitive(&mut self, name: String, kind: PrimitiveKind) -> Result<u64, String> {
        if self.objects.len() >= MAX_SCENE_OBJECTS {
            return Err(format!("scene_object_limit:max {MAX_SCENE_OBJECTS}"));
        }
        let id = self.next_id;
        self.next_id = self.next_id.saturating_add(1);
        self.objects.push(GameObject::with_primitive(id, name, kind));
        Ok(id)
    }

    pub fn find(&self, id: u64) -> Option<&GameObject> {
        self.objects.iter().find(|o| o.id == id)
    }

    pub fn find_mut(&mut self, id: u64) -> Option<&mut GameObject> {
        self.objects.iter_mut().find(|o| o.id == id)
    }

    /// Despawn an object by ID. Clears dangling parent references.
    pub fn despawn(&mut self, id: u64) -> bool {
        let Some(pos) = self.objects.iter().position(|o| o.id == id) else {
            return false;
        };
        self.objects.swap_remove(pos);
        for obj in &mut self.objects {
            if obj.parent_id == Some(id) {
                obj.parent_id = None;
            }
        }
        true
    }

    pub fn len(&self) -> usize {
        self.objects.len()
    }

    pub fn is_empty(&self) -> bool {
        self.objects.is_empty()
    }

    /// Validate entire scene.
    pub fn validate(&self) -> Result<(), String> {
        if self.objects.len() > MAX_SCENE_OBJECTS {
            return Err(format!(
                "scene_object_limit:{} > {MAX_SCENE_OBJECTS}",
                self.objects.len()
            ));
        }
        for obj in &self.objects {
            obj.validate().map_err(|e| format!("object '{}': {}", obj.name, e))?;
        }
        Ok(())
    }

    /// Root objects (no parent).
    pub fn roots(&self) -> impl Iterator<Item = &GameObject> {
        self.objects.iter().filter(|o| o.parent_id.is_none())
    }

    /// Children of a given parent.
    pub fn children_of(&self, parent_id: u64) -> impl Iterator<Item = &GameObject> {
        self.objects.iter().filter(move |o| o.parent_id == Some(parent_id))
    }

    /// Propagate transforms through the parent-child hierarchy.
    /// Each child's world matrix = parent_world * child_local.
    /// Stores results indexed by object position in `self.objects`.
    ///
    /// Uses topological BFS from roots — O(N) single pass, each object
    /// computed exactly once. Parents are always processed before children.
    pub fn propagate_transforms(&self) -> Vec<[f32; 16]> {
        use crate::transform::mat4_mul;

        let len = self.objects.len();
        let mut world: Vec<[f32; 16]> =
            vec![[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,]; len];
        if len == 0 {
            return world;
        }

        // Build id → index lookup and children adjacency list in one pass.
        let mut id_to_idx: std::collections::HashMap<u64, usize> = std::collections::HashMap::with_capacity(len);
        let mut children: Vec<Vec<usize>> = vec![Vec::new(); len];
        let mut roots: Vec<usize> = Vec::new();

        for (i, obj) in self.objects.iter().enumerate() {
            id_to_idx.insert(obj.id, i);
        }
        for (i, obj) in self.objects.iter().enumerate() {
            if let Some(pid) = obj.parent_id {
                if let Some(&pi) = id_to_idx.get(&pid) {
                    children[pi].push(i);
                } else {
                    roots.push(i); // orphaned parent ref → treat as root
                }
            } else {
                roots.push(i);
            }
        }

        // BFS from roots — parents always processed before children.
        let mut queue = std::collections::VecDeque::with_capacity(len);
        for &ri in &roots {
            world[ri] = self.objects[ri].transform.to_matrix();
            queue.push_back(ri);
        }

        while let Some(idx) = queue.pop_front() {
            for &ci in &children[idx] {
                let local = self.objects[ci].transform.to_matrix();
                world[ci] = mat4_mul(&world[idx], &local);
                queue.push_back(ci);
            }
        }

        world
    }

    /// Count of visible objects with a mesh binding.
    pub fn visible_mesh_count(&self) -> usize {
        self.objects
            .iter()
            .filter(|o| o.visible && !matches!(o.mesh, MeshBinding::None))
            .count()
    }
}

// ── Tests ──────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn transform_default_identity() {
        let t = Transform::default();
        assert_eq!(t.position, [0.0; 3]);
        assert_eq!(t.rotation, [0.0, 0.0, 0.0, 1.0]);
        assert_eq!(t.scale, [1.0, 1.0, 1.0]);
    }

    #[test]
    fn transform_identity_matrix() {
        let t = Transform::default();
        let m = t.to_matrix();
        #[rustfmt::skip]
        let expected = [
            1.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            0.0, 0.0, 0.0, 1.0,
        ];
        for (a, b) in m.iter().zip(expected.iter()) {
            assert!((a - b).abs() < 1e-6, "matrix mismatch: {a} vs {b}");
        }
    }

    #[test]
    fn transform_translation_in_matrix() {
        let t = Transform {
            position: [1.0, 2.0, 3.0],
            ..Default::default()
        };
        let m = t.to_matrix();
        assert_eq!(m[12], 1.0);
        assert_eq!(m[13], 2.0);
        assert_eq!(m[14], 3.0);
    }

    #[test]
    fn transform_scale_in_matrix() {
        let t = Transform {
            scale: [2.0, 3.0, 4.0],
            ..Default::default()
        };
        let m = t.to_matrix();
        assert!((m[0] - 2.0).abs() < 1e-6);
        assert!((m[5] - 3.0).abs() < 1e-6);
        assert!((m[10] - 4.0).abs() < 1e-6);
    }

    #[test]
    fn transform_validate_ok() {
        assert!(Transform::default().validate().is_ok());
    }

    #[test]
    fn transform_validate_zero_scale() {
        let t = Transform {
            scale: [0.0, 1.0, 1.0],
            ..Default::default()
        };
        assert!(t.validate().is_err());
    }

    #[test]
    fn transform_validate_nan_position() {
        let t = Transform {
            position: [f32::NAN, 0.0, 0.0],
            ..Default::default()
        };
        assert!(t.validate().is_err());
    }

    #[test]
    fn transform_validate_non_unit_quat() {
        let t = Transform {
            rotation: [1.0, 1.0, 1.0, 1.0],
            ..Default::default()
        };
        assert!(t.validate().is_err());
    }

    #[test]
    fn game_object_new_defaults() {
        let obj = GameObject::new(0, "Test".into());
        assert_eq!(obj.id, 0);
        assert!(obj.visible);
        assert!(obj.components.is_empty());
        assert_eq!(obj.mesh, MeshBinding::None);
        assert_eq!(obj.parent_id, None);
    }

    #[test]
    fn game_object_with_primitive() {
        let obj = GameObject::with_primitive(1, "Cube".into(), PrimitiveKind::Cube);
        assert!(matches!(
            obj.mesh,
            MeshBinding::Primitive {
                kind: PrimitiveKind::Cube,
                ..
            }
        ));
    }

    #[test]
    fn game_object_add_remove_component() {
        let mut obj = GameObject::new(0, "T".into());
        obj.add_component(ComponentSlot::new(ComponentKind::Physics)).unwrap();
        assert!(obj.has_component(ComponentKind::Physics));
        assert!(obj.remove_component(ComponentKind::Physics));
        assert!(!obj.has_component(ComponentKind::Physics));
    }

    #[test]
    fn game_object_component_limit() {
        let mut obj = GameObject::new(0, "T".into());
        for _ in 0..MAX_COMPONENTS_PER_OBJECT {
            obj.add_component(ComponentSlot::new(ComponentKind::Custom)).unwrap();
        }
        assert!(obj.add_component(ComponentSlot::new(ComponentKind::Custom)).is_err());
    }

    #[test]
    fn component_slot_properties() {
        let mut slot = ComponentSlot::new(ComponentKind::WaymarkScript);
        slot.set_property("speed", serde_json::json!(5.0)).unwrap();
        slot.set_property("health", serde_json::json!(100)).unwrap();
        assert_eq!(slot.get_property("speed"), Some(&serde_json::json!(5.0)));
        assert_eq!(slot.get_property("missing"), None);
    }

    #[test]
    fn scene_spawn_and_find() {
        let mut scene = GameObjectScene::new("Test".into());
        let id = scene.spawn("Player".into()).unwrap();
        assert_eq!(scene.len(), 1);
        assert_eq!(scene.find(id).unwrap().name, "Player");
    }

    #[test]
    fn scene_spawn_primitive() {
        let mut scene = GameObjectScene::new("Test".into());
        let id = scene.spawn_primitive("Cube".into(), PrimitiveKind::Cube).unwrap();
        let obj = scene.find(id).unwrap();
        assert!(matches!(
            obj.mesh,
            MeshBinding::Primitive {
                kind: PrimitiveKind::Cube,
                ..
            }
        ));
    }

    #[test]
    fn scene_despawn_clears_parent_refs() {
        let mut scene = GameObjectScene::new("Test".into());
        let parent = scene.spawn("Parent".into()).unwrap();
        let child = scene.spawn("Child".into()).unwrap();
        scene.find_mut(child).unwrap().parent_id = Some(parent);
        scene.despawn(parent);
        assert_eq!(scene.find(child).unwrap().parent_id, None);
    }

    #[test]
    fn scene_hierarchy() {
        let mut scene = GameObjectScene::new("Test".into());
        let p = scene.spawn("Parent".into()).unwrap();
        let c1 = scene.spawn("C1".into()).unwrap();
        let c2 = scene.spawn("C2".into()).unwrap();
        scene.find_mut(c1).unwrap().parent_id = Some(p);
        scene.find_mut(c2).unwrap().parent_id = Some(p);
        assert_eq!(scene.roots().count(), 1);
        assert_eq!(scene.children_of(p).count(), 2);
    }

    #[test]
    fn scene_serialize_roundtrip() {
        let mut scene = GameObjectScene::new("TestScene".into());
        let id = scene.spawn_primitive("Cube".into(), PrimitiveKind::Cube).unwrap();
        scene.find_mut(id).unwrap().transform.position = [1.0, 2.0, 3.0];

        let mut slot = ComponentSlot::new(ComponentKind::WaymarkScript);
        slot.set_property("speed", serde_json::json!(5.0)).unwrap();
        scene.find_mut(id).unwrap().add_component(slot).unwrap();

        let json = serde_json::to_string_pretty(&scene).unwrap();
        let restored: GameObjectScene = serde_json::from_str(&json).unwrap();

        assert_eq!(restored.name, "TestScene");
        assert_eq!(restored.len(), 1);
        assert_eq!(restored.objects[0].transform.position, [1.0, 2.0, 3.0]);
        assert_eq!(restored.objects[0].components[0].kind, ComponentKind::WaymarkScript);
    }

    #[test]
    fn scene_validate_ok() {
        let mut scene = GameObjectScene::new("Ok".into());
        scene.spawn_primitive("Cube".into(), PrimitiveKind::Cube).unwrap();
        assert!(scene.validate().is_ok());
    }

    #[test]
    fn scene_validate_bad_transform() {
        let mut scene = GameObjectScene::new("Bad".into());
        let id = scene.spawn("Bad".into()).unwrap();
        scene.find_mut(id).unwrap().transform.scale = [0.0, 1.0, 1.0];
        assert!(scene.validate().is_err());
    }

    #[test]
    fn primitive_kind_all_count() {
        assert_eq!(PrimitiveKind::ALL.len(), 9);
    }

    #[test]
    fn mesh_binding_default_is_none() {
        assert_eq!(MeshBinding::default(), MeshBinding::None);
    }

    #[test]
    fn game_object_validate_name_too_long() {
        let obj = GameObject::new(0, "x".repeat(257));
        assert!(obj.validate().is_err());
    }

    #[test]
    fn visible_mesh_count() {
        let mut scene = GameObjectScene::new("Test".into());
        scene.spawn_primitive("A".into(), PrimitiveKind::Cube).unwrap();
        scene.spawn("Empty".into()).unwrap(); // no mesh
        let id = scene.spawn_primitive("Hidden".into(), PrimitiveKind::Sphere).unwrap();
        scene.find_mut(id).unwrap().visible = false;
        assert_eq!(scene.visible_mesh_count(), 1);
    }

    #[test]
    fn propagate_transforms_root_only() {
        let mut scene = GameObjectScene::new("Test".into());
        let id = scene.spawn("A".into()).unwrap();
        scene.find_mut(id).unwrap().transform.position = [1.0, 2.0, 3.0];
        let world = scene.propagate_transforms();
        assert_eq!(world.len(), 1);
        assert_eq!(world[0][12], 1.0);
        assert_eq!(world[0][13], 2.0);
        assert_eq!(world[0][14], 3.0);
    }

    #[test]
    fn propagate_transforms_parent_child() {
        let mut scene = GameObjectScene::new("Test".into());
        let p = scene.spawn("Parent".into()).unwrap();
        scene.find_mut(p).unwrap().transform.position = [10.0, 0.0, 0.0];
        let c = scene.spawn("Child".into()).unwrap();
        scene.find_mut(c).unwrap().transform.position = [5.0, 0.0, 0.0];
        scene.find_mut(c).unwrap().parent_id = Some(p);

        let world = scene.propagate_transforms();
        // Child world position = parent(10,0,0) + child(5,0,0) = (15,0,0)
        assert!((world[1][12] - 15.0).abs() < 1e-5);
    }

    #[test]
    fn propagate_transforms_empty_scene() {
        let scene = GameObjectScene::new("Empty".into());
        let world = scene.propagate_transforms();
        assert!(world.is_empty());
    }

    #[test]
    fn next_id_monotonic() {
        let mut scene = GameObjectScene::new("Test".into());
        let a = scene.spawn("A".into()).unwrap();
        let b = scene.spawn("B".into()).unwrap();
        assert_eq!(a, 0);
        assert_eq!(b, 1);
        scene.despawn(a);
        let c = scene.spawn("C".into()).unwrap();
        assert_eq!(c, 2); // never reuses
    }
}