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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
// Dreamwell .dream File Format v1.0.0
//
// Binary scene container for the Dreamwell Simulation Development Kit.
// Equivalent to Unity .unity or Unreal .umap — packages everything needed
// to load a PBR scene into any Dreamwell client: editor, runtime, or benchmark.
//
// Format: 32-byte header + MessagePack-encoded payload + FNV-1a attestation.
// Assets are referenced by path (not embedded), resolved from project assets/ at load time.
//
// Clean Compute: zero per-frame allocation. Scenes are loaded once, GPU buffers
// pre-allocated from scene manifest, no hot-path deserialization.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Write;
use std::path::Path;

use crate::hash::fnv1a_64;
use crate::waymark::schema::{GridConfig, SimulationConfig, SpatialConfig};

// =============================================================================
// §0  CONSTANTS
// =============================================================================

/// Magic bytes: "DREAMWL\0" (8 bytes)
pub const DREAM_MAGIC: &[u8; 8] = b"DREAMWL\0";

/// File format version (u32). Increment on breaking schema changes.
pub const DREAM_VERSION: u32 = 1;

/// Scene schema version string.
pub const SCENE_SCHEMA_VERSION: &str = "dreamwell_scene_v1.0.0";

/// Tapestry schema version string.
pub const TAPESTRY_SCHEMA_VERSION: &str = "dreamwell_tapestry_v1.0.0";

// Flag bits
pub const FLAG_COMPRESSED: u32 = 1 << 0;
pub const FLAG_SIGNED: u32 = 1 << 1;

// =============================================================================
// §1  DREAM SCENE — scene.dream payload
// =============================================================================

/// Complete scene definition serialized into a .dream binary.
/// This is the compiled output of scene.json + zone/chunk/poi/avatar manifests.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DreamSceneV1 {
    // ── Identity ──
    pub scene_id: String,
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default = "default_scene_schema")]
    pub schema_version: String,

    // ── Topology ──
    #[serde(default = "default_topology_layer")]
    pub topology_layer: u8,
    #[serde(default)]
    pub starting_zone_id: String,
    #[serde(default)]
    pub world_id: Option<String>,

    // ── Camera ──
    #[serde(default = "default_camera")]
    pub default_camera: String,
    #[serde(default)]
    pub allowed_cameras: Vec<String>,

    // ── Scene graph ──
    #[serde(default)]
    pub objects: Vec<SceneObject>,

    // ── Lights ──
    #[serde(default)]
    pub directional_lights: Vec<DirectionalLightDef>,
    #[serde(default)]
    pub point_lights: Vec<PointLightDef>,
    #[serde(default)]
    pub spot_lights: Vec<SpotLightDef>,

    // ── Physics ──
    #[serde(default)]
    pub colliders: Vec<ColliderDef>,
    #[serde(default)]
    pub physics_defaults: PhysicsDefaults,

    // ── POIs ──
    #[serde(default)]
    pub pois: Vec<PoiDef>,

    // ── Asset references (paths relative to project root) ──
    #[serde(default)]
    pub asset_refs: Vec<AssetRef>,

    // ── GPU pipeline hints ──
    #[serde(default = "default_render_path")]
    pub render_path: String,
    #[serde(default)]
    pub quality_preset: Option<String>,
    #[serde(default)]
    pub feature_flags: FeatureFlags,

    // ── Waymark pack (optional, for server seeding) ──
    #[serde(default)]
    pub waymark_pack: Option<serde_json::Value>,

    // ── Spatial config ──
    #[serde(default)]
    pub grid: GridConfig,
    #[serde(default)]
    pub spatial: SpatialConfig,
    #[serde(default)]
    pub simulation: SimulationConfig,
}

fn default_scene_schema() -> String {
    SCENE_SCHEMA_VERSION.to_string()
}
fn default_topology_layer() -> u8 {
    6 // Area
}
fn default_camera() -> String {
    "ThirdPerson".to_string()
}
fn default_render_path() -> String {
    "Dreamwell".to_string()
}

impl Default for DreamSceneV1 {
    fn default() -> Self {
        Self {
            scene_id: String::new(),
            name: String::new(),
            description: String::new(),
            schema_version: default_scene_schema(),
            topology_layer: default_topology_layer(),
            starting_zone_id: String::new(),
            world_id: None,
            default_camera: default_camera(),
            allowed_cameras: Vec::new(),
            objects: Vec::new(),
            directional_lights: Vec::new(),
            point_lights: Vec::new(),
            spot_lights: Vec::new(),
            colliders: Vec::new(),
            physics_defaults: PhysicsDefaults::default(),
            pois: Vec::new(),
            asset_refs: Vec::new(),
            render_path: default_render_path(),
            quality_preset: None,
            feature_flags: FeatureFlags::default(),
            waymark_pack: None,
            grid: GridConfig::default(),
            spatial: SpatialConfig::default(),
            simulation: SimulationConfig::default(),
        }
    }
}

