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
//! Material descriptor types shared between engine and GPU crates.
//!
//! These are CPU-side descriptions — the GPU crate translates them
//! into pipeline-specific bind group data.

use serde::{Deserialize, Serialize};

/// Alpha blending mode for materials.
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub enum AlphaMode {
    /// Fully opaque. No blending.
    #[default]
    Opaque,
    /// Alpha-tested with cutoff threshold. Fragments below cutoff are discarded.
    Mask { cutoff: f32 },
    /// Alpha-blended. Requires sorted draw order.
    Blend,
}

/// Classification of material pipeline variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MaterialClass {
    PbrLit,
    PbrLitUntextured,
    PbrEmissive,
    PbrMasked,
    PbrTransparent,
    Unlit,
    SpriteLit2D,
    SpriteUnlit2D,
}

/// Ray tracing quality preset for SceneDreamMode::PbrRayTraced.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RtQuality {
    /// Full RT GI + RT shadows (highest quality, ~2x GPU cost).
    Full,
    /// RT shadows only (moderate cost, significant visual improvement).
    ShadowsOnly,
    /// RT GI only (high quality ambient, keep CSM shadows).
    GiOnly,
}

impl Default for RtQuality {
    fn default() -> Self {
        Self::Full
    }
}

/// Scene-wide rendering mode that controls which pipeline features are active.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SceneDreamMode {
    /// Full PBR with all texture slots, HDR post-processing, shadows.
    PbrDefault,
    /// PBR with reduced texture slots (no occlusion, no emissive). Lower VRAM.
    PbrLightweight,
    /// No lighting. Flat color / texture only. Fastest.
    Unlit,
    /// 2D sprites with normal-mapped PBR lighting.
    SpriteLit2D,
    /// 2D sprites, no lighting. Standard 2D game mode.
    SpriteUnlit2D,
    /// PBR with native ray-traced global illumination and/or shadows.
    /// Requires GPU with EXPERIMENTAL_RAY_QUERY support. Falls back to PbrDefault without RT hardware.
    PbrRayTraced(RtQuality),
    /// User-provided shader pipeline. Engine provides frame lifecycle only.
    Custom,
}

impl Default for SceneDreamMode {
    fn default() -> Self {
        Self::PbrDefault
    }
}

/// HDR tonemapping operator applied during post-processing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TonemapOperator {
    /// ACES fitted (BakingLab). Default. Best color fidelity.
    AcesFilmic,
    /// Uncharted 2 filmic (Hable). Warmer, cinematic look.
    Uncharted2,
    /// Reinhard. Simple x/(x+1). Useful for debugging.
    Reinhard,
    /// No tonemapping. Linear HDR passthrough.
    None,
}

impl Default for TonemapOperator {
    fn default() -> Self {
        Self::AcesFilmic
    }
}

/// PBR lit material descriptor.
/// Texture references are optional `u32` handles resolved by the GPU store.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PbrMaterial {
    /// Base color (RGBA linear).
    pub base_color: [f32; 4],
    /// Emissive color (RGB linear).
    pub emissive: [f32; 3],
    /// Roughness [0..1]. 0 = mirror, 1 = diffuse.
    pub roughness: f32,
    /// Metallic [0..1]. 0 = dielectric, 1 = metal.
    pub metallic: f32,
    /// Optional base color texture handle.
    pub base_color_tex: Option<u32>,
    /// Optional normal map texture handle.
    pub normal_tex: Option<u32>,
    /// Optional emissive texture handle.
    pub emissive_tex: Option<u32>,
    /// Optional roughness-metalness texture handle (R=metallic, G=roughness, glTF convention).
    pub roughness_metalness_tex: Option<u32>,
    /// Optional occlusion texture handle.
    pub occlusion_tex: Option<u32>,
    /// Occlusion strength [0..1]. 1.0 = full effect.
    pub occlusion_strength: f32,
    /// Normal map scale factor. 1.0 = unmodified normals.
    pub normal_scale: f32,
    /// Emissive strength multiplier. 1.0 = use emissive color as-is.
    pub emissive_strength: f32,
    /// Alpha blending mode.
    pub alpha_mode: AlphaMode,
    /// Render both front and back faces.
    pub double_sided: bool,
}

/// Backward compatibility alias.
pub type LitMaterialDesc = PbrMaterial;

// ═══════════════════════════════════════════════════════════════════════
// Dream Lighting — unified GI + reflection + shadow quality presets
// ═══════════════════════════════════════════════════════════════════════

