mirage-engine 0.2.0

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
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
use core::fmt::{self, Debug, Formatter};
use core::marker::PhantomData;
use core::time::Duration;

use crate::animation::posed::{Fading, Posed};
use crate::animation::{AnimationStates, Running, Timed, Transition};
use crate::mesh::Animation;

/// The weight a fade has run out at.
const WHOLE: f32 = 1.0;

/// Times the machine halves a tick's own span to reach the instant inside
/// it a transition started at, which leaves that instant known to within
/// `0.0001` of the span.
const CROSSINGS: u32 = 14;

/// The machine a game poses a draw with: the state it is in, what that
/// state plays, and the fade out of the state it left.
///
/// Typed by the mesh it poses, so a draw of another mesh does not take it.
/// [`ctx.animate`](crate::TickContext::animate) runs one and
/// [`Instance::posed`](crate::mesh::Instance::posed) draws in the pose it
/// holds; no clip length and no time of the game's own crosses either call.
pub struct Animator<M, S: AnimationStates> {
    state: S,
    motion: Timed,
    fading: Option<Fading>,
    changed: Option<Change<S>>,
    holding: Holding,
    /// The last instant `animate` ran it at, which a clock that goes back
    /// is held to.
    seen: Duration,
    mesh: PhantomData<fn() -> M>,
}

impl<M, S: AnimationStates> Animator<M, S> {
    /// A machine in its entry state, at the start of what that state plays
    /// reading the default input.
    pub fn new() -> Self {
        let state = S::entry();
        let motion = Timed::new(&state.motion(&S::Input::default()), None, 0.0);

        Self {
            state,
            motion,
            fading: None,
            changed: None,
            holding: Holding::Running,
            seen: Duration::ZERO,
            mesh: PhantomData,
        }
    }

    /// The state it is in, which is the state being faded into while a fade
    /// runs.
    pub fn state(&self) -> S {
        self.state
    }

    /// Whether a transition into `state` started the last time `animate`
    /// ran it.
    pub fn entered(&self, state: S) -> bool {
        self.changed.is_some_and(|changed| changed.entered == state)
    }

    /// Whether a transition out of `state` started the last time `animate`
    /// ran it.
    pub fn left(&self, state: S) -> bool {
        self.changed.is_some_and(|changed| changed.left == state)
    }

    /// Whether a fade out of the state it left was still running the last
    /// time `animate` ran it.
    pub fn transitioning(&self) -> bool {
        self.fading.is_some()
    }

    /// Holds what it plays where it is, until [`resume`](Self::resume).
    ///
    /// Required if you want a paused game to leave every mesh in the pose
    /// it is drawn in: the span between this call and the resume counts for
    /// nothing, so each motion runs on from where it was held.
    pub fn hold(&mut self) {
        self.holding = Holding::Held;
    }

    /// Plays on from where [`hold`](Self::hold) left it.
    pub fn resume(&mut self) {
        if self.holding == Holding::Held {
            self.holding = Holding::Resumed;
        }
    }

    /// Runs the machine up to `now`: where the state it is in goes from
    /// there, and what the state it lands in plays.
    pub(crate) fn animate(&mut self, input: &S::Input, now: Duration, clips: &[Animation]) {
        self.changed = None;
        let now = now.max(self.seen);
        let held = now.saturating_sub(self.seen);
        let mut since = self.seen;
        self.seen = now;
        if self.holding != Holding::Running {
            self.shift(held);
            if self.holding == Holding::Held {
                return;
            }
            self.holding = Holding::Running;
            // The hold moved every start by the span it covered, so no
            // progress lies between the tick before this one and this one.
            since = now;
        }
        self.settle(now);
        self.motion = self.motion.started_at(now);

        let at = self.motion.progress(now, clips);
        if let Some(transition) = self.state.next(input, at) {
            let crossing = self.crossing(transition.into, input, since, now, clips);
            self.enter(transition, crossing, input, clips);
        }
        let motion = self.state.motion(input);
        self.motion = self.motion.kept(&motion, now, clips);
    }

