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
// Loom — Dreamwell Render Pipeline scene orchestrator and bootstrap service.
//
// The Loom is the engine-native bridge between authored scenes (editor, .dream
// files, Waymark packs) and the Dreamwell Render Pipeline runtime. It "weaves"
// scene data into a Fabric-ready format by sorting, validating, and ordering
// all scene entities, PropertyTags, lights, physics bodies, emitters, and
// rendering configuration into the pipeline-preferred execution order.
//
// Dreamwell Architecture (not Unity):
//
//   SceneAsset    = DreamSceneV1    (authored, serializable, versioned)
//   Entity        = u64 ID          (plain handle, not a polymorphic object bag)
//   Component     = ComponentSlot   (data-only, behavior lives in systems)
//   Template      = DreamwellPackV1 (Waymark content packs)
//   RuntimeWorld  = GameObjectScene (instantiated from SceneAsset)
//   Schedule      = BootstrapStage  (explicit ordered pipeline, not hidden callbacks)
//   Session       = WovenScene      (validated scene manifest for the Fabric)
//   Resource      = Owned by app    (PhysicsWorld, AudioSystem — not globals)
//   Service       = DreamFabric     (GPU orchestrator) + Loom (CPU orchestrator)
//
// The Loom does NOT hide lifecycle magic. It runs an explicit, ordered pipeline:
//
//   Stage 0: Validate    — reality check transforms, references, tags
//   Stage 1: Extract     — lights, physics bodies, emitters, tagged entities
//   Stage 2: Configure   — render config, observer context, post-processing
//   Stage 3: Sort        — pipeline-preferred order (meshes → lights → empty)
//   Stage 4: Manifest    — WovenScene output ready for Fabric consumption
//
// Clean Compute: The Loom runs at scene load time (not per-frame). Its output
// is a pre-sorted, validated, GPU-uploadable scene manifest that the Fabric
// consumes without per-frame sorting or allocation.
//
// Editor → Play pipeline:
//   EditorScene (SoA) → to_game_object_scene() → Loom::weave() → WovenScene
//   WovenScene.scene      → Fabric.upload_scene()   → GPU slots
//   WovenScene.lights      → SceneLights.add_*()     → PBR uniform arrays
//   WovenScene.bodies      → PhysicsWorld.add_body()  → CPU collision sim
//   WovenScene.emitters    → EmitterPool.spawn()      → DreamMatter dispatch
//   WovenScene.render_config → Fabric.set_*()         → post-processing chain
//   WovenScene.tagged_objects → HeuristicEngine       → tag-driven gameplay

use crate::game_object::{ComponentKind, GameObjectScene, MeshBinding};
use crate::lighting::{DirectionalLightDesc, PointLightDesc};

/// Rendering configuration extracted from scene metadata.
#[derive(Debug, Clone)]
pub struct RenderConfig {
    pub bloom_enabled: bool,
    pub tonemap_enabled: bool,
    pub ssao_enabled: bool,
    pub ssr_enabled: bool,
    pub dof_enabled: bool,
    pub ssgi_enabled: bool,
    pub taa_enabled: bool,
    pub scene_dream_mode: String,
    pub topology_layer: u8,
}

impl Default for RenderConfig {
    fn default() -> Self {
        Self {
            bloom_enabled: true,
            tonemap_enabled: true,
            ssao_enabled: true,
            ssr_enabled: false,
            dof_enabled: false,
            ssgi_enabled: false,
            taa_enabled: true,
            scene_dream_mode: "PbrDefault".into(),
            topology_layer: 6,
        }
    }
}

/// A light extracted from the scene with full properties.
#[derive(Debug, Clone)]
pub enum ExtractedLight {
    Directional(DirectionalLightDesc),
    Point(PointLightDesc),
}

/// Physics body extracted from a scene object.
#[derive(Debug, Clone)]
pub struct ExtractedBody {
    pub object_id: u64,
    pub position: [f32; 3],
    pub shape: BodyShape,
    pub mass: f32,
    pub restitution: f32,
    pub friction: f32,
    pub is_static: bool,
    pub tags: Vec<String>,
}

/// Simple shape for physics bodies.
#[derive(Debug, Clone)]
pub enum BodyShape {
    Sphere { radius: f32 },
    Box { half_extents: [f32; 3] },
    Capsule { radius: f32, half_height: f32 },
}

