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
721
722
723
724
725
726
727
728
729
730
731
732
//! Loaded sources, and the names a game's builds read from them.

use core::mem::discriminant;
use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;

use crate::Error;
use crate::mesh::{Clip, MeshData, NoClips, Part};
use crate::skybox::SkyboxData;
use crate::sound::{Encoded, SoundData};

pub(crate) use model::{NamedAnimation, NamedModel, Readable};
pub(crate) use named::{NamedMesh, NamedSlot};
pub(crate) use ogg::Stream;
pub(crate) use texture::Textures;
pub use texture::{ReliefData, ShadingData, TextureData};
pub(crate) use unresolved::{QUALIFIER, Unresolved};

/// The example's asset source, loaded for every test that needs data.
#[cfg(test)]
pub(crate) const BEACON: &[u8] = include_bytes!("../../examples/assets/hello.glb");

/// A two-second tone, the sound every test that needs one loads.
#[cfg(test)]
pub(crate) const SWEEP: &[u8] = include_bytes!("../../tests/assets/sweep.ogg");

/// The models the tests read: a skinned rig of three joints under two clips,
/// the same rig under a root node scaled and turned, a keyed cube with
/// another under it no clip moves, one action written on two tracks, two
/// animations of one name, and a model two skins and a set of shapes cover.
#[cfg(test)]
pub(crate) const RIG: &[u8] = include_bytes!("../../tests/assets/a_rig.glb");
#[cfg(test)]
pub(crate) const SCALED: &[u8] = include_bytes!("../../tests/assets/a_rig_scaled.glb");
#[cfg(test)]
pub(crate) const PROP: &[u8] = include_bytes!("../../tests/assets/b_prop.glb");
#[cfg(test)]
pub(crate) const TRACKED: &[u8] = include_bytes!("../../tests/assets/two_tracks_same_action.glb");
#[cfg(test)]
pub(crate) const MERGED: &[u8] = include_bytes!("../../tests/assets/d_merge.glb");
#[cfg(test)]
pub(crate) const ROBOT: &[u8] = include_bytes!("../../tests/assets/robot-expressive.glb");

/// The two models the examples draw, which the tests read as well: one of
/// sixteen joints under four clips, and one whose two meshes share a skin.
#[cfg(test)]
pub(crate) const CORGI: &[u8] = include_bytes!("../../examples/assets/corgi.glb");
#[cfg(test)]
pub(crate) const CHEST: &[u8] = include_bytes!("../../examples/assets/chest.glb");

/// Four pixels, the texture source every test that needs one loads.
#[cfg(test)]
pub(crate) const IMP: &[u8] = include_bytes!("../../tests/assets/imp.png");

/// The example's font, the source every test that needs one loads.
#[cfg(test)]
pub(crate) const OPERATOR: &[u8] = include_bytes!("../../examples/assets/pixel-operator.ttf");

/// One source as [`Assets::load`] takes it: the file name it came in, and
/// its bytes.
#[cfg(test)]
pub(crate) fn file(source: &str, bytes: &[u8]) -> (String, Vec<u8>) {
    (source.to_owned(), bytes.to_vec())
}

/// Everything [`Config::with_assets`](crate::Config::with_assets) loaded, by
/// name across all sources.
///
/// A name only one source used is read bare, `"Ship"`; a name more than
/// one shares needs its source, `"props#Ship"`.
#[derive(Default)]
pub struct Assets {
    loaded: Loaded,
    /// `build` takes `&Assets`, not `&mut`, so what did not resolve is
    /// recorded here.
    unresolved: RefCell<BTreeSet<Unresolved>>,
}

impl Assets {
    /// The mesh a source loaded under `name`, its material names resolved
    /// to the parts `P`.
    ///
    /// A part names exactly one material; one that resolves to no part is
    /// drawn as authored unless a draw repaints every slot. A missing or
    /// ambiguous name, a part no material resolves to, and a part two
    /// materials resolve to each return empty data and become part of the
    /// startup error.
    pub fn mesh<P: Part>(&self, name: &str) -> MeshData<P, NoClips> {
        match self.loaded.find(name, Item::mesh) {
            Ok(mesh) => self.built(mesh.resolved(name)),
            Err(unaddressable) => {
                self.record(unaddressable);
                MeshData::empty()
            }
        }
    }