/// Dream Lighting quality preset — controls the entire lighting pipeline.
/// Maps to a fixed parameter matrix for all GI, shadow, reflection, and
/// post-processing subsystems.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DreamLightingQuality {
    /// Screen-space GI only, no RT. SSAO + TAA. Minimal VRAM.
    Low,
    /// Screen-space GI, CSM shadows, SSAO + SSR + TAA. Moderate VRAM.
    Medium,
    /// SHaRC RT GI + RT shadows, full screen-space stack, screen traces. ~150 MB.
    High,
    /// SHaRC RT GI (high density) + RT shadows, all effects, Hi-Z. ~250 MB.
    Ultra,
    /// Maximum quality: Dream TSR, 4-bounce GI, all effects at max settings.
    Cinematic,
}

impl Default for DreamLightingQuality {
    fn default() -> Self {
        Self::Medium
    }
}

impl DreamLightingQuality {
    /// Auto-detect quality from GPU capabilities (spec §4.3).
    pub fn auto_detect(ray_tracing: bool, max_storage_bytes: u64, max_tlas_instances: u32) -> Self {
        if !ray_tracing {
            if max_storage_bytes >= 64 * 1024 * 1024 {
                return Self::Medium;
            }
            return Self::Low;
        }
        // RT-capable GPU — select based on TLAS instance capacity
        if max_tlas_instances >= 16_000_000 {
            Self::Ultra
        } else {
            Self::High
        }
    }
}

/// Full Dream Lighting configuration — all 21 parameters from the lighting spec.
/// Created via `for_quality()` or manually tuned.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DreamLightingConfig {
    // ── RT features ──
    pub rt_gi_enabled: bool,
    pub rt_shadows_enabled: bool,
    // ── Screen-space effects ──
    pub ssgi_enabled: bool,
    pub ssao_enabled: bool,
    pub ssr_enabled: bool,
    pub taa_enabled: bool,
    pub screen_traces_enabled: bool,
    // ── SHaRC radiance cache ──
    pub sharc_hash_capacity: u32,
    pub sharc_sparse_rate: f32,
    pub sharc_max_bounces: u32,
    pub sharc_grid_log_base: f32,
    // ── Denoiser ──
    pub denoiser_enabled: bool,
    pub denoiser_temporal_alpha: f32,
    // ── Occlusion & motion ──
    pub hiz_enabled: bool,
    pub motion_vectors_enabled: bool,
    // ── Shadows ──
    pub csm_cascades: u32,
    // ── Reflections ──
    pub reflection_max_roughness: f32,
    // ── IBL ──
    pub ibl_resolution: u32,
    // ── Atmospheric ──
    pub volumetric_fog_enabled: bool,
    // ── DOF ──
    pub dof_enabled: bool,
    // ── TSR ──
    pub dream_tsr_enabled: bool,
}

impl Default for DreamLightingConfig {
    fn default() -> Self {
        Self::for_quality(DreamLightingQuality::Medium)
    }
}