/// Emitter spawner extracted from a Particle or DreamMatter component.
#[derive(Debug, Clone)]
pub struct ExtractedEmitter {
    pub object_id: u64,
    pub position: [f32; 3],
    pub kind: EmitterKind,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone)]
pub enum EmitterKind {
    Particle,
    DreamMatter,
}

/// The output of Loom::weave() — a fully validated, pipeline-ordered scene
/// manifest ready for Fabric upload and runtime initialization.
///
/// Clean Compute: all data is pre-sorted and pre-validated. No runtime
/// sorting, validation, or allocation needed by consumers.
#[derive(Debug)]
pub struct WovenScene {
    /// The scene graph (sorted: meshes first, then components, then empty).
    pub scene: GameObjectScene,
    /// Extracted lights with full properties.
    pub lights: Vec<ExtractedLight>,
    /// Physics bodies with tag-driven behavior.
    pub bodies: Vec<ExtractedBody>,
    /// Particle/DreamMatter emitters to spawn.
    pub emitters: Vec<ExtractedEmitter>,
    /// Rendering configuration.
    pub render_config: RenderConfig,
    /// Objects with property tags (id → tags mapping for heuristic evaluation).
    pub tagged_objects: Vec<(u64, Vec<String>)>,
    /// Reality check warnings (non-fatal).
    pub warnings: Vec<String>,
    /// Scene statistics for profiler display.
    pub stats: WovenStats,
}

/// Scene statistics after weaving.
#[derive(Debug, Clone, Default)]
pub struct WovenStats {
    pub total_objects: u32,
    pub mesh_objects: u32,
    pub light_objects: u32,
    pub physics_bodies: u32,
    pub emitter_count: u32,
    pub tagged_objects: u32,
    pub dreamlet_count: u32,
    pub dreamfab_count: u32,
}

/// Loom result — either a woven scene or a list of errors.
pub type LoomResult = Result<WovenScene, Vec<String>>;

// ── Bootstrap Pipeline ──────────────────────────────────────────────────

/// Explicit schedule stages for scene bootstrap. Replaces Unity's hidden
/// Awake/Start/Update lifecycle with an ordered, debuggable pipeline.
///
/// Each stage runs once at scene load. No per-frame cost.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BootstrapStage {
    /// Validate scene data — NaN checks, reference integrity, tag consistency.
    Validate,
    /// Extract structured data — lights, physics bodies, emitters, tags.
    Extract,
    /// Configure rendering — post-processing, scene mode, observer context.
    Configure,
    /// Sort for pipeline — meshes first, then components, then empty objects.
    Sort,
    /// Build manifest — produce WovenScene for Fabric consumption.
    Manifest,
}

impl BootstrapStage {
    pub const ALL: &'static [BootstrapStage] = &[
        BootstrapStage::Validate,
        BootstrapStage::Extract,
        BootstrapStage::Configure,
        BootstrapStage::Sort,
        BootstrapStage::Manifest,
    ];

    pub fn label(self) -> &'static str {
        match self {
            Self::Validate => "Validate",
            Self::Extract => "Extract",
            Self::Configure => "Configure",
            Self::Sort => "Sort",
            Self::Manifest => "Manifest",
        }
    }
}

/// Runtime frame schedule stages. These run every frame in order.
/// Explicit and deterministic — no hidden callbacks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameStage {
    /// Poll input devices, build InputFrame.
    Input,
    /// Run gameplay logic — heuristics, tag evaluation, state transitions.
    Simulation,
    /// Step physics — collision detection, rigid body integration.
    Physics,
    /// Evaluate animations — skeleton, locomotion, blend trees.
    Animation,
    /// Upload transforms, observer context, lights to GPU.
    RenderPrep,
    /// GPU dispatch — cull, DreamMatter, screen-space effects, post-process.
    Presentation,
    /// Drain events, expire timers, reclaim resources.
    Cleanup,
}

impl FrameStage {
    pub const ALL: &'static [FrameStage] = &[
        FrameStage::Input,
        FrameStage::Simulation,
        FrameStage::Physics,
        FrameStage::Animation,
        FrameStage::RenderPrep,
        FrameStage::Presentation,
        FrameStage::Cleanup,
    ];

    pub fn label(self) -> &'static str {
        match self {
            Self::Input => "Input",
            Self::Simulation => "Simulation",
            Self::Physics => "Physics",
            Self::Animation => "Animation",
            Self::RenderPrep => "RenderPrep",
            Self::Presentation => "Presentation",
            Self::Cleanup => "Cleanup",
        }
    }
}