    /// The model a source loaded under `name`: the mesh of one of its root
    /// nodes, the joints that pose it, and one animation per clip of `C`.
    ///
    /// Material names resolve to the parts `P` as [`mesh`](Assets::mesh)
    /// resolves them, and each clip resolves the one animation of the source
    /// whose name it matches. An animation no clip matches is left alone; a
    /// clip that matches none, a clip two animations match, and a clip whose
    /// animation moves no joint of this model each return empty data and
    /// become part of the startup error.
    pub fn model<P: Part, C: Clip>(&self, name: &str) -> MeshData<P, C> {
        match self.loaded.find(name, Item::model) {
            Ok(model) => self.built(model.resolved(name)),
            Err(unaddressable) => {
                self.record(unaddressable);
                MeshData::empty()
            }
        }
    }

    /// The mesh a name resolved to, with everything about it that did not
    /// resolve recorded for the startup error.
    fn built<P: Part, C: Clip>(
        &self,
        resolved: Result<MeshData<P, C>, Vec<Unresolved>>,
    ) -> MeshData<P, C> {
        match resolved {
            Ok(mesh) => mesh,
            Err(unresolved) => {
                unresolved.into_iter().for_each(|what| self.record(what));
                MeshData::empty()
            }
        }
    }

    /// The texture a source loaded under `name`.
    ///
    /// A missing name returns empty pixels and becomes part of the startup
    /// error.
    pub fn texture(&self, name: &str) -> TextureData {
        match self.loaded.find(name, Item::texture) {
            Ok(texture) => texture.clone(),
            Err(unaddressable) => {
                self.record(unaddressable);
                TextureData::default()
            }
        }
    }

    /// The texture a source loaded under `name`, read as a relief holding a
    /// normal and a depth per texel.
    ///
    /// A missing name returns empty pixels and becomes part of the startup
    /// error.
    pub fn relief(&self, name: &str) -> ReliefData {
        ReliefData::loaded(self.texture(name))
    }

    /// The same pixels read as the whole sky: the whole way around across
    /// the image, and zenith to nadir down it.
    ///
    /// A missing name returns a black sky and becomes part of the startup
    /// error, and so does an image that is no sky at all, under the name of
    /// the skybox it was built for.
    pub fn skybox(&self, name: &str) -> SkyboxData {
        let image = self.texture(name);

        match image.drawn() {
            true => SkyboxData::equirect(image),
            false => SkyboxData::default(),
        }
    }

    /// The sound a source loaded under `name`.
    ///
    /// A missing name returns silence and becomes part of the startup error.
    pub fn sound(&self, name: &str) -> SoundData {
        match self.loaded.find(name, Item::sound) {
            Ok(clip) => SoundData::loaded(Arc::clone(clip)),
            Err(unaddressable) => {
                self.record(unaddressable);
                SoundData::empty()
            }
        }
    }

    /// The font a source loaded under `name`.
    ///
    /// A missing or ambiguous name is the error it returns, not a recorded
    /// miss: a font is read once startup has already turned the record into
    /// its error, so a recorded miss would reach nothing.
    #[cfg(feature = "ui")]
    pub(crate) fn font(&self, name: &str) -> Result<Arc<[u8]>, Error> {
        match self.loaded.find(name, Item::font) {
            Ok(bytes) => Ok(Arc::clone(bytes)),
            Err(unaddressable) => Err(Error::msg(unaddressable.to_string())),
        }
    }