    /// What it is running, for the draw that poses a mesh by it, read at
    /// the instant it was held at while a hold stands.
    pub(crate) fn running(&self) -> Running {
        Running {
            posed: Posed::Playing(self.motion),
            fading: self.fading,
            held: self.holding.stands().then_some(self.seen),
        }
    }

    /// Moves into what `transition` states, fading out of what it plays now
    /// from `crossing`.
    ///
    /// A fade already running is interrupted, which stops what it drew at
    /// that instant; one that takes no time at all drops what it
    /// leaves.
    fn enter(
        &mut self,
        transition: Transition<S>,
        crossing: Duration,
        input: &S::Input,
        clips: &[Animation],
    ) {
        if transition.into == self.state && !transition.restarted {
            return;
        }
        self.fading = match transition.fade.is_zero() {
            true => None,
            false => Some(Fading {
                under: match self.fading {
                    Some(_) => Posed::Stopped(self.running().posing(crossing, clips)),
                    None => Posed::Playing(self.motion),
                },
                from: crossing,
                over: transition.fade,
            }),
        };
        self.motion = Timed::new(
            &transition.into.motion(input),
            Some(crossing),
            transition.entering_at,
        );
        self.changed = Some(Change {
            left: self.state,
            entered: transition.into,
        });
        self.state = transition.into;
    }

    /// The first instant between `since` and `now` at which how far the
    /// motion has run moves the state it is in into `into`, to within
    /// `0.0001` of that span.
    ///
    /// A tick reads the state once, and what moved it — a fraction of a
    /// cycle passed — crosses inside the tick. The state itself is the only
    /// thing that states where, so the machine reads it again over the
    /// span, at the progress each instant in it holds and at this tick's
    /// input, halving the span until the two ends of it read the same. The
    /// fade then starts at that crossing rather than at the tick, so a clip
    /// shorter than a tick fades from the first crossing inside it and no
    /// fade is paced by the frame rate. Where the state already moves at
    /// the start of the span, the input and not the progress moved it, and
    /// the transition starts at the tick that read it. The state is taken
    /// to move once across one tick.
    fn crossing(
        &self,
        into: S,
        input: &S::Input,
        since: Duration,
        now: Duration,
        clips: &[Animation],
    ) -> Duration {
        let moves = |at: Duration| {
            self.state
                .next(input, self.motion.progress(at, clips))
                .is_some_and(|transition| transition.into == into)
        };
        if since >= now || moves(since) {
            return now;
        }

        let mut before = since;
        let mut after = now;
        for _ in 0..CROSSINGS {
            let between = before + (after - before) / 2;
            match moves(between) {
                true => after = between,
                false => before = between,
            }
        }

        after
    }

    /// Drops a fade that has run out by `now`.
    fn settle(&mut self, now: Duration) {
        if self
            .fading
            .is_some_and(|fading| fading.weight(now) >= WHOLE)
        {
            self.fading = None;
        }
    }

    /// Moves every instant it holds `span` later, which leaves what it
    /// plays where it is.
    fn shift(&mut self, span: Duration) {
        self.motion = self.motion.shifted(span);
        self.fading = self.fading.map(|fading| fading.shifted(span));
    }
}

impl<M, S: AnimationStates> Clone for Animator<M, S> {
    fn clone(&self) -> Self {
        Self {
            state: self.state,
            motion: self.motion,
            fading: self.fading,
            changed: self.changed,
            holding: self.holding,
            seen: self.seen,
            mesh: PhantomData,
        }
    }
}

impl<M, S: AnimationStates> Debug for Animator<M, S> {
    /// The state it is in and whether it is still fading out of the one it
    /// left.
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Animator")
            .field("state", &self.state)
            .field("transitioning", &self.transitioning())
            .finish()
    }
}

