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
//! The data model: what a sequence IS, on disk and in memory. Everything
//! here is plain serde data; the runtime never reads it directly, it bakes
//! it first (see eval.rs). Times are seconds. Shot starts are absolute on
//! the sequence timeline; key times are local to their shot.

use bevy::prelude::*;
use serde::{Deserialize, Serialize};

/// A cinematic sequence: an ordered list of shots (the camera-cuts track)
/// plus named markers and an optional handback blend at the end.
#[derive(Asset, Reflect, Clone, Debug, Serialize, Deserialize)]
pub struct SequenceAsset {
    pub name: String,
    pub shots: Vec<Shot>,
    #[serde(default)]
    pub markers: Vec<Marker>,
    /// Overlay text: title cards, lower thirds, captions. Blocks live on
    /// the sequence timeline (not inside shots) so one caption can hold
    /// across a camera cut. Skipped when empty so text-free files stay
    /// byte-identical to what 0.3 wrote.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub texts: Vec<TextBlock>,
    /// Actor tracks: named animation cues aimed at world entities (the
    /// sleeping heroine, an opening door). The director publishes which
    /// cues the playhead is inside; the game maps cue names onto its own
    /// animation setup. Skipped when empty so actor-free files stay
    /// byte-identical to what 0.4 wrote.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actors: Vec<ActorTrack>,
    /// Blend back to the live gameplay camera when the sequence ends.
    /// None means a hard cut back.
    #[serde(default)]
    pub blend_out: Option<Blend>,
}

impl SequenceAsset {
    /// A sequence with no shots yet, for the viewfinder to fill.
    pub fn empty(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            shots: Vec::new(),
            markers: Vec::new(),
            texts: Vec::new(),
            actors: Vec::new(),
            blend_out: None,
        }
    }

    /// End of the last shot; zero for an empty sequence.
    pub fn duration(&self) -> f32 {
        self.shots
            .iter()
            .map(|s| s.start + s.duration)
            .fold(0.0, f32::max)
    }
}

/// One camera setup for a span of the timeline. Shots cut hard by default;
/// give a shot a blend_in to ease from the previous one (or, on the first
/// shot, from the live gameplay camera).
#[derive(Reflect, Clone, Debug, Serialize, Deserialize)]
pub struct Shot {
    /// Absolute start on the sequence timeline.
    pub start: f32,
    pub duration: f32,
    #[serde(default)]
    pub blend_in: Option<Blend>,
    pub rig: Rig,
    #[serde(default)]
    pub look: Look,
    #[serde(default)]
    pub lens: Lens,
    /// Handheld wobble layered on top of everything else.
    #[serde(default)]
    pub shake: Option<Shake>,
}

/// A deterministic handheld layer. Same seed, same take, every run.
#[derive(Reflect, Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Shake {
    /// Peak angular wobble, degrees.
    pub amplitude_deg: f32,
    pub frequency_hz: f32,
    #[serde(default)]
    pub seed: u32,
    /// Peak positional wobble in local space, meters.
    #[serde(default)]
    pub pos_amplitude: f32,
}

/// How the camera transform is produced over the shot.
#[derive(Reflect, Clone, Debug, Serialize, Deserialize)]
pub enum Rig {
    /// Keyframed poses, eased per key toward the next.
    Keys {
        keys: Vec<Key>,
        #[serde(default)]
        interp: KeyInterp,
    },
    /// A dolly on a spline through the given points. `progress` is the
    /// 0..1 travel over the shot (empty track = linear over the whole
    /// shot); `constant_speed` makes equal time cover equal distance.
    Rail {
        points: Vec<Vec3>,
        #[serde(default)]
        kind: RailKind,
        #[serde(default = "yes")]
        constant_speed: bool,
        #[serde(default)]
        progress: ScalarTrack,
    },
    /// A crane circling a target: spherical coordinates over time.
    /// Yaw 0 / pitch 0 sits on +Z of the center; yaw sweeps toward +X.
    Orbit {
        center: TargetRef,
        radius: ScalarTrack,
        #[serde(default)]
        yaw_deg: ScalarTrack,
        #[serde(default)]
        pitch_deg: ScalarTrack,
    },
}