    /// Builds a store by decoding `files` in load order. Each item is a file
    /// name and its bytes.
    ///
    /// Fails with one error naming every file the engine cannot read, every
    /// file whose name cannot qualify an item name, every file that names one
    /// item of a kind more than once, and every file name two files share. A
    /// name two files share is not an error: it is only read qualified.
    pub(crate) fn load(files: impl IntoIterator<Item = (String, Vec<u8>)>) -> Result<Self, Error> {
        let decoded = files
            .into_iter()
            .map(|(source, bytes)| DecodedFile::decode(&source, &bytes));

        let mut loaded = Loaded::default();
        let mut failures = Vec::new();
        for file in decoded {
            if let Err(error) = file.and_then(|file| loaded.place(file)) {
                failures.push(error.to_string());
            }
        }

        match failures.is_empty() {
            true => Ok(Self {
                loaded,
                unresolved: RefCell::default(),
            }),
            false => Err(Error::msg(format!(
                "the game's asset sources did not load: {}",
                failures.join("; ")
            ))),
        }
    }

    /// The one startup error for everything the builds needed and did not
    /// get; clears the record.
    pub(crate) fn unresolved(&self) -> Option<Error> {
        let unresolved = self.unresolved.take();
        (!unresolved.is_empty()).then(|| {
            let mut lines: Vec<String> = unresolved.iter().map(Unresolved::to_string).collect();
            lines.sort();
            Error::msg(format!(
                "the game's assets did not resolve: {}",
                lines.join("; ")
            ))
        })
    }

    /// Records something that did not resolve, once, for the startup error.
    pub(crate) fn record(&self, what: Unresolved) {
        let mut unresolved = self.unresolved.borrow_mut();
        if !unresolved.contains(&what) {
            log::debug!("{what}");
            unresolved.insert(what);
        }
    }
}

/// Everything the sources have loaded so far.
#[derive(Default)]
struct Loaded {
    /// Each name against every source that used it, in load order.
    items: HashMap<String, Vec<(Rc<str>, Item)>>,
    stems: HashSet<Rc<str>>,
}

impl Loaded {
    /// What `name` resolves to among the items `of` reads, or what to record
    /// if it resolves to nothing.
    ///
    /// A name an item holds whole is matched before the name is split at
    /// its `#`. One name reaches one item of every kind, so a source that
    /// holds a mesh and a model of one name is read either way.
    fn find<'a, T>(
        &'a self,
        name: &str,
        of: impl Fn(&'a Item) -> Option<T>,
    ) -> Result<T, Unresolved> {
        let held = |bare: &str| -> Vec<(&'a Rc<str>, T)> {
            self.items
                .get(bare)
                .into_iter()
                .flatten()
                .filter_map(|(stem, item)| of(item).map(|held| (stem, held)))
                .collect()
        };

        let mut shared = held(name);
        match shared.len() {
            1 => return Ok(shared.remove(0).1),
            0 => {}
            _ => {
                return Err(Unresolved::Ambiguous {
                    name: name.to_owned(),
                    sources: shared
                        .into_iter()
                        .map(|(stem, _)| stem.to_string())
                        .collect(),
                });
            }
        }

        let Some((stem, bare)) = name.split_once(QUALIFIER) else {
            return Err(Unresolved::absent(name));
        };
        held(bare)
            .into_iter()
            .find(|(other, _)| other.as_ref() == stem)
            .map(|(_, item)| item)
            .ok_or_else(|| Unresolved::absent(name))
    }

    /// Takes in the items `file` decoded, under the file name it read them
    /// by.
    ///
    /// Fails where a file of that name is in the store already, which nothing
    /// could then tell apart by name; the store is left as it was.
    fn place(&mut self, file: DecodedFile) -> Result<(), Error> {
        let DecodedFile { stem, items } = file;
        if !self.stems.insert(Rc::clone(&stem)) {
            return Err(shared_stem(&stem));
        }

        for (name, item) in items {
            self.items
                .entry(name)
                .or_default()
                .push((Rc::clone(&stem), item));
        }
        Ok(())
    }
}

/// One file decoded on its own: the file name its items are read by, and the
/// items it holds.
struct DecodedFile {
    stem: Rc<str>,
    items: Vec<(String, Item)>,
}

