bevy_director 0.7.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
//! The viewfinder: the director's chair, without a single widget. Toggle
//! it, fly the frame you want, press K, and the key is on the timeline.
//! Scrub with the brackets, preview with P, save with Ctrl+S. Everything
//! is keyboard and mouse; the overlay (gizmos.rs) is the only readout.
//!
//! This is a dev tool: it reads raw ButtonInput and writes RON to the
//! assets directory on native builds. Games gate their own input on the
//! director's run conditions while it is up.

use bevy::{
    input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll},
    prelude::*,
    window::{CursorGrabMode, CursorOptions},
};

use crate::{
    CineCamera, DirectorSet,
    eval::{
        CameraSnapshot, CompiledSequence, EvalCtx, bake, collect_active_actor_cues,
        collect_active_texts,
    },
    gizmos::{DirectorGizmoGroup, draw_playhead, draw_sequence},
    player::{
        ActiveActorCues, ActiveTexts, DirectorPhase, DirectorState, HandoffCamera, snapshot_of,
    },
    sequence::{FovSpec, Key, KeyInterp, Lens, Rig, ScalarKey, ScalarTrack, SequenceAsset, Shot},
};

const DEFAULT_SHOT_SECS: f32 = 5.0;
/// Capturing within this window of an existing key replaces it.
const REPLACE_WINDOW: f32 = 0.05;
/// Delete reaches this far from the camera.
const DELETE_RANGE: f32 = 2.0;
const MOUSE_SENSITIVITY: f32 = 0.0028;

/// Keybinds and the save location. Insert your own to rebind.
#[derive(Resource)]
pub struct ViewfinderConfig {
    /// Opens and ejects the viewfinder. `None` removes the keyboard
    /// toggle entirely, for builds that compile the authoring tools in
    /// but must never let a player key into them.
    pub toggle: Option<KeyCode>,
    pub capture: KeyCode,
    pub delete: KeyCode,
    pub play_pause: KeyCode,
    pub scrub_back: KeyCode,
    pub scrub_forward: KeyCode,
    /// Seconds per bracket tap; Shift steps a single frame (1/30).
    pub scrub_step: f32,
    pub fly_speed: f32,
    /// After-Effects-style auto-key: piloting the camera (moving, looking,
    /// or Ctrl+wheel on the lens) writes the key at the playhead into the
    /// shot under it, no K press needed. Only fires once a first shot
    /// exists, so flying around an empty take never creates data.
    pub auto_key: bool,
    /// Where Ctrl+S writes `<name>.dir.ron`, relative to the working dir.
    pub save_dir: std::path::PathBuf,
    /// Ease stamped on captured keys.
    pub capture_ease: EaseFunction,
}

impl Default for ViewfinderConfig {
    fn default() -> Self {
        Self {
            toggle: Some(KeyCode::Backquote),
            capture: KeyCode::KeyK,
            delete: KeyCode::Delete,
            play_pause: KeyCode::KeyP,
            scrub_back: KeyCode::BracketLeft,
            scrub_forward: KeyCode::BracketRight,
            scrub_step: 0.5,
            fly_speed: 8.0,
            auto_key: true,
            save_dir: std::path::PathBuf::from("assets/sequences"),
            capture_ease: EaseFunction::SmoothStep,
        }
    }
}

/// The working take. Lives across toggles so half-built sequences are not
/// lost by ejecting; saving writes it to disk.
#[derive(Resource)]
pub struct ViewfinderSession {
    pub sequence: SequenceAsset,
    pub armed_shot: usize,
    pub playhead: f32,
    pub playing: bool,
    yaw: f32,
    pitch: f32,
    pub(crate) fov_deg: f32,
    speed: f32,
    saved_cursor: Option<(bool, CursorGrabMode)>,
    pub(crate) compiled: Option<CompiledSequence>,
    /// The gameplay camera the viewfinder took over from, frozen at
    /// entry. Every preview path (play, scrub, editor, gizmo ghost)
    /// blends the first shot from THIS snapshot — the same one the
    /// runtime would use — so they all show the same take.
    pub(crate) live_snapshot: CameraSnapshot,
    /// Last previewed rotation, feeding damped looks while play-previewing
    /// exactly like the runtime's `last_pose`. None outside playback.
    pub(crate) preview_prev_rot: Option<Quat>,
    /// Which lens components the preview put on the camera, so dropping
    /// one takes it back off — the runtime's `Baked.lens_active`.
    pub(crate) preview_lens: crate::player::LensTouch,
}

