mirage-engine 0.1.1

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
//! The pose a draw is drawn in: what a clip holds at one time, what the
//! clips blended over it hold, and the matrices a rig takes a pose to.

use crate::math::Mat4;
use crate::mesh::{Animation, Local, Placed, Rig};

/// The clips a pose blends over the one it starts at.
pub(crate) const BLENDED: usize = 3;

/// The weight from which a pair that collapses keeps the clip blended over
/// the other rather than the one under it.
const NEARER: f32 = 0.5;

/// What a draw is posed by: a fold, which is one clip at a time along it
/// and up to three clips each blended over what came before.
///
/// A draw that holds none is drawn at the rest of every joint. Two draws
/// hold one pose where they name the same clips at the same times and
/// weights, so a frame composes such draws once between them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Posing {
    pub(crate) from: Sampled,
    pub(crate) over: [Option<Faded>; BLENDED],
}

impl Posing {
    /// The pose the clip at `clip` holds `at` seconds along its own
    /// timeline.
    pub(crate) fn clip(clip: u32, at: f32) -> Self {
        Self {
            from: Sampled { clip, at },
            over: [None; BLENDED],
        }
    }

    /// The same pose, `weight` of the way to what `sampled` holds.
    ///
    /// Past the third clip blended over the first, the two oldest collapse
    /// to whichever of them the pose lies nearer, so one pose reads four
    /// clips however many fades it came out of.
    pub(crate) fn blended(mut self, sampled: Sampled, weight: f32) -> Self {
        let faded = Faded {
            sampled,
            weight: weight.clamp(0.0, 1.0),
        };
        match self.over.iter().position(Option::is_none) {
            Some(free) => self.over[free] = Some(faded),
            None => {
                self = self.collapsed();
                self.over[BLENDED - 1] = Some(faded);
            }
        }

        self
    }

    /// The same pose with its two oldest clips collapsed to whichever it
    /// lies nearer, which leaves the last place free.
    fn collapsed(mut self) -> Self {
        if let Some(oldest) = self.over[0].filter(|oldest| oldest.weight >= NEARER) {
            self.from = oldest.sampled;
        }
        self.over.rotate_left(1);
        self.over[BLENDED - 1] = None;

        self
    }
}

/// One clip of a mesh, and the time along it a pose is read at.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Sampled {
    /// The clip's own place in its mesh's vocabulary.
    pub(crate) clip: u32,
    /// Seconds along the clip's own timeline; a time past either end reads
    /// that end.
    pub(crate) at: f32,
}

/// One clip blended over what lies under it in a pose.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Faded {
    pub(crate) sampled: Sampled,
    /// How far of the way from what lies under it to this clip the pose
    /// lies, in `0.0..=1.0`.
    pub(crate) weight: f32,
}

impl Sampled {
    /// What this clip moves, and nothing where `clips` holds no such clip.
    fn of(self, clips: &[Animation]) -> Option<&Animation> {
        clips.get(self.clip as usize)
    }
}

/// One local transform per joint of a rig, in joint order.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Pose {
    locals: Vec<Local>,
}

impl Pose {
    /// Fills this pose with the rest of every joint of `rig`.
    fn rest(&mut self, rig: &Rig) {
        self.locals.clear();
        self.locals
            .extend(rig.joints().iter().map(|joint| joint.rest));
    }

    /// Fills this pose with what `animation` holds `at` seconds along it:
    /// every joint of `rig` at rest, with each path a track of it moves at
    /// the value that track holds there.
    ///
    /// A clip that moves nothing of `rig` leaves it at rest.
    fn sample(&mut self, rig: &Rig, animation: Option<&Animation>, at: f32) {
        self.rest(rig);
        let Some(animation) = animation else {
            return;
        };
        for track in animation.tracks() {
            let Some(local) = self.locals.get_mut(track.joint as usize) else {
                continue;
            };
            *local = track.moves.moved(*local, at);
        }
    }