impl DecodedFile {
    /// Decodes the file `source` names out of `bytes`, against nothing else.
    ///
    /// Fails where that file name could qualify no item name, where the
    /// engine cannot read the bytes, and where they name one item of a kind
    /// more than once.
    fn decode(source: &str, bytes: &[u8]) -> Result<Self, Error> {
        let stem: Rc<str> = Rc::from(stem(source)?);
        let named = |error| Error::msg(format!("the asset source `{source}` {error}"));
        let items = match Kind::of(source) {
            Kind::Model => glb::decode(&stem, bytes).map_err(named)?,
            // A texture or a sound is one item, which its own file name is
            // the name of.
            Kind::Texture => vec![(
                stem.to_string(),
                Item::Texture(texture::decode(bytes).map_err(named)?),
            )],
            Kind::Sound => vec![(
                stem.to_string(),
                Item::Sound(Arc::new(ogg::decode(bytes).map_err(named)?)),
            )],
            Kind::Font => font_items(&stem, bytes).map_err(named)?,
        };

        let mut names = HashSet::with_capacity(items.len());
        for (name, item) in &items {
            if !names.insert((name.as_str(), discriminant(item))) {
                return Err(Error::msg(format!(
                    "the asset source `{source}` calls two things `{name}`"
                )));
            }
        }

        Ok(Self { stem, items })
    }
}

/// What a font source adds to the store under `stem`: its bytes, for the UI
/// to draw with.
#[cfg(feature = "ui")]
fn font_items(stem: &str, bytes: &[u8]) -> Result<Vec<(String, Item)>, Error> {
    let font = font::decode(bytes)?;
    Ok(vec![(stem.to_owned(), Item::Font(font))])
}

/// The same, without the UI: the source decodes the same way, and no item
/// keeps a font nothing can draw with.
#[cfg(not(feature = "ui"))]
fn font_items(_stem: &str, bytes: &[u8]) -> Result<Vec<(String, Item)>, Error> {
    font::decode(bytes)?;
    Ok(Vec::new())
}

/// The error for two sources one file name could mean either of.
fn shared_stem(stem: &str) -> Error {
    Error::msg(format!(
        "two asset sources are both called `{stem}`, and a shared item name is reached by \
         file name, so rename one of them"
    ))
}

/// One decoded item a source named.
enum Item {
    Mesh(NamedMesh),
    Model(NamedModel),
    Texture(TextureData),
    Sound(Arc<Encoded>),
    #[cfg(feature = "ui")]
    Font(Arc<[u8]>),
}

impl Item {
    fn mesh(&self) -> Option<&NamedMesh> {
        match self {
            Self::Mesh(mesh) => Some(mesh),
            _ => None,
        }
    }

    fn model(&self) -> Option<&NamedModel> {
        match self {
            Self::Model(model) => Some(model),
            _ => None,
        }
    }

    fn texture(&self) -> Option<&TextureData> {
        match self {
            Self::Texture(texture) => Some(texture),
            _ => None,
        }
    }

    fn sound(&self) -> Option<&Arc<Encoded>> {
        match self {
            Self::Sound(clip) => Some(clip),
            _ => None,
        }
    }

    #[cfg(feature = "ui")]
    fn font(&self) -> Option<&Arc<[u8]>> {
        match self {
            Self::Font(bytes) => Some(bytes),
            _ => None,
        }
    }
}

/// Kind of thing a source holds, from its file name.
enum Kind {
    Model,
    Texture,
    Sound,
    Font,
}

impl Kind {
    /// Kind a source holds, from the end of its file name.
    fn of(source: &str) -> Self {
        match source.rsplit_once('.') {
            Some((_, kind)) if kind.eq_ignore_ascii_case("ogg") => Self::Sound,
            Some((_, kind)) if kind.eq_ignore_ascii_case("png") => Self::Texture,
            Some((_, kind))
                if kind.eq_ignore_ascii_case("ttf") || kind.eq_ignore_ascii_case("otf") =>
            {
                Self::Font
            }
            _ => Self::Model,
        }
    }
}