impl Default for ViewfinderSession {
    fn default() -> Self {
        Self {
            sequence: SequenceAsset::empty("untitled"),
            armed_shot: 0,
            playhead: 0.0,
            playing: false,
            yaw: 0.0,
            pitch: 0.0,
            fov_deg: 45.0,
            speed: 8.0,
            saved_cursor: None,
            compiled: None,
            live_snapshot: CameraSnapshot {
                position: Vec3::new(0.0, 2.0, 8.0),
                rotation: Quat::IDENTITY,
                fov_y: 45f32.to_radians(),
            },
            preview_prev_rot: None,
            preview_lens: crate::player::LensTouch::default(),
        }
    }
}

impl ViewfinderSession {
    pub(crate) fn rebake(&mut self) {
        self.compiled = bake(&self.sequence).ok();
    }

    /// Index of the shot the playhead sits in: the last shot whose start
    /// is at or before the playhead (the same rule the evaluator uses),
    /// clamped to the first.
    pub(crate) fn shot_at_playhead(&self) -> usize {
        self.sequence
            .shots
            .iter()
            .rposition(|shot| shot.start <= self.playhead)
            .unwrap_or(0)
    }

    /// Capture a camera framing at the playhead. The keyboard viewfinder,
    /// auto-key, and the Director's Cut editor deliberately share this
    /// path so all of them author exactly the same asset data. The key
    /// always lands in the shot under the playhead — never a stale armed
    /// shot — and that shot becomes the armed one. Returns the shot index
    /// and, for key rigs, the index of the inserted or replaced key.
    pub(crate) fn capture_frame(
        &mut self,
        pos: Vec3,
        rot: Quat,
        fov_deg: f32,
        ease: EaseFunction,
    ) -> (usize, Option<usize>) {
        let playhead = self.playhead;
        if self.sequence.shots.is_empty() {
            self.sequence.shots.push(Shot {
                start: 0.0,
                duration: DEFAULT_SHOT_SECS.max(playhead),
                blend_in: None,
                rig: Rig::Keys {
                    keys: Vec::new(),
                    interp: KeyInterp::Eased,
                },
                look: Default::default(),
                lens: Lens {
                    fov: FovSpec::VerticalFovDeg(ScalarTrack { keys: Vec::new() }),
                    ..Default::default()
                },
                shake: None,
                camera: None,
            });
        }
        let armed = self.shot_at_playhead();
        self.armed_shot = armed;
        let shot = &mut self.sequence.shots[armed];
        let local = (playhead - shot.start).max(0.0);
        if local > shot.duration {
            shot.duration = local;
        }

        let mut camera_key = None;
        if let Rig::Keys { keys, .. } = &mut shot.rig {
            let key = Key {
                time: local,
                pos,
                rot: Some(rot),
                ease,
            };
            match keys
                .iter()
                .position(|key| (key.time - local).abs() <= REPLACE_WINDOW)
            {
                Some(index) => {
                    keys[index] = key;
                    camera_key = Some(index);
                }
                None => {
                    let at = keys.partition_point(|key| key.time < local);
                    keys.insert(at, key);
                    camera_key = Some(at);
                }
            }
        }

        if let FovSpec::VerticalFovDeg(track) = &mut shot.lens.fov {
            let key = ScalarKey {
                time: local,
                value: fov_deg,
                ease,
            };
            match track
                .keys
                .iter()
                .position(|key| (key.time - local).abs() <= REPLACE_WINDOW)
            {
                Some(index) => track.keys[index] = key,
                None => {
                    let at = track.keys.partition_point(|key| key.time < local);
                    track.keys.insert(at, key);
                }
            }
        }
        self.rebake();
        (armed, camera_key)
    }