impl DreamLightingConfig {
    /// Create a config for a specific quality preset.
    pub fn for_quality(quality: DreamLightingQuality) -> Self {
        match quality {
            // Spec §4.2: IBL ambient only. No RT, no screen traces, no SSGI.
            DreamLightingQuality::Low => Self {
                rt_gi_enabled: false,
                rt_shadows_enabled: false,
                ssgi_enabled: false,
                ssao_enabled: false,
                ssr_enabled: false,
                taa_enabled: false,
                screen_traces_enabled: false,
                sharc_hash_capacity: 0,
                sharc_sparse_rate: 0.0,
                sharc_max_bounces: 0,
                sharc_grid_log_base: 2.0,
                denoiser_enabled: false,
                denoiser_temporal_alpha: 0.0,
                hiz_enabled: false,
                motion_vectors_enabled: false,
                csm_cascades: 2,
                reflection_max_roughness: 0.0,
                ibl_resolution: 32,
                volumetric_fog_enabled: false,
                dof_enabled: false,
                dream_tsr_enabled: false,
            },
            // Spec §4.2: SSGI + SSAO + SSR + TAA. No RT.
            DreamLightingQuality::Medium => Self {
                rt_gi_enabled: false,
                rt_shadows_enabled: false,
                ssgi_enabled: true,
                ssao_enabled: true,
                ssr_enabled: true,
                taa_enabled: true,
                screen_traces_enabled: false,
                sharc_hash_capacity: 0,
                sharc_sparse_rate: 0.0,
                sharc_max_bounces: 0,
                sharc_grid_log_base: 2.0,
                denoiser_enabled: false,
                denoiser_temporal_alpha: 0.0,
                hiz_enabled: false,
                motion_vectors_enabled: true,
                csm_cascades: 4,
                reflection_max_roughness: 0.3,
                ibl_resolution: 64,
                volumetric_fog_enabled: false,
                dof_enabled: false,
                dream_tsr_enabled: false,
            },
            // Spec §4.2: Screen traces + SHaRC + RT shadows.
            DreamLightingQuality::High => Self {
                rt_gi_enabled: true,
                rt_shadows_enabled: true,
                ssgi_enabled: false,
                ssao_enabled: true,
                ssr_enabled: true,
                taa_enabled: true,
                screen_traces_enabled: true,
                sharc_hash_capacity: 1 << 18, // 262K
                sharc_sparse_rate: 0.02,
                sharc_max_bounces: 2,
                sharc_grid_log_base: 2.5,
                denoiser_enabled: true,
                denoiser_temporal_alpha: 0.80,
                hiz_enabled: true,
                motion_vectors_enabled: true,
                csm_cascades: 0, // RT shadows replace CSM
                reflection_max_roughness: 0.4,
                ibl_resolution: 128,
                volumetric_fog_enabled: false,
                dof_enabled: false,
                dream_tsr_enabled: false,
            },
            // Spec §4.2: Full Dream Lighting with multi-bounce + denoiser.
            DreamLightingQuality::Ultra => Self {
                rt_gi_enabled: true,
                rt_shadows_enabled: true,
                ssgi_enabled: false,
                ssao_enabled: true,
                ssr_enabled: true,
                taa_enabled: true,
                screen_traces_enabled: true,
                sharc_hash_capacity: 1 << 20, // 1M
                sharc_sparse_rate: 0.04,
                sharc_max_bounces: 3,
                sharc_grid_log_base: 2.0,
                denoiser_enabled: true,
                denoiser_temporal_alpha: 0.85,
                hiz_enabled: true,
                motion_vectors_enabled: true,
                csm_cascades: 0, // RT shadows replace CSM
                reflection_max_roughness: 0.5,
                ibl_resolution: 128,
                volumetric_fog_enabled: true,
                dof_enabled: false,
                dream_tsr_enabled: false,
            },
            // Spec §4.2: Maximum quality with Dream TSR + 5 bounces.
            DreamLightingQuality::Cinematic => Self {
                rt_gi_enabled: true,
                rt_shadows_enabled: true,
                ssgi_enabled: false,
                ssao_enabled: true,
                ssr_enabled: true,
                taa_enabled: false, // replaced by Dream TSR
                screen_traces_enabled: true,
                sharc_hash_capacity: 1 << 22, // 4M
                sharc_sparse_rate: 0.08,
                sharc_max_bounces: 5,
                sharc_grid_log_base: 1.5,
                denoiser_enabled: true,
                denoiser_temporal_alpha: 0.90,
                hiz_enabled: true,
                motion_vectors_enabled: true,
                csm_cascades: 0, // RT shadows replace CSM
                reflection_max_roughness: 0.6,
                ibl_resolution: 256,
                volumetric_fog_enabled: true,
                dof_enabled: true,
                dream_tsr_enabled: true,
            },
        }
    }

    /// The quality preset this config most closely matches (if any).
    pub fn infer_quality(&self) -> DreamLightingQuality {
        if self.dream_tsr_enabled {
            DreamLightingQuality::Cinematic
        } else if self.rt_gi_enabled && self.sharc_hash_capacity >= (1 << 20) {
            DreamLightingQuality::Ultra
        } else if self.rt_gi_enabled {
            DreamLightingQuality::High
        } else if self.ssgi_enabled {
            DreamLightingQuality::Medium
        } else {
            DreamLightingQuality::Low
        }
    }
}

impl Default for PbrMaterial {
    fn default() -> Self {
        Self {
            base_color: [1.0, 1.0, 1.0, 1.0],
            emissive: [0.0, 0.0, 0.0],
            roughness: 0.5,
            metallic: 0.0,
            base_color_tex: None,
            normal_tex: None,
            emissive_tex: None,
            roughness_metalness_tex: None,
            occlusion_tex: None,
            occlusion_strength: 1.0,
            normal_scale: 1.0,
            emissive_strength: 1.0,
            alpha_mode: AlphaMode::Opaque,
            double_sided: false,
        }
    }
}