/// The name a source qualifies its items by, without its file extension.
///
/// Fails where that name holds the mark a qualified name is read through,
/// which nothing could then read a shared name of the source by.
fn stem(source: &str) -> Result<&str, Error> {
    let file = source.rsplit(['/', '\\']).next().unwrap_or(source);
    let stem = file.rsplit_once('.').map_or(file, |(stem, _)| stem);
    if stem.contains(QUALIFIER) {
        return Err(Error::msg(format!(
            "the asset source `{stem}` holds a `{QUALIFIER}` in its file name, which is the \
             mark a shared item name is read through, so rename it"
        )));
    }
    Ok(stem)
}

pub(crate) mod font;
mod glb;
mod model;
mod named;
pub(crate) mod ogg;
mod texture;
mod unresolved;

#[cfg(test)]
mod tests {
    use core::time::Duration;

    use super::*;
    use crate::math::UVec2;
    use crate::mesh::NoParts;

    fn loaded(sources: &[&str]) -> Assets {
        Assets::load(sources.iter().map(|source| file(source, BEACON)))
            .expect("the example's model decodes")
    }

    #[test]
    fn a_miss_yields_empty_data_and_becomes_one_error() {
        let assets = Assets::default();

        assert_eq!(assets.mesh::<NoParts>("hull").slots().len(), 0);
        assert_eq!(assets.texture("paint").size(), UVec2::ZERO);
        assert_eq!(assets.mesh::<NoParts>("hull").slots().len(), 0);

        let error = assets.unresolved().expect("the misses were recorded");
        assert_eq!(
            error.to_string(),
            "the game's assets did not resolve: no asset is named `hull`; \
             no asset is named `paint`"
        );
        assert!(assets.unresolved().is_none(), "the record is cleared");
    }

    #[test]
    fn a_name_loaded_as_one_kind_is_a_miss_as_the_other() {
        let assets = loaded(&["hello.glb"]);

        assert!(assets.texture("beacon").pixels().is_empty());
        assert!(assets.unresolved().is_some());
    }

    #[test]
    fn a_name_two_sources_share_is_reachable_only_by_their_file_names() {
        let assets = loaded(&["art/props.glb", "art/scene.glb"]);

        assert_eq!(
            assets.mesh::<NoParts>("beacon").slots().len(),
            0,
            "bare, it reaches neither of them"
        );
        let error = assets.unresolved().expect("the ambiguity was recorded");
        assert_eq!(
            error.to_string(),
            "the game's assets did not resolve: several sources call something `beacon`; \
             ask for `props#beacon` or `scene#beacon`"
        );

        assert_eq!(assets.mesh::<NoParts>("props#beacon").slots().len(), 2);
        assert_eq!(
            assets.texture("scene#beacon_panels").size(),
            UVec2::splat(16)
        );
        assert!(assets.unresolved().is_none(), "qualified, both resolve");
    }

    #[test]
    fn a_name_only_one_source_uses_stays_bare() {
        let assets = loaded(&["props.glb"]);

        assert_eq!(assets.mesh::<NoParts>("beacon").slots().len(), 2);
        assert_eq!(assets.mesh::<NoParts>("props#beacon").slots().len(), 2);
        assert!(assets.unresolved().is_none(), "either way of asking works");
    }

    #[test]
    fn a_sound_source_is_named_by_its_own_file_name() {
        let assets = Assets::load([file("audio/theme.ogg", SWEEP)]).expect("the fixture decodes");

        assert_eq!(
            assets.sound("theme").duration(),
            Duration::from_secs(2),
            "one source, one sound, named by the file it came in"
        );
        assert!(assets.mesh::<NoParts>("theme").indices().is_empty());
        let error = assets.unresolved().expect("asking for it as a mesh missed");
        assert_eq!(
            error.to_string(),
            "the game's assets did not resolve: no asset is named `theme`"
        );
    }

    #[test]
    fn a_texture_source_is_named_by_its_own_file_name() {
        let assets = Assets::load([file("art/imp.png", IMP)]).expect("the fixture decodes");

        let imp = assets.texture("imp");
        assert_eq!(imp.size(), UVec2::splat(2), "one source, one texture");
        assert_eq!(
            imp.pixels()[..4],
            [u8::MAX, 0, 0, u8::MAX],
            "read row by row from the top left"
        );
        assert_eq!(assets.texture("imp#imp").size(), UVec2::splat(2));

        assert_eq!(assets.texture("goblin").size(), UVec2::ZERO);
        let error = assets.unresolved().expect("only the second pull missed");
        assert_eq!(
            error.to_string(),
            "the game's assets did not resolve: no asset is named `goblin`"
        );
    }