    pub(crate) fn sync_pilot_from_pose(&mut self, rotation: Quat, fov_y: f32) {
        let (yaw, pitch, _) = rotation.to_euler(EulerRot::YXZ);
        self.yaw = yaw;
        self.pitch = pitch;
        self.fov_deg = fov_y.to_degrees();
    }
}

pub struct ViewfinderPlugin;

impl Plugin for ViewfinderPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<ViewfinderConfig>()
            .init_resource::<ViewfinderSession>()
            .init_gizmo_group::<DirectorGizmoGroup>()
            .add_systems(
                Update,
                (
                    toggle_viewfinder,
                    fly_camera,
                    scrub_and_preview,
                    capture_key,
                    delete_key,
                    save_session,
                    draw_overlay,
                )
                    .chain(),
            )
            .add_systems(
                PostUpdate,
                (update_session_texts, update_session_actor_cues).in_set(DirectorSet::Apply),
            );
    }
}

/// While the viewfinder owns the frame, [`ActiveTexts`] mirrors the
/// working take at the session playhead — scrubbing paused previews text
/// exactly like camera pose. Reads the asset-side copy (not the bake) so
/// authoring works even when the sequence cannot bake yet, and indices
/// always match the editor's selection.
fn update_session_texts(
    state: Res<DirectorState>,
    session: Res<ViewfinderSession>,
    mut active: ResMut<ActiveTexts>,
) {
    if state.phase != DirectorPhase::Viewfinder {
        return;
    }
    if session.sequence.texts.is_empty() && active.blocks.is_empty() {
        return;
    }
    let blocks = &mut active.blocks;
    collect_active_texts(&session.sequence.texts, session.playhead, blocks);
}

/// The actor-cue twin of [`update_session_texts`]: while the viewfinder
/// owns the frame, [`ActiveActorCues`] mirrors the working take so a game
/// binder driving the scene sees the character sleep and wake live as the
/// playhead is scrubbed. Reads the asset-side copy so authoring works
/// before the sequence can bake, indices matching the editor's selection.
fn update_session_actor_cues(
    state: Res<DirectorState>,
    session: Res<ViewfinderSession>,
    mut active: ResMut<ActiveActorCues>,
) {
    if state.phase != DirectorPhase::Viewfinder {
        return;
    }
    if session.sequence.actors.is_empty() && active.cues.is_empty() {
        return;
    }
    let cues = &mut active.cues;
    collect_active_actor_cues(&session.sequence.actors, session.playhead, cues);
}

fn viewfinder_up(state: &DirectorState) -> bool {
    state.phase == DirectorPhase::Viewfinder
}