// =============================================================================
// §2  SCENE OBJECT — authored entity in the scene graph
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneObject {
    pub id: String,
    #[serde(default)]
    pub name: String,
    /// "Mesh" | "Light" | "Camera" | "Particle" | "Trigger" | "Meshlet" | "GltfMesh"
    #[serde(default = "default_kind")]
    pub kind: String,
    #[serde(default)]
    pub position: [f32; 3],
    /// Euler rotation in degrees.
    #[serde(default)]
    pub rotation: [f32; 3],
    #[serde(default = "default_scale")]
    pub scale: [f32; 3],
    #[serde(default)]
    pub parent_id: Option<String>,
    /// Key into DreamSceneV1.asset_refs for external assets.
    #[serde(default)]
    pub asset_ref: Option<String>,
    #[serde(default)]
    pub material: Option<MaterialDef>,
    /// Built-in primitive: "Cube" | "Sphere" | "Cylinder" | "Cone" | "Torus" | "Capsule" | "Plane"
    #[serde(default)]
    pub primitive: Option<String>,
    /// Arbitrary key-value properties for extensibility.
    #[serde(default)]
    pub properties: HashMap<String, serde_json::Value>,
}

fn default_kind() -> String {
    "Mesh".to_string()
}
fn default_scale() -> [f32; 3] {
    [1.0, 1.0, 1.0]
}