fn yes() -> bool {
    true
}

/// How key positions travel between keys.
#[derive(Reflect, Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyInterp {
    /// Straight line per segment, shaped by each key's ease.
    #[default]
    Eased,
    /// Catmull-Rom through the key positions: one smooth curve, still
    /// paced by each key's ease.
    CatmullRom,
}

/// The spline family under a rail.
#[derive(Reflect, Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum RailKind {
    /// Passes through every point. Needs at least 2.
    #[default]
    CatmullRom,
    /// Smoother, does not touch the points. Needs at least 4.
    BSpline,
}

/// Something in the world a shot can aim at or focus on.
#[derive(Reflect, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TargetRef {
    Point(Vec3),
    /// Resolved against bevy `Name` at runtime.
    Entity(String),
}

/// One captured framing.
#[derive(Reflect, Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Key {
    /// Seconds from the shot's start.
    pub time: f32,
    pub pos: Vec3,
    /// Used while the shot's look is Free. Rig rotations are ignored when
    /// a look-at owns the aim.
    #[serde(default)]
    pub rot: Option<Quat>,
    /// Shapes the travel toward the NEXT key.
    #[serde(default = "linear")]
    pub ease: EaseFunction,
}

fn linear() -> EaseFunction {
    EaseFunction::Linear
}

/// Where the camera aims.
#[derive(Reflect, Clone, Debug, Default, Serialize, Deserialize)]
pub enum Look {
    /// Aim comes from the rig's key rotations. Rails have none, so a
    /// rail shot must pick At or Velocity.
    #[default]
    Free,
    /// Track a target. `damping` is an exponential decay rate (higher =
    /// tighter); None snaps.
    At {
        target: TargetRef,
        #[serde(default)]
        damping: Option<f32>,
    },
    /// Face wherever the rig is moving: the dolly operator's default.
    Velocity,
}

/// A scalar animated over the shot: fov, and later focus and aperture.
#[derive(Reflect, Clone, Debug, Default, Serialize, Deserialize)]
pub struct ScalarTrack {
    pub keys: Vec<ScalarKey>,
}

#[derive(Reflect, Clone, Copy, Debug, Serialize, Deserialize)]
pub struct ScalarKey {
    pub time: f32,
    pub value: f32,
    #[serde(default = "linear")]
    pub ease: EaseFunction,
}

impl ScalarTrack {
    pub fn constant(value: f32) -> Self {
        Self {
            keys: vec![ScalarKey {
                time: 0.0,
                value,
                ease: EaseFunction::Linear,
            }],
        }
    }

    /// Sample at a shot-local time. Holds the first and last values
    /// outside the keyed range. Keys must be sorted (bake checks).
    pub fn sample(&self, t: f32) -> f32 {
        let keys = &self.keys;
        let Some(first) = keys.first() else {
            return 0.0;
        };
        if t <= first.time {
            return first.value;
        }
        for pair in keys.windows(2) {
            let (a, b) = (&pair[0], &pair[1]);
            if t <= b.time {
                let span = (b.time - a.time).max(f32::EPSILON);
                let w = a.ease.sample_clamped((t - a.time) / span);
                return a.value + (b.value - a.value) * w;
            }
        }
        keys.last().map_or(0.0, |k| k.value)
    }
}

/// The lens: field of view, focus, aperture, exposure. Focus and
/// aperture become bevy DepthOfField on the cine camera; exposure
/// becomes the Exposure component. All optional beyond fov.
#[derive(Reflect, Clone, Debug, Default, Serialize, Deserialize)]
pub struct Lens {
    #[serde(default)]
    pub fov: FovSpec,
    #[serde(default)]
    pub focus: Option<FocusTrack>,
    #[serde(default)]
    pub aperture_f_stops: Option<ScalarTrack>,
    #[serde(default)]
    pub exposure_ev100: Option<ScalarTrack>,
    #[serde(default)]
    pub dof_mode: DofMode,
}

