Skip to main content

nadir/
level.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Levels in the world (ADR-0038, `docs/subsystems/scene.md`, "Levels"):
16//! [`load_level`] reads a cooked level file, `levels/<name>.klvl`, and its
17//! prefabs, and makes its tile layers, its collision grid, its tall tiles
18//! and its entities; [`CurrentLevel`] keeps what it made, so that the next
19//! load removes the level whole; and the engine's `nadir::extract_level`
20//! draws its tile layers each frame, its background the clear colour.
21
22use std::fmt;
23
24use nadir_assets::{AssetError, AssetServer, FinalizeCtx, Handle, Scope};
25use nadir_collision::TileGrid;
26use nadir_core::log::info;
27use nadir_core::time::{Frame, Stopwatch};
28use nadir_core::{Color, IVec2, UVec2, Vec2};
29use nadir_ecs::{Entity, World};
30use nadir_render::{
31    Atlas, Flip, RenderFrame, Texture, Tile, TileLayer, TileLayerDraw, TileLayers, TileSet,
32};
33use nadir_scene::level::{Level, LevelFile};
34use nadir_scene::{PrefabError, PrefabLibrary, TypeRegistry};
35
36use crate::{ClipError, Clips, CollisionLayers, Collisions, Sprite, Transform, loading_context};
37
38/// The level the world holds, if any: what [`load_level`] made of it. A
39/// resource of every [`App`](crate::App), empty until a level loads.
40#[derive(Debug, Default)]
41pub struct CurrentLevel {
42    level: Option<Loaded>,
43}
44
45/// What a level made.
46#[derive(Debug)]
47struct Loaded {
48    name: String,
49    background: Color,
50    /// Its tall tiles' entities, then its prefabs', in the order they
51    /// spawned.
52    entities: Vec<Entity>,
53    /// Its tile layers, in [`TileLayers`], drawn in this order.
54    layers: Vec<TileLayerDraw>,
55    /// The atlases whose clips it holds in [`Clips`], by their pages.
56    atlases: Vec<Vec<Handle<Texture>>>,
57    /// Whether it set the collision grid.
58    grid: bool,
59    /// The clear colour it replaced, which it puts back when it goes.
60    clear: Color,
61}
62
63impl Loaded {
64    /// Its entities and tile layers counted, for the log.
65    fn counts(&self) -> String {
66        let count = |n: usize, one: &str, many: &str| match n {
67            1 => format!("1 {one}"),
68            n => format!("{n} {many}"),
69        };
70        format!(
71            "{}, {}",
72            count(self.entities.len(), "entity", "entities"),
73            count(self.layers.len(), "tile layer", "tile layers")
74        )
75    }
76}
77
78impl CurrentLevel {
79    /// The level's name, as [`load_level`] was given it, if one is loaded.
80    pub fn name(&self) -> Option<&str> {
81        self.level.as_ref().map(|level| level.name.as_str())
82    }
83
84    /// The level's background, the frames' clear colour while it is
85    /// loaded.
86    pub fn background(&self) -> Option<Color> {
87        self.level.as_ref().map(|level| level.background)
88    }
89
90    /// The entities the level spawned, its tall tiles' then its prefabs',
91    /// which the next load despawns. Empty if none is loaded.
92    pub fn entities(&self) -> &[Entity] {
93        self.level
94            .as_ref()
95            .map_or(&[], |level| level.entities.as_slice())
96    }
97
98    /// The level's tile layers, in [`TileLayers`], as the engine draws them
99    /// each frame, the first beneath. Empty if none is loaded.
100    pub fn tile_layers(&self) -> &[TileLayerDraw] {
101        self.level
102            .as_ref()
103            .map_or(&[], |level| level.layers.as_slice())
104    }
105
106    /// The path of the level's file, if one is loaded.
107    #[cfg(feature = "dev")]
108    pub(crate) fn path(&self) -> Option<String> {
109        self.name().and_then(level_path)
110    }
111
112    /// Knows the atlas of the level's that was known by `old`, its pages,
113    /// by `new` from now on, as [`Clips`] knows it after a reload
114    /// ([`Clips::reload_atlas`]), so that the level lets go of it there.
115    #[cfg(feature = "dev")]
116    pub(crate) fn replace_atlas_pages(&mut self, old: &[Handle<Texture>], new: &[Handle<Texture>]) {
117        if let Some(level) = &mut self.level {
118            for pages in &mut level.atlases {
119                if pages.as_slice() == old {
120                    *pages = new.to_vec();
121                }
122            }
123        }
124    }
125}
126
127/// Why a level could not be loaded. The previous level is gone then, and
128/// nothing of the new one is in the world but the prefabs it read, which
129/// the [`PrefabLibrary`] keeps.
130#[derive(Clone, Debug, PartialEq)]
131#[non_exhaustive]
132pub enum LevelError {
133    /// The name is not a level's: lowercase letters, digits and `_`, as the
134    /// cook names level files.
135    BadName {
136        /// The name.
137        name: String,
138    },
139    /// The level file, or an atlas of its tile sets, could not be loaded.
140    Load {
141        /// Its path.
142        path: String,
143        /// Why.
144        error: AssetError,
145    },
146    /// A tile set of the level is not a tile set of its atlas, or not of
147    /// the level's size.
148    Tileset {
149        /// The atlas.
150        atlas: String,
151        /// The tile set's sprite in it.
152        sprite: String,
153        /// What is wrong.
154        reason: &'static str,
155    },
156    /// The clips of an atlas of the level could not be added.
157    Clips {
158        /// The atlas.
159        atlas: String,
160        /// Why.
161        error: ClipError,
162    },
163    /// The level's grid is on a collision layer the game has not named
164    /// ([`App::collision_layers`](crate::App::collision_layers)).
165    UnknownLayer {
166        /// The layer's name.
167        name: String,
168    },
169    /// A prefab of the level's entities could not be loaded, or an entity
170    /// could not be spawned.
171    Prefab(PrefabError),
172}
173
174impl fmt::Display for LevelError {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        match self {
177            Self::BadName { name } => write!(
178                f,
179                "`{name}` is not a level's name: lowercase letters, digits and `_`"
180            ),
181            Self::Load { path, error } => write!(f, "`{path}` could not be loaded: {error}"),
182            Self::Tileset {
183                atlas,
184                sprite,
185                reason,
186            } => write!(
187                f,
188                "the tile set `{sprite}` of `{atlas}` is not the level's: {reason}"
189            ),
190            Self::Clips { atlas, error } => {
191                write!(f, "the clips of `{atlas}` could not be added: {error}")
192            }
193            Self::UnknownLayer { name } => write!(
194                f,
195                "the level's grid is on the collision layer `{name}`, which the game has not named"
196            ),
197            Self::Prefab(error) => write!(f, "{error}"),
198        }
199    }
200}
201
202impl std::error::Error for LevelError {
203    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
204        match self {
205            Self::Load { error, .. } => Some(error),
206            Self::Clips { error, .. } => Some(error),
207            Self::Prefab(error) => Some(error),
208            _ => None,
209        }
210    }
211}
212
213/// The path of the level file of the level `name`, if it is a level's
214/// name.
215fn level_path(name: &str) -> Option<String> {
216    let named = !name.is_empty()
217        && name
218            .bytes()
219            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_');
220    named.then(|| format!("levels/{name}.klvl"))
221}
222
223/// Loads the level `name` into `world`, the world of an
224/// [`App`](crate::App), in place of the one it holds (ADR-0038):
225///
226/// 1. The previous level goes, as [`unload_level`] removes it.
227/// 2. `levels/<name>.klvl` and its prefabs are read before this returns,
228///    the prefabs checked against the [`TypeRegistry`]. The level's assets
229///    load in [`Scope::Level`]; its textures stream in as any do, so they
230///    show a frame or more later. The [`PrefabLibrary`] keeps the prefabs,
231///    which later loads use without reading them again, as it keeps any.
232/// 3. Its tile sets' atlases are read, and their clips added to the
233///    [`Clips`], which hold an atlas the game added too only once
234///    ([`Clips::add_atlas`]).
235/// 4. Its tall tiles spawn as sprites (`TileSet::block_uv`), each with its
236///    feet at its place, then its entities spawn through their prefabs, each
237///    with its [`Transform`] at its place in the level.
238/// 5. Its tile layers go into [`TileLayers`], and the engine draws them
239///    each frame, in their order, in front of the clear colour, which is the
240///    level's background. Its grid replaces the [`Collisions`]' grid, on
241///    the collision layer the grid names; a level with none leaves an empty
242///    grid.
243///
244/// It logs how long it took.
245///
246/// # Errors
247///
248/// A [`LevelError`]: the name is not a level's; the level file or an atlas
249/// is missing or malformed; a tile set is not its atlas's; an atlas's
250/// clips cannot be added; the grid's collision layer is not named; or a
251/// prefab is missing, has a component the registry has not got, or a value
252/// that does not fit. Then the previous level is gone, and nothing of the
253/// new one is left in the world but the prefabs it read.
254///
255/// # Panics
256///
257/// If `world` lacks one of an [`App`](crate::App)'s resources, or one of
258/// them is borrowed elsewhere.
259pub fn load_level(world: &mut World, name: &str) -> Result<(), LevelError> {
260    let stopwatch = Stopwatch::start();
261    unload_level(world);
262    let Some(path) = level_path(name) else {
263        return Err(LevelError::BadName {
264            name: name.to_string(),
265        });
266    };
267    let mut made = Loaded {
268        name: name.to_string(),
269        background: Color::BLACK,
270        entities: Vec::new(),
271        layers: Vec::new(),
272        atlases: Vec::new(),
273        grid: false,
274        // With no level loaded, the clear colour is the game's.
275        clear: world.resource::<RenderFrame>().clear,
276    };
277    match make(world, &path, &mut made) {
278        Ok(()) => {
279            let ms = stopwatch.elapsed().as_secs_f64() * 1000.0;
280            info!("loaded the level `{name}` in {ms:.1} ms: {}", made.counts());
281            world.resource_mut::<CurrentLevel>().level = Some(made);
282            Ok(())
283        }
284        Err(error) => {
285            remove(world, made);
286            Err(error)
287        }
288    }
289}
290
291/// Removes the level `world` holds, if any, and returns whether there was
292/// one: despawns the entities it spawned, takes its tile layers out of
293/// [`TileLayers`], lets go of its atlases' clips in [`Clips`]
294/// ([`Clips::release_atlas`]), empties the grid it set, puts back the
295/// clear colour it replaced, and unloads [`Scope::Level`]. The prefabs it
296/// read stay in the [`PrefabLibrary`].
297///
298/// # Panics
299///
300/// As [`load_level`].
301pub fn unload_level(world: &mut World) -> bool {
302    let Some(level) = world.resource_mut::<CurrentLevel>().level.take() else {
303        return false;
304    };
305    remove(world, level);
306    true
307}
308
309/// Makes the level `world` holds again, from its files as they are now,
310/// in place of what it made, and returns whether there was one: the hot
311/// reload's, under `dev` (M5.8). Unlike [`load_level`], it keeps the
312/// handles a game may hold of the level:
313///
314/// - it unloads no scope, so its assets keep their handles, and a file
315///   loaded again gives the value it has now;
316/// - its tile layers keep theirs in [`TileLayers`], in their order: a
317///   layer more is added, and one fewer is removed;
318/// - its atlases' clips keep theirs in [`Clips`]: each atlas is held again
319///   before the last load's hold goes.
320///
321/// Its entities are spawned anew, so their [`Entity`] ids change, and what
322/// happened to them since the level loaded is undone. Its grid and its
323/// background are its new files'; the clear colour it puts back when it
324/// goes is the one from before its load. It logs how long it took.
325///
326/// # Errors
327///
328/// As [`load_level`]: then the level is as it was. Of its new files, the
329/// prefabs they read stay in the library, and the assets they loaded stay
330/// loaded, in [`Scope::Level`], until the level goes.
331#[cfg(feature = "dev")]
332pub(crate) fn reload_level(world: &mut World) -> Result<bool, LevelError> {
333    let Some(old) = world.resource_mut::<CurrentLevel>().level.take() else {
334        return Ok(false);
335    };
336    let stopwatch = Stopwatch::start();
337    let path = level_path(&old.name).expect("a level loaded by its name");
338    let mut made = Loaded {
339        name: old.name.clone(),
340        background: Color::BLACK,
341        entities: Vec::new(),
342        layers: Vec::new(),
343        atlases: Vec::new(),
344        grid: false,
345        clear: old.clear,
346    };
347    if let Err(error) = make(world, &path, &mut made) {
348        // `make` sets the grid last, so a failure left the old one.
349        take_apart(world, &made);
350        world.resource_mut::<CurrentLevel>().level = Some(old);
351        return Err(error);
352    }
353    for &entity in &old.entities {
354        world.despawn(entity);
355    }
356    {
357        let mut layers = world.resource_mut::<TileLayers>();
358        for (index, draw) in made.layers.iter_mut().enumerate() {
359            let Some(kept) = old.layers.get(index) else {
360                continue;
361            };
362            // A layer the game removed keeps the handle it was added under.
363            if layers.get(kept.tiles).is_some()
364                && let Some(layer) = layers.remove(draw.tiles)
365                && let Some(slot) = layers.get_mut(kept.tiles)
366            {
367                *slot = layer;
368                draw.tiles = kept.tiles;
369            }
370        }
371        for gone in old.layers.iter().skip(made.layers.len()) {
372            layers.remove(gone.tiles);
373        }
374    }
375    {
376        let mut clips = world.resource_mut::<Clips>();
377        for pages in &old.atlases {
378            clips.release_atlas(pages);
379        }
380    }
381    let ms = stopwatch.elapsed().as_secs_f64() * 1000.0;
382    info!(
383        "reloaded the level `{}` in {ms:.1} ms: {}",
384        made.name,
385        made.counts()
386    );
387    world.resource_mut::<CurrentLevel>().level = Some(made);
388    Ok(true)
389}
390
391/// Removes what `level` made, and unloads [`Scope::Level`].
392fn remove(world: &mut World, level: Loaded) {
393    take_apart(world, &level);
394    if level.grid {
395        world
396            .resource_mut::<Collisions>()
397            .set_grid(TileGrid::empty());
398    }
399    world.resource_mut::<RenderFrame>().clear = level.clear;
400    world
401        .resource_mut::<AssetServer>()
402        .unload_scope(Scope::Level);
403}
404
405/// Takes out what `level` made but its grid: despawns its entities, takes
406/// its tile layers out of [`TileLayers`], and lets go of its atlases' clips
407/// in [`Clips`].
408fn take_apart(world: &mut World, level: &Loaded) {
409    for &entity in &level.entities {
410        world.despawn(entity);
411    }
412    {
413        let mut layers = world.resource_mut::<TileLayers>();
414        for draw in &level.layers {
415            layers.remove(draw.tiles);
416        }
417    }
418    let mut clips = world.resource_mut::<Clips>();
419    for pages in &level.atlases {
420        clips.release_atlas(pages);
421    }
422}
423
424/// A tile set of the level: its texture's tiles, and a tile's size in
425/// pixels.
426#[derive(Clone, Copy)]
427struct Set {
428    tileset: TileSet,
429    tile: UVec2,
430}
431
432/// The cell at `index` of a grid `width` cells wide, row by row.
433fn cell(index: usize, width: u32) -> IVec2 {
434    let width = width.max(1) as usize;
435    // The reader bounds a level's sides by 2^24 pixels, and so its cells.
436    IVec2::new((index % width) as i32, (index / width) as i32)
437}
438
439fn point([x, y]: [i32; 2]) -> Vec2 {
440    Vec2::new(x as f32, y as f32)
441}
442
443/// Makes the level of `path` in `world`, noting in `made` what it makes, so
444/// that it can be removed if a later step fails.
445fn make(world: &mut World, path: &str, made: &mut Loaded) -> Result<(), LevelError> {
446    let load = |path: &str| {
447        let path = path.to_string();
448        move |error| LevelError::Load { path, error }
449    };
450    let file: LevelFile = {
451        let mut server = world.resource_mut::<AssetServer>();
452        let handle = server
453            .load_now_in::<Level>(path, Scope::Level, &mut FinalizeCtx::new())
454            .map_err(load(path))?;
455        server
456            .get(handle)
457            .map(|level| level.file().clone())
458            .ok_or_else(|| load(path)(AssetError::NotFound))?
459    };
460    made.background = Color::rgb(file.background[0], file.background[1], file.background[2]);
461
462    // Its prefabs, read and checked before anything is made.
463    #[cfg(feature = "dev")]
464    forget_unloaded_prefabs(world, &file);
465    {
466        let mut server = world.resource_mut::<AssetServer>();
467        let registry = world.resource::<TypeRegistry>();
468        world
469            .resource_mut::<PrefabLibrary>()
470            .load_level(&mut server, &registry, &file, Scope::Level)
471            .map_err(LevelError::Prefab)?;
472    }
473
474    // Its grid, on the collision layer it names.
475    let grid = match &file.grid {
476        Some(entry) => {
477            let mask = world
478                .resource::<CollisionLayers>()
479                .mask(&[entry.layer.as_str()])
480                .ok_or_else(|| LevelError::UnknownLayer {
481                    name: entry.layer.clone(),
482                })?;
483            let [width, height] = entry.size;
484            let mut grid = TileGrid::new(width, height, entry.cell as f32, point(entry.origin));
485            grid.layer = mask;
486            for (index, &solid) in entry.solid.iter().enumerate() {
487                if solid {
488                    grid.set_solid(cell(index, width), true);
489                }
490            }
491            grid
492        }
493        None => TileGrid::empty(),
494    };
495
496    // Its tile sets, and their atlases' clips.
497    let mut sets = Vec::with_capacity(file.tilesets.len());
498    for entry in &file.tilesets {
499        let fault = |reason| LevelError::Tileset {
500            atlas: entry.atlas.clone(),
501            sprite: entry.sprite.clone(),
502            reason,
503        };
504        let (atlas, pages) = {
505            let mut server = world.resource_mut::<AssetServer>();
506            let handle = server
507                .load_now_in::<Atlas>(&entry.atlas, Scope::Level, &mut FinalizeCtx::new())
508                .map_err(load(&entry.atlas))?;
509            let atlas = server
510                .get(handle)
511                .cloned()
512                .ok_or_else(|| load(&entry.atlas)(AssetError::NotFound))?;
513            let pages = atlas.load_pages(&mut server, Scope::Level);
514            (atlas, pages)
515        };
516        let sprite = atlas
517            .sprite(&entry.sprite)
518            .ok_or_else(|| fault("its atlas has no sprite of that name"))?;
519        let page = sprite
520            .frames()
521            .first()
522            .and_then(|frame| pages.get(frame.page()).copied());
523        let (Some(tileset), Some(tile)) = (
524            page.and_then(|texture| sprite.tile_set(texture)),
525            sprite.tile_size(),
526        ) else {
527            return Err(fault("the sprite is not a tile set"));
528        };
529        if (tileset.columns, tileset.rows) != (entry.columns, entry.rows) {
530            return Err(fault(
531                "its tiles across and down are not the level's: cook the level again",
532            ));
533        }
534        let held = world
535            .resource_mut::<Clips>()
536            .add_atlas(&atlas, &pages)
537            .map_err(|error| LevelError::Clips {
538                atlas: entry.atlas.clone(),
539                error,
540            })?;
541        // An atlas of no clip is not held, and is not let go of either.
542        if !held.is_empty() {
543            made.atlases.push(pages);
544        }
545        sets.push(Set { tileset, tile });
546    }
547    // The reader checked that each layer and tall tile names a tile set of
548    // the file.
549    let set = |index: u32| {
550        usize::try_from(index)
551            .ok()
552            .and_then(|index| sets.get(index).copied())
553            .ok_or(LevelError::Tileset {
554                atlas: String::new(),
555                sprite: String::new(),
556                reason: "the level names a tile set it has not got",
557            })
558    };
559
560    // Its tall tiles, as the y-sorted sprites of their blocks.
561    for tall in &file.tall {
562        let Set { tileset, tile } = set(tall.tileset)?;
563        let size = UVec2::new(u32::from(tall.size[0]), u32::from(tall.size[1]));
564        let mut sprite = Sprite::new(
565            tileset.texture,
566            Vec2::new((size.x * tile.x) as f32, (size.y * tile.y) as f32),
567        );
568        sprite.uv = tileset.block_uv(tall.tile, size);
569        sprite.layer = tall.layer;
570        let entity = world
571            .spawn()
572            .with(Transform::at(point(tall.feet)))
573            .with(sprite)
574            .id();
575        made.entities.push(entity);
576    }
577
578    // Its entities, through their prefabs, all made before any is spawned.
579    let spawned = {
580        let library = world.resource::<PrefabLibrary>();
581        let registry = world.resource::<TypeRegistry>();
582        let mut commands = world.commands();
583        loading_context(world, path, Scope::Level, |mut cx| {
584            library.spawn_level(&file, &registry, &mut commands, &mut cx)
585        })
586        .map_err(LevelError::Prefab)?
587    };
588    world.apply_commands();
589    {
590        let mut transforms = world.write::<Transform>();
591        for &(entity, position) in &spawned {
592            let at = point([position.x, position.y]);
593            match transforms.get_mut(entity) {
594                Some(transform) => transform.position = at,
595                None => {
596                    transforms.insert(entity, Transform::at(at));
597                }
598            }
599            made.entities.push(entity);
600        }
601    }
602
603    // Its tile layers.
604    {
605        let mut layers = world.resource_mut::<TileLayers>();
606        for entry in &file.layers {
607            let Set { tileset, .. } = set(entry.tileset)?;
608            let animations = &file.tilesets[entry.tileset as usize];
609            let [width, height] = entry.size;
610            let mut layer = TileLayer::new(
611                tileset,
612                UVec2::new(width, height),
613                entry.cell as f32,
614                point(entry.origin),
615            );
616            for (index, at) in entry.cells.iter().enumerate() {
617                let Some(at) = at else {
618                    continue;
619                };
620                let mut tile = match animations.animation(at.tile) {
621                    Some(animation) => Tile::animated(at.tile, animation.frames, animation.millis),
622                    None => Tile::new(at.tile),
623                };
624                tile.flip = Flip {
625                    x: at.flip_x,
626                    y: at.flip_y,
627                };
628                layer.set(cell(index, width), Some(tile));
629            }
630            made.layers.push(TileLayerDraw {
631                tiles: layers.add(layer),
632                layer: entry.layer,
633                depth: entry.depth,
634            });
635        }
636    }
637
638    world.resource_mut::<Collisions>().set_grid(grid);
639    made.grid = true;
640    Ok(())
641}
642
643/// Removes from the [`PrefabLibrary`] each prefab the entities of `file`
644/// spawn, and each base it extends as the library has it, whose file the
645/// asset server no longer holds, as when the last load of a level unloaded
646/// it: so that the level reads it from its file again, and the hot reload
647/// watches that file again (M5.8). A prefab the game inserted from
648/// another source is kept.
649#[cfg(feature = "dev")]
650fn forget_unloaded_prefabs(world: &World, file: &LevelFile) {
651    let server = world.resource::<AssetServer>();
652    let loaded = |path: &str| {
653        server
654            .assets::<nadir_scene::PrefabAsset>()
655            .and_then(|assets| assets.handle(path))
656            .is_some()
657    };
658    let mut library = world.resource_mut::<PrefabLibrary>();
659    for entity in &file.entities {
660        let mut next = Some(entity.prefab.clone());
661        // A chain longer than `load` takes, or a cycle, is its to report.
662        for _ in 0..=nadir_scene::MAX_EXTENDS {
663            let Some(name) = next.take() else {
664                break;
665            };
666            let Some(prefab) = library.get(&name) else {
667                break;
668            };
669            next = prefab.extends().map(str::to_string);
670            let path = PrefabLibrary::path(&name);
671            if prefab.source() == path && !loaded(&path) {
672                library.remove(&name);
673            }
674        }
675    }
676}
677
678/// Draws the level's tile layers into the [`RenderFrame`], in their order,
679/// before the game's own, and makes its background the clear colour: the
680/// engine's `nadir::extract_level`, in frame `Extract`. It allocates
681/// nothing once the frame's list has room for them.
682pub(crate) fn extract_level(world: &World, _frame: &Frame) {
683    let current = world.resource::<CurrentLevel>();
684    let Some(level) = &current.level else {
685        return;
686    };
687    let mut out = world.resource_mut::<RenderFrame>();
688    out.clear = level.background;
689    out.tile_layers.extend_from_slice(&level.layers);
690}
691
692#[cfg(test)]
693mod tests {
694    use std::collections::HashMap;
695    use std::time::Duration;
696
697    use nadir_assets::{AssetPath, OnFailure, Source};
698    use nadir_codec::qoi::{self, Channels, ColorSpace, Header};
699    use nadir_codec::{Limits, json, kbj};
700    use nadir_collision::{LayerMask, Shape};
701
702    use super::*;
703    use crate::{App, Collider, Config};
704
705    /// Files in memory, by path.
706    struct Memory(HashMap<String, Vec<u8>>);
707
708    impl Source for Memory {
709        fn read(&self, path: &AssetPath) -> Result<Vec<u8>, AssetError> {
710            self.0
711                .get(path.as_str())
712                .cloned()
713                .ok_or(AssetError::NotFound)
714        }
715    }
716
717    /// The atlas `atlas/tiles.kbj`: a flame of two frames, whose clip is
718    /// `tiles/flame/burn`, and the tile set `tiles/ground`, 2 × 1 tiles of
719    /// 16 on a page of its own.
720    const ATLAS: &str = r#"{ "version": 2,
721        "pages": [ { "path": "atlas/tiles_0.qoi", "w": 64, "h": 64 },
722                   { "path": "atlas/tiles/ground.tiles.qoi", "w": 32, "h": 16 } ],
723        "sprites": [
724          { "name": "tiles/flame",
725            "frames": [ { "page": 0, "x": 1, "y": 1, "w": 8, "h": 8, "ox": 0, "oy": 0, "sw": 8, "sh": 8 },
726                        { "page": 0, "x": 11, "y": 1, "w": 8, "h": 8, "ox": 0, "oy": 0, "sw": 8, "sh": 8 } ],
727            "pivot": [4.0, 8.0],
728            "clips": [ { "name": "burn", "loop": true, "frames": [[0, 100], [1, 100]] } ] },
729          { "name": "tiles/ground",
730            "frames": [ { "page": 1, "x": 0, "y": 0, "w": 32, "h": 16, "ox": 0, "oy": 0, "sw": 32, "sh": 16 } ],
731            "tiles": [16, 16] } ] }"#;
732
733    /// The level `meadow`: a layer of 4 × 3 cells, its first tile animated
734    /// and its second mirrored; a grid; a tall tile; two stones, the second
735    /// with its collider's offset overridden.
736    const MEADOW: &str = r#"{ "version": 1, "size": [64, 48], "background": [10, 20, 30],
737        "assets": ["atlas/tiles.kbj"],
738        "tilesets": [ { "atlas": "atlas/tiles.kbj", "sprite": "tiles/ground", "columns": 2, "rows": 1,
739                        "animations": [ { "tile": 0, "frames": 2, "ms": 200 } ] } ],
740        "layers": [ { "tileset": 0, "size": [4, 3], "cell": 16, "origin": [0, 0], "layer": 0, "depth": 0,
741                      "cells": [1, 65538, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2] } ],
742        "grid": { "size": [4, 3], "cell": 16, "origin": [0, 0], "layer": "World",
743                  "solid": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] },
744        "tall": [ { "tileset": 0, "tile": 1, "size": [1, 1], "feet": [24, 32], "layer": 1 } ],
745        "entities": [ { "prefab": "stone", "position": [40, 16], "overrides": {} },
746                      { "prefab": "stone", "position": [8, 40],
747                        "overrides": { "Collider": { "offset": [0, -4] } } } ] }"#;
748
749    /// The level `pond`: nothing but its size and background.
750    const POND: &str = r#"{ "version": 1, "size": [16, 16], "background": [1, 2, 3], "assets": [],
751        "tilesets": [], "layers": [], "tall": [], "entities": [] }"#;
752
753    /// The level `haunted`, of a ghost whose prefab has a component no one
754    /// registered.
755    const HAUNTED: &str = r#"{ "version": 1, "size": [16, 16], "background": [1, 2, 3], "assets": [],
756        "tilesets": [], "layers": [], "tall": [],
757        "entities": [ { "prefab": "ghost", "position": [0, 0], "overrides": {} } ] }"#;
758
759    fn kbj(text: &str) -> Vec<u8> {
760        let value = json::parse(text, Limits::default()).expect("the test's JSON");
761        kbj::encode(&value, Limits::default()).expect("KBJ")
762    }
763
764    fn page(width: u32, height: u32) -> Vec<u8> {
765        let header = Header {
766            width,
767            height,
768            channels: Channels::Rgba,
769            color_space: ColorSpace::Srgb,
770        };
771        qoi::encode(
772            &header,
773            &[90, 140, 70, 255].repeat((width * height) as usize),
774        )
775        .expect("a valid image")
776    }
777
778    /// The files above, by path, with the prefabs of the stone and the
779    /// ghost.
780    fn files() -> HashMap<String, Vec<u8>> {
781        HashMap::from([
782            ("atlas/tiles.kbj".to_string(), kbj(ATLAS)),
783            ("atlas/tiles_0.qoi".to_string(), page(64, 64)),
784            ("atlas/tiles/ground.tiles.qoi".to_string(), page(32, 16)),
785            ("levels/meadow.klvl".to_string(), kbj(MEADOW)),
786            ("levels/pond.klvl".to_string(), kbj(POND)),
787            ("levels/haunted.klvl".to_string(), kbj(HAUNTED)),
788            (
789                "data/prefabs/stone.kbj".to_string(),
790                kbj(r#"{ "name": "stone", "components": {
791                    "Collider": { "shape": { "Aabb": { "half": [4, 4] } },
792                                  "layer": ["World"], "mask": ["World"] } } }"#),
793            ),
794            (
795                "data/prefabs/ghost.kbj".to_string(),
796                kbj(r#"{ "name": "ghost", "components": { "Health": { "max": 3 } } }"#),
797            ),
798        ])
799    }
800
801    /// An app whose assets are the files above, with the collision layer
802    /// `World` named if `named`.
803    fn app(named: bool) -> App {
804        let app = App::new(Config::default()).insert_resource(AssetServer::with_source(
805            Memory(files()),
806            OnFailure::Nothing,
807        ));
808        if named {
809            app.collision_layers(&["World"])
810        } else {
811            app
812        }
813    }
814
815    #[test]
816    fn a_level_loads_its_tile_layers_grid_tall_tiles_and_entities() {
817        let mut app = app(true);
818        app.load_level("meadow").expect("the meadow");
819        let world = app.world();
820        let current = world.resource::<CurrentLevel>();
821        assert_eq!(current.name(), Some("meadow"));
822        assert_eq!(current.background(), Some(Color::rgb(10, 20, 30)));
823
824        // The layer, its tiles as the file has them.
825        let &[draw] = current.tile_layers() else {
826            panic!("one layer: {:?}", current.tile_layers());
827        };
828        assert_eq!((draw.layer, draw.depth), (0, 0));
829        let layers = world.resource::<TileLayers>();
830        let layer = layers.get(draw.tiles).expect("the layer");
831        assert_eq!(layer.size(), UVec2::new(4, 3));
832        assert_eq!(layer.get(IVec2::new(0, 0)), Some(Tile::animated(0, 2, 200)));
833        let mut mirrored = Tile::new(1);
834        mirrored.flip.x = true;
835        assert_eq!(layer.get(IVec2::new(1, 0)), Some(mirrored));
836        assert_eq!(layer.get(IVec2::new(2, 0)), None);
837        assert_eq!(layer.get(IVec2::new(3, 2)), Some(Tile::new(1)));
838        let tileset = layer.tileset();
839        assert_eq!((tileset.columns, tileset.rows), (2, 1));
840
841        // The grid, on `World`.
842        let collisions = world.resource::<Collisions>();
843        let grid = collisions.grid();
844        assert_eq!(grid.layer, LayerMask::bit(0));
845        assert!(grid.is_solid(IVec2::new(0, 0)) && grid.is_solid(IVec2::new(3, 2)));
846        assert!(!grid.is_solid(IVec2::new(1, 0)));
847
848        // The tall tile first, then the stones, each at its place.
849        let entities = current.entities();
850        assert_eq!(entities.len(), 3);
851        let transforms = world.read::<Transform>();
852        let at = |index: usize| transforms.get(entities[index]).map(|t| t.position);
853        assert_eq!(at(0), Some(Vec2::new(24.0, 32.0)));
854        assert_eq!(at(1), Some(Vec2::new(40.0, 16.0)));
855        assert_eq!(at(2), Some(Vec2::new(8.0, 40.0)));
856        let sprites = world.read::<Sprite>();
857        let tall = sprites.get(entities[0]).expect("the tall tile's sprite");
858        assert_eq!((tall.size, tall.layer), (Vec2::new(16.0, 16.0), 1));
859        assert_eq!(tall.uv, tileset.block_uv(1, UVec2::new(1, 1)));
860        assert_eq!(tall.texture, tileset.texture);
861        let colliders = world.read::<Collider>();
862        let stone = colliders.get(entities[1]).expect("a stone's collider");
863        assert_eq!(
864            stone.0.shape,
865            Shape::Aabb {
866                half: Vec2::splat(4.0)
867            }
868        );
869        assert_eq!(stone.0.offset, Vec2::ZERO);
870        let moved = colliders.get(entities[2]).expect("a stone's collider");
871        assert_eq!(moved.0.offset, Vec2::new(0.0, -4.0));
872        assert!(world.resource::<Clips>().find("tiles/flame/burn").is_some());
873        drop((current, layers, collisions, transforms, sprites, colliders));
874
875        // Each frame draws the layer, in front of the level's background.
876        app.update(Duration::ZERO, &[]);
877        let frame = app.world().resource::<RenderFrame>();
878        assert_eq!(frame.tile_layers, [draw]);
879        assert_eq!(frame.clear, Color::rgb(10, 20, 30));
880    }
881
882    #[test]
883    fn a_second_level_replaces_the_first_whole() {
884        let mut app = app(true);
885        // The game's clear colour, which the levels' backgrounds replace.
886        let game = Color::rgb(7, 8, 9);
887        app.world().resource_mut::<RenderFrame>().clear = game;
888        app.load_level("meadow").expect("the meadow");
889        let (entities, draws) = {
890            let current = app.world().resource::<CurrentLevel>();
891            (current.entities().to_vec(), current.tile_layers().to_vec())
892        };
893        let atlas = app
894            .world()
895            .resource_mut::<AssetServer>()
896            .load_in::<Atlas>("atlas/tiles.kbj", Scope::Level);
897
898        app.load_level("pond").expect("the pond");
899        let world = app.world();
900        assert_eq!(world.resource::<CurrentLevel>().name(), Some("pond"));
901        // The meadow's entities, layers, clips, grid and assets are gone.
902        assert!(entities.iter().all(|&entity| !world.is_alive(entity)));
903        assert_eq!(world.entity_count(), 0);
904        let layers = world.resource::<TileLayers>();
905        assert!(draws.iter().all(|draw| layers.get(draw.tiles).is_none()));
906        assert!(layers.is_empty());
907        assert!(world.resource::<Clips>().is_empty());
908        assert!(!world.resource::<Collisions>().grid().is_solid(IVec2::ZERO));
909        assert_eq!(world.resource::<AssetServer>().state(atlas), None);
910        drop(layers);
911
912        // Its own background, and no tile layer, from the next frame.
913        app.update(Duration::ZERO, &[]);
914        let frame = app.world().resource::<RenderFrame>();
915        assert!(frame.tile_layers.is_empty());
916        assert_eq!(frame.clear, Color::rgb(1, 2, 3));
917        drop(frame);
918        // With no level, the game's clear colour is back.
919        assert!(unload_level(app.world_mut()));
920        assert_eq!(app.world().resource::<CurrentLevel>().name(), None);
921        assert!(!unload_level(app.world_mut()));
922        app.update(Duration::ZERO, &[]);
923        assert_eq!(app.world().resource::<RenderFrame>().clear, game);
924    }
925
926    #[test]
927    fn an_atlas_the_game_added_keeps_its_clips_when_a_level_goes() {
928        let mut app = app(true);
929        {
930            let world = app.world();
931            let mut server = world.resource_mut::<AssetServer>();
932            let handle = server
933                .load_now::<Atlas>("atlas/tiles.kbj", &mut FinalizeCtx::new())
934                .expect("the atlas");
935            let atlas = server.get(handle).cloned().expect("the atlas");
936            let pages = atlas.load_pages(&mut server, Scope::Global);
937            world
938                .resource_mut::<Clips>()
939                .add_atlas(&atlas, &pages)
940                .expect("the clips");
941        }
942        let burn = app.world().resource::<Clips>().find("tiles/flame/burn");
943        assert!(burn.is_some());
944        // The level does not add them again, nor take them when it goes.
945        app.load_level("meadow").expect("the meadow");
946        app.load_level("pond").expect("the pond");
947        assert_eq!(
948            app.world().resource::<Clips>().find("tiles/flame/burn"),
949            burn
950        );
951    }
952
953    #[test]
954    fn an_atlas_the_game_adds_after_a_level_keeps_its_clips_when_it_goes() {
955        let mut app = app(true);
956        app.load_level("meadow").expect("the meadow");
957        let burn = app.world().resource::<Clips>().find("tiles/flame/burn");
958        assert!(burn.is_some());
959        // The game adds the atlas the level added: the same clips, held by
960        // both, which stay when the level goes.
961        {
962            let world = app.world();
963            let mut server = world.resource_mut::<AssetServer>();
964            let handle = server
965                .load_now::<Atlas>("atlas/tiles.kbj", &mut FinalizeCtx::new())
966                .expect("the atlas");
967            let atlas = server.get(handle).cloned().expect("the atlas");
968            let pages = atlas.load_pages(&mut server, Scope::Global);
969            let added = world
970                .resource_mut::<Clips>()
971                .add_atlas(&atlas, &pages)
972                .expect("the clips");
973            assert_eq!(added.first().copied(), burn);
974        }
975        app.load_level("pond").expect("the pond");
976        assert_eq!(
977            app.world().resource::<Clips>().find("tiles/flame/burn"),
978            burn
979        );
980    }
981
982    #[test]
983    fn a_level_that_cannot_load_says_why_and_leaves_nothing() {
984        let mut app = app(true);
985        app.load_level("meadow").expect("the meadow");
986        let error = app.load_level("haunted").expect_err("an unknown component");
987        assert!(
988            matches!(
989                &error,
990                LevelError::Prefab(PrefabError::UnknownComponent { prefab, component, .. })
991                    if prefab == "ghost" && component == "Health"
992            ),
993            "{error}"
994        );
995        let world = app.world();
996        assert_eq!(world.resource::<CurrentLevel>().name(), None);
997        assert_eq!(world.entity_count(), 0);
998        assert!(world.resource::<TileLayers>().is_empty());
999        // But for the prefabs it read, which the library keeps.
1000        assert!(world.resource::<PrefabLibrary>().get("ghost").is_some());
1001
1002        assert_eq!(
1003            app.load_level("nowhere"),
1004            Err(LevelError::Load {
1005                path: "levels/nowhere.klvl".to_string(),
1006                error: AssetError::NotFound,
1007            })
1008        );
1009        assert_eq!(
1010            app.load_level("../meadow"),
1011            Err(LevelError::BadName {
1012                name: "../meadow".to_string()
1013            })
1014        );
1015        // A grid on a layer the game has not named.
1016        let mut unnamed = self::app(false);
1017        assert_eq!(
1018            unnamed.load_level("meadow"),
1019            Err(LevelError::UnknownLayer {
1020                name: "World".to_string()
1021            })
1022        );
1023        assert_eq!(unnamed.world().entity_count(), 0);
1024    }
1025
1026    /// A level made again by the hot reload, under `dev` (M5.8).
1027    #[cfg(feature = "dev")]
1028    mod reloaded {
1029        use std::path::Path;
1030        use std::sync::{Arc, Mutex, PoisonError};
1031
1032        use super::*;
1033        use crate::hot_reload::{HotReload, Reloads};
1034
1035        type Files = Arc<Mutex<HashMap<String, Vec<u8>>>>;
1036
1037        /// The hot reload of `app`, its asset half: no shaders are watched.
1038        fn hot(app: &App) -> HotReload {
1039            HotReload::start(app.world(), Path::new(""))
1040        }
1041
1042        /// The files above, which a test changes.
1043        struct Changing(Files);
1044
1045        impl Source for Changing {
1046            fn read(&self, path: &AssetPath) -> Result<Vec<u8>, AssetError> {
1047                let files = self.0.lock().unwrap_or_else(PoisonError::into_inner);
1048                files
1049                    .get(path.as_str())
1050                    .cloned()
1051                    .ok_or(AssetError::NotFound)
1052            }
1053        }
1054
1055        /// The meadow, loaded, and its files.
1056        fn meadow() -> (App, Files) {
1057            let files = Arc::new(Mutex::new(files()));
1058            let source = Changing(Arc::clone(&files));
1059            let mut app = App::new(Config::default())
1060                .insert_resource(AssetServer::with_source(source, OnFailure::Nothing))
1061                .collision_layers(&["World"]);
1062            app.load_level("meadow").expect("the meadow");
1063            (app, files)
1064        }
1065
1066        /// Writes `text` as the KBJ file at `path`, and reloads it as the
1067        /// watcher would.
1068        fn rewrite(app: &App, files: &Files, path: &str, text: &str) {
1069            files
1070                .lock()
1071                .unwrap_or_else(PoisonError::into_inner)
1072                .insert(path.to_string(), kbj(text));
1073            let mut server = app.world().resource_mut::<AssetServer>();
1074            assert_eq!(server.reload(path), 1, "{path} is loaded once");
1075            server.finish_all_loads(&mut FinalizeCtx::new());
1076        }
1077
1078        /// The meadow with each `(from, to)` of `edits` made in its file.
1079        fn edited(edits: &[(&str, &str)]) -> String {
1080            edits.iter().fold(MEADOW.to_string(), |text, (from, to)| {
1081                assert!(text.contains(from), "the meadow has {from}");
1082                text.replace(from, to)
1083            })
1084        }
1085
1086        #[test]
1087        fn a_level_made_again_keeps_its_handles_and_spawns_its_entities_anew() {
1088            let (mut app, files) = meadow();
1089            let (entities, draw) = {
1090                let current = app.world().resource::<CurrentLevel>();
1091                (current.entities().to_vec(), current.tile_layers()[0])
1092            };
1093            let (burn, atlas) = {
1094                let world = app.world();
1095                let server = world.resource::<AssetServer>();
1096                let atlas = server
1097                    .assets::<Atlas>()
1098                    .and_then(|it| it.handle("atlas/tiles.kbj"));
1099                (world.resource::<Clips>().find("tiles/flame/burn"), atlas)
1100            };
1101            assert!(burn.is_some() && atlas.is_some());
1102
1103            // The first stone moved, the last cell of the layer emptied,
1104            // and a second layer, of one cell.
1105            let second = r#", { "tileset": 0, "size": [1, 1], "cell": 16, "origin": [0, 0],
1106                    "layer": 2, "depth": 1, "cells": [1] } ],"#;
1107            let text = edited(&[
1108                (r#""position": [40, 16]"#, r#""position": [44, 20]"#),
1109                ("0, 0, 0, 0, 2] } ],", &format!("0, 0, 0, 0, 0] }}{second}")),
1110            ]);
1111            rewrite(&app, &files, "levels/meadow.klvl", &text);
1112            assert_eq!(reload_level(app.world_mut()), Ok(true));
1113
1114            let world = app.world();
1115            let current = world.resource::<CurrentLevel>();
1116            // Its first layer under its handle, the second new.
1117            let draws = current.tile_layers();
1118            assert_eq!(draws.len(), 2);
1119            assert_eq!(draws[0], draw);
1120            assert_ne!(draws[1].tiles, draw.tiles);
1121            let layers = world.resource::<TileLayers>();
1122            assert_eq!(layers.len(), 2);
1123            let layer = layers.get(draw.tiles).expect("the first layer");
1124            assert_eq!(layer.get(IVec2::new(3, 2)), None);
1125            assert_eq!(layer.get(IVec2::new(1, 0)).map(|tile| tile.index), Some(1));
1126            // Its entities spawned anew, the stone at its new place.
1127            assert!(entities.iter().all(|&entity| !world.is_alive(entity)));
1128            assert_eq!(world.entity_count(), 3);
1129            let stone = current.entities()[1];
1130            let at = world.read::<Transform>().get(stone).map(|it| it.position);
1131            assert_eq!(at, Some(Vec2::new(44.0, 20.0)));
1132            // Its clips and its assets under their handles.
1133            assert_eq!(world.resource::<Clips>().find("tiles/flame/burn"), burn);
1134            let server = world.resource::<AssetServer>();
1135            assert!(atlas.is_some_and(|it| server.state(it).is_some()));
1136            drop((current, layers, server));
1137
1138            // Made again as it first was: the second layer goes.
1139            rewrite(&app, &files, "levels/meadow.klvl", MEADOW);
1140            assert_eq!(reload_level(app.world_mut()), Ok(true));
1141            let world = app.world();
1142            assert_eq!(world.resource::<CurrentLevel>().tile_layers(), [draw]);
1143            assert_eq!(world.resource::<TileLayers>().len(), 1);
1144            assert_eq!(world.entity_count(), 3);
1145
1146            // The atlas is held once, by the level: its clips go with it.
1147            assert!(unload_level(app.world_mut()));
1148            assert!(app.world().resource::<Clips>().is_empty());
1149            assert!(app.world().resource::<TileLayers>().is_empty());
1150            assert_eq!(reload_level(app.world_mut()), Ok(false));
1151        }
1152
1153        #[test]
1154        fn a_level_that_cannot_be_made_again_stays_as_it_was() {
1155            let (mut app, files) = meadow();
1156            let before = {
1157                let current = app.world().resource::<CurrentLevel>();
1158                (current.entities().to_vec(), current.tile_layers().to_vec())
1159            };
1160            let burn = app.world().resource::<Clips>().find("tiles/flame/burn");
1161            // A stone of a prefab no one cooked: nothing is made.
1162            let text = edited(&[(
1163                r#""prefab": "stone", "position": [40, 16]"#,
1164                r#""prefab": "boulder", "position": [40, 16]"#,
1165            )]);
1166            rewrite(&app, &files, "levels/meadow.klvl", &text);
1167            let error = reload_level(app.world_mut()).expect_err("no boulder");
1168            assert!(
1169                matches!(&error, LevelError::Prefab(PrefabError::Load { path, .. })
1170                    if path == "data/prefabs/boulder.kbj"),
1171                "{error}"
1172            );
1173            assert_eq!(app.world().entity_count(), 3);
1174            // A stone whose value does not fit, once its atlas is held again
1175            // and its tall tile spawned.
1176            let text = edited(&[("[0, -4]", r#""up""#)]);
1177            rewrite(&app, &files, "levels/meadow.klvl", &text);
1178            let error = reload_level(app.world_mut()).expect_err("a bad offset");
1179            assert!(matches!(&error, LevelError::Prefab(_)), "{error}");
1180
1181            let world = app.world();
1182            let current = world.resource::<CurrentLevel>();
1183            assert_eq!(current.name(), Some("meadow"));
1184            assert_eq!(
1185                (current.entities().to_vec(), current.tile_layers().to_vec()),
1186                before
1187            );
1188            assert!(before.0.iter().all(|&entity| world.is_alive(entity)));
1189            assert_eq!(world.entity_count(), 3);
1190            assert_eq!(world.resource::<TileLayers>().len(), 1);
1191            assert_eq!(world.resource::<Clips>().find("tiles/flame/burn"), burn);
1192            assert!(world.resource::<Collisions>().grid().is_solid(IVec2::ZERO));
1193            drop((world, current));
1194
1195            // Fixed, it is made again; the failure held nothing.
1196            rewrite(&app, &files, "levels/meadow.klvl", MEADOW);
1197            assert_eq!(reload_level(app.world_mut()), Ok(true));
1198            assert!(unload_level(app.world_mut()));
1199            assert!(app.world().resource::<Clips>().is_empty());
1200        }
1201
1202        #[test]
1203        fn a_level_loaded_again_reads_the_prefabs_its_last_load_unloaded() {
1204            let (mut app, files) = meadow();
1205            // The last load's prefab files go with its scope; the stone is
1206            // edited meanwhile, its box larger.
1207            app.load_level("pond").expect("the pond");
1208            files.lock().unwrap_or_else(PoisonError::into_inner).insert(
1209                "data/prefabs/stone.kbj".to_string(),
1210                kbj(r#"{ "name": "stone", "components": {
1211                    "Collider": { "shape": { "Aabb": { "half": [6, 6] } },
1212                                  "layer": ["World"], "mask": ["World"] } } }"#),
1213            );
1214            app.load_level("meadow").expect("the meadow again");
1215            let world = app.world();
1216            let stone = world.resource::<CurrentLevel>().entities()[1];
1217            let shape = world.read::<Collider>().get(stone).map(|it| it.0.shape);
1218            assert_eq!(
1219                shape,
1220                Some(Shape::Aabb {
1221                    half: Vec2::splat(6.0)
1222                })
1223            );
1224            // Its file is loaded, and so watched, again.
1225            let mut server = world.resource_mut::<AssetServer>();
1226            assert_eq!(server.reload("data/prefabs/stone.kbj"), 1);
1227        }
1228
1229        #[test]
1230        fn an_atlas_that_gains_its_first_clip_keeps_it_through_the_level() {
1231            // The meadow's atlas, its flame of no clip.
1232            let still = ATLAS.replace(
1233                r#""pivot": [4.0, 8.0],
1234            "clips": [ { "name": "burn", "loop": true, "frames": [[0, 100], [1, 100]] } ] },"#,
1235                r#""pivot": [4.0, 8.0] },"#,
1236            );
1237            assert_ne!(still, ATLAS);
1238            let files = Arc::new(Mutex::new(files()));
1239            files
1240                .lock()
1241                .unwrap_or_else(PoisonError::into_inner)
1242                .insert("atlas/tiles.kbj".to_string(), kbj(&still));
1243            let source = Changing(Arc::clone(&files));
1244            let mut app = App::new(Config::default())
1245                .insert_resource(AssetServer::with_source(source, OnFailure::Nothing))
1246                .collision_layers(&["World"]);
1247            app.load_level("meadow").expect("the meadow");
1248            assert!(app.world().resource::<Clips>().is_empty());
1249
1250            // The flame gains its clip: none of the atlas's was added, so
1251            // the level made again adds it.
1252            rewrite(&app, &files, "atlas/tiles.kbj", ATLAS);
1253            {
1254                let world = app.world();
1255                let mut server = world.resource_mut::<AssetServer>();
1256                let handle = server
1257                    .assets::<Atlas>()
1258                    .and_then(|it| it.handle("atlas/tiles.kbj"));
1259                let atlas = handle
1260                    .and_then(|it| server.get(it))
1261                    .cloned()
1262                    .expect("the atlas");
1263                let pages = atlas.load_pages(&mut server, Scope::Level);
1264                assert_eq!(
1265                    world.resource_mut::<Clips>().reload_atlas(&atlas, &pages),
1266                    None
1267                );
1268            }
1269            assert_eq!(reload_level(app.world_mut()), Ok(true));
1270            let burn = app.world().resource::<Clips>().find("tiles/flame/burn");
1271            assert!(
1272                burn.is_some(),
1273                "the clip is there after the level is made again"
1274            );
1275            assert_eq!(reload_level(app.world_mut()), Ok(true));
1276            assert_eq!(
1277                app.world().resource::<Clips>().find("tiles/flame/burn"),
1278                burn
1279            );
1280            // Held once, by the level.
1281            assert!(unload_level(app.world_mut()));
1282            assert!(app.world().resource::<Clips>().is_empty());
1283        }
1284
1285        #[test]
1286        fn a_level_due_waits_until_no_load_is_pending() {
1287            let (mut app, files) = meadow();
1288            let mut hot = hot(&app);
1289            let longer = ATLAS.replace("[[0, 100], [1, 100]]", "[[0, 100], [1, 300]]");
1290            rewrite(&app, &files, "atlas/tiles.kbj", &longer);
1291            // A load read, and not made yet.
1292            app.world()
1293                .resource_mut::<AssetServer>()
1294                .load::<Texture>("atlas/elsewhere.qoi");
1295            hot.assets(app.world_mut());
1296            hot.assets(app.world_mut());
1297            let reloads = *app.world().resource::<Reloads>();
1298            assert_eq!((reloads.atlases, reloads.levels), (1, 0));
1299            // Made: the level is made again, once.
1300            app.world()
1301                .resource_mut::<AssetServer>()
1302                .finish_all_loads(&mut FinalizeCtx::new());
1303            hot.assets(app.world_mut());
1304            hot.assets(app.world_mut());
1305            assert_eq!(app.world().resource::<Reloads>().levels, 1);
1306        }
1307
1308        #[test]
1309        fn a_prefab_reloaded_reads_its_new_base_and_one_named_otherwise_is_refused() {
1310            let files = Arc::new(Mutex::new(files()));
1311            let source = Changing(Arc::clone(&files));
1312            let mut app = App::new(Config::default())
1313                .insert_resource(AssetServer::with_source(source, OnFailure::Nothing));
1314            {
1315                let world = app.world();
1316                let mut server = world.resource_mut::<AssetServer>();
1317                let registry = world.resource::<TypeRegistry>();
1318                world
1319                    .resource_mut::<PrefabLibrary>()
1320                    .load(&mut server, &registry, "stone", Scope::Global)
1321                    .expect("the stone");
1322            }
1323            let mut hot = hot(&app);
1324
1325            // The stone extends a pebble now, which no one read yet.
1326            files.lock().unwrap_or_else(PoisonError::into_inner).insert(
1327                "data/prefabs/pebble.kbj".to_string(),
1328                kbj(r#"{ "name": "pebble", "components": {} }"#),
1329            );
1330            let extends = r#"{ "name": "stone", "extends": "pebble", "components": {} }"#;
1331            rewrite(&app, &files, "data/prefabs/stone.kbj", extends);
1332            hot.assets(app.world_mut());
1333            {
1334                let world = app.world();
1335                let library = world.resource::<PrefabLibrary>();
1336                let chain = library.chain("stone").map(|it| it.len());
1337                assert_eq!(chain, Ok(2), "the pebble is read");
1338                assert_eq!(world.resource::<Reloads>().prefabs, 1);
1339            }
1340
1341            // Its file names another prefab now: the stone stays.
1342            let renamed = r#"{ "name": "boulder", "components": {} }"#;
1343            rewrite(&app, &files, "data/prefabs/stone.kbj", renamed);
1344            hot.assets(app.world_mut());
1345            let world = app.world();
1346            let library = world.resource::<PrefabLibrary>();
1347            assert_eq!(
1348                library.get("stone").and_then(|it| it.extends()),
1349                Some("pebble")
1350            );
1351            assert!(library.get("boulder").is_none());
1352            assert_eq!(world.resource::<Reloads>().prefabs, 1);
1353        }
1354
1355        #[test]
1356        fn an_atlas_on_more_pages_is_let_go_of_by_its_new_ones() {
1357            let (mut app, files) = meadow();
1358            let burn = app.world().resource::<Clips>().find("tiles/flame/burn");
1359            // The atlas gains a page, which the flame's second frame is on.
1360            files
1361                .lock()
1362                .unwrap_or_else(PoisonError::into_inner)
1363                .insert("atlas/tiles_1.qoi".to_string(), page(64, 64));
1364            let text = ATLAS
1365                .replace(
1366                    r#"{ "path": "atlas/tiles/ground.tiles.qoi", "w": 32, "h": 16 } ],"#,
1367                    r#"{ "path": "atlas/tiles/ground.tiles.qoi", "w": 32, "h": 16 },
1368                       { "path": "atlas/tiles_1.qoi", "w": 64, "h": 64 } ],"#,
1369                )
1370                .replace(
1371                    r#"{ "page": 0, "x": 11, "y": 1,"#,
1372                    r#"{ "page": 2, "x": 11, "y": 1,"#,
1373                );
1374            assert_ne!(text, ATLAS);
1375            let mut hot = hot(&app);
1376            rewrite(&app, &files, "atlas/tiles.kbj", &text);
1377            // The hot reload finds its clips again with its pages, the new
1378            // one loaded, and makes the level again once it is made.
1379            hot.assets(app.world_mut());
1380            app.world()
1381                .resource_mut::<AssetServer>()
1382                .finish_all_loads(&mut FinalizeCtx::new());
1383            hot.assets(app.world_mut());
1384            let world = app.world();
1385            assert_eq!(
1386                *world.resource::<Reloads>(),
1387                Reloads {
1388                    started: true,
1389                    atlases: 1,
1390                    levels: 1,
1391                    ..Reloads::default()
1392                }
1393            );
1394            let server = world.resource::<AssetServer>();
1395            let page = server
1396                .assets::<Texture>()
1397                .and_then(|it| it.handle("atlas/tiles_1.qoi"));
1398            let clips = world.resource::<Clips>();
1399            let frames = burn.and_then(|it| clips.get(it)).map(crate::Clip::frames);
1400            assert_eq!(frames.map(|it| Some(it[1].texture)), Some(page));
1401            assert_eq!(clips.find("tiles/flame/burn"), burn);
1402            drop((server, clips));
1403            // The level held it once, through its loads: it goes with it.
1404            assert!(unload_level(app.world_mut()));
1405            assert!(app.world().resource::<Clips>().is_empty());
1406        }
1407    }
1408}