    /// Mixes every joint of this pose `weight` of the way to `other`'s,
    /// which is the pose it holds at `1.0` and this one at `0.0`.
    fn blend(&mut self, other: &Self, weight: f32) {
        let weight = weight.clamp(0.0, 1.0);
        for (local, &blended) in self.locals.iter_mut().zip(&other.locals) {
            *local = local.mixed(blended, weight);
        }
    }

    /// Appends the matrices `rig` takes this pose to: each joint's own
    /// transform under what it is placed in, then the transform into its own
    /// space.
    ///
    /// A rig at rest whose bind is the inverse of where it lies in the model
    /// leaves every one of them the matrix that moves nothing, so a model
    /// drawn at rest is drawn where its corners already lie. A joint this
    /// pose holds no local for is taken at its rest.
    fn compose(&self, rig: &Rig, into: &mut Vec<Mat4>) {
        let start = into.len();
        for (at, joint) in rig.joints().iter().enumerate() {
            let local = self.locals.get(at).copied().unwrap_or(joint.rest);
            let above = match joint.placed {
                // A joint's parent lies before it, so its world transform is
                // already written; the read only keeps this total.
                Placed::Under(parent) => into
                    .get(start + parent as usize)
                    .copied()
                    .unwrap_or(Mat4::IDENTITY),
                Placed::Within(above) => above,
            };
            into.push(above * local.matrix());
        }
        for (matrix, joint) in into[start..].iter_mut().zip(rig.joints()) {
            *matrix *= joint.bind;
        }
    }
}

/// Which mesh a run of the palette poses: a draw's own mesh, by its place
/// in the cache the frame resolved it through.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Skinned(pub(crate) u32);

/// The joint matrices every posed draw of a frame is skinned by, one run per
/// mesh and pose it draws.
///
/// A draw reads its run from where it starts; the vertex stages and both
/// caster passes read the same one, so a posed draw casts the shadow of the
/// pose it is drawn in.
#[derive(Default)]
pub(crate) struct Palette {
    matrices: Vec<Mat4>,
    taken: Vec<Taken>,
    posed: Pose,
    blended: Pose,
}

impl Palette {
    /// Drops what the frame before took.
    pub(crate) fn clear(&mut self) {
        self.matrices.clear();
        self.taken.clear();
    }

    /// The matrices a draw of `mesh` posed by `posing` is skinned by, and
    /// where its run starts.
    ///
    /// One mesh in one pose is composed once a frame: every draw that
    /// matches one already taken reads that run, so many draws of one mesh
    /// at rest take one between them. A mesh with no joints takes no
    /// matrices and reads none.
    pub(crate) fn take(
        &mut self,
        mesh: Skinned,
        rig: &Rig,
        clips: &[Animation],
        posing: Option<Posing>,
    ) -> u32 {
        if !rig.skins() {
            return 0;
        }
        // Draws cluster by mesh and by pose, so the run a frame is taking
        // now is usually the one it took last.
        let matching = self
            .taken
            .iter()
            .rev()
            .find(|taken| taken.mesh == mesh && taken.posing == posing);
        if let Some(taken) = matching {
            return taken.at;
        }

        let at = self.composed(rig, clips, posing);
        self.taken.push(Taken { mesh, posing, at });

        at
    }

    /// The matrices `rig` posed by `posing` takes, appended as a run of
    /// their own, and where that run starts.
    ///
    /// Composes the pose whether or not a frame has composed it already,
    /// which is what a mesh measured over every pose of its clips needs.
    pub(crate) fn composed(
        &mut self,
        rig: &Rig,
        clips: &[Animation],
        posing: Option<Posing>,
    ) -> u32 {
        if !rig.skins() {
            return 0;
        }
        let Self {
            matrices,
            posed,
            blended,
            ..
        } = self;
        let at = matrices.len() as u32;

        match posing {
            None => posed.rest(rig),
            Some(posing) => {
                posed.sample(rig, posing.from.of(clips), posing.from.at);
                for faded in posing.over.iter().flatten() {
                    blended.sample(rig, faded.sampled.of(clips), faded.sampled.at);
                    posed.blend(blended, faded.weight);
                }
            }
        }
        posed.compose(rig, matrices);

        at
    }