/// Enter from Idle only; eject back to Idle. A dedicated cine camera
/// keeps its last pose; a borrowed gameplay camera is put back where the
/// session found it. The cursor comes back exactly as it was either way.
#[allow(clippy::too_many_arguments)] // a mode switch touches many doors
fn toggle_viewfinder(
    mut commands: Commands,
    keys: Res<ButtonInput<KeyCode>>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    mut state: ResMut<DirectorState>,
    // p0 reads cameras to find the live one; p1 flips is_active.
    mut cameras: ParamSet<(
        Query<
            (
                Entity,
                &Camera,
                &Transform,
                Option<&Projection>,
                Has<HandoffCamera>,
            ),
            (With<Camera3d>, Without<CineCamera>),
        >,
        Query<&mut Camera>,
    )>,
    cine_query: Query<Entity, With<CineCamera>>,
    mut transforms: Query<(&mut Transform, &mut Projection), With<CineCamera>>,
    mut cursor: Single<&mut CursorOptions>,
) {
    let Some(toggle) = config.toggle else {
        return;
    };
    if !keys.just_pressed(toggle) {
        return;
    }

    if viewfinder_up(&state) {
        // Eject.
        if let Some((visible, grab)) = session.saved_cursor.take() {
            cursor.visible = visible;
            cursor.grab_mode = grab;
        }
        let mut writable = cameras.p1();
        crate::player::restore_live(&mut commands, &mut state, &mut writable);
        return;
    }
    if state.phase != DirectorPhase::Idle {
        warn!("viewfinder only opens while the director is idle");
        return;
    }

    // Take over from wherever the live camera is looking; the marked one
    // wins, exactly as the runtime resolves it.
    let live = {
        let p0 = cameras.p0();
        p0.iter()
            .find(|(_, _, _, _, marked)| *marked)
            .or_else(|| p0.iter().find(|(_, cam, ..)| cam.is_active))
            .map(|(e, _, t, p, _)| (e, snapshot_of(t, p)))
    };
    let live_snapshot = live.map(|(_, s)| s).unwrap_or(CameraSnapshot {
        position: Vec3::new(0.0, 2.0, 8.0),
        rotation: Quat::IDENTITY,
        fov_y: 45f32.to_radians(),
    });

    // With no cine camera the session flies the gameplay camera itself,
    // so what the human frames is what the game renders. A fresh spawn
    // (nothing to borrow either) carries the live pose and active flag in
    // its bundle: commands have not flushed, so a same-frame get_mut
    // cannot reach it.
    let existing = cine_query.iter().next();
    let borrowed = existing.is_none() && live.is_some();
    let cine = existing.or(live.map(|(e, _)| e)).unwrap_or_else(|| {
        commands
            .spawn((
                Name::new("cine camera"),
                CineCamera,
                Camera3d::default(),
                Camera {
                    is_active: true,
                    ..Default::default()
                },
                Projection::Perspective(PerspectiveProjection {
                    fov: live_snapshot.fov_y,
                    ..Default::default()
                }),
                Transform::from_translation(live_snapshot.position)
                    .with_rotation(live_snapshot.rotation),
            ))
            .id()
    });
    commands
        .entity(cine)
        .queue(crate::player::begin_take(if borrowed {
            crate::player::TakeRole::Borrowed
        } else {
            crate::player::TakeRole::Dedicated
        }));

    // A borrowed camera is already at the live pose by definition.
    if !borrowed && let Ok((mut transform, mut projection)) = transforms.get_mut(cine) {
        transform.translation = live_snapshot.position;
        transform.rotation = live_snapshot.rotation;
        if let Projection::Perspective(p) = &mut *projection {
            p.fov = live_snapshot.fov_y;
        }
    }
    let (yaw, pitch, _) = live_snapshot.rotation.to_euler(EulerRot::YXZ);
    session.yaw = yaw;
    session.pitch = pitch;
    session.fov_deg = live_snapshot.fov_y.to_degrees();
    session.speed = config.fly_speed;
    session.playing = false;
    // Every preview blends the first shot from this frozen snapshot,
    // exactly like the runtime snapshots the gameplay camera at play.
    session.live_snapshot = live_snapshot;
    session.preview_prev_rot = None;
    session.preview_lens = crate::player::LensTouch::default();
    session.rebake();

    if !borrowed {
        let mut writable = cameras.p1();
        if let Some((live_entity, _)) = live
            && 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;
        }
    }

    session.saved_cursor = Some((cursor.visible, cursor.grab_mode));
    cursor.visible = false;
    cursor.grab_mode = CursorGrabMode::Locked;

    state.phase = DirectorPhase::Viewfinder;
    state.camera = Some(cine);
    state.anchor = Some(cine);
    state.live_camera = live.map(|(e, _)| e);
    info!(
        "viewfinder up: fly WASD/QE, K captures, [ ] scrub, P previews, ctrl+S saves '{}'",
        session.sequence.name
    );
}