impl PbrMaterial {
    pub fn painted_metal() -> Self {
        Self {
            roughness: 0.4,
            metallic: 1.0,
            base_color: [0.8, 0.1, 0.1, 1.0],
            ..Default::default()
        }
    }

    pub fn brushed_steel() -> Self {
        Self {
            roughness: 0.3,
            metallic: 1.0,
            base_color: [0.7, 0.7, 0.7, 1.0],
            ..Default::default()
        }
    }

    pub fn matte_plastic() -> Self {
        Self {
            roughness: 0.9,
            metallic: 0.0,
            base_color: [0.8, 0.8, 0.8, 1.0],
            ..Default::default()
        }
    }

    pub fn glossy_ceramic() -> Self {
        Self {
            roughness: 0.15,
            metallic: 0.0,
            base_color: [0.95, 0.95, 0.9, 1.0],
            ..Default::default()
        }
    }

    pub fn rough_wood() -> Self {
        Self {
            roughness: 0.85,
            metallic: 0.0,
            base_color: [0.55, 0.35, 0.2, 1.0],
            ..Default::default()
        }
    }

    pub fn polished_marble() -> Self {
        Self {
            roughness: 0.2,
            metallic: 0.0,
            base_color: [0.95, 0.93, 0.88, 1.0],
            ..Default::default()
        }
    }

    pub fn wet_stone() -> Self {
        Self {
            roughness: 0.3,
            metallic: 0.0,
            base_color: [0.4, 0.4, 0.4, 1.0],
            ..Default::default()
        }
    }

    pub fn gold() -> Self {
        Self {
            roughness: 0.25,
            metallic: 1.0,
            base_color: [1.0, 0.76, 0.33, 1.0],
            ..Default::default()
        }
    }

    pub fn copper() -> Self {
        Self {
            roughness: 0.3,
            metallic: 1.0,
            base_color: [0.95, 0.64, 0.54, 1.0],
            ..Default::default()
        }
    }

    pub fn rubber() -> Self {
        Self {
            roughness: 0.95,
            metallic: 0.0,
            base_color: [0.15, 0.15, 0.15, 1.0],
            ..Default::default()
        }
    }

    pub fn glass() -> Self {
        Self {
            roughness: 0.05,
            metallic: 0.0,
            alpha_mode: AlphaMode::Blend,
            base_color: [1.0, 1.0, 1.0, 0.3],
            ..Default::default()
        }
    }

    pub fn fabric() -> Self {
        Self {
            roughness: 0.8,
            metallic: 0.0,
            base_color: [0.6, 0.5, 0.4, 1.0],
            ..Default::default()
        }
    }

    pub fn skin() -> Self {
        Self {
            roughness: 0.5,
            metallic: 0.0,
            base_color: [0.9, 0.7, 0.6, 1.0],
            ..Default::default()
        }
    }