    /// Every matrix the frame's posed draws read, the runs in the order they
    /// were taken.
    pub(crate) fn matrices(&self) -> &[Mat4] {
        &self.matrices
    }
}

/// One run of the palette and what it poses: the mesh, what its draws are
/// posed by, and where the run starts.
struct Taken {
    mesh: Skinned,
    posing: Option<Posing>,
    at: u32,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assets::{Assets, RIG, SCALED, file};
    use crate::math::{Quat, Vec3};
    use crate::mesh::{Clip, Geometry, Joint, Keys, Moves, NoParts, Track, Weighted};

    /// The clips each rig fixture is posed by, named by hand as the derive
    /// names them for a game.
    #[derive(Clone, Debug, Eq, Hash, PartialEq)]
    enum Paces {
        Idle,
        Walk,
    }

    impl Clip for Paces {
        fn from_name(name: &str) -> Option<Self> {
            match name {
                "idle" => Some(Self::Idle),
                "walk" => Some(Self::Walk),
                _ => None,
            }
        }

        fn all() -> Vec<Self> {
            vec![Self::Idle, Self::Walk]
        }

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

    /// The model `source` holds under the name `Rig`, built whole.
    fn rig_of(source: &[u8]) -> Geometry {
        let assets = Assets::load([file("rig.glb", source)]).expect("the fixture decodes");

        assets
            .model::<NoParts, Paces>("Rig")
            .erased()
            .expect("built whole")
    }

    /// A joint at rest at `position`, placed by `placed`, whose bind is the
    /// inverse of where it lies in the model.
    fn joint(placed: Placed, position: Vec3, above: Mat4) -> Joint {
        let rest = Local::new(position, Quat::IDENTITY, Vec3::ONE);

        Joint {
            placed,
            rest,
            bind: (above * rest.matrix()).inverse(),
        }
    }

    /// A rig of a joint a meter up and a second one a meter above that, one
    /// vertex taking each of them whole.
    fn stack() -> Rig {
        let root = joint(Placed::Within(Mat4::IDENTITY), Vec3::Y, Mat4::IDENTITY);

        Rig::new(
            vec![root, joint(Placed::Under(0), Vec3::Y, root.rest.matrix())],
            vec![Weighted::whole(0), Weighted::whole(1)],
        )
    }

    /// The clip that moves the joint at `joint` along `moves`.
    fn clip(joint: u32, moves: Moves) -> Vec<Animation> {
        vec![Animation::new(vec![Track { joint, moves }])]
    }

    /// The matrices `rig` posed by `posing` takes, over `clips` and no
    /// other clip.
    fn palette(rig: &Rig, clips: &[Animation], posing: Option<Posing>) -> Vec<Mat4> {
        let mut palette = Palette::default();
        palette.composed(rig, clips, posing);

        palette.matrices().to_vec()
    }

    /// The pose `moves` holds `at` seconds along it, for a rig of one joint
    /// at rest at the origin.
    fn moved(moves: Moves, at: f32) -> Local {
        let rig = Rig::new(
            vec![joint(
                Placed::Within(Mat4::IDENTITY),
                Vec3::ZERO,
                Mat4::IDENTITY,
            )],
            vec![Weighted::whole(0)],
        );
        let clips = clip(0, moves);
        let mut pose = Pose::default();
        pose.sample(&rig, clips.first(), at);

        pose.locals[0]
    }

    /// The position that pose holds.
    fn position(moves: Moves, at: f32) -> Vec3 {
        moved(moves, at).position
    }

    /// Three positions a linear channel steps between.
    fn stepping() -> Vec<(f32, Vec3)> {
        vec![
            (1.0, Vec3::ZERO),
            (2.0, Vec3::X * 10.0),
            (4.0, Vec3::X * 20.0),
        ]
    }