/// Free flight. Any stick input while previewing hands the camera back to
/// the pilot. With `auto_key` on, piloting also writes the framing into
/// the shot under the playhead every frame it changes — After Effects'
/// autokey, with the replace window collapsing a whole adjustment into
/// one key.
#[allow(clippy::too_many_arguments)] // piloting reads the whole cockpit
fn fly_camera(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    motion: Res<AccumulatedMouseMotion>,
    scroll: Res<AccumulatedMouseScroll>,
    time: Res<Time<Real>>,
    mut cine: Query<(&mut Transform, &mut Projection), With<CineCamera>>,
    #[cfg(feature = "editor")] editor: Option<Res<crate::editor::DirectorsCutState>>,
) {
    if !viewfinder_up(&state) || session.playing {
        return;
    }
    #[cfg(feature = "editor")]
    if editor.is_some_and(|editor| editor.open) {
        return;
    }
    let Some(camera) = state.camera else {
        return;
    };
    let Ok((mut transform, mut projection)) = cine.get_mut(camera) else {
        return;
    };

    let ctrl = keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
    let lens_changed = ctrl && scroll.delta.y != 0.0;
    if ctrl {
        // Ctrl+wheel: the lens, not the legs.
        session.fov_deg = (session.fov_deg - scroll.delta.y * 1.5).clamp(10.0, 120.0);
    } else if scroll.delta.y.abs() > 0.0 {
        session.speed = (session.speed * 1.1f32.powf(scroll.delta.y)).clamp(0.5, 200.0);
    }

    session.yaw -= motion.delta.x * MOUSE_SENSITIVITY;
    session.pitch = (session.pitch - motion.delta.y * MOUSE_SENSITIVITY).clamp(-1.54, 1.54);
    transform.rotation = Quat::from_euler(EulerRot::YXZ, session.yaw, session.pitch, 0.0);

    let mut wish = Vec3::ZERO;
    let flat_forward = transform.forward().as_vec3();
    let right = transform.right().as_vec3();
    if keys.pressed(KeyCode::KeyW) {
        wish += flat_forward;
    }
    if keys.pressed(KeyCode::KeyS) {
        wish -= flat_forward;
    }
    if keys.pressed(KeyCode::KeyD) {
        wish += right;
    }
    if keys.pressed(KeyCode::KeyA) {
        wish -= right;
    }
    if keys.pressed(KeyCode::KeyE) {
        wish += Vec3::Y;
    }
    if keys.pressed(KeyCode::KeyQ) {
        wish -= Vec3::Y;
    }
    let sprint = if keys.pressed(KeyCode::ShiftLeft) {
        3.0
    } else {
        1.0
    };
    transform.translation += wish.normalize_or_zero() * session.speed * sprint * time.delta_secs();

    if let Projection::Perspective(p) = &mut *projection {
        p.fov = session.fov_deg.to_radians();
    }

    // Auto-key: the camera changed, so the take changes with it. Only
    // once a first shot exists — exploring an empty take stays free.
    let camera_changed = motion.delta != Vec2::ZERO || wish != Vec3::ZERO || lens_changed;
    if config.auto_key && camera_changed && !session.sequence.shots.is_empty() {
        let fov_deg = session.fov_deg;
        session.capture_frame(
            transform.translation,
            transform.rotation,
            fov_deg,
            config.capture_ease,
        );
    }
}

