bevy_director 0.5.0-dev

Unreal-Sequencer-inspired cinematic camera and sequence system for Bevy
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
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
//! The runtime: who renders, when, and what the camera does about it.
//! One state machine (DirectorState.phase): Idle until asked, Shooting
//! while a sequence owns the frame, Handback while it glides to the live
//! camera, Viewfinder while a human flies. All mutation happens in
//! PostUpdate before transform propagation, so a pose written this frame
//! renders this frame.

use bevy::{
    camera::Exposure,
    post_process::dof::{DepthOfField, DepthOfFieldMode},
    prelude::*,
};

use crate::{
    eval::{ActiveActorCue, ActiveText, CameraPose, CameraSnapshot, CompiledSequence, EvalCtx, bake, mix},
    letterbox::LetterboxSettings,
    sequence::{Blend, SequenceAsset},
};

/// The director's camera. Spawn your own with your post stack and the
/// director adopts it; otherwise a plain one is spawned on first use.
#[derive(Component, Default)]
pub struct CineCamera;

/// Optional marker naming the gameplay camera to hand off from and back
/// to, for apps with several non-cine cameras. With exactly one active
/// camera the director finds it by itself.
#[derive(Component)]
pub struct HandoffCamera;

/// Playback state for a sequence, on the cine camera entity.
#[derive(Component)]
pub struct SequencePlayer {
    pub sequence: Handle<SequenceAsset>,
    pub playhead: f32,
    pub rate: f32,
    pub playback: Playback,
    pub clock: ClockSource,
    pub loop_mode: LoopMode,
}

impl SequencePlayer {
    pub fn new(sequence: Handle<SequenceAsset>) -> Self {
        Self {
            sequence,
            playhead: 0.0,
            rate: 1.0,
            playback: Playback::Playing,
            clock: ClockSource::default(),
            loop_mode: LoopMode::default(),
        }
    }

