dreamwell-runtime 1.0.0

Dreamwell Runtime — cross-platform GPU-accelerated game client
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
// RuntimeApp — implements winit ApplicationHandler for the game loop.

use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;
use winit::window::WindowId;

use dreamwell_engine::game_object::PrimitiveKind;
use dreamwell_engine::TopologyLayer;
use dreamwell_fabric::packets::SyncPacket;

use crate::authority::{AuthorityClient, AuthorityEvent, LocalAuthority};
use crate::game_state::GameState;
use crate::input::InputState;
use crate::play::SimulationService;
use crate::renderer::SceneRenderer;
use crate::scene::Scene;
use crate::sync::stage::StagingBuffer;
use crate::time::FrameTimer;
use crate::window::WindowState;
use crate::{AuthorityMode, RuntimeConfig};
use dreamwell_fabric::decoder::{CausalEngineDecoder, DecoderInput};

// ── Chase Camera Constants ────────────────────────────────────────────
// Tuned for responsive third-person feel: camera tracks player with
// minimal perceived lag while avoiding mechanical snap.
//
// Reference: Unreal SpringArm defaults (lag speed 10, rotation lag speed 10).
// We use dt-scaled exponential lerp: alpha = 1 - e^(-rate * dt).
// At 60fps (dt=0.0167): rate=16 → alpha≈0.23 (4-frame 90% settle).

/// Minimum camera pitch (radians). -0.3 ≈ -17° allows looking slightly below horizon.
const MIN_PITCH: f32 = -0.3;
/// Maximum camera pitch (radians). 1.40 ≈ 80° near-overhead view.
const MAX_PITCH: f32 = 1.40;
/// Minimum camera distance from player (meters).
const MIN_CAMERA_DIST: f32 = 0.5;
/// Maximum camera distance from player (meters).
const MAX_CAMERA_DIST: f32 = 200.0;
/// Default camera distance from player (meters). 3.0m — tight third-person for 0.4m capsule.
const DEFAULT_CAMERA_DIST: f32 = 3.0;
/// Camera position smoothing rate. Higher = snappier. 16 ≈ 4-frame settle at 60fps.
const CAMERA_POSITION_LERP_RATE: f32 = 16.0;
/// Camera look-at smoothing rate. Slightly faster than position for crisp tracking.
const CAMERA_LOOKAT_LERP_RATE: f32 = 20.0;
/// Zoom smoothing rate.
const ZOOM_LERP_RATE: f32 = 14.0;
/// Over-shoulder horizontal offset (meters). Subtle — keeps character slightly left of center.
const SHOULDER_OFFSET: f32 = 0.3;
/// Look-at target height above player origin (meters). ~waist/chest height for particle centroid.
const LOOKAT_HEIGHT: f32 = 0.9;
/// Extra camera pull-back distance while sprinting (meters).
const SPRINT_PULL_BACK: f32 = 1.0;

/// Form-aware camera tuning profile.
/// Lerped between Cohere and Wave forms based on coherence parameter.
pub struct CameraProfile {
    pub boom_length: f32,
    pub yaw_lag: f32,
    pub fov: f32,
    pub shoulder_offset: f32,
    pub lookat_height: f32,
}

impl CameraProfile {
    /// Compact fibonacci particle — tighter camera.
    pub fn cohere() -> Self {
        Self {
            boom_length: 5.0,
            yaw_lag: 0.15,
            fov: 60.0,
            shoulder_offset: 0.4,
            lookat_height: 1.2,
        }
    }

    /// Broad wave fabric — wider camera.
    pub fn wave() -> Self {
        Self {
            boom_length: 7.0,
            yaw_lag: 0.25,
            fov: 65.0,
            shoulder_offset: 0.6,
            lookat_height: 1.0,
        }
    }

    /// Linearly interpolate between two profiles.
    pub fn lerp(a: &Self, b: &Self, t: f32) -> Self {
        let t = t.clamp(0.0, 1.0);
        Self {
            boom_length: a.boom_length + (b.boom_length - a.boom_length) * t,
            yaw_lag: a.yaw_lag + (b.yaw_lag - a.yaw_lag) * t,
            fov: a.fov + (b.fov - a.fov) * t,
            shoulder_offset: a.shoulder_offset + (b.shoulder_offset - a.shoulder_offset) * t,
            lookat_height: a.lookat_height + (b.lookat_height - a.lookat_height) * t,
        }
    }
}

/// Error type for runtime operations.
#[derive(Debug)]
pub enum RuntimeError {
    /// A scene or pack loading error.
    Load(String),
    /// Window or GPU initialization error.
    Init(String),
}

impl std::fmt::Display for RuntimeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Load(msg) => write!(f, "load error: {msg}"),
            Self::Init(msg) => write!(f, "init error: {msg}"),
        }
    }
}

impl std::error::Error for RuntimeError {}

/// The runtime application, driven by winit's event loop.
pub struct RuntimeApp {
    config: RuntimeConfig,
    window_state: Option<WindowState>,
    renderer: Option<SceneRenderer>,
    scene: Scene,
    game_state: GameState,
    input: InputState,
    timer: FrameTimer,
    /// Authority backend (local or remote).
    authority: Box<dyn AuthorityClient>,
    /// Staging buffer for authority events awaiting tick-boundary application.
    staging: StagingBuffer,
    /// Per-frame sync packet drained from DreamFabric.
    sync_packet: SyncPacket,
    /// Mounted content pack JSON, stored for deferred scene loading.
    mounted_pack: Option<String>,
    /// Pre-allocated scratch buffer for authority events — reused every frame.
    /// Capacity is set at construction and never reallocated on the hot path.
    authority_events: Vec<AuthorityEvent>,
    /// SimulationService — CausalComputeKernel + SDK dispatch (gate-routed).
    /// Active when a tapestry lock file is loaded (Shapes and Dimensions demo).
    simulation: Option<SimulationService>,
    /// CausalEngineDecoder — formal GPU orchestration (encoder→bridge→decoder).
    decoder: Option<CausalEngineDecoder>,
    /// Chase camera orbit yaw in radians (accumulated from mouse drag).
    camera_orbit_yaw: f32,
    /// Chase camera orbit pitch in radians (clamped to [MIN_PITCH, MAX_PITCH]).
    camera_orbit_pitch: f32,
    /// Current camera distance from player (smoothed toward target).
    camera_distance: f32,
    /// Target camera distance — scroll sets this, actual distance lerps toward it.
    camera_target_distance: f32,
    /// Gilrs context for gamepad input (present only when `gamepad` feature is enabled).
    #[cfg(feature = "gamepad")]
    gilrs: gilrs::Gilrs,
    /// Audio system with OddioBackend (present only when `audio` feature is enabled).
    /// OddioBackend provides spatial 3D audio via oddio + cpal. Falls back to
    /// headless (no-op) mode when no audio device is available.
    #[cfg(feature = "audio")]
    audio: dreamwell_audio::AudioSystem<dreamwell_audio::OddioBackend>,
}