/// Field of view over the shot.
#[derive(Reflect, Clone, Debug, Serialize, Deserialize)]
pub enum FovSpec {
    /// Vertical fov in DEGREES (the engine wants radians; eval converts).
    VerticalFovDeg(ScalarTrack),
    /// A real lens: focal length in millimeters against a filmback.
    /// fov_y = 2 atan(sensor_height / 2 focal).
    FocalLengthMm {
        track: ScalarTrack,
        #[serde(default)]
        filmback: Filmback,
    },
}

impl Default for FovSpec {
    fn default() -> Self {
        FovSpec::VerticalFovDeg(ScalarTrack::constant(45.0))
    }
}

/// Sensor heights for the focal-length math. Super35 matches bevy's
/// PhysicalCameraParameters default (18.66 mm).
#[derive(Reflect, Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Filmback {
    #[default]
    Super35,
    FullFrame,
    Super16,
    Custom {
        sensor_height_mm: f32,
    },
}

impl Filmback {
    pub fn sensor_height_mm(&self) -> f32 {
        match self {
            Filmback::Super35 => 18.66,
            Filmback::FullFrame => 24.0,
            Filmback::Super16 => 7.41,
            Filmback::Custom { sensor_height_mm } => *sensor_height_mm,
        }
    }
}

/// Where the focus plane sits over the shot.
#[derive(Reflect, Clone, Debug, Serialize, Deserialize)]
pub enum FocusTrack {
    /// Meters from the camera.
    Distance(ScalarTrack),
    /// Follow a target; offset shifts the plane in meters.
    Target {
        target: TargetRef,
        #[serde(default)]
        offset: f32,
    },
}

/// bevy's two depth-of-field looks.
#[derive(Reflect, Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum DofMode {
    /// Cheap and safe everywhere.
    #[default]
    Gaussian,
    /// The pretty one; needs dual-source blending support.
    Bokeh,
}

/// An eased transition window.
#[derive(Reflect, Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Blend {
    pub secs: f32,
    pub ease: EaseFunction,
}

/// A named point on the timeline. Markers are presentation cues (sound
/// stingers, one-shot effects): they fire only while playing forward
/// across their time, and skipping does not retro-fire them. On-screen
/// text belongs on [`TextBlock`]s; story-critical flags belong on
/// SequenceFinished.
#[derive(Reflect, Clone, Debug, Serialize, Deserialize)]
pub struct Marker {
    pub time: f32,
    pub name: String,
}

/// Overlay text shown for a span of the sequence: a title card, a lower
/// third, a caption. Unlike markers (edge-triggered cues), text blocks are
/// level-triggered: whatever the playhead is inside is visible, so seeks,
/// loops, and negative rates need no special handling.
#[derive(Reflect, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TextBlock {
    /// Absolute seconds on the sequence timeline (like a marker or a shot
    /// start). Blocks may overlap each other and span shot cuts.
    pub start: f32,
    pub duration: f32,
    pub text: String,
    #[serde(default)]
    pub anchor: TextAnchor,
    /// Seconds to ramp alpha 0 -> 1 from the start.
    #[serde(default)]
    pub fade_in: f32,
    /// Seconds to ramp alpha 1 -> 0 into the end.
    #[serde(default)]
    pub fade_out: f32,
    #[serde(default)]
    pub style: TextBlockStyle,
}

/// Where a block sits on screen. Layout is done in the cine camera's
/// viewport, so anchors stay inside the letterbox crop.
#[derive(Reflect, Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum TextAnchor {
    /// Dead center: title cards.
    Center,
    /// The subtitle zone above the bottom edge.
    #[default]
    LowerThird,
    /// Below the top edge: chapter names, location stamps.
    TopCenter,
}