    #[test]
    fn a_channel_reads_its_keys_and_mixes_between_them() {
        let moves = Moves::Position(Keys::Linear(stepping()));

        assert_eq!(position(moves.clone(), 1.0), Vec3::ZERO, "at a key");
        assert_eq!(position(moves.clone(), 2.0), Vec3::X * 10.0);
        assert_eq!(
            position(moves.clone(), 1.5),
            Vec3::X * 5.0,
            "halfway between two keys"
        );
        assert_eq!(
            position(moves, 3.0),
            Vec3::X * 15.0,
            "and halfway along an interval twice as long"
        );
    }

    #[test]
    fn a_time_either_side_of_the_ends_reads_the_nearest_end() {
        let moves = Moves::Position(Keys::Linear(stepping()));

        assert_eq!(position(moves.clone(), 0.0), Vec3::ZERO);
        assert_eq!(position(moves.clone(), -100.0), Vec3::ZERO);
        assert_eq!(position(moves.clone(), 4.5), Vec3::X * 20.0);
        assert_eq!(position(moves, 1e9), Vec3::X * 20.0);
    }

    #[test]
    fn a_step_channel_holds_the_earlier_key_until_the_next() {
        let moves = Moves::Position(Keys::Step(stepping()));

        assert_eq!(position(moves.clone(), 1.0), Vec3::ZERO);
        assert_eq!(position(moves.clone(), 1.99), Vec3::ZERO, "held, not mixed");
        assert_eq!(position(moves.clone(), 2.0), Vec3::X * 10.0);
        assert_eq!(position(moves, 3.9), Vec3::X * 10.0);
    }

    #[test]
    fn a_turn_takes_the_shorter_way_round_whichever_way_a_key_spells_it() {
        let quarter = Quat::from_rotation_y(core::f32::consts::FRAC_PI_2);
        let turning = |later: Quat| {
            let moves = Moves::Turn(Keys::Linear(vec![(0.0, Quat::IDENTITY), (1.0, later)]));
            moved(moves, 0.5).turn
        };
        let eighth = Quat::from_rotation_y(core::f32::consts::FRAC_PI_4);

        assert!(turning(quarter).abs_diff_eq(eighth, 1e-5));
        assert!(
            turning(-quarter).abs_diff_eq(eighth, 1e-5)
                || turning(-quarter).abs_diff_eq(-eighth, 1e-5),
            "the same turn spelled the other way round mixes the same way"
        );
        let halfway = turning(-quarter);
        assert!(
            (halfway.to_scaled_axis().length() - eighth.to_scaled_axis().length()).abs() < 1e-5,
            "{halfway} turned further than half of a quarter"
        );
    }

    #[test]
    fn a_cubic_key_between_two_keys_reads_the_spline_and_a_key_reads_the_key() {
        // One interval a second long, from the origin out to `X`, leaving
        // the first key along `X` at 3 meters a second and met along `Y` at
        // 3. Halfway across, the four curves of the interval are 0.5, 0.125,
        // 0.5 and -0.125, so it holds
        // 0.125 * (3, 0, 0) + 0.5 * (1, 0, 0) - 0.125 * (0, 3, 0).
        let keys = vec![
            (0.0, [Vec3::ZERO, Vec3::ZERO, Vec3::X * 3.0]),
            (1.0, [Vec3::Y * 3.0, Vec3::X, Vec3::ZERO]),
        ];
        let moves = Moves::Position(Keys::Cubic(keys));

        assert_eq!(position(moves.clone(), 0.0), Vec3::ZERO, "at the first key");
        assert_eq!(position(moves.clone(), 1.0), Vec3::X, "and at the last");
        let middle = position(moves, 0.5);
        assert!(
            middle.abs_diff_eq(Vec3::new(0.875, -0.375, 0.0), 1e-6),
            "{middle} is not where the spline lies halfway across"
        );
    }

    #[test]
    fn two_keys_at_one_time_read_the_later_of_the_two() {
        let keys = vec![
            (0.0, Vec3::ZERO),
            (1.0, Vec3::X),
            (1.0, Vec3::Y),
            (2.0, Vec3::Y * 2.0),
        ];
        let stepped = Moves::Position(Keys::Step(keys.clone()));
        let mixed = Moves::Position(Keys::Linear(keys));

        assert_eq!(position(stepped, 1.0), Vec3::Y);
        assert_eq!(position(mixed.clone(), 1.0), Vec3::Y);
        assert_eq!(
            position(mixed, 1.5),
            Vec3::Y * 1.5,
            "and the interval past them starts at the later key"
        );
    }