fn create_authority(mode: AuthorityMode) -> Box<dyn AuthorityClient> {
    match mode {
        AuthorityMode::Local => Box::new(LocalAuthority::new()),
        #[cfg(feature = "multiplayer")]
        AuthorityMode::Remote => Box::new(crate::authority::RemoteAuthority::new()),
        #[cfg(not(feature = "multiplayer"))]
        AuthorityMode::Remote => {
            log::warn!("Remote authority requested but multiplayer feature not enabled, falling back to local");
            Box::new(LocalAuthority::new())
        }
    }
}

impl RuntimeApp {
    /// Create a new runtime application.
    ///
    /// Returns `Err` if authority backend creation fails for the requested mode.
    pub fn new(config: RuntimeConfig) -> Result<Self, RuntimeError> {
        let authority = create_authority(config.authority_mode);
        Ok(Self {
            config,
            window_state: None,
            renderer: None,
            scene: Scene::default(),
            game_state: GameState::default(),
            input: InputState::default(),
            timer: FrameTimer::new(),
            authority,
            staging: StagingBuffer::new(),
            sync_packet: SyncPacket::new(),
            mounted_pack: None,
            // Pre-allocate with a reasonable capacity. Reallocates only if
            // more than 64 authority events arrive in a single frame (rare).
            authority_events: Vec::with_capacity(64),
            simulation: None,
            decoder: None,
            camera_orbit_yaw: 0.0,
            camera_orbit_pitch: 0.35, // ~20 degrees above horizon (natural third-person)
            camera_distance: 6.0,
            camera_target_distance: 6.0,
            #[cfg(feature = "gamepad")]
            gilrs: gilrs::Gilrs::new().unwrap_or_else(|e| {
                log::warn!("gamepad_init_failed:{e} — gamepad input disabled");
                // gilrs::Gilrs::new() returns a Result; the error variant also
                // contains a valid (empty) Gilrs instance.
                e.into()
            }),
            #[cfg(feature = "audio")]
            audio: {
                match dreamwell_audio::OddioBackend::new() {
                    Ok(backend) => dreamwell_audio::AudioSystem::new(backend),
                    Err(e) => {
                        log::warn!("audio_init_failed:{e} — falling back to headless");
                        dreamwell_audio::AudioSystem::new(dreamwell_audio::OddioBackend::headless())
                    }
                }
            },
        })
    }

    /// Mount a content pack from JSON. The pack data is stored and available
    /// for subsequent `load_scene` calls to reference.
    ///
    /// This does not immediately alter the running scene; it stages the pack
    /// for deferred loading via `load_scene`.
    pub fn mount_pack(&mut self, pack_json: &str) -> Result<(), String> {
        // Validate that the JSON is at least well-formed.
        if pack_json.is_empty() {
            return Err("mount_pack:empty pack JSON".into());
        }
        // Store the pack for later scene loading.
        self.mounted_pack = Some(pack_json.to_string());
        log::info!("Pack mounted ({} bytes)", pack_json.len());
        Ok(())
    }

    /// Load a scene by name. If a content pack has been mounted, the scene
    /// definition is resolved from the pack. Otherwise, falls back to the
    /// built-in demo scene.
    ///
    /// This is a structural stub that resets the scene and seeds objects.
    /// Full pack-driven scene deserialization is planned for a future release.
    pub fn load_scene(&mut self, scene_name: &str) -> Result<(), String> {
        if scene_name.is_empty() {
            return Err("load_scene:empty scene name".into());
        }
        // Reset scene state.
        self.scene = Scene::default();
        self.game_state = GameState::default();

        if let Some(ref pack_json) = self.mounted_pack {
            match dreamwell_engine::waymark::loader::PackLoader::load_pack_config(pack_json) {
                Ok(pack) => {
                    let loaded = dreamwell_engine::waymark::loader::load_pack_to_scene(&pack);
                    self.scene.game_objects = loaded.objects;
                    log::info!(
                        "Loaded scene '{}' from pack: {} objects",
                        scene_name,
                        self.scene.game_objects.len()
                    );
                    return Ok(());
                }
                Err(e) => {
                    log::warn!("Pack parse failed, falling back to demo: {}", e);
                }
            }
        }

        self.seed_demo_scene();
        log::info!("Scene '{}' loaded (demo fallback)", scene_name);
        Ok(())
    }

    /// Switch authority mode at runtime. Replaces the authority backend and
    /// clears staged events.
    ///
    /// Note: switching from Remote to Local while connected will drop the
    /// remote connection. Switching to Remote requires the `multiplayer`
    /// feature to be enabled; otherwise it falls back to Local with a warning.
    pub fn set_authority_mode(&mut self, mode: AuthorityMode) {
        if mode == self.config.authority_mode {
            return;
        }
        log::info!(
            "Switching authority mode: {:?} -> {:?}",
            self.config.authority_mode,
            mode
        );
        self.authority = create_authority(mode);
        self.staging = StagingBuffer::new();
        self.config.authority_mode = mode;
    }