// =============================================================================
// §3  LIGHTS
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectionalLightDef {
    #[serde(default)]
    pub id: String,
    pub direction: [f32; 3],
    #[serde(default = "default_light_color")]
    pub color: [f32; 3],
    #[serde(default = "default_one")]
    pub intensity: f32,
    #[serde(default)]
    pub cast_shadows: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PointLightDef {
    #[serde(default)]
    pub id: String,
    pub position: [f32; 3],
    #[serde(default = "default_light_color")]
    pub color: [f32; 3],
    #[serde(default = "default_one")]
    pub intensity: f32,
    #[serde(default = "default_light_range")]
    pub range: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpotLightDef {
    #[serde(default)]
    pub id: String,
    pub position: [f32; 3],
    pub direction: [f32; 3],
    #[serde(default = "default_light_color")]
    pub color: [f32; 3],
    #[serde(default = "default_one")]
    pub intensity: f32,
    #[serde(default = "default_light_range")]
    pub range: f32,
    /// Inner cone angle in degrees.
    #[serde(default = "default_inner_cone")]
    pub inner_cone_degrees: f32,
    /// Outer cone angle in degrees.
    #[serde(default = "default_outer_cone")]
    pub outer_cone_degrees: f32,
}

fn default_light_color() -> [f32; 3] {
    [1.0, 1.0, 1.0]
}
fn default_one() -> f32 {
    1.0
}
fn default_light_range() -> f32 {
    20.0
}
fn default_inner_cone() -> f32 {
    30.0
}
fn default_outer_cone() -> f32 {
    45.0
}

// =============================================================================
// §4  PHYSICS
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColliderDef {
    #[serde(default)]
    pub id: String,
    /// "Sphere" | "Plane" | "Aabb" | "Capsule" | "Cylinder" | "Cone"
    pub shape: String,
    #[serde(default)]
    pub position: [f32; 3],
    /// Shape-specific dimensions: radius, half_extents, half_height, etc.
    #[serde(default)]
    pub dimensions: HashMap<String, f32>,
    #[serde(default = "default_one")]
    pub restitution: f32,
    #[serde(default = "default_friction")]
    pub friction: f32,
    #[serde(default)]
    pub is_static: bool,
}

fn default_friction() -> f32 {
    0.5
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhysicsDefaults {
    #[serde(default = "default_gravity")]
    pub gravity: [f32; 3],
    #[serde(default = "default_friction")]
    pub friction: f32,
    #[serde(default = "default_one")]
    pub atmosphere_density: f32,
}

fn default_gravity() -> [f32; 3] {
    [0.0, -9.81, 0.0]
}

impl Default for PhysicsDefaults {
    fn default() -> Self {
        Self {
            gravity: default_gravity(),
            friction: default_friction(),
            atmosphere_density: 1.0,
        }
    }
}

// =============================================================================
// §5  MATERIALS
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialDef {
    #[serde(default = "default_base_color")]
    pub base_color: [f32; 4],
    #[serde(default = "default_roughness")]
    pub roughness: f32,
    #[serde(default)]
    pub metallic: f32,
    #[serde(default)]
    pub emissive: [f32; 3],
    #[serde(default = "default_one")]
    pub emissive_strength: f32,
    #[serde(default)]
    pub double_sided: bool,
}

fn default_base_color() -> [f32; 4] {
    [0.8, 0.8, 0.8, 1.0]
}
fn default_roughness() -> f32 {
    0.5
}

// =============================================================================
// §6  POI
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoiDef {
    pub id: String,
    pub position: [f32; 3],
    #[serde(default = "default_poi_radius")]
    pub interaction_radius: f32,
    #[serde(default)]
    pub property_tag: String,
    #[serde(default)]
    pub animation_binding: Option<String>,
    #[serde(default)]
    pub transition_target: Option<TransitionTarget>,
}

fn default_poi_radius() -> f32 {
    2.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransitionTarget {
    pub zone_id: String,
    #[serde(default)]
    pub layer: Option<String>,
    #[serde(default)]
    pub camera_profile: Option<String>,
}

// =============================================================================
// §7  ASSET REFERENCES
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssetRef {
    /// Unique key within the scene.
    pub key: String,
    /// Path relative to project root: "assets/dreamwell/models/glTF/model.zip"
    pub path: String,
    /// "gltf" | "fbx" | "texture" | "audio" | "pbr_pack"
    #[serde(default = "default_asset_kind")]
    pub kind: String,
}

fn default_asset_kind() -> String {
    "gltf".to_string()
}

// =============================================================================
// §8  FEATURE FLAGS
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureFlags {
    #[serde(default)]
    pub quantum_culling: bool,
    #[serde(default)]
    pub rtx_gi: bool,
    #[serde(default)]
    pub rtx_shadows: bool,
    #[serde(default)]
    pub ssao: bool,
    #[serde(default)]
    pub ssr: bool,
    #[serde(default)]
    pub ssgi: bool,
    #[serde(default)]
    pub taa: bool,
    #[serde(default)]
    pub volumetric_fog: bool,
    #[serde(default)]
    pub dof: bool,
    #[serde(default)]
    pub bloom: bool,
    #[serde(default)]
    pub motion_vectors: bool,
    #[serde(default)]
    pub hiz_culling: bool,
    #[serde(default)]
    pub dream_tsr: bool,
    #[serde(default)]
    pub dreamphysics: bool,
    #[serde(default)]
    pub dreammatter: bool,
    #[serde(default)]
    pub procedural_terrain: bool,
    #[serde(default)]
    pub fbx_avatar: bool,
}

impl Default for FeatureFlags {
    fn default() -> Self {
        Self {
            quantum_culling: true,
            rtx_gi: false,
            rtx_shadows: false,
            ssao: true,
            ssr: true,
            ssgi: true,
            taa: true,
            volumetric_fog: false,
            dof: false,
            bloom: true,
            motion_vectors: true,
            hiz_culling: true,
            dream_tsr: false,
            dreamphysics: true,
            dreammatter: true,
            procedural_terrain: false,
            fbx_avatar: false,
        }
    }
}

// =============================================================================
// §9  TAPESTRY — project manifest (tapestry.dream)
// =============================================================================

/// Project-level manifest — the master entry point for all Dreamwell clients.
/// Equivalent to a Unity project or Unreal .uproject file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TapestryV1 {
    #[serde(default = "default_tapestry_schema")]
    pub schema_version: String,
    pub project_name: String,
    pub project_id: String,
    #[serde(default = "default_engine_version")]
    pub engine_version: String,

    /// Registered scenes in this project.
    #[serde(default)]
    pub scenes: Vec<SceneEntry>,

    /// Scene loaded on startup.
    #[serde(default)]
    pub starting_scene: String,

    /// Asset root directories relative to project root.
    #[serde(default)]
    pub asset_roots: Vec<String>,

    /// Waymark pack directories to scan.
    #[serde(default)]
    pub waymark_packs: Vec<String>,

    /// Build profiles for different benchmark/release configurations.
    #[serde(default)]
    pub profiles: Vec<BuildProfile>,

    /// System simulation config override.
    #[serde(default)]
    pub simulation: Option<SimulationConfig>,
}

fn default_tapestry_schema() -> String {
    TAPESTRY_SCHEMA_VERSION.to_string()
}
fn default_engine_version() -> String {
    "1.0.0".to_string()
}

/// A scene registered in the tapestry manifest.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SceneEntry {
    pub scene_id: String,
    pub name: String,
    /// Path to scene.dream relative to project root.
    pub path: String,
    #[serde(default)]
    pub topology_layer: String,
    #[serde(default)]
    pub tags: Vec<String>,
}

/// A build profile: named configuration for benchmarks or releases.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildProfile {
    pub id: String,
    pub scene_id: String,
    #[serde(default = "default_render_path")]
    pub render_path: String,
    #[serde(default)]
    pub quality_preset: Option<String>,
    #[serde(default)]
    pub cli_args: Vec<String>,
}

// =============================================================================
// §10  BINARY READ/WRITE — Clean Compute attestable scene I/O
// =============================================================================

/// Write a DreamSceneV1 to a .dream binary file.
///
/// Format: 32-byte header (magic + version + flags + content_len + hash) + MessagePack payload.
/// Attestation: FNV-1a hash over content bytes, verified on read.
pub fn write_dream_file(path: &Path, scene: &DreamSceneV1) -> Result<(), String> {
    let content = rmp_serde::to_vec(scene).map_err(|e| format!("dream_serialize:{e}"))?;
    let hash = fnv1a_64(&content);
    let mut file = std::fs::File::create(path).map_err(|e| format!("dream_create:{e}"))?;
    file.write_all(DREAM_MAGIC).map_err(|e| format!("dream_write:{e}"))?;
    file.write_all(&DREAM_VERSION.to_le_bytes())
        .map_err(|e| format!("dream_write:{e}"))?;
    file.write_all(&0u32.to_le_bytes())
        .map_err(|e| format!("dream_write:{e}"))?;
    file.write_all(&(content.len() as u64).to_le_bytes())
        .map_err(|e| format!("dream_write:{e}"))?;
    file.write_all(&hash.to_le_bytes())
        .map_err(|e| format!("dream_write:{e}"))?;
    file.write_all(&content).map_err(|e| format!("dream_write:{e}"))?;
    Ok(())
}

/// Read a DreamSceneV1 from a .dream binary file.
///
/// Validates: magic bytes, version, content length, FNV-1a attestation hash.
pub fn read_dream_file(path: &Path) -> Result<DreamSceneV1, String> {
    let data = std::fs::read(path).map_err(|e| format!("dream_read:{e}"))?;
    deserialize_dream_scene(&data)
}

/// Deserialize a DreamSceneV1 from raw .dream bytes (header + payload).
pub fn deserialize_dream_scene(data: &[u8]) -> Result<DreamSceneV1, String> {
    if data.len() < 32 {
        return Err("dream_validate:file too small (< 32 bytes)".into());
    }
    if &data[0..8] != DREAM_MAGIC {
        return Err("dream_validate:invalid magic bytes (expected DREAMWL\\0)".into());
    }
    let version = u32::from_le_bytes(data[8..12].try_into().map_err(|_| "dream_validate:bad version bytes")?);
    if version != DREAM_VERSION {
        return Err(format!(
            "dream_validate:unsupported version {version} (expected {DREAM_VERSION})"
        ));
    }
    let content_len = u64::from_le_bytes(
        data[16..24]
            .try_into()
            .map_err(|_| "dream_validate:bad content_len bytes")?,
    ) as usize;
    let expected_hash = u64::from_le_bytes(data[24..32].try_into().map_err(|_| "dream_validate:bad hash bytes")?);
    if data.len() < 32 + content_len {
        return Err(format!(
            "dream_validate:content truncated (expected {content_len} bytes, got {})",
            data.len() - 32
        ));
    }
    let content = &data[32..32 + content_len];
    let actual_hash = fnv1a_64(content);
    if actual_hash != expected_hash {
        return Err(format!(
            "dream_validate:attestation hash mismatch (expected {expected_hash:#x}, got {actual_hash:#x})"
        ));
    }
    rmp_serde::from_slice(content).map_err(|e| format!("dream_deserialize:{e}"))
}

/// Write a TapestryV1 to a tapestry.dream binary file.
pub fn write_tapestry(path: &Path, tapestry: &TapestryV1) -> Result<(), String> {
    let content = rmp_serde::to_vec(tapestry).map_err(|e| format!("tapestry_serialize:{e}"))?;
    let hash = fnv1a_64(&content);
    let mut file = std::fs::File::create(path).map_err(|e| format!("tapestry_create:{e}"))?;
    file.write_all(DREAM_MAGIC).map_err(|e| format!("tapestry_write:{e}"))?;
    file.write_all(&DREAM_VERSION.to_le_bytes())
        .map_err(|e| format!("tapestry_write:{e}"))?;
    file.write_all(&FLAG_SIGNED.to_le_bytes())
        .map_err(|e| format!("tapestry_write:{e}"))?;
    file.write_all(&(content.len() as u64).to_le_bytes())
        .map_err(|e| format!("tapestry_write:{e}"))?;
    file.write_all(&hash.to_le_bytes())
        .map_err(|e| format!("tapestry_write:{e}"))?;
    file.write_all(&content).map_err(|e| format!("tapestry_write:{e}"))?;
    Ok(())
}

/// Read a TapestryV1 from a tapestry.dream binary file.
pub fn read_tapestry(path: &Path) -> Result<TapestryV1, String> {
    let data = std::fs::read(path).map_err(|e| format!("tapestry_read:{e}"))?;
    if data.len() < 32 {
        return Err("tapestry_validate:file too small".into());
    }
    if &data[0..8] != DREAM_MAGIC {
        return Err("tapestry_validate:invalid magic bytes".into());
    }
    let version = u32::from_le_bytes(data[8..12].try_into().map_err(|_| "tapestry_validate:bad version")?);
    if version != DREAM_VERSION {
        return Err(format!("tapestry_validate:unsupported version {version}"));
    }
    let content_len = u64::from_le_bytes(
        data[16..24]
            .try_into()
            .map_err(|_| "tapestry_validate:bad content_len")?,
    ) as usize;
    let expected_hash = u64::from_le_bytes(data[24..32].try_into().map_err(|_| "tapestry_validate:bad hash")?);
    if data.len() < 32 + content_len {
        return Err("tapestry_validate:content truncated".into());
    }
    let content = &data[32..32 + content_len];
    let actual_hash = fnv1a_64(content);
    if actual_hash != expected_hash {
        return Err("tapestry_validate:attestation hash mismatch".into());
    }
    rmp_serde::from_slice(content).map_err(|e| format!("tapestry_deserialize:{e}"))
}

// =============================================================================
// §11  SCENE JSON COMPILER — scene.json → DreamSceneV1
// =============================================================================

/// Compile a scene.json (human-authored JSON) into a DreamSceneV1.
///
/// The scene.json is a direct JSON serialization of DreamSceneV1.
/// Additional zone/chunk/poi manifests in the same directory are merged if present.
pub fn compile_scene_json(scene_json: &str) -> Result<DreamSceneV1, String> {
    serde_json::from_str(scene_json).map_err(|e| format!("scene_compile:{e}"))
}

/// Compile a tapestry.json (human-authored JSON) into a TapestryV1.
pub fn compile_tapestry_json(tapestry_json: &str) -> Result<TapestryV1, String> {
    serde_json::from_str(tapestry_json).map_err(|e| format!("tapestry_compile:{e}"))
}

/// Compile a scene.json file and write the .dream binary next to it.
///
/// Reads `{scene_dir}/scene.json`, compiles to DreamSceneV1, writes `{scene_dir}/scene.dream`.
pub fn compile_scene_dir(scene_dir: &Path) -> Result<(), String> {
    let json_path = scene_dir.join("scene.json");
    let dream_path = scene_dir.join("scene.dream");
    let json_str = std::fs::read_to_string(&json_path).map_err(|e| format!("scene_read:{json_path:?}:{e}"))?;
    let scene = compile_scene_json(&json_str)?;
    write_dream_file(&dream_path, &scene)?;
    log::info!("Compiled {} → {}", json_path.display(), dream_path.display());
    Ok(())
}

/// Compile an entire project: tapestry.json + all scene.json files.
pub fn compile_project(project_dir: &Path) -> Result<(), String> {
    // Compile tapestry
    let tapestry_json_path = project_dir.join("tapestry.json");
    if tapestry_json_path.exists() {
        let json_str = std::fs::read_to_string(&tapestry_json_path).map_err(|e| format!("tapestry_read:{e}"))?;
        let tapestry = compile_tapestry_json(&json_str)?;
        write_tapestry(&project_dir.join("tapestry.dream"), &tapestry)?;
        log::info!("Compiled tapestry.dream");
    }

    // Compile all scenes
    let scenes_dir = project_dir.join("scenes");
    if scenes_dir.is_dir() {
        let entries = std::fs::read_dir(&scenes_dir).map_err(|e| format!("scenes_scan:{e}"))?;
        for entry in entries.flatten() {
            if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                let scene_json = entry.path().join("scene.json");
                if scene_json.exists() {
                    compile_scene_dir(&entry.path())?;
                }
            }
        }
    }

    Ok(())
}