    pub fn emissive_panel() -> Self {
        Self {
            emissive: [5.0, 5.0, 5.0],
            emissive_strength: 2.0,
            base_color: [0.1, 0.1, 0.1, 1.0],
            ..Default::default()
        }
    }
}

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

    #[test]
    fn alpha_mode_default_opaque() {
        assert_eq!(AlphaMode::default(), AlphaMode::Opaque);
    }

    #[test]
    fn pbr_material_default() {
        let m = PbrMaterial::default();
        assert_eq!(m.base_color, [1.0, 1.0, 1.0, 1.0]);
        assert_eq!(m.roughness, 0.5);
        assert_eq!(m.metallic, 0.0);
        assert!(!m.double_sided);
    }

    #[test]
    fn alpha_mask_cutoff() {
        let mode = AlphaMode::Mask { cutoff: 0.5 };
        if let AlphaMode::Mask { cutoff } = mode {
            assert_eq!(cutoff, 0.5);
        } else {
            panic!("expected Mask");
        }
    }

    #[test]
    fn serde_roundtrip() {
        let m = PbrMaterial {
            roughness: 0.8,
            metallic: 1.0,
            alpha_mode: AlphaMode::Blend,
            ..Default::default()
        };
        let json = serde_json::to_string(&m).unwrap();
        let back: PbrMaterial = serde_json::from_str(&json).unwrap();
        assert_eq!(m, back);
    }

    #[test]
    fn pbr_material_new_fields_default() {
        let m = PbrMaterial::default();
        assert_eq!(m.roughness_metalness_tex, None);
        assert_eq!(m.occlusion_tex, None);
        assert_eq!(m.occlusion_strength, 1.0);
        assert_eq!(m.normal_scale, 1.0);
        assert_eq!(m.emissive_strength, 1.0);
    }

    #[test]
    fn scene_dream_mode_default() {
        assert_eq!(SceneDreamMode::default(), SceneDreamMode::PbrDefault);
    }

    #[test]
    fn rt_quality_default() {
        assert_eq!(RtQuality::default(), RtQuality::Full);
    }

    #[test]
    fn scene_dream_mode_ray_traced() {
        let mode = SceneDreamMode::PbrRayTraced(RtQuality::Full);
        assert_ne!(mode, SceneDreamMode::PbrDefault);
        let mode2 = SceneDreamMode::PbrRayTraced(RtQuality::ShadowsOnly);
        assert_ne!(mode, mode2);
    }

    #[test]
    fn serde_roundtrip_rt_quality() {
        let q = RtQuality::GiOnly;
        let json = serde_json::to_string(&q).unwrap();
        let back: RtQuality = serde_json::from_str(&json).unwrap();
        assert_eq!(q, back);
    }

    #[test]
    fn serde_roundtrip_pbr_ray_traced() {
        let mode = SceneDreamMode::PbrRayTraced(RtQuality::Full);
        let json = serde_json::to_string(&mode).unwrap();
        let back: SceneDreamMode = serde_json::from_str(&json).unwrap();
        assert_eq!(mode, back);
    }

    #[test]
    fn tonemap_operator_default() {
        assert_eq!(TonemapOperator::default(), TonemapOperator::AcesFilmic);
    }

    #[test]
    fn material_class_variants() {
        let variants = [
            MaterialClass::PbrLit,
            MaterialClass::PbrLitUntextured,
            MaterialClass::PbrEmissive,
            MaterialClass::PbrMasked,
            MaterialClass::PbrTransparent,
            MaterialClass::Unlit,
            MaterialClass::SpriteLit2D,
            MaterialClass::SpriteUnlit2D,
        ];
        assert_eq!(variants.len(), 8);
    }

    #[test]
    fn preset_painted_metal() {
        let m = PbrMaterial::painted_metal();
        assert_eq!(m.roughness, 0.4);
        assert_eq!(m.metallic, 1.0);
        assert_eq!(m.base_color, [0.8, 0.1, 0.1, 1.0]);
    }

    #[test]
    fn preset_glass_is_blend() {
        let m = PbrMaterial::glass();
        assert_eq!(m.alpha_mode, AlphaMode::Blend);
        assert_eq!(m.base_color[3], 0.3);
    }

    #[test]
    fn serde_roundtrip_scene_dream_mode() {
        let mode = SceneDreamMode::SpriteLit2D;
        let json = serde_json::to_string(&mode).unwrap();
        let back: SceneDreamMode = serde_json::from_str(&json).unwrap();
        assert_eq!(mode, back);
    }

    #[test]
    fn serde_roundtrip_tonemap() {
        let op = TonemapOperator::Uncharted2;
        let json = serde_json::to_string(&op).unwrap();
        let back: TonemapOperator = serde_json::from_str(&json).unwrap();
        assert_eq!(op, back);
    }

    #[test]
    fn serde_roundtrip_material_class() {
        let cls = MaterialClass::PbrEmissive;
        let json = serde_json::to_string(&cls).unwrap();
        let back: MaterialClass = serde_json::from_str(&json).unwrap();
        assert_eq!(cls, back);
    }

    // ── Dream Lighting tests ──

    #[test]
    fn dream_lighting_quality_default() {
        assert_eq!(DreamLightingQuality::default(), DreamLightingQuality::Medium);
    }

    #[test]
    fn dream_lighting_config_default_matches_medium() {
        let config = DreamLightingConfig::default();
        let medium = DreamLightingConfig::for_quality(DreamLightingQuality::Medium);
        assert_eq!(config.rt_gi_enabled, medium.rt_gi_enabled);
        assert_eq!(config.ssao_enabled, medium.ssao_enabled);
        assert_eq!(config.csm_cascades, medium.csm_cascades);
        assert!(!config.hiz_enabled); // spec §4.2: Medium has no Hi-Z
        assert_eq!(config.ibl_resolution, 64); // spec §4.2
        assert!((config.reflection_max_roughness - 0.3).abs() < 0.01);
    }

    #[test]
    fn quality_preset_low_no_rt() {
        let config = DreamLightingConfig::for_quality(DreamLightingQuality::Low);
        assert!(!config.rt_gi_enabled);
        assert!(!config.rt_shadows_enabled);
        assert!(!config.ssgi_enabled);
        assert!(!config.ssao_enabled); // spec §4.2: Low has no SSAO
        assert!(!config.taa_enabled); // spec §4.2: Low has no TAA
        assert_eq!(config.ibl_resolution, 32);
        assert_eq!(config.csm_cascades, 2);
    }

    #[test]
    fn quality_preset_high_has_rt() {
        let config = DreamLightingConfig::for_quality(DreamLightingQuality::High);
        assert!(config.rt_gi_enabled);
        assert!(config.rt_shadows_enabled);
        assert!(config.screen_traces_enabled);
        assert_eq!(config.sharc_hash_capacity, 1 << 18); // spec: 262K
        assert_eq!(config.sharc_max_bounces, 2); // spec: 2
        assert_eq!(config.csm_cascades, 0); // spec: RT replaces CSM
        assert!((config.sharc_sparse_rate - 0.02).abs() < 0.001);
        assert!((config.sharc_grid_log_base - 2.5).abs() < 0.01);
        assert!((config.denoiser_temporal_alpha - 0.80).abs() < 0.01);
        assert_eq!(config.ibl_resolution, 128);
    }

    #[test]
    fn quality_preset_cinematic_has_tsr() {
        let config = DreamLightingConfig::for_quality(DreamLightingQuality::Cinematic);
        assert!(config.dream_tsr_enabled);
        assert!(!config.taa_enabled); // TSR replaces TAA
        assert_eq!(config.sharc_max_bounces, 5); // spec: 5
        assert_eq!(config.sharc_hash_capacity, 1 << 22);
        assert_eq!(config.csm_cascades, 0); // spec: RT replaces CSM
        assert_eq!(config.ibl_resolution, 256);
        assert!((config.sharc_grid_log_base - 1.5).abs() < 0.01);
        assert!((config.denoiser_temporal_alpha - 0.90).abs() < 0.01);
        assert!((config.reflection_max_roughness - 0.6).abs() < 0.01);
    }

    #[test]
    fn auto_detect_no_rt_64mb_returns_medium() {
        let q = DreamLightingQuality::auto_detect(false, 64 * 1024 * 1024, 0);
        assert_eq!(q, DreamLightingQuality::Medium);
    }

    #[test]
    fn auto_detect_no_rt_low_storage_returns_low() {
        let q = DreamLightingQuality::auto_detect(false, 32 * 1024 * 1024, 0);
        assert_eq!(q, DreamLightingQuality::Low);
    }

    #[test]
    fn auto_detect_rt_16m_tlas_returns_ultra() {
        let q = DreamLightingQuality::auto_detect(true, 512 * 1024 * 1024, 16_000_000);
        assert_eq!(q, DreamLightingQuality::Ultra);
    }

    #[test]
    fn auto_detect_rt_below_16m_returns_high() {
        let q = DreamLightingQuality::auto_detect(true, 256 * 1024 * 1024, 100_000);
        assert_eq!(q, DreamLightingQuality::High);
    }

    #[test]
    fn infer_quality_roundtrip() {
        for quality in [
            DreamLightingQuality::Low,
            DreamLightingQuality::Medium,
            DreamLightingQuality::High,
            DreamLightingQuality::Ultra,
            DreamLightingQuality::Cinematic,
        ] {
            let config = DreamLightingConfig::for_quality(quality);
            assert_eq!(
                config.infer_quality(),
                quality,
                "infer_quality failed for {:?}",
                quality
            );
        }
    }

    #[test]
    fn serde_roundtrip_dream_lighting_quality() {
        let q = DreamLightingQuality::Cinematic;
        let json = serde_json::to_string(&q).unwrap();
        let back: DreamLightingQuality = serde_json::from_str(&json).unwrap();
        assert_eq!(q, back);
    }

    #[test]
    fn serde_roundtrip_dream_lighting_config() {
        let config = DreamLightingConfig::for_quality(DreamLightingQuality::Ultra);
        let json = serde_json::to_string(&config).unwrap();
        let back: DreamLightingConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config.rt_gi_enabled, back.rt_gi_enabled);
        assert_eq!(config.sharc_hash_capacity, back.sharc_hash_capacity);
        assert_eq!(config.dream_tsr_enabled, back.dream_tsr_enabled);
    }
}