    /// Load scene from tapestry.lock if available, else seed demo primitives.
    /// When a lock file is present, initializes the full CausalComputeKernel
    /// simulation with gate-routed SDK dispatch per THE_BRAIDED_PATH.
    fn seed_demo_scene(&mut self) {
        // Try loading from tapestry.lock (Shapes and Dimensions or any authored scene).
        if let Some(ref lock_path) = self.config.lock_file {
            if let Ok(json) = std::fs::read_to_string(lock_path) {
                if let Ok(lock) = dreamwell_sdk::tapestry::TapestryLock::from_json(&json) {
                    log::info!("Loading scene from tapestry.lock: {} objects", lock.object_count);
                    self.load_scene_from_lock(&lock);
                    return;
                }
            }
            log::warn!("Failed to load lock file '{}', falling back to demo", lock_path);
        }

        // Fallback: canonical 3D template (player particle + ground + skybox).
        // Uses the same template as CLI `dream up init` and Editor New Project.
        let tmpl = dreamwell_sdk::templates::default_3d_scene();

        // Set active layer to Point (9) BEFORE anything else — template objects live on layer 9.
        // This must happen unconditionally so the observer matches the scene content.
        self.game_state.active_layer = TopologyLayer::Point;

        let scene = &mut self.scene.game_objects;
        for obj in &tmpl.objects {
            let kind = match obj.name.as_str() {
                "Ground" => Some(PrimitiveKind::Plane),
                _ => None,
            };
            let id = if let Some(k) = kind {
                scene.spawn_primitive(obj.name.clone(), k)
            } else {
                scene.spawn(obj.name.clone())
            };
            if let Ok(id) = id {
                if let Some(go) = scene.find_mut(id) {
                    go.transform.position = obj.position;
                    go.transform.scale = obj.scale;
                    go.property_tags = obj.tags.clone();
                    // Transfer material preset from template.
                    if let Some(ref mat) = obj.material {
                        go.property_tags.push(format!("material={mat}"));
                    }
                }
            }
        }

        // Template lights will be added to the renderer's DreamFabric after it's created.
        // Store them for deferred application in the resumed() handler.
        // (GpuScene adds a default directional sun if no lights are explicitly set.)

        log::info!(
            "Demo scene seeded from template '{}': {} objects, {} lights",
            tmpl.name,
            scene.len(),
            tmpl.lights.len(),
        );

        // Initialize SimulationService from template scene.
        let spawn_pos = tmpl
            .objects
            .iter()
            .find(|o| o.tags.iter().any(|t| t == "isInputReceiver"))
            .map(|o| o.position)
            .unwrap_or([0.0, 0.5, 0.0]);

        let mut go_scene = dreamwell_engine::game_object::GameObjectScene::new(tmpl.name.clone());
        for obj in &tmpl.objects {
            let kind = match obj.name.as_str() {
                "Ground" => Some(PrimitiveKind::Plane),
                _ => None,
            };
            let id = if let Some(k) = kind {
                go_scene.spawn_primitive(obj.name.clone(), k)
            } else {
                go_scene.spawn(obj.name.clone())
            };
            if let Ok(id) = id {
                if let Some(go) = go_scene.find_mut(id) {
                    go.transform.position = obj.position;
                    go.transform.scale = obj.scale;
                    go.property_tags = obj.tags.clone();
                }
            }
        }

        let particle_count = dreamwell_metaphors::DEFAULT_PARTICLE_COUNT;
        let mut sim = SimulationService::new(&tmpl.name, crate::play::SimulationMode::Published);
        if let Err(e) = sim.initialize(go_scene, spawn_pos, particle_count) {
            log::error!("Simulation init failed: {e}");
            // Layer is already set to Point — scene will still render even without simulation
        } else {
            self.simulation = Some(sim);
            self.decoder = Some(dreamwell_fabric::decoder::CausalEngineDecoder::new());
        }
        self.game_state.player_position = glam::Vec3::from_array(spawn_pos);

        // Position chase camera behind and above the player.
        // 0.30 rad ≈ 17° elevation — standard third-person overhead angle.
        self.camera_orbit_pitch = 0.30;
        self.camera_distance = DEFAULT_CAMERA_DIST;
        self.camera_target_distance = DEFAULT_CAMERA_DIST;
        let pitch = self.camera_orbit_pitch;
        let yaw = self.camera_orbit_yaw;
        let horiz = pitch.cos() * self.camera_distance;
        let height = pitch.sin() * self.camera_distance;
        let cam_offset = glam::Vec3::new(
            -yaw.cos() * horiz + yaw.sin() * SHOULDER_OFFSET,
            height,
            -yaw.sin() * horiz - yaw.cos() * SHOULDER_OFFSET,
        );
        let player = glam::Vec3::from_array(spawn_pos);
        self.scene.camera.position = player + cam_offset;
        self.scene.camera.center = glam::Vec3::new(spawn_pos[0], spawn_pos[1] + LOOKAT_HEIGHT, spawn_pos[2]);
        self.scene.camera.update_view_matrix();
    }