// =============================================================================
// §12  REALITY CHECK — validate a loaded scene against engine expectations
// =============================================================================

/// Validate a loaded DreamSceneV1 for correctness.
///
/// Returns (warnings, errors). Scene is loadable if errors is empty.
pub fn reality_check(scene: &DreamSceneV1) -> (Vec<String>, Vec<String>) {
    let mut warnings = Vec::new();
    let mut errors = Vec::new();

    // Identity
    if scene.scene_id.is_empty() {
        errors.push("reality_check:scene_id is empty".into());
    }
    if scene.name.is_empty() {
        warnings.push("reality_check:scene name is empty".into());
    }
    if scene.schema_version != SCENE_SCHEMA_VERSION {
        warnings.push(format!(
            "reality_check:schema_version mismatch (got '{}', expected '{SCENE_SCHEMA_VERSION}')",
            scene.schema_version
        ));
    }

    // Topology
    if scene.topology_layer > 9 {
        errors.push(format!("reality_check:topology_layer {} > 9", scene.topology_layer));
    }

    // Objects
    let mut obj_ids = std::collections::HashSet::new();
    for obj in &scene.objects {
        if obj.id.is_empty() {
            errors.push("reality_check:object with empty id".into());
        }
        if !obj_ids.insert(&obj.id) {
            errors.push(format!("reality_check:duplicate object id '{}'", obj.id));
        }
        // Validate position is finite
        for &v in &obj.position {
            if !v.is_finite() {
                errors.push(format!("reality_check:object '{}' has non-finite position", obj.id));
                break;
            }
        }
        // Validate asset ref exists
        if let Some(ref key) = obj.asset_ref {
            if !scene.asset_refs.iter().any(|a| &a.key == key) {
                errors.push(format!(
                    "reality_check:object '{}' references unknown asset '{key}'",
                    obj.id
                ));
            }
        }
    }

    // Lights
    for light in &scene.directional_lights {
        let len_sq: f32 = light.direction.iter().map(|v| v * v).sum();
        if len_sq < 0.001 {
            warnings.push(format!(
                "reality_check:directional light '{}' has near-zero direction",
                light.id
            ));
        }
    }

    // POIs
    for poi in &scene.pois {
        if poi.interaction_radius <= 0.0 {
            errors.push(format!("reality_check:POI '{}' has non-positive radius", poi.id));
        }
    }

    (warnings, errors)
}