    #[test]
    fn a_path_no_track_moves_holds_the_rest() {
        let turned = Moves::Turn(Keys::Linear(vec![(
            0.0,
            Quat::from_rotation_x(core::f32::consts::FRAC_PI_2),
        )]));
        let rig = stack();
        let clips = clip(1, turned);
        let mut pose = Pose::default();
        pose.sample(&rig, clips.first(), 0.0);

        assert_eq!(
            pose.locals[0],
            rig.joints()[0].rest,
            "the joint no track names is left at rest"
        );
        let moved = pose.locals[1];
        assert_eq!(
            (moved.position, moved.scale),
            (rig.joints()[1].rest.position, rig.joints()[1].rest.scale),
            "and the paths of the joint it does name that it never moves"
        );
        assert_ne!(moved.turn, rig.joints()[1].rest.turn);
    }

    #[test]
    fn a_joint_is_placed_within_its_parent_and_never_its_parent_within_it() {
        let rig = stack();
        let turn = Moves::Turn(Keys::Step(vec![(
            0.0,
            Quat::from_rotation_z(core::f32::consts::FRAC_PI_2),
        )]));
        // A corner a meter above the joint above the root, which both of
        // them take with them.
        let tip = Vec3::Y * 3.0;
        let turned = |joint| {
            let posed = palette(&rig, &clip(joint, turn.clone()), Some(Posing::clip(0, 0.0)));
            [posed[0], posed[1]].map(|matrix| matrix.transform_point3(tip))
        };

        let [by_root, under_root] = turned(0);
        assert!(
            by_root.abs_diff_eq(Vec3::new(-2.0, 1.0, 0.0), 1e-5),
            "{by_root} is not where the turned root takes a corner two meters above it"
        );
        assert!(
            under_root.abs_diff_eq(by_root, 1e-5),
            "{under_root}, the joint under it, carries that corner the same way"
        );

        let [by_parent, moved] = turned(1);
        assert_eq!(by_parent, tip, "a turn under a joint leaves that joint be");
        assert!(
            moved.abs_diff_eq(Vec3::new(-1.0, 2.0, 0.0), 1e-5),
            "{moved} is not where the turned joint takes a corner a meter above it"
        );
    }

    #[test]
    fn a_rig_at_rest_composes_to_the_identity_palette_a_model_is_drawn_by() {
        for source in [RIG, SCALED] {
            let rig = rig_of(source);
            let at_rest = palette(rig.rig(), rig.clips(), None);

            assert_eq!(at_rest.len(), 3, "one matrix per joint");
            for (at, matrix) in at_rest.iter().enumerate() {
                assert!(
                    matrix.abs_diff_eq(Mat4::IDENTITY, 1e-5),
                    "joint {at} composes to {matrix} where its bind is the inverse of where it \
                     rests in the model"
                );
            }
        }
    }

    #[test]
    fn the_root_node_a_scaled_model_stands_in_reaches_its_corners_and_not_its_palette() {
        let scaled = rig_of(SCALED);
        let Placed::Within(above) = scaled.rig().joints()[0].placed else {
            panic!("the root joint hangs under no joint");
        };
        let placement = Mat4::from_scale_rotation_translation(
            Vec3::splat(0.5),
            Quat::from_rotation_y(core::f32::consts::FRAC_PI_6),
            Vec3::new(1.0, 0.0, -2.0),
        );

        assert!(
            above.abs_diff_eq(placement, 1e-6),
            "the root node's own transform stands above the joints"
        );
        let plain = rig_of(RIG);
        assert_ne!(
            scaled.vertices().len(),
            0,
            "and the corners the source states already carry it"
        );
        assert_ne!(
            scaled.vertices()[0].position,
            plain.vertices()[0].position,
            "so a scaled model's corners lie where the scale leaves them"
        );
    }