    /// Load a full scene from TapestryLock and initialize SimulationService.
    /// Follows THE_BRAIDED_PATH: tapestry.lock → Loom::weave → WovenScene
    /// → CausalComputeKernel + DreamGate + SDK Decoherence on layer 9.
    fn load_scene_from_lock(&mut self, lock: &dreamwell_sdk::tapestry::TapestryLock) {
        use dreamwell_engine::loom;

        // Reconstruct GameObjectScene from lock objects.
        let mut scene = dreamwell_engine::game_object::GameObjectScene::new(lock.scene_name.clone());
        for obj in &lock.objects {
            // Determine primitive kind from tags/name for mesh geometry.
            let primitive = Self::infer_primitive_kind(&obj.tags, &obj.name);
            let id = if let Some(kind) = primitive {
                scene.spawn_primitive(obj.name.clone(), kind)
            } else {
                scene.spawn(obj.name.clone())
            };
            if let Ok(id) = id {
                if let Some(go) = scene.find_mut(id) {
                    go.transform.position = obj.position;
                    go.transform.rotation = obj.rotation;
                    go.transform.scale = obj.scale;
                    go.visible = obj.visible;
                    go.parent_id = obj.parent_id;
                    go.property_tags = obj.tags.clone();
                    // Parse topology layer from tags.
                    for tag in &obj.tags {
                        if let Some(rest) = tag.strip_prefix("isTopologyLayer") {
                            if let Ok(layer) = rest.parse::<u8>() {
                                go.topology_layer = layer.min(9);
                            }
                        }
                    }
                }
            }
        }

        // Hydrate tags from template if lock has empty tag arrays.
        Self::hydrate_tags_from_template(&mut scene);

        // Weave through Loom for validation + physics body extraction.
        let woven = match loom::weave(scene, loom::RenderConfig::default()) {
            Ok(w) => w,
            Err(errs) => {
                log::error!("Loom validation failed: {:?}", errs);
                return;
            }
        };

        // Find spawn position (isInputReceiver tag).
        let spawn_pos = woven
            .scene
            .objects
            .iter()
            .find(|o| o.property_tags.iter().any(|t| t == "isInputReceiver"))
            .map(|o| o.transform.position)
            .unwrap_or([0.0, 0.5, 0.0]);

        // Initialize SimulationService with full gate-routed SDK dispatch.
        let mut sim = SimulationService::new(&woven.scene.name, crate::play::SimulationMode::Published);

        // Collect decoherence fields from scene tags.
        sim.decoherence_fields = Self::collect_decoherence_fields(&woven);

        // Set active layer BEFORE simulation init — scene content lives on layer 9.
        self.game_state.active_layer = TopologyLayer::Point;

        // Initialize kernel at spawn point on topology layer 9 (Point).
        // sim.initialize() sets sim.scene internally from the woven scene.
        let particle_count = dreamwell_metaphors::DEFAULT_PARTICLE_COUNT;
        if let Err(e) = sim.initialize(woven.scene, spawn_pos, particle_count) {
            log::error!("Simulation init failed: {e}");
            return;
        }
        self.game_state.player_position = glam::Vec3::from_array(spawn_pos);

        // Store the woven scene as the renderable scene.
        self.scene.game_objects = sim.scene.clone();

        // Initialize chase camera from kernel facing direction.
        let init_yaw = sim
            .encoder
            .as_ref()
            .map(|e| e.kernel().facing_yaw)
            .or_else(|| sim.kernel.as_ref().map(|k| k.facing_yaw));
        if let Some(yaw) = init_yaw {
            self.camera_orbit_yaw = yaw;
        }
        self.camera_orbit_pitch = 0.35; // ~20 degrees above horizon
        self.camera_distance = DEFAULT_CAMERA_DIST;
        self.camera_target_distance = DEFAULT_CAMERA_DIST;

        // Position camera behind and above the spawn point, looking forward.
        let yaw = self.camera_orbit_yaw;
        let pitch = self.camera_orbit_pitch;
        let horiz = pitch.cos() * self.camera_distance;
        let height = pitch.sin() * self.camera_distance;
        let cam_offset = glam::Vec3::new(
            -yaw.cos() * horiz + yaw.sin() * SHOULDER_OFFSET,
            height,
            -yaw.sin() * horiz - yaw.cos() * SHOULDER_OFFSET,
        );
        self.scene.camera.position = glam::Vec3::from_array(spawn_pos) + cam_offset;
        self.scene.camera.center = glam::Vec3::new(spawn_pos[0], spawn_pos[1] + LOOKAT_HEIGHT, spawn_pos[2]);
        self.scene.camera.update_view_matrix();

        // Diagnostic: count mesh bindings for debugging visibility issues.
        let mesh_count = self
            .scene
            .game_objects
            .objects
            .iter()
            .filter(|o| matches!(o.mesh, dreamwell_engine::game_object::MeshBinding::Primitive { .. }))
            .count();
        let visible_mesh_count = self
            .scene
            .game_objects
            .objects
            .iter()
            .filter(|o| matches!(o.mesh, dreamwell_engine::game_object::MeshBinding::Primitive { .. }) && o.visible)
            .count();
        for obj in &self.scene.game_objects.objects {
            log::debug!(
                "  obj '{}': mesh={:?}, visible={}, pos=[{:.1},{:.1},{:.1}]",
                obj.name,
                obj.mesh,
                obj.visible,
                obj.transform.position[0],
                obj.transform.position[1],
                obj.transform.position[2],
            );
        }
        log::info!(
            "Tapestry scene loaded: {} objects ({} meshes, {} visible), spawn at [{:.1}, {:.1}, {:.1}], layer 9 (Point)",
            self.scene.game_objects.len(),
            mesh_count, visible_mesh_count,
            spawn_pos[0], spawn_pos[1], spawn_pos[2],
        );

        self.simulation = Some(sim);
        self.decoder = Some(CausalEngineDecoder::new());
    }

    /// Convert CPU InterferenceKernels to GPU-uploadable GpuParticleKernel array.
    /// Maps 10 Complex pairs × 3 axes to flat 60-float per-particle kernel.
    fn convert_interference_kernels(
        kernels: &dreamwell_quantum::InterferenceKernels,
        particle_count: u32,
    ) -> Vec<dreamwell_gpu::dreamlet_catalog::GpuParticleKernel> {
        let n = (particle_count as usize).min(kernels.kernels.len());
        let mut gpu_kernels = Vec::with_capacity(n);
        for p in 0..n {
            let mut flat = [0.0f32; 60];
            for pair in 0..10 {
                for axis in 0..3 {
                    let c = kernels.kernels[p][pair][axis];
                    flat[pair * 6 + axis * 2] = c.re;
                    flat[pair * 6 + axis * 2 + 1] = c.im;
                }
            }
            gpu_kernels.push(dreamwell_gpu::dreamlet_catalog::GpuParticleKernel {
                kernels: flat,
                _pad: [0.0; 4],
            });
        }
        gpu_kernels
    }