/// How a block looks. The `titles` feature's renderer honors all of it;
/// custom renderers reading [`ActiveTexts`](crate::ActiveTexts) may use
/// as much or as little as they like.
#[derive(Reflect, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TextBlockStyle {
    #[serde(default = "default_title_size")]
    pub font_size: f32,
    #[serde(default = "default_title_color")]
    pub color: Color,
    /// Drop shadow for legibility over bright scenes.
    #[serde(default = "yes")]
    pub shadow: bool,
    /// A box behind the text, e.g. semi-transparent black for subtitles.
    #[serde(default)]
    pub background: Option<Color>,
}

fn default_title_size() -> f32 {
    28.0
}

fn default_title_color() -> Color {
    Color::WHITE
}

impl Default for TextBlockStyle {
    fn default() -> Self {
        Self {
            font_size: default_title_size(),
            color: default_title_color(),
            shadow: true,
            background: None,
        }
    }
}

impl TextBlock {
    /// End of the block on the sequence timeline.
    pub fn end(&self) -> f32 {
        self.start + self.duration
    }

    /// Whether the block is visible at all at `t`. The window is
    /// half-open: a block ends exactly when the next may begin.
    pub fn active_at(&self, t: f32) -> bool {
        self.duration > 0.0 && t >= self.start && t < self.end()
    }

    /// Opacity at `t`: 0 outside the window, otherwise the lesser of the
    /// fade-in and fade-out ramps. Zero-length fades are instant; fades
    /// longer than the block degrade to a triangular ramp that never
    /// reaches full opacity, no special case needed.
    pub fn alpha_at(&self, t: f32) -> f32 {
        if !self.active_at(t) {
            return 0.0;
        }
        let ramp_in = if self.fade_in > 0.0 {
            (t - self.start) / self.fade_in
        } else {
            1.0
        };
        let ramp_out = if self.fade_out > 0.0 {
            (self.end() - t) / self.fade_out
        } else {
            1.0
        };
        ramp_in.min(ramp_out).clamp(0.0, 1.0)
    }
}

/// One directed entity: who, plus the animation cues it performs over
/// the sequence. The director never plays animations itself — it only
/// reports which cues the playhead is inside (see
/// [`ActiveActorCues`](crate::ActiveActorCues)); the game owns the
/// mapping from cue names to its animation graph, so the camera core
/// stays free of any particular rig or player setup.
#[derive(Reflect, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActorTrack {
    /// Who performs. `Entity(name)` is the normal case; a `Point` target
    /// can never resolve to a performer and is reported as authored for
    /// the game to ignore or warn about.
    pub target: TargetRef,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cues: Vec<ActorCue>,
}

/// One animation cue: a named performance over a span of the sequence.
/// Like text blocks (and unlike markers), cues are level-triggered:
/// whatever the playhead sits inside is active, so seeks, skips, and
/// negative rates need no special handling.
#[derive(Reflect, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActorCue {
    /// Absolute seconds on the sequence timeline, like a text block.
    pub start: f32,
    pub duration: f32,
    /// The game-defined performance name, e.g. "cutscene.sleeping".
    pub anim: String,
    /// Seconds the game should take to crossfade INTO the performance.
    /// Also shapes [`ActorCue::alpha_at`] for weight-aware consumers.
    #[serde(default)]
    pub fade_in: f32,
    /// Seconds to crossfade OUT toward the end of the window.
    #[serde(default)]
    pub fade_out: f32,
    /// Playback rate hint for the clip. 1.0 is authored speed.
    #[serde(default = "one")]
    pub speed: f32,
}

fn one() -> f32 {
    1.0
}

impl ActorCue {
    /// End of the cue on the sequence timeline.
    pub fn end(&self) -> f32 {
        self.start + self.duration
    }

    /// Whether the cue is active at `t`. The window is half-open: a cue
    /// ends exactly when the next may begin.
    pub fn active_at(&self, t: f32) -> bool {
        self.duration > 0.0 && t >= self.start && t < self.end()
    }