    /// The clip at `clip` read `at` seconds along it.
    fn sampled(clip: u32, at: f32) -> Sampled {
        Sampled { clip, at }
    }

    #[test]
    fn a_blend_at_either_end_is_the_pose_at_that_end_and_a_pose_blends_to_itself() {
        let rig = rig_of(RIG);
        let ends = |weight| {
            palette(
                rig.rig(),
                rig.clips(),
                Some(Posing::clip(0, 0.4).blended(sampled(1, 0.4), weight)),
            )
        };
        let alone = |clip| palette(rig.rig(), rig.clips(), Some(Posing::clip(clip, 0.4)));

        assert_eq!(ends(0.0), alone(0));
        assert_eq!(ends(1.0), alone(1));
        assert_ne!(alone(0), alone(1), "the two clips hold poses of their own");

        let itself = palette(
            rig.rig(),
            rig.clips(),
            Some(Posing::clip(1, 0.4).blended(sampled(1, 0.4), 0.5)),
        );
        assert_eq!(itself, alone(1));
    }

    #[test]
    fn a_pose_reads_four_clips_however_many_are_blended_over_it() {
        let blended = (0..8).fold(Posing::clip(0, 0.0), |posing, over| {
            posing.blended(sampled(1, over as f32), 0.9)
        });

        assert_eq!(
            blended.over.iter().flatten().count(),
            BLENDED,
            "three over the one it starts at, and no more"
        );
        assert_eq!(
            blended.from,
            sampled(1, 4.0),
            "and the collapsed pairs kept the clip each lay nearer"
        );

        let under = (0..8).fold(Posing::clip(0, 0.0), |posing, over| {
            posing.blended(sampled(1, over as f32), 0.1)
        });
        assert_eq!(
            under.from,
            sampled(0, 0.0),
            "a pair the pose lies nearer the first of keeps that one"
        );
    }

    #[test]
    fn a_mesh_with_no_joints_takes_no_matrices() {
        let mut palette = Palette::default();

        assert_eq!(palette.take(Skinned(0), &Rig::default(), &[], None), 0);
        assert!(palette.matrices().is_empty());
    }

    /// The run a draw of `mesh` posed by `posing` reads, out of a palette a
    /// test fills draw by draw.
    fn taking(
        palette: &mut Palette,
        model: &Geometry,
        mesh: Skinned,
        posing: Option<Posing>,
    ) -> u32 {
        palette.take(mesh, model.rig(), model.clips(), posing)
    }

    #[test]
    fn draws_of_one_mesh_in_one_pose_take_one_run_of_the_palette() {
        let model = rig_of(RIG);
        let joints = model.rig().joints().len() as u32;
        let mut palette = Palette::default();

        for _ in 0..90 {
            assert_eq!(
                taking(&mut palette, &model, Skinned(0), None),
                0,
                "every draw reads the first run"
            );
        }
        assert_eq!(
            palette.matrices().len() as u32,
            joints,
            "ninety draws of one mesh at rest take one run of it"
        );

        let walking = Posing::clip(1, 0.4);
        assert_eq!(
            taking(&mut palette, &model, Skinned(1), None),
            joints,
            "a second mesh takes a run of its own"
        );
        assert_eq!(
            taking(&mut palette, &model, Skinned(0), Some(walking)),
            2 * joints,
            "and so does a pose of the first"
        );
        assert_eq!(
            taking(&mut palette, &model, Skinned(0), Some(Posing::clip(1, 0.4))),
            2 * joints,
            "a draw in a pose equal to one already taken reads that run"
        );
        assert_eq!(
            taking(&mut palette, &model, Skinned(0), None),
            0,
            "and the rest run stands where it was"
        );
        assert_eq!(palette.matrices().len() as u32, 3 * joints);

        palette.clear();
        assert_eq!(
            taking(&mut palette, &model, Skinned(0), Some(walking)),
            0,
            "a frame takes afresh"
        );
    }
}