    /// Extract quantum DecoherenceFields from woven scene objects.
    fn collect_decoherence_fields(
        woven: &dreamwell_engine::loom::WovenScene,
    ) -> Vec<dreamwell_quantum::DecoherenceField> {
        use dreamwell_engine::input::parse_decoherence_tag;
        use dreamwell_engine::input::wave::{DecoherenceTagValue, WaveForm};

        fn to_quantum_form(f: WaveForm) -> dreamwell_quantum::WaveForm {
            match f {
                WaveForm::Particle => dreamwell_quantum::WaveForm::Particle,
                WaveForm::Humanoid => dreamwell_quantum::WaveForm::Humanoid,
                WaveForm::Vehicle => dreamwell_quantum::WaveForm::Vehicle,
                WaveForm::Fluid => dreamwell_quantum::WaveForm::Fluid,
            }
        }

        let mut fields = Vec::new();
        for obj in &woven.scene.objects {
            let is_zone = obj.property_tags.iter().any(|t| t == "isDecoherenceZone");
            if !is_zone {
                continue;
            }

            let mut target_form = WaveForm::Humanoid;
            let mut gamma = 2.0f32;
            let mut clip = String::new();
            for tag in &obj.property_tags {
                if let Some(val) = parse_decoherence_tag(tag) {
                    match val {
                        DecoherenceTagValue::Form(form, animation) => {
                            target_form = form;
                            clip = animation;
                        }
                        DecoherenceTagValue::Gamma(rate) => {
                            gamma = rate;
                        }
                    }
                }
            }

            let radius = obj
                .property_tags
                .iter()
                .find_map(|t| t.strip_prefix("decohere.radius=").and_then(|v| v.parse::<f32>().ok()))
                .unwrap_or(10.0);

            fields.push(dreamwell_quantum::DecoherenceField {
                position: obj.transform.position,
                radius,
                target_form: to_quantum_form(target_form),
                gamma,
                animation_clip: clip,
                source_tag: "isDecoherenceZone".into(),
            });
        }
        fields
    }

    #[cfg(feature = "bundled-skybox")]
    fn default_skybox_bytes() -> &'static [u8] {
        include_bytes!("../assets/skyboxes/textures/basic_skybox.jpeg")
    }

    #[cfg(not(feature = "bundled-skybox"))]
    fn default_skybox_bytes() -> &'static [u8] {
        &[]
    }

    /// Infer PrimitiveKind from object tags and name.
    /// Returns None for objects that shouldn't have geometry (skybox, player, zone markers).
    fn infer_primitive_kind(tags: &[String], name: &str) -> Option<PrimitiveKind> {
        let has_tag = |t: &str| tags.iter().any(|s| s == t);
        // Skybox, player avatar, and zone markers have no mesh geometry.
        if has_tag("isSkybox") || has_tag("isInputReceiver") || has_tag("isPlayer") {
            return None;
        }
        // Zone topology markers (no position/scale) are invisible.
        if name.starts_with("Zone ") {
            return None;
        }
        // Ground/floor → Plane (rendered as a flat slab via cube with thin Y scale)
        if has_tag("isGround") {
            return Some(PrimitiveKind::Cube);
        }
        // Walls → Cube
        if has_tag("isWall") || has_tag("isCollider") {
            return Some(PrimitiveKind::Cube);
        }
        // POI/Fractal → Sphere
        if has_tag("poi") || has_tag("isInteractable") || has_tag("isFractal") {
            return Some(PrimitiveKind::Sphere);
        }
        // Default: Cube for any remaining visible object
        if !tags.is_empty() {
            return Some(PrimitiveKind::Cube);
        }
        None
    }

    /// Hydrate tags from template when lock file has empty tags arrays.
    /// Also assigns MeshBinding::Primitive based on hydrated tags, since
    /// objects from stale locks have MeshBinding::None.
    fn hydrate_tags_from_template(scene: &mut dreamwell_engine::game_object::GameObjectScene) {
        if scene.objects.iter().any(|o| !o.property_tags.is_empty()) {
            // Tags already present — still ensure mesh bindings are assigned.
            for obj in &mut scene.objects {
                if matches!(obj.mesh, dreamwell_engine::game_object::MeshBinding::None) {
                    if let Some(kind) = Self::infer_primitive_kind(&obj.property_tags, &obj.name) {
                        obj.mesh = dreamwell_engine::game_object::MeshBinding::Primitive {
                            kind,
                            color: [0.7, 0.7, 0.7, 1.0],
                        };
                    }
                }
            }
            return;
        }
        let tmpl = dreamwell_sdk::templates::shapes_and_dimensions();
        for obj in &mut scene.objects {
            if let Some(tmpl_obj) = tmpl.objects.iter().find(|t| t.name == obj.name) {
                obj.property_tags = tmpl_obj.tags.clone();
                for tag in &obj.property_tags {
                    if let Some(rest) = tag.strip_prefix("isTopologyLayer") {
                        if let Ok(layer) = rest.parse::<u8>() {
                            obj.topology_layer = layer.min(9);
                        }
                    }
                }
                // Assign mesh binding from hydrated tags.
                if matches!(obj.mesh, dreamwell_engine::game_object::MeshBinding::None) {
                    if let Some(kind) = Self::infer_primitive_kind(&obj.property_tags, &obj.name) {
                        obj.mesh = dreamwell_engine::game_object::MeshBinding::Primitive {
                            kind,
                            color: [0.7, 0.7, 0.7, 1.0],
                        };
                    }
                }
            }
        }
        log::info!("Tag hydration: applied template tags to stale lock");
    }
}

impl ApplicationHandler for RuntimeApp {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window_state.is_some() {
            return;
        }

        let window_state = WindowState::new(event_loop, &self.config.title, self.config.width, self.config.height);
        let renderer = SceneRenderer::with_msaa(&window_state, self.config.msaa_samples);
        self.window_state = Some(window_state);
        self.renderer = Some(renderer);

        // Validate GPU shaders via naga IR (no GPU device needed).
        let naga_report = dreamwell_naga::validate_startup();
        if naga_report.is_ok() {
            log::info!(
                "Naga: {}/{} shaders OK",
                naga_report.passed,
                naga_report.shader_results.len()
            );
        } else {
            log::warn!("Naga validation warnings:\n{}", naga_report.summary());
        }