    /// Blend weight at `t`: 0 outside the window, otherwise the lesser
    /// of the fade ramps — the same shape as [`TextBlock::alpha_at`].
    pub fn alpha_at(&self, t: f32) -> f32 {
        if !self.active_at(t) {
            return 0.0;
        }
        let ramp_in = if self.fade_in > 0.0 {
            (t - self.start) / self.fade_in
        } else {
            1.0
        };
        let ramp_out = if self.fade_out > 0.0 {
            (self.end() - t) / self.fade_out
        } else {
            1.0
        };
        ramp_in.min(ramp_out).clamp(0.0, 1.0)
    }
}

// ---------- code-side authoring ----------

impl Key {
    /// A key at a shot-local time, filled in with the builder calls.
    pub fn at(time: f32) -> Self {
        Self {
            time,
            pos: Vec3::ZERO,
            rot: None,
            ease: EaseFunction::Linear,
        }
    }

    pub fn pos(mut self, pos: Vec3) -> Self {
        self.pos = pos;
        self
    }

    pub fn rot(mut self, rot: Quat) -> Self {
        self.rot = Some(rot);
        self
    }

    /// Aim this key at a point (a Free-look convenience).
    pub fn looking_at(mut self, target: Vec3) -> Self {
        self.rot = Some(
            Transform::from_translation(self.pos)
                .looking_at(target, Vec3::Y)
                .rotation,
        );
        self
    }

    pub fn ease(mut self, ease: EaseFunction) -> Self {
        self.ease = ease;
        self
    }
}

impl Shot {
    /// A keyed shot with defaults everywhere else.
    pub fn keys(start: f32, duration: f32, keys: impl Into<Vec<Key>>) -> Self {
        Self {
            start,
            duration,
            blend_in: None,
            rig: Rig::Keys {
                keys: keys.into(),
                interp: KeyInterp::Eased,
            },
            look: Look::default(),
            lens: Lens::default(),
            shake: None,
        }
    }

    pub fn blend_in(mut self, secs: f32, ease: EaseFunction) -> Self {
        self.blend_in = Some(Blend { secs, ease });
        self
    }

    pub fn look(mut self, look: Look) -> Self {
        self.look = look;
        self
    }

    pub fn lens(mut self, lens: Lens) -> Self {
        self.lens = lens;
        self
    }

    pub fn shake(mut self, shake: Shake) -> Self {
        self.shake = Some(shake);
        self
    }
}

impl TextBlock {
    /// A block at an absolute time, filled in with the builder calls.
    pub fn at(start: f32, duration: f32, text: impl Into<String>) -> Self {
        Self {
            start,
            duration,
            text: text.into(),
            anchor: TextAnchor::default(),
            fade_in: 0.0,
            fade_out: 0.0,
            style: TextBlockStyle::default(),
        }
    }

    pub fn anchor(mut self, anchor: TextAnchor) -> Self {
        self.anchor = anchor;
        self
    }

    pub fn fades(mut self, fade_in: f32, fade_out: f32) -> Self {
        self.fade_in = fade_in;
        self.fade_out = fade_out;
        self
    }

    pub fn style(mut self, style: TextBlockStyle) -> Self {
        self.style = style;
        self
    }
}

impl ActorTrack {
    /// A track performed by the named entity, filled with `.cue()` calls.
    pub fn entity(name: impl Into<String>) -> Self {
        Self {
            target: TargetRef::Entity(name.into()),
            cues: Vec::new(),
        }
    }

    pub fn cue(mut self, cue: ActorCue) -> Self {
        self.cues.push(cue);
        self
    }
}

impl ActorCue {
    /// A cue at an absolute time, filled in with the builder calls.
    pub fn at(start: f32, duration: f32, anim: impl Into<String>) -> Self {
        Self {
            start,
            duration,
            anim: anim.into(),
            fade_in: 0.0,
            fade_out: 0.0,
            speed: 1.0,
        }
    }