// =============================================================================
// §13  TESTS
// =============================================================================

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

    fn sample_scene() -> DreamSceneV1 {
        DreamSceneV1 {
            scene_id: "test-scene".into(),
            name: "Test Scene".into(),
            description: "Unit test scene".into(),
            objects: vec![SceneObject {
                id: "ground".into(),
                name: "Ground Plane".into(),
                kind: "Mesh".into(),
                position: [0.0, 0.0, 0.0],
                rotation: [0.0, 0.0, 0.0],
                scale: [80.0, 1.0, 80.0],
                parent_id: None,
                asset_ref: None,
                material: Some(MaterialDef {
                    base_color: [0.3, 0.5, 0.2, 1.0],
                    roughness: 0.8,
                    metallic: 0.0,
                    emissive: [0.0, 0.0, 0.0],
                    emissive_strength: 0.0,
                    double_sided: false,
                }),
                primitive: Some("Plane".into()),
                properties: HashMap::new(),
            }],
            directional_lights: vec![DirectionalLightDef {
                id: "sun".into(),
                direction: [0.4, -0.7, 0.3],
                color: [1.0, 0.95, 0.85],
                intensity: 1.2,
                cast_shadows: true,
            }],
            point_lights: vec![PointLightDef {
                id: "fill".into(),
                position: [5.0, 3.0, 0.0],
                color: [0.6, 0.8, 1.0],
                intensity: 0.5,
                range: 15.0,
            }],
            pois: vec![PoiDef {
                id: "demo-poi".into(),
                position: [8.0, 0.0, 0.0],
                interaction_radius: 2.0,
                property_tag: "interact.demo.spawn".into(),
                animation_binding: None,
                transition_target: None,
            }],
            ..Default::default()
        }
    }

    fn sample_tapestry() -> TapestryV1 {
        TapestryV1 {
            schema_version: TAPESTRY_SCHEMA_VERSION.into(),
            project_name: "Test Project".into(),
            project_id: "test-project".into(),
            engine_version: "1.0.0".into(),
            scenes: vec![SceneEntry {
                scene_id: "test-scene".into(),
                name: "Test Scene".into(),
                path: "scenes/test/scene.dream".into(),
                topology_layer: "Area".into(),
                tags: vec!["test".into()],
            }],
            starting_scene: "test-scene".into(),
            asset_roots: vec!["assets/dreamwell".into()],
            waymark_packs: vec!["waymark/".into()],
            profiles: vec![BuildProfile {
                id: "default".into(),
                scene_id: "test-scene".into(),
                render_path: "Dreamwell".into(),
                quality_preset: None,
                cli_args: vec!["--dream".into()],
            }],
            simulation: None,
        }
    }

    #[test]
    fn dream_file_roundtrip() {
        let scene = sample_scene();
        let dir = std::env::temp_dir().join("dreamwell_test_roundtrip");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.dream");

        write_dream_file(&path, &scene).unwrap();
        let loaded = read_dream_file(&path).unwrap();

        assert_eq!(scene.scene_id, loaded.scene_id);
        assert_eq!(scene.name, loaded.name);
        assert_eq!(scene.objects.len(), loaded.objects.len());
        assert_eq!(scene.directional_lights.len(), loaded.directional_lights.len());
        assert_eq!(scene.point_lights.len(), loaded.point_lights.len());
        assert_eq!(scene.pois.len(), loaded.pois.len());
        assert_eq!(scene.objects[0].id, loaded.objects[0].id);
        assert_eq!(scene.objects[0].scale, loaded.objects[0].scale);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn dream_file_rejects_bad_magic() {
        let mut data = vec![0u8; 64];
        data[0..8].copy_from_slice(b"NOTDREAM");
        let result = deserialize_dream_scene(&data);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid magic bytes"));
    }

    #[test]
    fn dream_file_rejects_bad_version() {
        let scene = sample_scene();
        let content = rmp_serde::to_vec(&scene).unwrap();
        let hash = fnv1a_64(&content);
        let mut data = Vec::new();
        data.extend_from_slice(DREAM_MAGIC);
        data.extend_from_slice(&99u32.to_le_bytes()); // bad version
        data.extend_from_slice(&0u32.to_le_bytes());
        data.extend_from_slice(&(content.len() as u64).to_le_bytes());
        data.extend_from_slice(&hash.to_le_bytes());
        data.extend_from_slice(&content);

        let result = deserialize_dream_scene(&data);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("unsupported version 99"));
    }

    #[test]
    fn dream_file_rejects_bad_hash() {
        let scene = sample_scene();
        let content = rmp_serde::to_vec(&scene).unwrap();
        let mut data = Vec::new();
        data.extend_from_slice(DREAM_MAGIC);
        data.extend_from_slice(&DREAM_VERSION.to_le_bytes());
        data.extend_from_slice(&0u32.to_le_bytes());
        data.extend_from_slice(&(content.len() as u64).to_le_bytes());
        data.extend_from_slice(&0xDEADBEEFu64.to_le_bytes()); // wrong hash
        data.extend_from_slice(&content);

        let result = deserialize_dream_scene(&data);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("attestation hash mismatch"));
    }

    #[test]
    fn dream_file_rejects_too_small() {
        let result = deserialize_dream_scene(&[0u8; 16]);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("too small"));
    }

    #[test]
    fn tapestry_roundtrip() {
        let tapestry = sample_tapestry();
        let dir = std::env::temp_dir().join("dreamwell_test_tapestry");
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("tapestry.dream");

        write_tapestry(&path, &tapestry).unwrap();
        let loaded = read_tapestry(&path).unwrap();

        assert_eq!(tapestry.project_name, loaded.project_name);
        assert_eq!(tapestry.project_id, loaded.project_id);
        assert_eq!(tapestry.scenes.len(), loaded.scenes.len());
        assert_eq!(tapestry.profiles.len(), loaded.profiles.len());
        assert_eq!(tapestry.starting_scene, loaded.starting_scene);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn scene_json_compile() {
        let scene = sample_scene();
        let json = serde_json::to_string_pretty(&scene).unwrap();
        let compiled = compile_scene_json(&json).unwrap();
        assert_eq!(compiled.scene_id, "test-scene");
        assert_eq!(compiled.objects.len(), 1);
    }

    #[test]
    fn tapestry_json_compile() {
        let tapestry = sample_tapestry();
        let json = serde_json::to_string_pretty(&tapestry).unwrap();
        let compiled = compile_tapestry_json(&json).unwrap();
        assert_eq!(compiled.project_id, "test-project");
        assert_eq!(compiled.scenes.len(), 1);
    }

    #[test]
    fn reality_check_valid_scene() {
        let scene = sample_scene();
        let (warnings, errors) = reality_check(&scene);
        assert!(errors.is_empty(), "Unexpected errors: {errors:?}");
        assert!(warnings.is_empty(), "Unexpected warnings: {warnings:?}");
    }

    #[test]
    fn reality_check_catches_empty_id() {
        let mut scene = sample_scene();
        scene.scene_id = String::new();
        let (_, errors) = reality_check(&scene);
        assert!(errors.iter().any(|e| e.contains("scene_id is empty")));
    }

    #[test]
    fn reality_check_catches_duplicate_object_ids() {
        let mut scene = sample_scene();
        scene.objects.push(scene.objects[0].clone());
        let (_, errors) = reality_check(&scene);
        assert!(errors.iter().any(|e| e.contains("duplicate object id")));
    }

    #[test]
    fn reality_check_catches_bad_asset_ref() {
        let mut scene = sample_scene();
        scene.objects[0].asset_ref = Some("nonexistent".into());
        let (_, errors) = reality_check(&scene);
        assert!(errors.iter().any(|e| e.contains("unknown asset")));
    }

    #[test]
    fn reality_check_catches_bad_topology() {
        let mut scene = sample_scene();
        scene.topology_layer = 15;
        let (_, errors) = reality_check(&scene);
        assert!(errors.iter().any(|e| e.contains("topology_layer 15 > 9")));
    }

    #[test]
    fn default_feature_flags() {
        let flags = FeatureFlags::default();
        assert!(flags.quantum_culling);
        assert!(flags.ssao);
        assert!(flags.bloom);
        assert!(!flags.rtx_gi);
        assert!(!flags.rtx_shadows);
    }

    #[test]
    fn default_physics() {
        let phys = PhysicsDefaults::default();
        assert_eq!(phys.gravity, [0.0, -9.81, 0.0]);
    }

    #[test]
    fn compile_keynote_scene_from_project() {
        // Compile the real keynote scene.json from the benchmark project
        let project_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("dreamwell-benchmark-project");
        let scene_json_path = project_root.join("scenes").join("keynote").join("scene.json");
        if !scene_json_path.exists() {
            // Skip if project folder not present (CI environments)
            return;
        }
        let json_str = std::fs::read_to_string(&scene_json_path).unwrap();
        let scene = compile_scene_json(&json_str).unwrap();

        assert_eq!(scene.scene_id, "keynote");
        assert_eq!(scene.name, "Dreamwell Keynote Benchmark");
        assert_eq!(scene.topology_layer, 6); // Area
        assert!(
            scene.objects.len() >= 15,
            "Expected 15+ objects, got {}",
            scene.objects.len()
        );
        assert_eq!(scene.directional_lights.len(), 2);
        assert_eq!(scene.point_lights.len(), 8);
        assert!(scene.colliders.len() >= 5);
        assert_eq!(scene.render_path, "Dreamwell");
        assert!(scene.feature_flags.quantum_culling);
        assert!(scene.feature_flags.bloom);
        assert!(scene.feature_flags.dreammatter);

        // Reality check
        let (warnings, errors) = reality_check(&scene);
        assert!(errors.is_empty(), "Keynote scene has errors: {errors:?}");
        for w in &warnings {
            eprintln!("  warning: {w}");
        }

        // Round-trip: JSON → DreamSceneV1 → .dream binary → DreamSceneV1
        let dir = std::env::temp_dir().join("dreamwell_keynote_compile_test");
        std::fs::create_dir_all(&dir).unwrap();
        let dream_path = dir.join("keynote.dream");
        write_dream_file(&dream_path, &scene).unwrap();
        let reloaded = read_dream_file(&dream_path).unwrap();
        assert_eq!(reloaded.scene_id, "keynote");
        assert_eq!(reloaded.objects.len(), scene.objects.len());
        assert_eq!(reloaded.directional_lights.len(), 2);
        assert_eq!(reloaded.point_lights.len(), 8);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn compile_all_scenes_from_project() {
        let project_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("dreamwell-benchmark-project");
        let scenes_dir = project_root.join("scenes");
        if !scenes_dir.exists() {
            return;
        }

        let expected = [
            "keynote",
            "spawn_test",
            "micro_dreamlet",
            "avatar_demo",
            "ray_tracing_demo",
            "ray_tracing_gallery",
            "stress_test",
        ];
        let mut compiled = 0;
        for scene_name in &expected {
            let json_path = scenes_dir.join(scene_name).join("scene.json");
            if !json_path.exists() {
                continue;
            }
            let json_str = std::fs::read_to_string(&json_path)
                .unwrap_or_else(|e| panic!("Failed to read {scene_name}/scene.json: {e}"));
            let scene = compile_scene_json(&json_str).unwrap_or_else(|e| panic!("Failed to compile {scene_name}: {e}"));
            assert_eq!(scene.scene_id, *scene_name, "scene_id mismatch for {scene_name}");
            assert!(!scene.name.is_empty(), "empty name for {scene_name}");

            let (warnings, errors) = reality_check(&scene);
            assert!(errors.is_empty(), "{scene_name} reality check errors: {errors:?}");

            // Round-trip through .dream binary
            let dir = std::env::temp_dir().join(format!("dreamwell_compile_{scene_name}"));
            std::fs::create_dir_all(&dir).unwrap();
            let dream_path = dir.join("scene.dream");
            write_dream_file(&dream_path, &scene).unwrap();
            let reloaded = read_dream_file(&dream_path).unwrap();
            assert_eq!(reloaded.scene_id, scene.scene_id);
            assert_eq!(reloaded.objects.len(), scene.objects.len());
            std::fs::remove_dir_all(&dir).ok();

            compiled += 1;
            for w in &warnings {
                eprintln!("  {scene_name} warning: {w}");
            }
        }
        assert!(compiled >= 5, "Expected to compile at least 5 scenes, got {compiled}");
    }

    #[test]
    fn compile_tapestry_from_project() {
        let project_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .join("dreamwell-benchmark-project");
        let tapestry_json_path = project_root.join("tapestry.json");
        if !tapestry_json_path.exists() {
            return;
        }
        let json_str = std::fs::read_to_string(&tapestry_json_path).unwrap();
        let tapestry = compile_tapestry_json(&json_str).unwrap();

        assert_eq!(tapestry.project_id, "dreamwell-benchmarks");
        assert_eq!(tapestry.starting_scene, "keynote");
        assert!(
            tapestry.scenes.len() >= 6,
            "Expected 6+ scenes, got {}",
            tapestry.scenes.len()
        );
        assert!(
            tapestry.profiles.len() >= 6,
            "Expected 6+ profiles, got {}",
            tapestry.profiles.len()
        );

        // Verify all scene_ids in profiles reference valid scenes
        for profile in &tapestry.profiles {
            assert!(
                tapestry.scenes.iter().any(|s| s.scene_id == profile.scene_id),
                "Profile '{}' references unknown scene '{}'",
                profile.id,
                profile.scene_id
            );
        }

        // Round-trip
        let dir = std::env::temp_dir().join("dreamwell_tapestry_compile_test");
        std::fs::create_dir_all(&dir).unwrap();
        let dream_path = dir.join("tapestry.dream");
        write_tapestry(&dream_path, &tapestry).unwrap();
        let reloaded = read_tapestry(&dream_path).unwrap();
        assert_eq!(reloaded.project_id, "dreamwell-benchmarks");
        assert_eq!(reloaded.scenes.len(), tapestry.scenes.len());
        std::fs::remove_dir_all(&dir).ok();
    }
}