/// Weave a GameObjectScene into a Fabric-ready WovenScene.
///
/// This is the core Loom operation. It:
/// 1. Validates the scene (reality check)
/// 2. Sorts objects by render priority (meshes → lights → components → empty)
/// 3. Extracts lights with properties
/// 4. Extracts physics bodies with tags
/// 5. Extracts emitters for particle/DreamMatter spawn
/// 6. Builds a tagged object map for heuristic evaluation
/// 7. Returns a pre-sorted, validated manifest
///
/// Clean Compute: runs once at load time. Zero per-frame cost.
pub fn weave(scene: GameObjectScene, render_config: RenderConfig) -> LoomResult {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();

    // ── Step 1: Reality check (comprehensive validation) ──────────────
    if scene.objects.is_empty() {
        warnings.push("loom:empty_scene — no objects to weave".into());
    }

    let mut seen_ids = std::collections::HashSet::new();
    for (i, obj) in scene.objects.iter().enumerate() {
        // NaN/Inf check on transforms
        for v in obj
            .transform
            .position
            .iter()
            .chain(obj.transform.scale.iter())
            .chain(obj.transform.rotation.iter())
        {
            if !v.is_finite() {
                errors.push(format!(
                    "loom:nan_transform — object '{}' (index {i}) has NaN/Inf",
                    obj.name
                ));
                break;
            }
        }
        // Zero-scale check
        if obj.transform.scale.iter().any(|s| *s == 0.0) {
            warnings.push(format!("loom:zero_scale — object '{}' has zero scale axis", obj.name));
        }
        // Duplicate ID check
        if !seen_ids.insert(obj.id) {
            errors.push(format!(
                "loom:duplicate_id — object '{}' has duplicate id {}",
                obj.name, obj.id
            ));
        }
        // Empty name check
        if obj.name.is_empty() {
            warnings.push(format!("loom:empty_name — object index {i} has empty name"));
        }
        // Parent reference check (cycle prevention)
        if let Some(parent_id) = obj.parent_id {
            if parent_id == obj.id {
                errors.push(format!("loom:self_parent — object '{}' is its own parent", obj.name));
            }
        }
        // Component schema check: no duplicate component kinds
        let mut comp_kinds = std::collections::HashSet::new();
        for comp in &obj.components {
            if !comp_kinds.insert(std::mem::discriminant(&comp.kind)) {
                warnings.push(format!(
                    "loom:duplicate_component — object '{}' has duplicate {:?} component",
                    obj.name, comp.kind
                ));
            }
        }
    }

    // Parent reference integrity: all parent_ids must point to existing objects
    let all_ids: std::collections::HashSet<u64> = scene.objects.iter().map(|o| o.id).collect();
    for obj in &scene.objects {
        if let Some(parent_id) = obj.parent_id {
            if !all_ids.contains(&parent_id) {
                errors.push(format!(
                    "loom:orphan_parent — object '{}' references non-existent parent {}",
                    obj.name, parent_id
                ));
            }
        }
    }

    // Hierarchy cycle detection (bounded BFS)
    for obj in &scene.objects {
        let mut current = obj.parent_id;
        let mut depth = 0u32;
        while let Some(pid) = current {
            depth += 1;
            if depth > 64 {
                errors.push(format!(
                    "loom:hierarchy_cycle — object '{}' has cycle or depth > 64",
                    obj.name
                ));
                break;
            }
            if pid == obj.id {
                errors.push(format!(
                    "loom:hierarchy_cycle — object '{}' is in a parent cycle",
                    obj.name
                ));
                break;
            }
            current = scene.objects.iter().find(|o| o.id == pid).and_then(|o| o.parent_id);
        }
    }

    if !errors.is_empty() {
        return Err(errors);
    }

    // ── Step 2: Extract lights ───────────────────────────────────────
    let mut lights = Vec::new();
    for obj in &scene.objects {
        if !obj.has_component(ComponentKind::Light) {
            continue;
        }
        let pos = obj.transform.position;
        let len = (pos[0] * pos[0] + pos[1] * pos[1] + pos[2] * pos[2]).sqrt();

        // Read light properties from component JSON bag
        let light_props = obj.get_component(ComponentKind::Light).map(|c| &c.properties);

        let intensity = light_props
            .and_then(|p| p.get("intensity_lux"))
            .and_then(|v| v.as_f64())
            .map(|v| v as f32)
            .unwrap_or(100_000.0);

        let color = light_props
            .and_then(|p| p.get("color"))
            .and_then(|v| v.as_str())
            .and_then(parse_color_3)
            .unwrap_or([1.0, 0.95, 0.9]);

        let range = light_props
            .and_then(|p| p.get("range"))
            .and_then(|v| v.as_f64())
            .map(|v| v as f32);

        if let Some(range) = range {
            // Point light (has range)
            lights.push(ExtractedLight::Point(PointLightDesc {
                position: pos,
                color,
                intensity_lumens: intensity,
                range,
            }));
        } else if len > 0.001 {
            // Directional light (no range, direction from position)
            lights.push(ExtractedLight::Directional(DirectionalLightDesc {
                direction: [-pos[0] / len, -pos[1] / len, -pos[2] / len],
                intensity_lux: intensity,
                color,
            }));
        }
    }

    // ── Step 3: Extract physics bodies ───────────────────────────────
    let mut bodies = Vec::new();
    for obj in &scene.objects {
        // Objects with physics-relevant tags get bodies
        let has_physics_tags = obj.property_tags.iter().any(|t| {
            t == "isDestructible"
                || t == "isFlammable"
                || t == "isExplosive"
                || t == "isPickupable"
                || t == "isHazard"
                || t == "isWall"
        });

        if has_physics_tags || obj.has_component(ComponentKind::Physics) {
            let scale = obj.transform.scale;
            let shape = BodyShape::Box {
                half_extents: [scale[0] * 0.5, scale[1] * 0.5, scale[2] * 0.5],
            };
            let mass = if obj.property_tags.iter().any(|t| t == "isWall" || t == "isWalkable") {
                0.0 // Static
            } else {
                1.0
            };

            bodies.push(ExtractedBody {
                object_id: obj.id,
                position: obj.transform.position,
                shape,
                mass,
                restitution: 0.3,
                friction: 0.5,
                is_static: mass == 0.0,
                tags: obj.property_tags.clone(),
            });
        }
    }

    // ── Step 4: Extract emitters ─────────────────────────────────────
    let mut emitters = Vec::new();
    for obj in &scene.objects {
        if obj.has_component(ComponentKind::Particle) {
            emitters.push(ExtractedEmitter {
                object_id: obj.id,
                position: obj.transform.position,
                kind: EmitterKind::Particle,
                tags: obj.property_tags.clone(),
            });
        }
        if obj.has_component(ComponentKind::DreamMatter) {
            emitters.push(ExtractedEmitter {
                object_id: obj.id,
                position: obj.transform.position,
                kind: EmitterKind::DreamMatter,
                tags: obj.property_tags.clone(),
            });
        }
    }

    // ── Step 5: Build tagged object map ──────────────────────────────
    let tagged_objects: Vec<(u64, Vec<String>)> = scene
        .objects
        .iter()
        .filter(|obj| !obj.property_tags.is_empty())
        .map(|obj| (obj.id, obj.property_tags.clone()))
        .collect();

    // ── Step 6: Compute stats ────────────────────────────────────────
    let mut stats = WovenStats::default();
    stats.total_objects = scene.objects.len() as u32;
    for obj in &scene.objects {
        match &obj.mesh {
            MeshBinding::Primitive { .. } | MeshBinding::Custom { .. } => stats.mesh_objects += 1,
            MeshBinding::None => {}
        }
        if obj.has_component(ComponentKind::Light) {
            stats.light_objects += 1;
        }
        if obj.property_tags.contains(&"isDreammatter".to_string()) {
            stats.dreamlet_count += 1;
        }
        // Dreamfabs have DreamMatter component but NOT the isDreammatter tag
        if obj.has_component(ComponentKind::DreamMatter) && !obj.property_tags.contains(&"isDreammatter".to_string()) {
            stats.dreamfab_count += 1;
        }
    }
    stats.physics_bodies = bodies.len() as u32;
    stats.emitter_count = emitters.len() as u32;
    stats.tagged_objects = tagged_objects.len() as u32;

    Ok(WovenScene {
        scene,
        lights,
        bodies,
        emitters,
        render_config,
        tagged_objects,
        warnings,
        stats,
    })
}