    pub fn fades(mut self, fade_in: f32, fade_out: f32) -> Self {
        self.fade_in = fade_in;
        self.fade_out = fade_out;
        self
    }

    pub fn speed(mut self, speed: f32) -> Self {
        self.speed = speed;
        self
    }
}

impl SequenceAsset {
    /// The one-shot convenience for code and tests.
    pub fn single_shot(name: impl Into<String>, shot: Shot) -> Self {
        Self {
            name: name.into(),
            shots: vec![shot],
            markers: Vec::new(),
            texts: Vec::new(),
            actors: Vec::new(),
            blend_out: None,
        }
    }
}

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

    #[test]
    fn text_block_alpha_ramps_and_boundaries() {
        let block = TextBlock::at(2.0, 4.0, "caption").fades(1.0, 2.0);
        // Outside the half-open window.
        assert_eq!(block.alpha_at(1.999), 0.0);
        assert_eq!(block.alpha_at(6.0), 0.0);
        // Start of a fade-in is fully transparent.
        assert_eq!(block.alpha_at(2.0), 0.0);
        // Mid fade-in.
        assert!((block.alpha_at(2.5) - 0.5).abs() < 1e-6);
        // Plateau between the ramps.
        assert_eq!(block.alpha_at(3.5), 1.0);
        // Mid fade-out: 1.5 s left of a 2 s ramp.
        assert!((block.alpha_at(4.5) - 0.75).abs() < 1e-6);
    }

    #[test]
    fn text_block_zero_fades_are_instant() {
        let block = TextBlock::at(1.0, 2.0, "cut in");
        assert_eq!(block.alpha_at(1.0), 1.0);
        assert_eq!(block.alpha_at(2.999), 1.0);
        assert_eq!(block.alpha_at(3.0), 0.0);
    }

    #[test]
    fn text_block_overlong_fades_peak_below_one() {
        // 1 s in + 1 s out over a 1 s block: a triangle peaking at 0.5.
        let block = TextBlock::at(0.0, 1.0, "flash").fades(1.0, 1.0);
        assert!((block.alpha_at(0.5) - 0.5).abs() < 1e-6);
        assert!(block.alpha_at(0.25) < 0.5);
        assert!(block.alpha_at(0.75) < 0.5);
    }

    #[test]
    fn text_block_zero_duration_is_never_active() {
        let block = TextBlock::at(1.0, 0.0, "nothing");
        assert!(!block.active_at(1.0));
        assert_eq!(block.alpha_at(1.0), 0.0);
    }

    #[test]
    fn actor_cue_alpha_ramps_and_boundaries() {
        let cue = ActorCue::at(2.0, 4.0, "cutscene.sleeping").fades(1.0, 2.0);
        // Outside the half-open window.
        assert_eq!(cue.alpha_at(1.999), 0.0);
        assert_eq!(cue.alpha_at(6.0), 0.0);
        // Start of a fade-in is fully transparent.
        assert_eq!(cue.alpha_at(2.0), 0.0);
        // Mid fade-in, plateau, mid fade-out.
        assert!((cue.alpha_at(2.5) - 0.5).abs() < 1e-6);
        assert_eq!(cue.alpha_at(3.5), 1.0);
        assert!((cue.alpha_at(4.5) - 0.75).abs() < 1e-6);
    }

    #[test]
    fn actor_cue_zero_duration_is_never_active() {
        let cue = ActorCue::at(1.0, 0.0, "nothing");
        assert!(!cue.active_at(1.0));
        assert_eq!(cue.alpha_at(1.0), 0.0);
    }

    #[test]
    fn actor_cue_default_speed_is_one() {
        let cue = ActorCue::at(0.0, 1.0, "walk");
        assert_eq!(cue.speed, 1.0);
        assert_eq!(cue.speed(1.5).speed, 1.5);
    }
}