        // Seed demo scene and upload to GPU.
        self.seed_demo_scene();
        if let (Some(ws), Some(r)) = (&self.window_state, &mut self.renderer) {
            // Set projection matrix from actual window dimensions.
            let aspect = ws.surface_config.width as f32 / ws.surface_config.height.max(1) as f32;
            self.scene.camera.update_projection(aspect, 60.0);

            r.fabric.upload_scene(&ws.device, &self.scene.game_objects);

            // Add template directional sun — required for PBR lighting.
            // Without this, Cook-Torrance BRDF receives zero light and outputs black.
            {
                let sun_dir = glam::Vec3::new(0.3, -1.0, 0.4).normalize();
                r.fabric.gpu_scene_mut().scene_lights.add_directional(
                    dreamwell_engine::lighting::DirectionalLightDesc {
                        direction: sun_dir.to_array(),
                        color: [1.0, 0.98, 0.92],
                        intensity_lux: 2.0,
                    },
                );
            }

            // Load skybox environment map.
            let skybox_bytes = Self::default_skybox_bytes();
            if !skybox_bytes.is_empty() {
                if r.fabric.load_skybox_image(&ws.device, &ws.queue, skybox_bytes) {
                    log::info!("Skybox loaded ({} bytes)", skybox_bytes.len());
                } else {
                    log::warn!("Skybox decode failed");
                }
            }

            // If simulation is active (tapestry.lock loaded), initialize particle dreamlets
            // for the wave controller avatar. 256 particles on golden spiral, uploaded to
            // DreamFabric for GPU particle physics compute (THE_BRAIDED_PATH Phase G).
            if let Some(ref sim) = self.simulation {
                if !sim.particle_offsets.is_empty() {
                    let spawn_pos = sim
                        .encoder
                        .as_ref()
                        .map(|e| e.kernel().position)
                        .or_else(|| sim.kernel.as_ref().map(|k| k.position))
                        .unwrap_or([0.0, 0.5, 0.0]);
                    let dreamlets = dreamwell_gpu::dreamlet_catalog::generate_particle(
                        spawn_pos,
                        sim.particle_offsets.len() as u32,
                        0.8,
                        [0.4, 0.6, 1.0, 0.85],
                        &sim.particle_offsets,
                    );
                    r.fabric.ensure_dreamlet_catalog_ready(&ws.device, &ws.queue);
                    r.fabric.init_particle_physics(&ws.device);
                    r.fabric.upload_dreamlets(&ws.queue, &dreamlets);
                    r.fabric.mark_particle_uploaded();

                    // Initialize quantum bridge (CPU→GPU density matrix upload).
                    let particle_count = dreamlets.len() as u32;
                    r.fabric.init_quantum_bridge(&ws.device, particle_count);

                    // Upload per-particle interference kernels from quantum state (once).
                    let quantum_kernels = sim
                        .encoder
                        .as_ref()
                        .map(|e| &e.kernel().quantum.kernels)
                        .or_else(|| sim.kernel.as_ref().map(|k| &k.quantum.kernels));
                    if let Some(kernels) = quantum_kernels {
                        let gpu_kernels = Self::convert_interference_kernels(kernels, particle_count);
                        r.fabric.upload_interference_kernels(&ws.queue, &gpu_kernels);
                    }

                    log::info!(
                        "Particle dreamlets uploaded: {} particles, quantum bridge active",
                        dreamlets.len()
                    );
                }
            }

            // Warm up pipeline cache synchronously before first frame.
            let mut warmup = dreamwell_fabric::WarmupPhase::standard_entries();
            warmup.complete_all(&ws.device, r.fabric.pipeline_cache_mut());
            r.fabric.init_post_process_pipelines(&ws.device);
            log::info!("Tapestry warmed: {} pipelines compiled", warmup.total());
        }

        // Configure render mode. PbrDefault auto-enables HDR (Rgba16Float) framebuffer.
        // Particles render to HDR, then tonemap composites to swapchain surface.
        // Without tonemap enabled, HDR content is never presented — particles invisible.
        if let (Some(_ws), Some(r)) = (&self.window_state, &mut self.renderer) {
            r.set_scene_dream_mode(dreamwell_engine::material::SceneDreamMode::PbrDefault);
            // for_pbr() enables bloom + ACES tonemap — ensures HDR→surface compositing.
            r.set_post_process_config(dreamwell_gpu::post::PostProcessConfig::for_pbr());
            log::info!("Render mode: PbrDefault, post-processing: bloom + ACES tonemap");
        }