/// Brackets scrub, P plays the working copy in place. While scrubbing or
/// playing, the camera sits on the evaluated pose. The evaluation context
/// mirrors the runtime's: the first shot blends from the frozen
/// gameplay-camera snapshot (never the camera's own last pose, which
/// would feed back through blend windows), and entity targets resolve
/// against the world — so play, scrub, and in-game playback agree.
#[allow(clippy::too_many_arguments)] // the preview needs the runtime's inputs
fn scrub_and_preview(
    mut commands: Commands,
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    motion: Res<AccumulatedMouseMotion>,
    time: Res<Time<Real>>,
    names: Query<(&Name, &GlobalTransform)>,
    mut cine: Query<(&mut Transform, &mut Projection), With<CineCamera>>,
    pre_take: Query<&crate::player::PreTakeState>,
    #[cfg(feature = "editor")] editor: Option<Res<crate::editor::DirectorsCutState>>,
) {
    if !viewfinder_up(&state) {
        return;
    }
    // A text field owns the keyboard: brackets and P are just letters.
    #[cfg(feature = "editor")]
    if editor.as_ref().is_some_and(|editor| editor.typing()) {
        return;
    }
    let step = if keys.pressed(KeyCode::ShiftLeft) {
        1.0 / 30.0
    } else {
        config.scrub_step
    };
    let mut moved = false;
    let mut advancing = false;
    if keys.just_pressed(config.scrub_back) {
        session.playhead = (session.playhead - step).max(0.0);
        moved = true;
    }
    if keys.just_pressed(config.scrub_forward) {
        session.playhead += step;
        moved = true;
    }
    if keys.just_pressed(config.play_pause) {
        session.playing = !session.playing;
        if session.playing {
            // A fresh take starts clean, like the runtime's player.
            session.preview_prev_rot = None;
            if session.playhead >= session.sequence.duration() {
                session.playhead = 0.0;
            }
        }
        moved = true;
    }
    if session.playing {
        session.playhead += time.delta_secs();
        if session.playhead >= session.sequence.duration() {
            session.playing = false;
        }
        // The pilot takes over the instant they touch the stick.
        #[cfg(feature = "editor")]
        let editor_open = editor.is_some_and(|editor| editor.open);
        #[cfg(not(feature = "editor"))]
        let editor_open = false;
        if motion.delta.length_squared() > 4.0 && !editor_open {
            session.playing = false;
            return;
        }
        moved = true;
        advancing = true;
    }
    if !moved {
        return;
    }

    let duration = session.sequence.duration();
    session.playhead = session.playhead.clamp(0.0, duration.max(0.0));
    let Some(camera) = state.camera else {
        return;
    };
    let Ok((mut transform, mut projection)) = cine.get_mut(camera) else {
        return;
    };
    let live = session.live_snapshot;
    let resolve = |wanted: &str| {
        names
            .iter()
            .find(|(name, _)| name.as_str() == wanted)
            .map(|(_, gt)| gt.translation())
    };
    // Scrubs are seeks: damped looks snap, like the runtime seeking.
    let ctx = EvalCtx {
        live: &live,
        dt: if advancing { time.delta_secs() } else { 0.0 },
        prev_rot: if advancing {
            session.preview_prev_rot
        } else {
            None
        },
        resolve_entity: &resolve,
        // Previews never cut, so Held shots ride the piloted camera's
        // own parked pose.
        held: pre_take.get(camera).ok().map(|p| p.held_snapshot()),
    };
    let Some(compiled) = &session.compiled else {
        return;
    };
    let pose = compiled.pose_at(session.playhead, &ctx);
    transform.translation = pose.position;
    transform.rotation = pose.rotation;
    if let Projection::Perspective(p) = &mut *projection {
        p.fov = pose.fov_y;
    }
    // Author the lens with your eyes, not the numbers: the preview puts
    // the same components on as playback. They hold their last sampled
    // values while the pilot flies, and the session's PreTakeState puts
    // the camera's own back on eject.
    let touch = crate::player::LensTouch::of(&pose);
    crate::player::apply_lens_components(
        &mut commands,
        camera,
        &pose,
        touch.union(session.preview_lens),
        pre_take.get(camera).ok().and_then(|p| p.grading()),
    );
    session.preview_lens = touch;
    session.preview_prev_rot = Some(pose.rotation);
    session.sync_pilot_from_pose(pose.rotation, pose.fov_y);
}