impl<M, S: AnimationStates> Default for Animator<M, S> {
    /// A machine in its entry state; see [`Animator::new`].
    fn default() -> Self {
        Self::new()
    }
}

/// Whether a machine's clock runs: on, held where it is, or running again
/// from where it was held.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Holding {
    Running,
    Held,
    Resumed,
}

impl Holding {
    /// Whether the machine stands at the last instant it read: held, or
    /// resumed and not yet run on from there.
    fn stands(self) -> bool {
        self != Self::Running
    }
}

/// The transition the last run of `animate` started: the state it left and
/// the state it entered.
#[derive(Clone, Copy, Debug)]
struct Change<S> {
    left: S,
    entered: S,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::animation::{Motion, Progress};
    use crate::math::Vec3;
    use crate::mesh::{Clip, Keys, Moves, Posing, Track};

    /// The fade every transition below takes.
    const FADE: Duration = Duration::from_millis(200);

    /// A tick of a sixtieth of a second, which no clip below runs for a
    /// whole number of.
    const TICK: Duration = Duration::from_nanos(16_666_667);

    /// How long `Step::Long` runs for, in seconds: a length no tick lands
    /// on.
    const LONG: f32 = 0.458_333_34;

    /// How long each clip of `Step` runs for, in seconds.
    const SPANS: [f32; 4] = [1.0, 0.25, LONG, 0.01];

    /// The mesh every machine below poses, which no test of them draws.
    struct Puppet;

    /// The clips every machine below plays.
    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
    enum Step {
        Slow,
        Quick,
        Long,
        Brief,
    }

    impl Clip for Step {
        fn from_name(_name: &str) -> Option<Self> {
            None
        }

        fn all() -> Vec<Self> {
            vec![Self::Slow, Self::Quick, Self::Long, Self::Brief]
        }

        fn index(&self) -> u32 {
            *self as u32
        }
    }

    /// What those clips hold: one joint moved out along `X` over the clip's
    /// own span, so the time a pose is read at is what a test reads back.
    fn clips() -> Vec<Animation> {
        SPANS
            .iter()
            .map(|&span| {
                Animation::new(vec![Track {
                    joint: 0,
                    moves: Moves::Position(Keys::Linear(vec![(0.0, Vec3::ZERO), (span, Vec3::X)])),
                }])
            })
            .collect()
    }

    /// What every machine below reads: where the game moves it, and the
    /// values two of them are posed by.
    #[derive(Clone, Copy, Debug)]
    struct Told {
        go: bool,
        restart: bool,
        entering_at: f32,
        step: u32,
        weight: f32,
        pace: f32,
        openness: f32,
    }

    impl Default for Told {
        /// Moves nothing, at the pace every clip states.
        fn default() -> Self {
            Self {
                go: false,
                restart: false,
                entering_at: 0.0,
                step: 0,
                weight: 0.0,
                pace: 1.0,
                openness: 0.0,
            }
        }
    }

    /// What moves a machine on.
    fn go() -> Told {
        Told {
            go: true,
            ..Told::default()
        }
    }

    /// What moves a machine into what it already plays, entering `at` of
    /// the way in.
    fn restart(at: f32) -> Told {
        Told {
            restart: true,
            entering_at: at,
            ..Told::default()
        }
    }

    /// A blend at `weight`, paced by `pace`.
    fn mix(weight: f32, pace: f32) -> Told {
        Told {
            weight,
            pace,
            ..Told::default()
        }
    }

    /// A value that scrubs a clip.
    fn open(openness: f32) -> Told {
        Told {
            openness,
            ..Told::default()
        }
    }