    #[cfg(feature = "ui")]
    #[test]
    fn a_font_source_is_named_by_its_own_file_name() {
        let assets =
            Assets::load([file("art/pixel-operator.ttf", OPERATOR)]).expect("the fixture decodes");

        assert_eq!(
            assets
                .font("pixel-operator")
                .expect("one source, one font, named by the file it came in")
                .len(),
            OPERATOR.len(),
            "the bytes the source held"
        );
        assert_eq!(
            assets
                .font("nothing")
                .expect_err("no source holds that name")
                .to_string(),
            "no asset is named `nothing`"
        );
        assert!(
            assets.unresolved().is_none(),
            "a font that missed is the error it returned, never a recorded miss"
        );

        let assets = Assets::load([
            file("art/pixel-operator.ttf", OPERATOR),
            file("art/OTHER.OTF", OPERATOR),
        ])
        .expect("either extension, in either case");
        assert!(assets.font("OTHER").is_ok());
    }

    #[test]
    fn a_font_source_that_does_not_decode_cannot_start() {
        let Err(error) = Assets::load([file("junk.ttf", b"not a font at all")]) else {
            panic!("nothing decodes that");
        };

        assert!(
            error.to_string().starts_with(
                "the game's asset sources did not load: the asset source `junk.ttf` did not decode"
            ),
            "got {error}"
        );
    }

    #[test]
    fn a_texture_source_that_does_not_decode_cannot_start() {
        let Err(error) = Assets::load([file("junk.png", b"not a texture at all")]) else {
            panic!("nothing decodes that");
        };

        assert!(
            error.to_string().starts_with(
                "the game's asset sources did not load: the asset source `junk.png` did not decode"
            ),
            "got {error}"
        );
    }

    #[test]
    fn a_source_whose_file_name_holds_the_qualifier_cannot_start() {
        let Err(error) = Assets::load([file("art/art#hello.glb", BEACON)]) else {
            panic!("nothing could reach a name it shared");
        };

        assert_eq!(
            error.to_string(),
            "the game's asset sources did not load: the asset source `art#hello` holds a `#` in \
             its file name, which is the mark a shared item name is read through, so rename it"
        );
    }

    #[test]
    fn two_sources_with_one_file_name_cannot_start() {
        let Err(error) = Assets::load([
            file("art/hello.glb", BEACON),
            file("other/hello.glb", BEACON),
        ]) else {
            panic!("nothing could tell the two apart");
        };

        assert_eq!(
            error.to_string(),
            "the game's asset sources did not load: two asset sources are both called `hello`, \
             and a shared item name is reached by file name, so rename one of them"
        );
    }

    #[test]
    fn every_source_that_did_not_load_is_named_in_one_error() {
        let Err(error) = Assets::load([
            file("art/hello.glb", BEACON),
            file("other/hello.glb", BEACON),
            file("art#props.glb", BEACON),
        ]) else {
            panic!("two file names are one, and the third holds the qualifier");
        };

        assert_eq!(
            error.to_string(),
            "the game's asset sources did not load: two asset sources are both called `hello`, \
             and a shared item name is reached by file name, so rename one of them; the asset \
             source `art#props` holds a `#` in its file name, which is the mark a shared item \
             name is read through, so rename it",
            "one error, in load order, naming both"
        );

        let Err(error) = Assets::load([
            file("junk/beacon.glb", b"not a container at all"),
            file("art/beacon.glb", BEACON),
        ]) else {
            panic!("the first of these two does not decode");
        };

        let text = error.to_string();
        assert!(
            text.starts_with(
                "the game's asset sources did not load: the asset source `junk/beacon.glb` did \
                 not decode"
            ),
            "got {text}"
        );
        assert!(
            !text.contains("both called"),
            "and the file that did not load claims no file name: {text}"
        );
    }
}