/// K: this framing, at this playhead, onto the armed shot.
fn capture_key(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    cine: Query<&Transform, With<CineCamera>>,
    #[cfg(feature = "editor")] editor: Option<Res<crate::editor::DirectorsCutState>>,
) {
    if !viewfinder_up(&state) || !keys.just_pressed(config.capture) {
        return;
    }
    // Typing a "k" into a text field must not capture a camera key.
    #[cfg(feature = "editor")]
    if editor.is_some_and(|editor| editor.typing()) {
        return;
    }
    let Some(transform) = state.camera.and_then(|e| cine.get(e).ok()) else {
        return;
    };

    let fov_deg = session.fov_deg;
    session.capture_frame(
        transform.translation,
        transform.rotation,
        fov_deg,
        config.capture_ease,
    );
    let armed = session.armed_shot;
    let local = (session.playhead - session.sequence.shots[armed].start).max(0.0);
    info!(
        "key at {:.2}s in shot {} ({} keys)",
        local,
        armed,
        key_count(&session.sequence, armed)
    );
}

fn key_count(sequence: &SequenceAsset, shot: usize) -> usize {
    match &sequence.shots[shot].rig {
        Rig::Keys { keys, .. } => keys.len(),
        _ => 0,
    }
}

/// Delete: the nearest key within reach of the camera.
fn delete_key(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    mut session: ResMut<ViewfinderSession>,
    cine: Query<&Transform, With<CineCamera>>,
    #[cfg(feature = "editor")] editor: Option<Res<crate::editor::DirectorsCutState>>,
) {
    if !viewfinder_up(&state) || !keys.just_pressed(config.delete) {
        return;
    }
    // Backspacing in a text field must not reach into the 3D scene.
    #[cfg(feature = "editor")]
    if editor.is_some_and(|editor| editor.typing()) {
        return;
    }
    let Some(transform) = state.camera.and_then(|e| cine.get(e).ok()) else {
        return;
    };
    let from = transform.translation;

    let mut best: Option<(usize, usize, f32)> = None;
    for (si, shot) in session.sequence.shots.iter().enumerate() {
        let Rig::Keys { keys, .. } = &shot.rig else {
            continue;
        };
        for (ki, key) in keys.iter().enumerate() {
            let d = key.pos.distance(from);
            if d <= DELETE_RANGE && best.is_none_or(|(_, _, bd)| d < bd) {
                best = Some((si, ki, d));
            }
        }
    }
    let Some((si, ki, _)) = best else {
        info!("no key within {DELETE_RANGE} m to delete");
        return;
    };
    let Rig::Keys { keys, .. } = &mut session.sequence.shots[si].rig else {
        return;
    };
    let removed = keys.remove(ki);
    session.rebake();
    info!("removed key at {:.2}s from shot {si}", removed.time);
}

/// Ctrl+S: the working take to disk, where the asset server reads.
fn save_session(
    keys: Res<ButtonInput<KeyCode>>,
    state: Res<DirectorState>,
    config: Res<ViewfinderConfig>,
    session: Res<ViewfinderSession>,
    #[cfg(feature = "editor")] editor: Option<Res<crate::editor::DirectorsCutState>>,
) {
    if !viewfinder_up(&state) || !keys.just_pressed(KeyCode::KeyS) {
        return;
    }
    #[cfg(feature = "editor")]
    if editor.is_some_and(|editor| editor.typing()) {
        return;
    }
    if !(keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight)) {
        return;
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        let path = config
            .save_dir
            .join(format!("{}.dir.ron", session.sequence.name));
        match crate::loader::save_sequence(&session.sequence, &path) {
            Ok(()) => info!("saved {}", path.display()),
            Err(err) => error!("could not save sequence: {err}"),
        }
    }
    #[cfg(target_arch = "wasm32")]
    warn!("saving sequences is native-only");
}