    /// Jump the playhead. Seeks never fire markers.
    pub fn seek(&mut self, t: f32) {
        self.playhead = t.max(0.0);
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Playback {
    Stopped,
    #[default]
    Playing,
    Paused,
}

/// Which clock advances the playhead. Virtual freezes with the game's
/// pause; Real keeps rolling through it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ClockSource {
    #[default]
    Virtual,
    Real,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LoopMode {
    #[default]
    Once,
    Loop,
    /// Bounce between the ends, flipping the rate.
    PingPong,
}

/// What the director is doing right now. A plain resource: map it onto
/// your own game states however you like.
#[derive(Resource, Default)]
pub struct DirectorState {
    pub phase: DirectorPhase,
    /// The cine camera being driven, while any phase is active.
    pub camera: Option<Entity>,
    /// The gameplay camera the director took the frame from.
    pub live_camera: Option<Entity>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DirectorPhase {
    #[default]
    Idle,
    Shooting,
    Handback,
    Viewfinder,
}

/// The text blocks visible this frame, fades resolved, refreshed during
/// [`DirectorSet::Apply`](crate::DirectorSet); empty whenever nothing is
/// on. This is the whole contract for custom caption rendering: read it
/// and draw. The `titles` feature ships a built-in renderer over the
/// same data.
#[derive(Resource, Default, Debug, Clone)]
pub struct ActiveTexts {
    pub blocks: Vec<ActiveText>,
}

/// The actor cues the playhead is inside this frame, weights resolved,
/// refreshed during [`DirectorSet::Apply`](crate::DirectorSet); empty
/// whenever no take runs. This is the whole actor-track contract: the
/// game reads it, matches each cue's `Entity(name)` target against its
/// own entities, and drives its own animation setup — deriving start and
/// stop edges from the stable `(track, cue_index)` pair. There are
/// deliberately no per-cue messages: a level-triggered resource survives
/// seeks, skips, loops, and reverse playback with no cursor bookkeeping.
#[derive(Resource, Default, Debug, Clone)]
pub struct ActiveActorCues {
    pub cues: Vec<ActiveActorCue>,
}

/// Run condition: no directed camera work at all.
pub fn director_idle(state: Res<DirectorState>) -> bool {
    state.phase == DirectorPhase::Idle
}

/// Run condition: a sequence or the viewfinder owns the frame.
pub fn director_active(state: Res<DirectorState>) -> bool {
    state.phase != DirectorPhase::Idle
}

/// Run condition for the game's own camera-driving system: true while the
/// gameplay camera should keep moving. That includes Handback, where the
/// director chases the live camera, so keep your rig running under this.
pub fn gameplay_camera_free(state: Res<DirectorState>) -> bool {
    matches!(state.phase, DirectorPhase::Idle | DirectorPhase::Handback)
}

// ---------- messages ----------

/// A sequence took the frame.
#[derive(Message, Debug, Clone)]
pub struct SequenceStarted {
    pub camera: Entity,
    pub sequence: AssetId<SequenceAsset>,
}

/// The playhead crossed a marker while playing forward.
#[derive(Message, Debug, Clone)]
pub struct MarkerReached {
    pub camera: Entity,
    pub name: String,
    pub time: f32,
}

/// The sequence gave the frame back (or is about to glide it back).
#[derive(Message, Debug, Clone)]
pub struct SequenceFinished {
    pub camera: Entity,
    pub reason: FinishReason,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FinishReason {
    Completed,
    Skipped,
    Stopped,
}

/// Internal control-channel messages, written by DirectorCommands.
#[derive(Message)]
pub(crate) enum DirectorRequest {
    Play {
        handle: Handle<SequenceAsset>,
        options: PlayOptions,
    },
    Skip,
    Stop,
}

/// Tuning for one playback.
#[derive(Clone, Debug)]
pub struct PlayOptions {
    pub rate: f32,
    pub clock: ClockSource,
    pub loop_mode: LoopMode,
    /// Overrides the asset's blend_out when set.
    pub blend_out: Option<Blend>,
    /// Crop the take to this aspect (e.g. 2.39 for scope) with real
    /// letterbox bars; cleared when the take ends.
    pub letterbox: Option<f32>,
}

impl Default for PlayOptions {
    fn default() -> Self {
        Self {
            rate: 1.0,
            clock: ClockSource::default(),
            loop_mode: LoopMode::default(),
            blend_out: None,
            letterbox: None,
        }
    }
}

/// Fire-and-forget control surface on Commands.
pub trait DirectorCommands {
    fn play_sequence(&mut self, handle: Handle<SequenceAsset>);
    fn play_sequence_with(&mut self, handle: Handle<SequenceAsset>, options: PlayOptions);
    /// Jump to the end and take the normal blend_out home.
    fn skip_sequence(&mut self);
    /// Hard stop: instant swap back to the live camera.
    fn stop_sequence(&mut self);
}

impl DirectorCommands for Commands<'_, '_> {
    fn play_sequence(&mut self, handle: Handle<SequenceAsset>) {
        self.play_sequence_with(handle, PlayOptions::default());
    }

    fn play_sequence_with(&mut self, handle: Handle<SequenceAsset>, options: PlayOptions) {
        self.queue(move |world: &mut World| {
            world.write_message(DirectorRequest::Play { handle, options });
        });
    }

    fn skip_sequence(&mut self) {
        self.queue(|world: &mut World| {
            world.write_message(DirectorRequest::Skip);
        });
    }

    fn stop_sequence(&mut self) {
        self.queue(|world: &mut World| {
            world.write_message(DirectorRequest::Stop);
        });
    }
}

// ---------- internal components ----------

/// The compiled sequence and the live-camera snapshot it blends from.
#[derive(Component)]
pub(crate) struct Baked {
    pub(crate) compiled: CompiledSequence,
    pub(crate) live: CameraSnapshot,
    /// Marker cursor: starts just below zero so a t=0 marker fires.
    pub(crate) marker_cursor: f32,
    pub(crate) blend_out: Option<Blend>,
    /// The last pose applied: feeds damped looks and seeds the handback.
    pub(crate) last_pose: Option<CameraPose>,
    /// Whether the director put lens components on the camera.
    pub(crate) dof_active: bool,
    pub(crate) exposure_active: bool,
}

/// A play request waiting for its asset to finish loading.
#[derive(Component)]
pub(crate) struct PendingPlay {
    handle: Handle<SequenceAsset>,
    options: PlayOptions,
}

/// The glide home at the end: from a frozen pose toward the live camera,
/// sampled fresh every frame.
#[derive(Component)]
pub(crate) struct HandbackBlend {
    from: CameraPose,
    elapsed: f32,
    blend: Blend,
    clock: ClockSource,
}

// ---------- systems ----------

pub(crate) fn snapshot_of(
    transform: &Transform,
    projection: Option<&Projection>,
) -> CameraSnapshot {
    let fov_y = match projection {
        Some(Projection::Perspective(p)) => p.fov,
        _ => 45f32.to_radians(),
    };
    CameraSnapshot {
        position: transform.translation,
        rotation: transform.rotation,
        fov_y,
    }
}

/// Find the gameplay camera to hand off from: prefer HandoffCamera, else
/// the unique active non-cine 3D camera.
fn resolve_live_camera(
    cameras: &Query<(Entity, &Camera, Has<HandoffCamera>), (With<Camera3d>, Without<CineCamera>)>,
) -> Option<Entity> {
    if let Some((e, ..)) = cameras.iter().find(|(_, _, marked)| *marked) {
        return Some(e);
    }
    let mut actives = cameras.iter().filter(|(_, cam, _)| cam.is_active);
    let first = actives.next().map(|(e, ..)| e);
    if actives.next().is_some() {
        warn!("several active cameras and no HandoffCamera marker; picking one arbitrarily");
    }
    first
}

/// Spawn the fallback cine camera. Games with a post stack should spawn
/// their own CineCamera entity instead; this one is bare bones. The
/// active flag rides the bundle because a same-frame get_mut cannot see
/// an entity whose commands have not flushed yet.
fn spawn_fallback_cine_camera(commands: &mut Commands, active: bool) -> Entity {
    commands
        .spawn((
            Name::new("cine camera"),
            CineCamera,
            Camera3d::default(),
            Camera {
                is_active: active,
                ..Default::default()
            },
            Projection::default(),
            Transform::default(),
        ))
        .id()
}

/// Drain control requests. Play resolves cameras, bakes (or parks a
/// PendingPlay until the asset arrives), snapshots the live pose, and
/// swaps is_active in this one place so the two flags never disagree.
#[allow(clippy::too_many_arguments)] // the control hub touches everything
pub(crate) fn handle_requests(
    mut commands: Commands,
    mut requests: MessageReader<DirectorRequest>,
    mut state: ResMut<DirectorState>,
    assets: Res<Assets<SequenceAsset>>,
    // p0 reads cameras to pick the live one; p1 writes is_active. A
    // ParamSet because they overlap on Camera.
    mut cameras: ParamSet<(
        Query<(Entity, &Camera, Has<HandoffCamera>), (With<Camera3d>, Without<CineCamera>)>,
        Query<&mut Camera>,
    )>,
    cine_cameras: Query<Entity, With<CineCamera>>,
    pending: Query<(Entity, &PendingPlay)>,
    mut players: Query<(&mut SequencePlayer, Option<&Baked>)>,
    transforms: Query<(&Transform, Option<&Projection>)>,
    mut started: MessageWriter<SequenceStarted>,
    mut finished: MessageWriter<SequenceFinished>,
) {
    // Retry a parked play once its asset shows up.
    let retry: Option<(Handle<SequenceAsset>, PlayOptions, Entity)> = pending
        .iter()
        .next()
        .filter(|(_, p)| assets.contains(&p.handle))
        .map(|(e, p)| (p.handle.clone(), p.options.clone(), e));
    let mut plays: Vec<(Handle<SequenceAsset>, PlayOptions)> = Vec::new();
    if let Some((handle, options, entity)) = retry {
        commands.entity(entity).remove::<PendingPlay>();
        plays.push((handle, options));
    }

    for request in requests.read() {
        match request {
            DirectorRequest::Play { handle, options } => {
                plays.push((handle.clone(), options.clone()));
            }
            DirectorRequest::Skip => {
                if state.phase == DirectorPhase::Shooting
                    && let Some(camera) = state.camera
                    && let Ok((mut player, baked)) = players.get_mut(camera)
                    && let Some(baked) = baked
                {
                    // Jump to the end; the tick system routes the finish.
                    player.playhead = baked.compiled.duration();
                    player.playback = Playback::Playing;
                    player.loop_mode = LoopMode::Once;
                    finished.write(SequenceFinished {
                        camera,
                        reason: FinishReason::Skipped,
                    });
                    commands.entity(camera).insert(SkipRequested);
                }
            }
            DirectorRequest::Stop => {
                if state.phase == DirectorPhase::Shooting || state.phase == DirectorPhase::Handback
                {
                    if let Some(camera) = state.camera {
                        finished.write(SequenceFinished {
                            camera,
                            reason: FinishReason::Stopped,
                        });
                    }
                    let mut writable = cameras.p1();
                    restore_live(&mut commands, &mut state, &mut writable);
                }
            }
        }
    }

    for (handle, options) in plays {
        if state.phase != DirectorPhase::Idle {
            warn!(
                "play_sequence ignored: the director is already {:?}",
                state.phase
            );
            continue;
        }
        let existing = cine_cameras.iter().next();

        let Some(asset) = assets.get(&handle) else {
            // Not loaded yet: park the request on the cine camera.
            let cine = existing.unwrap_or_else(|| spawn_fallback_cine_camera(&mut commands, false));
            commands.entity(cine).insert(PendingPlay {
                handle: handle.clone(),
                options,
            });
            continue;
        };
        // A fresh fallback spawns already active; the swap below only
        // needs to reach cameras that exist.
        let cine = existing.unwrap_or_else(|| spawn_fallback_cine_camera(&mut commands, true));
        let compiled = match bake(asset) {
            Ok(compiled) => compiled,
            Err(err) => {
                error!("sequence '{}' failed to bake: {err}", asset.name);
                continue;
            }
        };

        let live_entity = resolve_live_camera(&cameras.p0());
        let live = live_entity
            .and_then(|e| transforms.get(e).ok())
            .map(|(t, p)| snapshot_of(t, p))
            .unwrap_or(CameraSnapshot {
                position: Vec3::ZERO,
                rotation: Quat::IDENTITY,
                fov_y: 45f32.to_radians(),
            });

        let blend_out = options.blend_out.or(compiled.blend_out());
        let mut cine_commands = commands.entity(cine);
        cine_commands.insert((
            SequencePlayer {
                sequence: handle.clone(),
                playhead: 0.0,
                rate: options.rate,
                playback: Playback::Playing,
                clock: options.clock,
                loop_mode: options.loop_mode,
            },
            Baked {
                compiled,
                live,
                marker_cursor: -f32::EPSILON,
                blend_out,
                last_pose: None,
                dof_active: false,
                exposure_active: false,
            },
        ));
        if let Some(aspect) = options.letterbox {
            cine_commands.insert(LetterboxSettings { aspect });
        }

        // The swap: exactly one camera active, flipped together.
        let mut writable = cameras.p1();
        if let Some(live_entity) = live_entity
            && let Ok(mut cam) = writable.get_mut(live_entity)
        {
            cam.is_active = false;
        }
        if let Ok(mut cam) = writable.get_mut(cine) {
            cam.is_active = true;
        }

        state.phase = DirectorPhase::Shooting;
        state.camera = Some(cine);
        state.live_camera = live_entity;
        started.write(SequenceStarted {
            camera: cine,
            sequence: handle.id(),
        });
    }
}

/// Skip was requested this frame; suppresses the Completed message when
/// the tick routes the finish.
#[derive(Component)]
pub(crate) struct SkipRequested;

/// Hot reload: rebake when the asset file changes under a live player.
pub(crate) fn rebake_on_asset_change(
    mut events: MessageReader<AssetEvent<SequenceAsset>>,
    assets: Res<Assets<SequenceAsset>>,
    mut players: Query<(&mut SequencePlayer, &mut Baked)>,
) {
    for event in events.read() {
        let AssetEvent::Modified { id } = event else {
            continue;
        };
        for (mut player, mut baked) in &mut players {
            if player.sequence.id() != *id {
                continue;
            }
            let Some(asset) = assets.get(*id) else {
                continue;
            };
            match bake(asset) {
                Ok(compiled) => {
                    player.playhead = player.playhead.min(compiled.duration());
                    baked.compiled = compiled;
                    info!("sequence '{}' rebaked from disk", asset.name);
                }
                Err(err) => error!("sequence '{}' failed to rebake: {err}", asset.name),
            }
        }
    }
}

/// If the cine camera (or its player) vanished mid-flight, put the live
/// camera back on air. This is what keeps a quit-to-title mid-cutscene
/// from black-screening the menu.
pub(crate) fn guard_orphans(
    mut commands: Commands,
    mut state: ResMut<DirectorState>,
    players: Query<&SequencePlayer>,
    mut cameras: Query<&mut Camera>,
    mut finished: MessageWriter<SequenceFinished>,
) {
    if state.phase == DirectorPhase::Idle {
        return;
    }
    let camera_gone = state.camera.is_none_or(|e| {
        if state.phase == DirectorPhase::Viewfinder {
            cameras.get(e).is_err()
        } else {
            players.get(e).is_err()
        }
    });
    if !camera_gone {
        return;
    }
    if let Some(camera) = state.camera {
        finished.write(SequenceFinished {
            camera,
            reason: FinishReason::Stopped,
        });
    }
    restore_live(&mut commands, &mut state, &mut cameras);
}

/// Back to Idle: live camera on, cine camera off, playback components
/// gone. Safe against despawned entities on either side.
pub(crate) fn restore_live(
    commands: &mut Commands,
    state: &mut DirectorState,
    cameras: &mut Query<&mut Camera>,
) {
    if let Some(live) = state.live_camera
        && let Ok(mut cam) = cameras.get_mut(live)
    {
        cam.is_active = true;
    }
    if let Some(cine) = state.camera {
        if let Ok(mut cam) = cameras.get_mut(cine) {
            cam.is_active = false;
            cam.viewport = None;
        }
        if let Ok(mut e) = commands.get_entity(cine) {
            // The director owns the lens components on the cine camera
            // while a take runs; a stop clears them wholesale.
            e.remove::<(
                SequencePlayer,
                Baked,
                HandbackBlend,
                PendingPlay,
                SkipRequested,
                LetterboxSettings,
                DepthOfField,
                Exposure,
            )>();
        }
    }
    state.phase = DirectorPhase::Idle;
    state.camera = None;
    state.live_camera = None;
}

/// Advance playheads, fire markers, and route the end of the sequence
/// into a handback (or an instant swap when there is no blend_out).
pub(crate) fn tick_players(
    mut commands: Commands,
    mut state: ResMut<DirectorState>,
    virtual_time: Res<Time<Virtual>>,
    real_time: Res<Time<Real>>,
    mut players: Query<(Entity, &mut SequencePlayer, &mut Baked, Has<SkipRequested>)>,
    mut cameras: Query<&mut Camera>,
    mut markers: MessageWriter<MarkerReached>,
    mut finished: MessageWriter<SequenceFinished>,
) {
    if state.phase != DirectorPhase::Shooting {
        return;
    }
    let Some(camera) = state.camera else {
        return;
    };
    let Ok((entity, mut player, mut baked, skipping)) = players.get_mut(camera) else {
        return;
    };
    if player.playback != Playback::Playing {
        return;
    }

    let dt = match player.clock {
        ClockSource::Virtual => virtual_time.delta_secs(),
        ClockSource::Real => real_time.delta_secs(),
    } * player.rate;
    player.playhead += dt;

    let duration = baked.compiled.duration();
    let cursor = baked.marker_cursor;

    if !skipping {
        let fire = |m: &crate::sequence::Marker, markers: &mut MessageWriter<MarkerReached>| {
            markers.write(MarkerReached {
                camera: entity,
                name: m.name.clone(),
                time: m.time,
            });
        };
        if dt >= 0.0 {
            for marker in baked.compiled.markers_between(cursor, player.playhead) {
                fire(marker, &mut markers);
            }
        } else {
            for marker in baked
                .compiled
                .markers_between_backward(player.playhead, cursor)
            {
                fire(marker, &mut markers);
            }
        }
    }
    baked.marker_cursor = player.playhead;

    let over = dt >= 0.0 && player.playhead >= duration;
    let under = dt < 0.0 && player.playhead <= 0.0;
    if !over && !under {
        return;
    }

    match player.loop_mode {
        LoopMode::Loop => {
            let wrapped = if over {
                // Tail markers fired above; fire the head range too.
                let wrapped = (player.playhead - duration).max(0.0);
                if !skipping {
                    for marker in baked.compiled.markers_between(-f32::EPSILON, wrapped) {
                        markers.write(MarkerReached {
                            camera: entity,
                            name: marker.name.clone(),
                            time: marker.time,
                        });
                    }
                }
                wrapped
            } else {
                (player.playhead + duration).clamp(0.0, duration)
            };
            player.playhead = wrapped;
            baked.marker_cursor = wrapped;
        }
        LoopMode::PingPong => {
            player.rate = -player.rate;
            player.playhead = if over {
                (2.0 * duration - player.playhead).clamp(0.0, duration)
            } else {
                (-player.playhead).clamp(0.0, duration)
            };
            baked.marker_cursor = player.playhead;
        }
        LoopMode::Once => {
            player.playhead = if over { duration } else { 0.0 };
            player.playback = Playback::Stopped;
            if !skipping {
                finished.write(SequenceFinished {
                    camera: entity,
                    reason: FinishReason::Completed,
                });
            }
            match baked.blend_out {
                Some(blend) if blend.secs > 0.0 => {
                    // Start the glide from the last pose actually shown.
                    let from = baked.last_pose.unwrap_or_else(|| {
                        baked
                            .compiled
                            .pose_at(player.playhead, &EvalCtx::still(&baked.live))
                    });
                    commands.entity(entity).insert(HandbackBlend {
                        from,
                        elapsed: 0.0,
                        blend,
                        clock: player.clock,
                    });
                    state.phase = DirectorPhase::Handback;
                }
                _ => restore_live(&mut commands, &mut state, &mut cameras),
            }
        }
    }
}

/// Write the evaluated pose onto the cine camera: transform, fov, and
/// the lens components (depth of field, exposure) when the shot asks.
/// During handback, chase the live camera's fresh pose (the game's rig
/// runs and we glide to it).
#[allow(clippy::too_many_arguments)] // the frame's one write-out
pub(crate) fn apply_pose(
    mut commands: Commands,
    mut state: ResMut<DirectorState>,
    virtual_time: Res<Time<Virtual>>,
    real_time: Res<Time<Real>>,
    mut cine: Query<
        (
            &mut Transform,
            &mut Projection,
            Option<(&SequencePlayer, &mut Baked)>,
            Option<&mut HandbackBlend>,
        ),
        With<CineCamera>,
    >,
    live: Query<(&Transform, Option<&Projection>), Without<CineCamera>>,
    names: Query<(&Name, &GlobalTransform)>,
    mut cameras: Query<&mut Camera>,
) {
    let Some(camera) = state.camera else {
        return;
    };
    let Ok((mut transform, mut projection, playing, handback)) = cine.get_mut(camera) else {
        return;
    };
    // Name positions are last frame's globals: fine for aim targets.
    let resolve = |wanted: &str| {
        names
            .iter()
            .find(|(name, _)| name.as_str() == wanted)
            .map(|(_, gt)| gt.translation())
    };

    let (pose, lens_flags) = match state.phase {
        DirectorPhase::Shooting => {
            let Some((player, mut baked)) = playing else {
                return;
            };
            let dt = match player.clock {
                ClockSource::Virtual => virtual_time.delta_secs(),
                ClockSource::Real => real_time.delta_secs(),
            };
            let ctx = EvalCtx {
                live: &baked.live,
                dt,
                prev_rot: baked.last_pose.map(|p| p.rotation),
                resolve_entity: &resolve,
            };
            let pose = baked.compiled.pose_at(player.playhead, &ctx);
            baked.last_pose = Some(pose);
            let flags = Some((
                pose.dof.is_some() || baked.dof_active,
                pose.exposure_ev100.is_some() || baked.exposure_active,
            ));
            baked.dof_active = pose.dof.is_some();
            baked.exposure_active = pose.exposure_ev100.is_some();
            (pose, flags)
        }
        DirectorPhase::Handback => {
            let Some(mut handback) = handback else {
                return;
            };
            handback.elapsed += match handback.clock {
                ClockSource::Virtual => virtual_time.delta_secs(),
                ClockSource::Real => real_time.delta_secs(),
            };
            let target = state
                .live_camera
                .and_then(|e| live.get(e).ok())
                .map(|(t, p)| snapshot_of(t, p))
                .unwrap_or(CameraSnapshot {
                    position: handback.from.position,
                    rotation: handback.from.rotation,
                    fov_y: handback.from.fov_y,
                });
            let target = CameraPose {
                position: target.position,
                rotation: target.rotation,
                fov_y: target.fov_y,
                dof: None,
                exposure_ev100: None,
            };
            let w = handback
                .blend
                .ease
                .sample_clamped((handback.elapsed / handback.blend.secs).clamp(0.0, 1.0));
            let pose = mix(&handback.from, &target, w);
            if handback.elapsed >= handback.blend.secs {
                restore_live(&mut commands, &mut state, &mut cameras);
            }
            (pose, None)
        }
        _ => return,
    };

    transform.translation = pose.position;
    transform.rotation = pose.rotation;
    if let Projection::Perspective(perspective) = &mut *projection {
        perspective.fov = pose.fov_y;
    }

    // Lens components ride along only while a shot uses them; the flags
    // keep the no-lens common case free of per-frame commands.
    if let Some((touch_dof, touch_exposure)) = lens_flags {
        if touch_dof {
            match pose.dof {
                Some(d) => {
                    commands.entity(camera).insert(DepthOfField {
                        mode: if d.bokeh {
                            DepthOfFieldMode::Bokeh
                        } else {
                            DepthOfFieldMode::Gaussian
                        },
                        focal_distance: d.focal_distance,
                        aperture_f_stops: d.aperture_f_stops,
                        sensor_height: d.sensor_height,
                        ..Default::default()
                    });
                }
                None => {
                    commands.entity(camera).remove::<DepthOfField>();
                }
            }
        }
        if touch_exposure {
            match pose.exposure_ev100 {
                Some(ev100) => {
                    commands.entity(camera).insert(Exposure { ev100 });
                }
                None => {
                    commands.entity(camera).remove::<Exposure>();
                }
            }
        }
    }
}

/// Refresh [`ActiveTexts`] from the playing take. Level-triggered off
/// the playhead, so seeks, loops, and reverse playback just work. The
/// viewfinder phase is deliberately left alone: the editor's session
/// writer owns the resource there.
pub(crate) fn update_active_texts(
    state: Res<DirectorState>,
    players: Query<(&SequencePlayer, &Baked)>,
    mut active: ResMut<ActiveTexts>,
) {
    match state.phase {
        DirectorPhase::Shooting => {
            let playing = state.camera.and_then(|camera| players.get(camera).ok());
            match playing {
                Some((player, baked)) => {
                    // Don't dirty the resource while it stays empty.
                    if baked.compiled.texts().is_empty() && active.blocks.is_empty() {
                        return;
                    }
                    let blocks = &mut active.blocks;
                    baked.compiled.active_texts_into(player.playhead, blocks);
                }
                None => {
                    if !active.blocks.is_empty() {
                        active.blocks.clear();
                    }
                }
            }
        }
        DirectorPhase::Viewfinder => {}
        _ => {
            if !active.blocks.is_empty() {
                active.blocks.clear();
            }
        }
    }
}

/// Refresh [`ActiveActorCues`] from the playing take: the actor twin of
/// [`update_active_texts`], with the same rules — level-triggered off
/// the playhead, cleared outside Shooting (a skip empties it the same
/// frame the finish routes), and left alone during Viewfinder where the
/// editor's session writer owns it.
pub(crate) fn update_active_actor_cues(
    state: Res<DirectorState>,
    players: Query<(&SequencePlayer, &Baked)>,
    mut active: ResMut<ActiveActorCues>,
) {
    match state.phase {
        DirectorPhase::Shooting => {
            let playing = state.camera.and_then(|camera| players.get(camera).ok());
            match playing {
                Some((player, baked)) => {
                    // Don't dirty the resource while it stays empty.
                    if baked.compiled.actors().is_empty() && active.cues.is_empty() {
                        return;
                    }
                    let cues = &mut active.cues;
                    baked.compiled.active_actor_cues_into(player.playhead, cues);
                }
                None => {
                    if !active.cues.is_empty() {
                        active.cues.clear();
                    }
                }
            }
        }
        DirectorPhase::Viewfinder => {}
        _ => {
            if !active.cues.is_empty() {
                active.cues.clear();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DirectorPlugin;
    use crate::sequence::*;
    use bevy::app::App;
    use bevy::asset::AssetPlugin;
    use bevy::time::TimeUpdateStrategy;
    use std::time::Duration;

    fn test_sequence(blend_out: Option<Blend>) -> SequenceAsset {
        SequenceAsset {
            name: "test".into(),
            shots: vec![Shot {
                start: 0.0,
                duration: 0.1,
                blend_in: None,
                rig: Rig::Keys {
                    keys: vec![Key {
                        time: 0.0,
                        pos: Vec3::new(5.0, 0.0, 0.0),
                        rot: Some(Quat::IDENTITY),
                        ease: EaseFunction::Linear,
                    }],
                    interp: KeyInterp::Eased,
                },
                look: Look::Free,
                lens: Lens::default(),
                shake: None,
            }],
            markers: vec![Marker {
                time: 0.05,
                name: "beat".into(),
            }],
            texts: vec![],
            actors: vec![],
            blend_out,
        }
    }

    fn test_app() -> (App, Entity, Handle<SequenceAsset>) {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default(), DirectorPlugin));
        app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_millis(
            16,
        )));
        let live = app
            .world_mut()
            .spawn((
                Camera3d::default(),
                Camera::default(),
                Projection::default(),
                Transform::from_xyz(0.0, 9.0, 0.0),
            ))
            .id();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(test_sequence(None));
        (app, live, handle)
    }

    fn phase(app: &App) -> DirectorPhase {
        app.world().resource::<DirectorState>().phase
    }

    fn is_active(app: &mut App, e: Entity) -> bool {
        app.world().get::<Camera>(e).unwrap().is_active
    }

    #[test]
    fn play_swaps_is_active_and_finishes() {
        let (mut app, live, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        assert!(!is_active(&mut app, live));
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        assert!(is_active(&mut app, cine));
        // 0.1 s sequence at 16 ms steps: done well within 20 frames.
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(is_active(&mut app, live));
        assert!(!is_active(&mut app, cine));
        // The pose landed on the cine camera while it was shooting.
        let t = app.world().get::<Transform>(cine).unwrap();
        assert_eq!(t.translation.x, 5.0);
    }

    #[test]
    fn blend_out_routes_through_handback() {
        let (mut app, live, _) = test_app();
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(test_sequence(Some(Blend {
                secs: 0.05,
                ease: EaseFunction::Linear,
            })));
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        let mut saw_handback = false;
        for _ in 0..40 {
            app.update();
            if phase(&app) == DirectorPhase::Handback {
                saw_handback = true;
            }
        }
        assert!(saw_handback);
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(is_active(&mut app, live));
    }

    #[test]
    fn orphan_guard_restores_live_camera() {
        let (mut app, live, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        app.world_mut().entity_mut(cine).despawn();
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(is_active(&mut app, live));
    }

    #[test]
    fn pause_of_virtual_clock_freezes_playhead() {
        let (mut app, _, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        app.world_mut().resource_mut::<Time<Virtual>>().pause();
        for _ in 0..10 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        let head = app.world().get::<SequencePlayer>(cine).unwrap().playhead;
        // One 16 ms step landed before the pause; nothing after.
        assert!(head <= 0.017, "playhead crept to {head}");
    }

    #[derive(Resource, Default)]
    struct MarkerHits(usize);

    fn count_markers(mut hits: ResMut<MarkerHits>, mut reader: MessageReader<MarkerReached>) {
        hits.0 += reader.read().count();
    }

    #[test]
    fn marker_fires_exactly_once() {
        let (mut app, _, handle) = test_app();
        app.init_resource::<MarkerHits>();
        app.add_systems(Update, count_markers);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        for _ in 0..30 {
            app.update();
        }
        assert_eq!(app.world().resource::<MarkerHits>().0, 1);
    }

    #[test]
    fn active_texts_fill_while_shooting_and_clear_after() {
        let (mut app, _, _) = test_app();
        let mut sequence = test_sequence(None);
        sequence.texts = vec![TextBlock::at(0.0, 0.1, "caption")];
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        let active = app.world().resource::<ActiveTexts>();
        assert_eq!(active.blocks.len(), 1);
        assert_eq!(active.blocks[0].block.text, "caption");
        assert_eq!(active.blocks[0].alpha, 1.0);
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(app.world().resource::<ActiveTexts>().blocks.is_empty());
    }

    #[test]
    fn active_actor_cues_fill_while_shooting_and_clear_after() {
        let (mut app, _, _) = test_app();
        let mut sequence = test_sequence(None);
        sequence.actors =
            vec![ActorTrack::entity("player").cue(ActorCue::at(0.0, 0.1, "cutscene.sleeping"))];
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert_eq!(phase(&app), DirectorPhase::Shooting);
        let active = app.world().resource::<ActiveActorCues>();
        assert_eq!(active.cues.len(), 1);
        assert_eq!(active.cues[0].cue.anim, "cutscene.sleeping");
        assert!(matches!(
            &active.cues[0].target,
            crate::sequence::TargetRef::Entity(name) if name == "player"
        ));
        let first_local = active.cues[0].local_time;
        app.update();
        let advanced = app.world().resource::<ActiveActorCues>().cues[0].local_time;
        assert!(advanced > first_local, "local_time never advanced");
        for _ in 0..20 {
            app.update();
        }
        assert_eq!(phase(&app), DirectorPhase::Idle);
        assert!(app.world().resource::<ActiveActorCues>().cues.is_empty());
    }

    #[test]
    fn skip_clears_actor_cues_immediately() {
        let (mut app, _, _) = test_app();
        let mut sequence = test_sequence(None);
        // Long take: without the skip it would still be mid-cue.
        sequence.shots[0].duration = 10.0;
        sequence.actors = vec![ActorTrack::entity("player").cue(ActorCue::at(0.0, 10.0, "sleep"))];
        let handle = app
            .world_mut()
            .resource_mut::<Assets<SequenceAsset>>()
            .add(sequence);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        assert!(!app.world().resource::<ActiveActorCues>().cues.is_empty());
        app.world_mut().write_message(DirectorRequest::Skip);
        app.update();
        assert!(app.world().resource::<ActiveActorCues>().cues.is_empty());
    }

    #[test]
    fn pingpong_bounces_between_the_ends() {
        let (mut app, _, handle) = test_app();
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions {
                loop_mode: LoopMode::PingPong,
                ..Default::default()
            },
        });
        app.update();
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        let mut flipped = false;
        for _ in 0..40 {
            app.update();
            let player = app.world().get::<SequencePlayer>(cine).unwrap();
            assert!((-0.001..=0.101).contains(&player.playhead));
            flipped |= player.rate < 0.0;
        }
        assert!(flipped, "the rate never reflected");
        assert_eq!(phase(&app), DirectorPhase::Shooting);
    }

    #[test]
    fn backward_markers_fire_on_the_mirror_rule() {
        let (mut app, _, handle) = test_app();
        app.init_resource::<MarkerHits>();
        app.add_systems(Update, count_markers);
        app.world_mut().write_message(DirectorRequest::Play {
            handle,
            options: PlayOptions::default(),
        });
        app.update();
        let cine = app.world().resource::<DirectorState>().camera.unwrap();
        {
            let mut entity = app.world_mut().entity_mut(cine);
            let duration = entity.get::<Baked>().unwrap().compiled.duration();
            entity.get_mut::<Baked>().unwrap().marker_cursor = duration;
            let mut player = entity.get_mut::<SequencePlayer>().unwrap();
            player.playhead = duration;
            player.rate = -1.0;
        }
        for _ in 0..30 {
            app.update();
        }
        assert_eq!(app.world().resource::<MarkerHits>().0, 1);
        assert_eq!(phase(&app), DirectorPhase::Idle);
    }
}