    /// A machine that walks a clip once where the game moves it on, and
    /// then holds a pose the game states.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Walk {
        Still,
        Going,
        Done,
    }

    impl AnimationStates for Walk {
        type Clip = Step;
        type Input = Told;

        fn entry() -> Self {
            Self::Still
        }

        fn motion(&self, input: &Told) -> Motion<Step> {
            match self {
                Self::Still => Motion::looping(Step::Slow),
                Self::Going => Motion::once(Step::Long),
                Self::Done => Motion::scrubbed(Step::Slow, input.openness),
            }
        }

        fn next(&self, input: &Told, at: Progress) -> Option<Transition<Self>> {
            match self {
                Self::Still if input.go => Some(Self::Going.fade(FADE)),
                Self::Going if at.ended() => Some(Self::Done.fade(FADE)),
                _ => None,
            }
        }
    }

    /// A machine that moves on part way through a loop of its own.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Round {
        Turning,
        Past,
    }

    impl AnimationStates for Round {
        type Clip = Step;
        type Input = Told;

        fn entry() -> Self {
            Self::Turning
        }

        fn motion(&self, _input: &Told) -> Motion<Step> {
            match self {
                Self::Turning => Motion::looping(Step::Brief),
                Self::Past => Motion::looping(Step::Slow),
            }
        }

        fn next(&self, _input: &Told, at: Progress) -> Option<Transition<Self>> {
            match self {
                Self::Turning if at.past(0.5) => Some(Self::Past.fade(FADE)),
                _ => None,
            }
        }
    }

    /// A machine that moves to whatever state the game states, so that a
    /// fade of its own can be interrupted.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Steps {
        First,
        Second,
        Third,
    }

    impl AnimationStates for Steps {
        type Clip = Step;
        type Input = Told;

        fn entry() -> Self {
            Self::First
        }

        fn motion(&self, _input: &Told) -> Motion<Step> {
            match self {
                Self::First => Motion::looping(Step::Slow),
                Self::Second => Motion::looping(Step::Quick),
                Self::Third => Motion::looping(Step::Long),
            }
        }

        fn next(&self, input: &Told, _at: Progress) -> Option<Transition<Self>> {
            let wanted = match input.step {
                0 => Self::First,
                1 => Self::Second,
                _ => Self::Third,
            };

            (wanted != *self).then(|| wanted.fade(FADE))
        }
    }

    /// A machine of one state, which the game moves to that same state.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Only {
        It,
    }

    impl AnimationStates for Only {
        type Clip = Step;
        type Input = Told;

        fn entry() -> Self {
            Self::It
        }

        fn motion(&self, _input: &Told) -> Motion<Step> {
            Motion::looping(Step::Slow)
        }

        fn next(&self, input: &Told, _at: Progress) -> Option<Transition<Self>> {
            match (input.restart, input.go) {
                (true, _) => Some(Self::It.restarted().entering_at(input.entering_at)),
                (_, true) => Some(Self::It.fade(FADE)),
                _ => None,
            }
        }
    }

    /// A machine that fades from one clip into a pair of them blended.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Into {
        One,
        Pair,
    }

    impl AnimationStates for Into {
        type Clip = Step;
        type Input = Told;

        fn entry() -> Self {
            Self::One
        }

        fn motion(&self, _input: &Told) -> Motion<Step> {
            match self {
                Self::One => Motion::looping(Step::Slow),
                Self::Pair => Motion::blend(Step::Quick, Step::Long, 0.5),
            }
        }

        fn next(&self, input: &Told, _at: Progress) -> Option<Transition<Self>> {
            match input.go {
                true => Some(Self::Pair.fade(FADE)),
                false => None,
            }
        }
    }

    /// A machine of one state, posed by a value of the game's own.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Opening {
        It,
    }

    impl AnimationStates for Opening {
        type Clip = Step;
        type Input = Told;

        fn entry() -> Self {
            Self::It
        }

        fn motion(&self, input: &Told) -> Motion<Step> {
            Motion::scrubbed(Step::Slow, input.openness)
        }

        fn next(&self, _input: &Told, _at: Progress) -> Option<Transition<Self>> {
            None
        }
    }

    /// A machine of one state, blending two clips at a weight and a pace the
    /// game states.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum Mixing {
        It,
    }

    impl AnimationStates for Mixing {
        type Clip = Step;
        type Input = Told;

        fn entry() -> Self {
            Self::It
        }

        fn motion(&self, input: &Told) -> Motion<Step> {
            Motion::blend(Step::Slow, Step::Quick, input.weight).paced(input.pace)
        }

        fn next(&self, _input: &Told, _at: Progress) -> Option<Transition<Self>> {
            None
        }
    }

    /// A machine of `S` over the test clips.
    fn machine<S: AnimationStates<Input = Told>>() -> Animator<Puppet, S> {
        Animator::new()
    }

    /// Runs `animator` up to `at` seconds on the run clock.
    fn animate<S: AnimationStates<Input = Told>>(
        animator: &mut Animator<Puppet, S>,
        input: Told,
        at: f32,
    ) {
        animator.animate(&input, seconds(at), &clips());
    }

    /// The pose `animator` holds `at` seconds on the run clock.
    fn posing<S: AnimationStates<Input = Told>>(animator: &Animator<Puppet, S>, at: f32) -> Posing {
        animator.running().posing(seconds(at), &clips())
    }

    /// `at` seconds on the run clock.
    fn seconds(at: f32) -> Duration {
        Duration::from_secs_f32(at)
    }

    /// The time along its own clip the pose starts at.
    fn started(posing: Posing) -> f32 {
        posing.from.at
    }

    /// How far of the way to the clip blended over that one the pose lies,
    /// and nothing where none is blended over it.
    fn weight(posing: Posing) -> Option<f32> {
        posing.over[0].map(|faded| faded.weight)
    }

    /// The time along its own clip the clip blended over the first is read
    /// at.
    fn blended(posing: Posing) -> Option<f32> {
        posing.over[0].map(|faded| faded.sampled.at)
    }

    #[test]
    fn a_machine_starts_in_its_entry_state_at_the_start_of_what_that_state_plays() {
        let animator = machine::<Walk>();

        assert_eq!(animator.state(), Walk::Still);
        assert!(!animator.transitioning());
        assert_eq!(
            started(posing(&animator, 3.0)),
            0.0,
            "no clock has reached it yet"
        );
    }

    #[test]
    fn a_transition_starts_a_fade_of_the_length_it_states_and_is_entered_for_one_tick() {
        let mut animator = machine::<Walk>();
        animate(&mut animator, Told::default(), 0.0);
        assert!(!animator.entered(Walk::Going));

        animate(&mut animator, go(), 0.1);
        assert_eq!(animator.state(), Walk::Going);
        assert!(animator.entered(Walk::Going) && animator.left(Walk::Still));
        assert!(animator.transitioning());
        assert_eq!(weight(posing(&animator, 0.1)), Some(0.0));
        assert_eq!(weight(posing(&animator, 0.2)), Some(0.5), "half a fade in");
        assert_eq!(
            weight(posing(&animator, 0.3)),
            Some(1.0),
            "and whole at its end"
        );

        animate(&mut animator, go(), 0.15);
        assert!(
            !animator.entered(Walk::Going) && !animator.left(Walk::Still),
            "which reads for the tick the transition started in alone"
        );
    }

    #[test]
    fn the_motion_a_fade_leaves_runs_on_under_it() {
        let mut animator = machine::<Walk>();
        animate(&mut animator, Told::default(), 0.0);
        animate(&mut animator, go(), 0.1);

        assert!(
            (started(posing(&animator, 0.1)) - 0.1).abs() < 1e-6,
            "the loop it left is read where it had reached"
        );
        assert!(
            (started(posing(&animator, 0.25)) - 0.25).abs() < 1e-6,
            "and runs on while the fade does"
        );
        assert_eq!(
            blended(posing(&animator, 0.1)),
            Some(0.0),
            "as the one it entered starts"
        );
    }

    #[test]
    fn a_transition_that_enters_part_way_in_starts_what_it_plays_there() {
        let mut animator = machine::<Only>();
        animate(&mut animator, Told::default(), 0.0);
        animate(&mut animator, restart(0.25), 0.5);

        assert_eq!(
            blended(posing(&animator, 0.5)),
            Some(0.25),
            "a quarter of the way along a clip a second long"
        );
    }

    #[test]
    fn a_transition_to_the_state_it_is_in_moves_nothing_unless_it_starts_again() {
        let mut running = machine::<Only>();
        animate(&mut running, Told::default(), 0.0);
        animate(&mut running, go(), 0.5);

        assert!(!running.transitioning(), "there is nothing to fade between");
        assert!(
            (started(posing(&running, 0.5)) - 0.5).abs() < 1e-6,
            "and what it plays runs on"
        );

        let mut again = machine::<Only>();
        animate(&mut again, Told::default(), 0.0);
        animate(&mut again, restart(0.0), 0.5);

        assert!(again.transitioning());
        assert!(again.entered(Only::It) && again.left(Only::It));
        assert_eq!(blended(posing(&again, 0.5)), Some(0.0), "from the start");
    }

    #[test]
    fn a_motion_that_ends_fades_from_the_instant_it_ended_and_not_from_the_tick_that_read_it() {
        let mut animator = machine::<Walk>();
        animate(&mut animator, go(), 0.0);
        let mut read = Duration::ZERO;
        while !animator.entered(Walk::Done) && read.as_secs_f32() < 1.0 {
            read += TICK;
            animator.animate(&go(), read, &clips());
        }
        let read = read.as_secs_f32();

        assert_eq!(animator.state(), Walk::Done);
        assert!(read > LONG, "the tick that read the end landed past it");
        let crossed = (read - LONG) / FADE.as_secs_f32();
        let weight = weight(posing(&animator, read)).expect("the fade is running");
        assert!(
            // The crossing is read to within `0.0001` of the tick, which
            // leaves the fade within `1e-5` of the way in.
            (weight - crossed).abs() < 2e-5,
            "the fade reads {weight} of the way in at the tick, not the {crossed} that a fade \
             from the end of the clip reads"
        );
    }

    #[test]
    fn a_clip_shorter_than_a_tick_fades_from_the_first_crossing_inside_the_tick() {
        let mut animator = machine::<Round>();
        animate(&mut animator, Told::default(), 0.0);
        animator.animate(&Told::default(), TICK, &clips());
        let read = TICK.as_secs_f32();

        assert_eq!(animator.state(), Round::Past);
        // A loop `0.01` seconds long passes half of a cycle at `0.005` and
        // every `0.01` after, and the machine moves at the first instant
        // inside the tick that its state would have moved at.
        let crossed = (read - 0.005) / FADE.as_secs_f32();
        let weight = weight(posing(&animator, read)).expect("the fade is running");
        assert!(
            // The crossing is read to within `0.0001` of the tick, which
            // leaves the fade within `1e-5` of the way in.
            (weight - crossed).abs() < 2e-5,
            "the fade reads {weight} of the way in, not the {crossed} of a fade from the first \
             crossing"
        );
    }

    #[test]
    fn interrupting_a_fade_stops_what_it_drew_at_the_instant_it_was_interrupted() {
        let mut animator = machine::<Steps>();
        animate(&mut animator, Told::default(), 0.0);
        animate(
            &mut animator,
            Told {
                step: 1,
                ..Told::default()
            },
            0.1,
        );
        animate(
            &mut animator,
            Told {
                step: 2,
                ..Told::default()
            },
            0.2,
        );

        let interrupted = posing(&animator, 0.2);
        assert!(
            (started(interrupted) - 0.2).abs() < 1e-6,
            "the first clip is read where it stood at the interruption"
        );
        let over = interrupted.over[0].expect("the fade it interrupted is stopped under it");
        assert!(
            (over.sampled.at - 0.1).abs() < 1e-6 && (over.weight - 0.5).abs() < 1e-5,
            "{over:?} is not the second clip at the weight the fade had reached"
        );
        assert_eq!(interrupted.over[1].map(|faded| faded.weight), Some(0.0));

        let later = posing(&animator, 0.3);
        assert_eq!(
            (started(later), later.over[0]),
            (started(interrupted), interrupted.over[0]),
            "and what was stopped is read the same a fade later"
        );
        let entering = later.over[1].expect("the state it entered fades in over that");
        assert!(
            (entering.weight - 0.5).abs() < 1e-5,
            "{entering:?} is not half of the way into the fade that interrupted"
        );
    }

    #[test]
    fn a_fade_into_a_blend_takes_two_places_of_the_pose_and_reads_as_one_fade() {
        let mut animator = machine::<Into>();
        animate(&mut animator, Told::default(), 0.0);
        animate(&mut animator, go(), 0.0);

        // Half of the way into the fade, the pose is half the clip it left
        // and a quarter of each of the pair, which the pose states as a
        // third of the way to the first of the pair and then a quarter of
        // the way to the second.
        let half = posing(&animator, 0.1);
        let over = |at: usize| half.over[at].map(|faded| faded.weight);

        assert!(
            over(0).is_some_and(|weight| (weight - 1.0 / 3.0).abs() < 1e-5),
            "{half:?} does not read as half of what it left"
        );
        assert!(
            over(1).is_some_and(|weight| (weight - 0.25).abs() < 1e-5),
            "{half:?} does not read as a quarter of the second of the pair"
        );

        let whole = posing(&animator, 0.2);
        assert_eq!(
            (
                whole.over[0].map(|faded| faded.weight),
                whole.over[1].map(|faded| faded.weight)
            ),
            (Some(1.0), Some(0.5)),
            "and at the end of the fade the clip it left is gone and the pair \
             is read at its own weight"
        );
    }

    #[test]
    fn a_scrubbed_motion_follows_the_value_it_is_given_and_no_clock() {
        let mut animator = machine::<Opening>();
        animate(&mut animator, open(0.25), 0.0);

        assert_eq!(started(posing(&animator, 0.0)), 0.25);
        assert_eq!(
            started(posing(&animator, 9.0)),
            0.25,
            "which no clock moves"
        );

        animate(&mut animator, open(1.0), 1.0);
        assert_eq!(started(posing(&animator, 1.0)), 1.0);

        animate(&mut animator, open(4.0), 2.0);
        assert_eq!(
            started(posing(&animator, 2.0)),
            1.0,
            "a fraction past the end is held inside the clip"
        );
    }

    #[test]
    fn a_blend_keeps_its_place_across_a_change_of_weight() {
        let mut animator = machine::<Mixing>();
        animate(&mut animator, mix(0.0, 1.0), 0.0);
        let before = posing(&animator, 0.3);
        animate(&mut animator, mix(1.0, 1.0), 0.3);
        let after = posing(&animator, 0.3);

        assert_eq!(
            (started(before), blended(before)),
            (started(after), blended(after)),
            "both clips are read where they already were"
        );
        assert_eq!(weight(after), Some(1.0), "at the weight it was given");
        assert!(
            (started(posing(&animator, 0.55)) - 0.3).abs() < 1e-6,
            "and a cycle of the clip it now reads runs on from there"
        );
    }

    #[test]
    fn a_paced_motion_keeps_its_position_across_a_change_of_pace() {
        let mut animator = machine::<Mixing>();
        animate(&mut animator, mix(0.0, 1.0), 0.0);
        let before = started(posing(&animator, 0.5));
        animate(&mut animator, mix(0.0, 2.0), 0.5);

        assert_eq!(started(posing(&animator, 0.5)), before);
        assert!(
            (started(posing(&animator, 0.6)) - 0.7).abs() < 1e-6,
            "and runs on at twice the pace"
        );
    }

    #[test]
    fn a_weight_or_a_pace_outside_what_a_motion_takes_is_held_inside_it() {
        let mut animator = machine::<Mixing>();
        animate(&mut animator, mix(4.0, 1.0), 0.0);
        assert_eq!(weight(posing(&animator, 0.0)), Some(1.0));

        animate(&mut animator, mix(f32::NAN, 1.0), 0.1);
        assert_eq!(
            weight(posing(&animator, 0.1)),
            Some(0.0),
            "and a weight that is no number reads as none of the second clip"
        );

        let mut held = machine::<Mixing>();
        animate(&mut held, mix(0.0, -2.0), 0.0);
        let standing = started(posing(&held, 0.0));
        animate(&mut held, mix(0.0, -2.0), 1.0);

        assert_eq!(
            started(posing(&held, 1.0)),
            standing,
            "a pace of nothing or less holds a motion where it is"
        );
    }

    #[test]
    fn holding_a_machine_leaves_what_it_plays_where_it_is_until_it_resumes() {
        let mut animator = machine::<Only>();
        animate(&mut animator, Told::default(), 0.0);
        animate(&mut animator, Told::default(), 0.5);
        let held = started(posing(&animator, 0.5));

        animator.hold();
        animate(&mut animator, Told::default(), 2.0);
        assert_eq!(
            started(posing(&animator, 2.0)),
            held,
            "the span it was held over counts for nothing"
        );

        animator.resume();
        animate(&mut animator, Told::default(), 2.25);
        assert_eq!(
            started(posing(&animator, 2.25)),
            held,
            "it plays on from there"
        );

        animate(&mut animator, Told::default(), 2.5);
        assert!((started(posing(&animator, 2.5)) - 0.75).abs() < 1e-6);
    }

    #[test]
    fn a_held_machine_is_drawn_at_the_instant_it_was_held_whatever_instant_the_frame_draws_at() {
        let mut animator = machine::<Walk>();
        animate(&mut animator, Told::default(), 0.0);
        animate(&mut animator, go(), 0.1);
        let before = posing(&animator, 0.1);
        animator.hold();
        animate(&mut animator, go(), 0.15);

        assert_eq!(
            posing(&animator, 0.15),
            before,
            "the tick that holds it leaves the pose where the tick before found it"
        );
        assert_eq!(
            posing(&animator, 0.158),
            before,
            "a frame half a tick past that tick reads the same pose"
        );
        assert_eq!(
            posing(&animator, 0.166),
            before,
            "and so does one a whole tick past it, mid-fade"
        );
    }

    #[test]
    fn a_clock_that_goes_back_is_held_to_the_last_instant_the_machine_read() {
        let mut animator = machine::<Only>();
        animate(&mut animator, Told::default(), 0.0);
        animate(&mut animator, Told::default(), 0.75);
        animate(&mut animator, Told::default(), 0.25);

        animator.hold();
        animate(&mut animator, Told::default(), 1.0);
        assert!(
            (started(posing(&animator, 1.0)) - 0.75).abs() < 1e-6,
            "the hold counted the span since the instant it had read, not one before it"
        );
    }

    #[test]
    fn two_machines_run_alike_read_alike() {
        let mut one = machine::<Walk>();
        let mut two = machine::<Walk>();

        for tick in 0..48 {
            let at = tick as f32 * TICK.as_secs_f32();
            let told = Told {
                go: tick > 3,
                openness: 0.3,
                ..Told::default()
            };
            animate(&mut one, told, at);
            animate(&mut two, told, at);

            assert_eq!(one.state(), two.state());
            assert_eq!(posing(&one, at), posing(&two, at));
            assert_eq!(one.transitioning(), two.transitioning());
        }
        assert_eq!(
            one.state(),
            Walk::Done,
            "and both ran the whole way through"
        );
    }
}