/// The whole overlay: paths, keys, aim rays, and the playhead ghost.
fn draw_overlay(
    state: Res<DirectorState>,
    session: Res<ViewfinderSession>,
    mut gizmos: Gizmos<DirectorGizmoGroup>,
) {
    if !viewfinder_up(&state) {
        return;
    }
    draw_sequence(&mut gizmos, &session.sequence);
    if let Some(compiled) = &session.compiled {
        // The same snapshot every preview blends from, so the ghost sits
        // where the camera will actually be.
        let live = session.live_snapshot;
        let pose = compiled.pose_at(session.playhead, &EvalCtx::still(&live));
        draw_playhead(&mut gizmos, pose.position, pose.rotation);
    }
}

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

    fn two_shot_session() -> ViewfinderSession {
        let mut session = ViewfinderSession::default();
        session.sequence.shots = vec![
            Shot::keys(
                0.0,
                2.0,
                vec![Key::at(0.0).pos(Vec3::ZERO).rot(Quat::IDENTITY)],
            ),
            Shot::keys(
                2.0,
                2.0,
                vec![Key::at(0.0).pos(Vec3::X).rot(Quat::IDENTITY)],
            ),
        ];
        session
    }

    #[test]
    fn capture_targets_the_shot_under_the_playhead() {
        let mut session = two_shot_session();
        // A stale armed shot must not catch the key.
        session.armed_shot = 0;
        session.playhead = 3.0;
        let (shot, key) =
            session.capture_frame(Vec3::splat(2.0), Quat::IDENTITY, 45.0, EaseFunction::Linear);
        assert_eq!(shot, 1);
        assert_eq!(key, Some(1));
        assert_eq!(session.armed_shot, 1);
        let Rig::Keys { keys, .. } = &session.sequence.shots[1].rig else {
            panic!("expected key rig");
        };
        assert_eq!(keys.len(), 2);
        assert!((keys[1].time - 1.0).abs() < 1e-6);
        // Shot 0 was left alone.
        let Rig::Keys { keys, .. } = &session.sequence.shots[0].rig else {
            panic!("expected key rig");
        };
        assert_eq!(keys.len(), 1);
    }

    #[test]
    fn capture_replaces_within_the_window_and_reports_the_index() {
        let mut session = two_shot_session();
        session.playhead = 3.0;
        let first = session.capture_frame(Vec3::ONE, Quat::IDENTITY, 45.0, EaseFunction::Linear);
        let second =
            session.capture_frame(Vec3::splat(9.0), Quat::IDENTITY, 45.0, EaseFunction::Linear);
        assert_eq!(first, second);
        let Rig::Keys { keys, .. } = &session.sequence.shots[1].rig else {
            panic!("expected key rig");
        };
        assert_eq!(keys.len(), 2);
        assert_eq!(keys[1].pos, Vec3::splat(9.0));
    }

    #[test]
    fn capture_past_the_last_shot_extends_it() {
        let mut session = two_shot_session();
        session.playhead = 5.0;
        let (shot, _) =
            session.capture_frame(Vec3::ZERO, Quat::IDENTITY, 45.0, EaseFunction::Linear);
        assert_eq!(shot, 1);
        assert!((session.sequence.shots[1].duration - 3.0).abs() < 1e-6);
    }

    #[test]
    fn first_capture_creates_a_shot() {
        let mut session = ViewfinderSession::default();
        let (shot, key) =
            session.capture_frame(Vec3::ZERO, Quat::IDENTITY, 45.0, EaseFunction::Linear);
        assert_eq!((shot, key), (0, Some(0)));
        assert_eq!(session.sequence.shots.len(), 1);
    }

    #[test]
    fn auto_key_defaults_on() {
        assert!(ViewfinderConfig::default().auto_key);
    }

    #[test]
    fn toggle_defaults_to_backquote_and_can_be_turned_off() {
        assert_eq!(ViewfinderConfig::default().toggle, Some(KeyCode::Backquote));
        let silent = ViewfinderConfig {
            toggle: None,
            ..Default::default()
        };
        assert_eq!(silent.toggle, None);
    }
}