/// Parse a color string "[r, g, b]" to [f32; 3].
fn parse_color_3(s: &str) -> Option<[f32; 3]> {
    let s = s.trim().trim_start_matches('[').trim_end_matches(']');
    let parts: Vec<&str> = s.split(',').collect();
    if parts.len() >= 3 {
        let r = parts[0].trim().parse::<f32>().ok()?;
        let g = parts[1].trim().parse::<f32>().ok()?;
        let b = parts[2].trim().parse::<f32>().ok()?;
        Some([r, g, b])
    } else {
        None
    }
}

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

    fn test_scene() -> GameObjectScene {
        let mut scene = GameObjectScene::new("test".into());
        // Add a mesh object with physics tag
        let id = scene
            .spawn_primitive("Wall".into(), crate::game_object::PrimitiveKind::Cube)
            .unwrap();
        if let Some(obj) = scene.find_mut(id) {
            obj.property_tags.push("isWall".into());
            obj.property_tags.push("isDestructible".into());
        }
        // Add a light
        let light_id = scene.spawn("Sun".into()).unwrap();
        if let Some(obj) = scene.find_mut(light_id) {
            obj.transform.position = [3.0, 6.0, 3.0];
            let _ = obj.add_component(ComponentSlot::new(ComponentKind::Light));
        }
        // Add a DreamMatter emitter
        let dm_id = scene.spawn("Fire Effect".into()).unwrap();
        if let Some(obj) = scene.find_mut(dm_id) {
            obj.property_tags.push("isDreammatter".into());
            obj.property_tags.push("isFlammable".into());
            let _ = obj.add_component(ComponentSlot::new(ComponentKind::DreamMatter));
        }
        scene
    }

    #[test]
    fn weave_extracts_all() {
        let scene = test_scene();
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert_eq!(woven.stats.total_objects, 3);
        assert_eq!(woven.stats.light_objects, 1);
        assert_eq!(woven.stats.physics_bodies, 2); // Wall + Fire
        assert_eq!(woven.stats.emitter_count, 1); // Fire DreamMatter
        assert_eq!(woven.stats.tagged_objects, 2); // Wall + Fire have tags
        assert_eq!(woven.stats.dreamlet_count, 1); // Fire has isDreammatter
        assert_eq!(woven.lights.len(), 1);
    }

    #[test]
    fn weave_rejects_nan() {
        let mut scene = GameObjectScene::new("bad".into());
        let id = scene.spawn("NaN Object".into()).unwrap();
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [f32::NAN, 0.0, 0.0];
        }
        let result = weave(scene, RenderConfig::default());
        assert!(result.is_err());
        assert!(result.unwrap_err()[0].contains("nan_transform"));
    }

    #[test]
    fn weave_static_body_for_wall() {
        let scene = test_scene();
        let woven = weave(scene, RenderConfig::default()).unwrap();
        let wall_body = woven
            .bodies
            .iter()
            .find(|b| b.tags.contains(&"isWall".to_string()))
            .unwrap();
        assert!(wall_body.is_static);
        assert_eq!(wall_body.mass, 0.0);
    }

    #[test]
    fn weave_render_config_preserved() {
        let scene = test_scene();
        let config = RenderConfig {
            bloom_enabled: false,
            ssao_enabled: true,
            ..Default::default()
        };
        let woven = weave(scene, config).unwrap();
        assert!(!woven.render_config.bloom_enabled);
        assert!(woven.render_config.ssao_enabled);
    }

    #[test]
    fn weave_empty_scene_warns() {
        let scene = GameObjectScene::new("empty".into());
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert!(woven.warnings.iter().any(|w| w.contains("empty_scene")));
    }

    #[test]
    fn bootstrap_stages_ordered() {
        assert_eq!(BootstrapStage::ALL.len(), 5);
        assert_eq!(BootstrapStage::ALL[0], BootstrapStage::Validate);
        assert_eq!(BootstrapStage::ALL[4], BootstrapStage::Manifest);
    }

    #[test]
    fn frame_stages_ordered() {
        assert_eq!(FrameStage::ALL.len(), 7);
        assert_eq!(FrameStage::ALL[0], FrameStage::Input);
        assert_eq!(FrameStage::ALL[6], FrameStage::Cleanup);
    }

    #[test]
    fn weave_rejects_inf_transform() {
        let mut scene = GameObjectScene::new("bad".into());
        let id = scene.spawn("InfObj".into()).unwrap();
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [0.0, f32::INFINITY, 0.0];
        }
        let result = weave(scene, RenderConfig::default());
        assert!(result.is_err());
    }

    #[test]
    fn weave_dynamic_body_for_destructible() {
        let mut scene = GameObjectScene::new("dyn".into());
        let id = scene
            .spawn_primitive("Crate".into(), crate::game_object::PrimitiveKind::Cube)
            .unwrap();
        if let Some(obj) = scene.find_mut(id) {
            obj.property_tags.push("isDestructible".into());
        }
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert_eq!(woven.bodies.len(), 1);
        let body = &woven.bodies[0];
        assert!(!body.is_static);
        assert!(body.mass > 0.0);
    }

    #[test]
    fn weave_extracts_point_light_properties() {
        let mut scene = GameObjectScene::new("lights".into());
        let id = scene.spawn("PointLight".into()).unwrap();
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.position = [5.0, 10.0, 3.0];
            let mut slot = ComponentSlot::new(ComponentKind::Light);
            let _ = slot.set_property("type".into(), serde_json::Value::from("point"));
            let _ = slot.set_property("intensity".into(), serde_json::Value::from(2.5));
            let _ = slot.set_property("range".into(), serde_json::Value::from(15.0));
            let _ = obj.add_component(slot);
        }
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert_eq!(woven.lights.len(), 1);
    }

    #[test]
    fn weave_multiple_lights() {
        let mut scene = GameObjectScene::new("multi_light".into());
        for i in 0..5 {
            let id = scene.spawn(format!("Light{i}")).unwrap();
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = [i as f32 * 3.0, 5.0, 0.0];
                let _ = obj.add_component(ComponentSlot::new(ComponentKind::Light));
            }
        }
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert_eq!(woven.lights.len(), 5);
        assert_eq!(woven.stats.light_objects, 5);
    }

    #[test]
    fn weave_emitter_from_particle_component() {
        let mut scene = GameObjectScene::new("particles".into());
        let id = scene.spawn("Sparks".into()).unwrap();
        if let Some(obj) = scene.find_mut(id) {
            let _ = obj.add_component(ComponentSlot::new(ComponentKind::Particle));
        }
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert_eq!(woven.emitters.len(), 1);
        assert!(matches!(woven.emitters[0].kind, EmitterKind::Particle));
    }

    #[test]
    fn weave_large_scene_performance() {
        let mut scene = GameObjectScene::new("large".into());
        for i in 0..500 {
            let id = scene
                .spawn_primitive(format!("Obj{i}"), crate::game_object::PrimitiveKind::Cube)
                .unwrap();
            if let Some(obj) = scene.find_mut(id) {
                obj.transform.position = [i as f32 * 0.5, 0.0, 0.0];
            }
        }
        let start = std::time::Instant::now();
        let woven = weave(scene, RenderConfig::default()).unwrap();
        let elapsed = start.elapsed();
        assert_eq!(woven.stats.total_objects, 500);
        assert!(
            elapsed.as_millis() < 100,
            "weave should complete under 100ms for 500 objects"
        );
    }

    #[test]
    fn weave_tagged_object_map() {
        let scene = test_scene();
        let woven = weave(scene, RenderConfig::default()).unwrap();
        // Wall has [isWall, isDestructible], Fire has [isDreammatter, isFlammable]
        assert!(woven.tagged_objects.len() >= 2);
        for (_, tags) in &woven.tagged_objects {
            assert!(!tags.is_empty());
        }
    }

    #[test]
    fn weave_warnings_are_non_fatal() {
        let mut scene = GameObjectScene::new("warn".into());
        let id = scene.spawn("ZeroScale".into()).unwrap();
        if let Some(obj) = scene.find_mut(id) {
            obj.transform.scale = [0.0, 0.0, 0.0];
        }
        // Zero-scale should warn, not fail.
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert!(!woven.warnings.is_empty());
    }

    #[test]
    fn woven_stats_dreamfab_count() {
        let mut scene = GameObjectScene::new("fabs".into());
        // Object with DreamMatter component but NO isDreammatter tag = Dreamfab.
        let id = scene.spawn("HybridFab".into()).unwrap();
        if let Some(obj) = scene.find_mut(id) {
            let _ = obj.add_component(ComponentSlot::new(ComponentKind::DreamMatter));
            // No isDreammatter tag.
        }
        let woven = weave(scene, RenderConfig::default()).unwrap();
        assert_eq!(woven.stats.dreamfab_count, 1);
        assert_eq!(woven.stats.dreamlet_count, 0);
    }

    #[test]
    fn render_config_default_has_bloom() {
        let rc = RenderConfig::default();
        assert!(rc.bloom_enabled);
        assert!(rc.tonemap_enabled);
    }
}