        log::info!("Runtime initialized");
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
        match event {
            WindowEvent::CloseRequested => {
                event_loop.exit();
            }
            WindowEvent::Resized(size) => {
                if let Some(ws) = &mut self.window_state {
                    ws.resize(size.width, size.height);
                    if let Some(r) = &mut self.renderer {
                        r.resize(size.width, size.height, &ws.device);
                    }
                }
            }
            WindowEvent::KeyboardInput { event, .. } => {
                self.input.handle_keyboard(&event);
                if let winit::keyboard::PhysicalKey::Code(code) = event.physical_key {
                    use winit::event::ElementState;
                    use winit::keyboard::KeyCode;
                    match (code, event.state) {
                        // TAB: cycle active metaphor profile (Wave → Fibonacci → Stream → Wave).
                        (KeyCode::Tab, ElementState::Pressed) => {
                            if let Some(ref mut sim) = self.simulation {
                                let name = sim.cycle_metaphor();
                                log::info!("Metaphor: {name}");
                            }
                        }
                        // Q: Cohere form (fibonacci, coherent particles)
                        (KeyCode::KeyQ, ElementState::Pressed) => {
                            if let Some(ref mut sim) = self.simulation {
                                sim.set_coherence_target(1.0);
                            }
                        }
                        // E: Wave form (sinusoidal, decoherent particles)
                        (KeyCode::KeyE, ElementState::Pressed) => {
                            if let Some(ref mut sim) = self.simulation {
                                sim.set_coherence_target(0.0);
                            }
                        }
                        // Ctrl: Gather mode (hold)
                        (KeyCode::ControlLeft | KeyCode::ControlRight, ElementState::Pressed) => {
                            if let Some(ref mut sim) = self.simulation {
                                sim.set_gather(true);
                            }
                        }
                        (KeyCode::ControlLeft | KeyCode::ControlRight, ElementState::Released) => {
                            if let Some(ref mut sim) = self.simulation {
                                sim.set_gather(false);
                            }
                        }
                        _ => {}
                    }
                }
            }
            WindowEvent::MouseInput { state, button, .. } => {
                self.input.handle_mouse_button(button, state);
                // Primary mouse button: emit strength
                if button == winit::event::MouseButton::Left {
                    if let Some(ref mut sim) = self.simulation {
                        match state {
                            winit::event::ElementState::Pressed => sim.set_emit_strength(1.0),
                            winit::event::ElementState::Released => sim.set_emit_strength(0.0),
                        }
                    }
                }
            }
            WindowEvent::CursorMoved { position, .. } => {
                self.input.handle_cursor_move(position.x as f32, position.y as f32);
            }
            WindowEvent::MouseWheel { delta, .. } => {
                self.input.handle_scroll(&delta);
            }
            WindowEvent::RedrawRequested => {
                self.timer.tick();

                // Phase 1: PollInput — collect window/input events.
                // When simulation is active, WASD drives the kernel (not camera pan).
                // Camera follows the player via chase-cam in Phase 5a.
                if self.simulation.is_none() {
                    self.input
                        .apply_to_camera(&mut self.scene.camera, self.timer.delta_time());
                } else {
                    // Only apply mouse look (scroll zoom, drag rotation) — not WASD pan.
                    self.input
                        .apply_mouse_to_camera(&mut self.scene.camera, self.timer.delta_time());
                }

                // Phase 1b: Gamepad input (feature-gated, no-op when disabled).
                #[cfg(feature = "gamepad")]
                self.input.handle_gamepad(&mut self.gilrs, &mut self.scene.camera);

                // Phase 2: PollAuthority — non-blocking check for authority events
                self.authority_events.clear();
                self.authority.poll_events(&mut self.authority_events);

                // Phase 3: StageAuthorityEvents — buffer events for atomic application.
                // Explicit reborrow to satisfy the borrow checker: staging and
                // authority_events are disjoint fields but accessed through `self`.
                {
                    let staging = &mut self.staging;
                    let events = &mut self.authority_events;
                    staging.extend(events.drain(..));
                }

                // Phase 4: ApplyAuthorityEvents — apply staged events at tick boundary
                for event in self.staging.drain() {
                    match event {
                        AuthorityEvent::Ack { .. } => { /* intent acknowledged */ }
                        AuthorityEvent::Reject { seq, reason } => {
                            log::debug!("Authority rejected intent {seq}: {reason}");
                        }
                        AuthorityEvent::CanonEvent { tick, event_type, .. } => {
                            log::trace!("Canon event at tick {tick}: {event_type}");
                        }
                        AuthorityEvent::SnapshotChunk { .. } => { /* snapshot processing */ }
                    }
                }

                // Phase 5: UpdateMirror — update client mirror from applied events
                self.game_state.update(self.timer.delta_time());

                // Phase 5a: CausalComputeKernel tick (THE_BRAIDED_PATH phases B-E).
                // Single canonical input path: FabricInput.build_frame() → InputPacket::from_frame().
                // Binding-aware: rebinding WASD works. Gamepad overlays via synthetic key presses.
                if let Some(ref mut sim) = self.simulation {
                    let dt_secs = self.timer.delta_time();

                    // Gamepad → synthetic key presses into FabricInput (before build_frame).
                    #[cfg(feature = "gamepad")]
                    {
                        use dreamwell_engine::input::VirtualKey;
                        const DEADZONE: f32 = 0.2;
                        use gilrs::Axis;
                        if let Some((_id, gamepad)) = self.gilrs.gamepads().next() {
                            let lx = gamepad.value(Axis::LeftStickX);
                            let ly = gamepad.value(Axis::LeftStickY);
                            if ly > DEADZONE {
                                self.input.fabric.key_down(VirtualKey::W);
                            }
                            if ly < -DEADZONE {
                                self.input.fabric.key_down(VirtualKey::S);
                            }
                            if lx < -DEADZONE {
                                self.input.fabric.key_down(VirtualKey::A);
                            }
                            if lx > DEADZONE {
                                self.input.fabric.key_down(VirtualKey::D);
                            }
                            if gamepad.is_pressed(gilrs::Button::South) {
                                self.input.fabric.key_down(VirtualKey::Space);
                            }
                            if gamepad.is_pressed(gilrs::Button::LeftTrigger2) {
                                self.input.fabric.key_down(VirtualKey::ShiftLeft);
                            }
                        }
                    }

                    // Consume orbit input BEFORE building InputPacket so camera_yaw is current.
                    self.camera_orbit_yaw += self.input.orbit_dx;
                    self.camera_orbit_pitch =
                        (self.camera_orbit_pitch + self.input.orbit_dy).clamp(MIN_PITCH, MAX_PITCH);
                    self.camera_target_distance =
                        (self.camera_target_distance - self.input.scroll_delta).clamp(MIN_CAMERA_DIST, MAX_CAMERA_DIST);

                    // Build binding-aware InputFrame → InputPacket (single canonical path).
                    // coherence_current is the smoothly-lerped value (lerped inside sim.tick
                    // last frame). This gives the encoder a gradual transition, not a hard snap.
                    let frame = self.input.fabric.build_frame();
                    let packet = dreamwell_engine::input::InputPacket::from_frame(
                        &frame,
                        self.camera_orbit_yaw,
                        dt_secs,
                        sim.elapsed_time as f64,
                        sim.tick + 1,
                        sim.encoder.as_ref().map(|e| e.kernel().grounded).unwrap_or(true),
                        sim.coherence_current,
                        sim.gather_active,
                        sim.emit_strength,
                    );

                    // Smooth zoom: lerp actual distance toward target for buttery scroll feel.
                    let zoom_t = 1.0 - (-ZOOM_LERP_RATE * dt_secs).exp();
                    self.camera_distance += (self.camera_target_distance - self.camera_distance) * zoom_t;

                    if sim.frame == 0 {
                        log::info!(
                            "Sim pre-tick: input_enabled={} readiness={:?} encoder={} movement=[{:.2},{:.2}]",
                            sim.input_enabled(),
                            sim.readiness,
                            sim.encoder.is_some(),
                            packet.movement[0],
                            packet.movement[1],
                        );
                    }
                    if let Some(result) = sim.tick(&packet) {
                        if sim.frame <= 3 || sim.frame % 600 == 0 {
                            log::info!(
                                "Sim tick #{}: pos=[{:.2},{:.2},{:.2}] mode={} bridge={}",
                                sim.frame,
                                result.position[0],
                                result.position[1],
                                result.position[2],
                                result.locomotion_mode,
                                sim.last_bridge_packet.is_some(),
                            );
                        }
                        // Sync kernel result back to game state for GPU upload.
                        self.game_state.player_position = glam::Vec3::from_array(result.position);
                        if result.layer_changed {
                            if let Some(layer) = TopologyLayer::from_u8(result.topology_layer) {
                                self.game_state.active_layer = layer;
                            }
                        }
                        // Sync scene from simulation (mutations applied by DreamGate).
                        self.scene.game_objects = sim.scene.clone();

                        // POI interaction + collision dispatch.
                        sim.tick_collisions();
                        sim.tick_poi_interactions();

                        // Chase camera: third-person over-shoulder follow.
                        // Sprint pull-back: widen the view slightly while sprinting.
                        let sprint_extra = if packet.sprint { SPRINT_PULL_BACK } else { 0.0 };
                        let effective_dist = self.camera_distance + sprint_extra;

                        // Use encoder kernel if available, else fall back to direct kernel.
                        let kernel_pos = sim
                            .encoder
                            .as_ref()
                            .map(|e| e.kernel().position)
                            .or_else(|| sim.kernel.as_ref().map(|k| k.position));
                        if let Some(kpos) = kernel_pos {
                            let pos = glam::Vec3::from_array(kpos);
                            let yaw = self.camera_orbit_yaw;
                            let pitch = self.camera_orbit_pitch;

                            // Spherical offset: pitch controls elevation, yaw controls azimuth.
                            // cos(pitch) = horizontal distance factor, sin(pitch) = height factor.
                            let horiz = pitch.cos() * effective_dist;
                            let height = pitch.sin() * effective_dist;
                            let offset = glam::Vec3::new(
                                -yaw.cos() * horiz + yaw.sin() * SHOULDER_OFFSET,
                                height,
                                -yaw.sin() * horiz - yaw.cos() * SHOULDER_OFFSET,
                            );
                            let target_cam_pos = pos + offset;
                            // Exponential smoothing: alpha = 1 - e^(-rate * dt).
                            // Frame-rate independent — identical behavior at 30/60/144fps.
                            let pos_t = 1.0 - (-CAMERA_POSITION_LERP_RATE * dt_secs).exp();
                            let look_t = 1.0 - (-CAMERA_LOOKAT_LERP_RATE * dt_secs).exp();
                            self.scene.camera.position = self.scene.camera.position.lerp(target_cam_pos, pos_t);
                            self.scene.camera.center = self
                                .scene
                                .camera
                                .center
                                .lerp(pos + glam::Vec3::Y * LOOKAT_HEIGHT, look_t);
                            // Recompute view matrix from updated position/center.
                            // Without this, shaders use the stale default VP matrix.
                            self.scene.camera.update_view_matrix();
                        }

                        // Bridge packet is produced inside sim.tick() and consumed in Phase 5c.
                    }
                }

                // Phase 5b: Audio tick — mixer update, not render pass (feature-gated).
                #[cfg(feature = "audio")]
                {
                    let _ = &self.audio;
                }

                // Phase 5c: Consume pre-bridged packet from SimulationService.
                // The bridge was already called in sim.tick(), so we just consume the packet.
                let mut decoder_handled = false;
                if let (Some(ref mut sim), Some(ref mut decoder), Some(r)) =
                    (&mut self.simulation, &mut self.decoder, &mut self.renderer)
                {
                    if let Some(ref packet) = sim.last_bridge_packet {
                        let input = DecoderInput::from_bridge_packet(packet);
                        decoder.submit(&mut r.fabric, &input);
                        decoder_handled = true;
                    }
                }

                // Phase 6: UpdatePresentation — rebuild render-facing interpolated state
                // (currently handled by game_state.update above)

                // Phase 7: AssembleFrame — prepare observer context + render packet
                let dt = self.timer.delta_time();
                let player_pos = self.game_state.player_position();
                let active_layer = self.game_state.active_layer();

                // Phase 7: AssembleFrame — observer context from game state.
                // The bridge packet (Phase 5c) is the sole source of GPU state.
                // No fallback path — if the bridge didn't produce a packet, GPU uses last-frame state.
                let _ = decoder_handled;

                // Phase 8: Render — submit DreamFabric frame
                if let (Some(ws), Some(r)) = (&self.window_state, &mut self.renderer) {
                    r.render(ws, &self.scene, dt, player_pos, active_layer);
                }

                // Phase 9: DrainSync — drain sync packet and enqueue outgoing work
                if let Some(r) = &mut self.renderer {
                    self.sync_packet.clear();
                    r.fabric.drain_sync(&mut self.sync_packet);
                    if !self.sync_packet.intents.is_empty() {
                        self.authority.submit_intents(&self.sync_packet.intents);
                    }
                }

                // End-of-frame input cleanup
                self.input.end_frame();

                // Request next frame
                if let Some(ws) = &self.window_state {
                    ws.window.request_redraw();
                }
            }
            _ => {}
        }
    }
}