Skip to main content

nadir/
debug_ui.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//! The debug UI in the game, in development builds (feature `dev`;
16//! roadmap M7.10, ADR-0058): the windows a game adds, each shown and hidden
17//! by its own key; nadir-debug's UI fed from the window's events, drawn
18//! after the game's UI in the engine's font, and holding the game's input
19//! off while it has the pointer or the keyboard; and its windows' places,
20//! kept in `debug_ui.jsonc`. The engine's own windows are the stats
21//! overlay on F1 and the profiler on F3, which writes its traces to the
22//! logs folder (roadmap M7.3, ADR-0059), and shows the GPU's time over each
23//! frame drawn, from the renderer's timers (roadmap M7.12, ADR-0061); and
24//! the inspector on F2, which outlines the entity it shows in the world and
25//! writes its prefabs to the logs folder's `prefabs` (roadmap M7.4,
26//! ADR-0062); the console on the backtick, over the engine's log, with the
27//! engine's commands and the game's (roadmap M7.5, ADR-0063); and the debug
28//! drawing on F4, whose window ticks the overlays drawn into the world, and
29//! the time controls, F5 to F7, which pause, step and scale the game's time,
30//! a label in the corner saying so (roadmap M7.6, ADR-0064).
31
32mod draw;
33mod font;
34#[cfg(test)]
35mod golden;
36mod places;
37mod time;
38
39use std::fmt::Write as _;
40use std::fs;
41use std::ops::RangeInclusive;
42use std::path::{Path, PathBuf};
43use std::sync::OnceLock;
44use std::time::{Duration, Instant, SystemTime};
45
46use nadir_assets::{
47    AssetError, AssetPath, AssetServer, FinalizeCtx, Handle, LooseSource, Scope, Source,
48};
49use nadir_audio::Audio;
50use nadir_core::civil::DateTime;
51use nadir_core::log::{self, Level, error, info, warn};
52use nadir_core::profile::ScopeRecord;
53use nadir_core::{Color, Key, MouseButton, Rect, UVec2, Vec2};
54use nadir_debug::{
55    Args, Console, ConsoleError, ConsoleOut, DebugInput, DebugUi, FontMetrics, FrameTiming,
56    GpuTiming, Inspector, Profiler, Stats, Style, Ui,
57};
58use nadir_ecs::{Entity, Schedule, World};
59use nadir_input::{Capture, Input, UiEvent, UiEvents};
60use nadir_platform::Event;
61use nadir_render::{
62    Font, FrameStats, GpuTimes, RenderFrame, SortMode, SpriteDraw, TextDraw, Texture, UiList,
63    UiScale, UiSpace, UiView,
64};
65use nadir_scene::{FromValue, PrefabError, PrefabLibrary, TypeRegistry};
66
67use crate::{
68    Collider, FrameAllocs, LevelError, Parent, Player, PrevTransform, SaveId, Sprite, TickStats,
69    Transform, WindowSize, loading_context, reflect_context,
70};
71
72pub(crate) use places::FILE_NAME;
73
74/// A window of the debug UI, which fills it with widgets each frame it is
75/// open: a function of the world and the window's [`Ui`], added with
76/// [`App::add_debug_window`](crate::App::add_debug_window).
77pub type DebugWindow = fn(&World, &mut Ui<'_>);
78
79/// A command of the game's in the debug console: a function of the world,
80/// the arguments typed, checked against the command's usage, and where to
81/// print, added with
82/// [`App::add_console_command`](crate::App::add_console_command). An error
83/// it returns ([`ConsoleError::Failed`] with why) is printed in red.
84pub type ConsoleCommand = fn(&World, &Args<'_>, &mut ConsoleOut<'_>) -> Result<(), ConsoleError>;
85
86/// The stats overlay's key, title and first place.
87const STATS: (Key, &str, Rect) = (
88    Key::F1,
89    "Stats##nadir::stats",
90    Rect::new(Vec2::new(8.0, 8.0), Vec2::new(208.0, 172.0)),
91);
92
93/// The profiler's key, title and first place.
94const PROFILER: (Key, &str, Rect) = (
95    Key::F3,
96    "Profiler##nadir::profiler",
97    Rect::new(Vec2::new(216.0, 8.0), Vec2::new(576.0, 308.0)),
98);
99
100/// The inspector's key, title and first place.
101const INSPECTOR: (Key, &str, Rect) = (
102    Key::F2,
103    "Inspector##nadir::inspector",
104    Rect::new(Vec2::new(584.0, 8.0), Vec2::new(944.0, 508.0)),
105);
106
107/// The console's key, title and first place.
108const CONSOLE: (Key, &str, Rect) = (
109    Key::Grave,
110    "Console##nadir::console",
111    Rect::new(Vec2::new(8.0, 316.0), Vec2::new(944.0, 556.0)),
112);
113
114/// The debug drawing's key, title and first place.
115const DEBUG_DRAW: (Key, &str, Rect) = (
116    Key::F4,
117    "Debug draw##nadir::debug_draw",
118    Rect::new(Vec2::new(952.0, 8.0), Vec2::new(1092.0, 128.0)),
119);
120
121/// How far the time controls' label is from the screen's top-right
122/// corner, in the debug UI's units.
123const CORNER: f32 = 8.0;
124
125/// The source the inspector's values are read and written under, which
126/// its errors and warnings name.
127const INSPECTED: &str = "the inspector";
128
129/// The source the console's spawns are read under, which their errors
130/// name.
131const TYPED: &str = "the console";
132
133/// The time scales `timescale` takes: F7's range (roadmap M7.6).
134const TIME_SCALES: RangeInclusive<f32> = 0.25..=4.0;
135
136/// The engine's own commands in the console.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138enum Builtin {
139    Schedule,
140    Spawn,
141    Tp,
142    Timescale,
143    Level,
144    Reload,
145    Profile,
146    Log,
147    Quit,
148}
149
150/// The engine's commands: each one's usage, help and command, in the order
151/// `help` lists them, after its own.
152const BUILTINS: [(&str, &str, Builtin); 9] = [
153    (
154        "schedule",
155        "lists the systems in the order they run",
156        Builtin::Schedule,
157    ),
158    (
159        "spawn <prefab> [x] [y]",
160        "spawns a prefab at (x, y), or where the camera looks",
161        Builtin::Spawn,
162    ),
163    ("tp <x> <y>", "moves the player to (x, y)", Builtin::Tp),
164    (
165        "timescale <scale>",
166        "runs the game's time at scale times real time, 0.25 to 4",
167        Builtin::Timescale,
168    ),
169    (
170        "level <name>",
171        "loads the level levels/<name>.klvl",
172        Builtin::Level,
173    ),
174    (
175        "reload",
176        "reads every loaded asset's file again",
177        Builtin::Reload,
178    ),
179    (
180        "profile dump [path]",
181        "writes the profiler's trace to path, or beside the log",
182        Builtin::Profile,
183    ),
184    (
185        "log level <target> <error|warn|info|debug|trace>",
186        "sets how much a module, and those in it, logs",
187        Builtin::Log,
188    ),
189    (
190        "quit",
191        "ends the game, as closing its window does",
192        Builtin::Quit,
193    ),
194];
195
196/// A command of the console: the engine's or the game's.
197#[derive(Clone, Copy)]
198enum Command {
199    Engine(Builtin),
200    Game(ConsoleCommand),
201}
202
203/// The folder of the logs folder the inspector's prefabs are written to.
204const PREFABS: &str = "prefabs";
205
206/// The components a prefab the inspector saves leaves out: a spawn places
207/// the entity, and gives it its own save number.
208const NOT_IN_PREFABS: [&str; 2] = [Transform::TYPE_NAME, SaveId::TYPE_NAME];
209
210/// The color of the outline around the entity the inspector shows.
211const OUTLINE: Color = Color::rgb(255, 200, 0);
212
213/// Half the side of the box outlined around an entity with a place but no
214/// sprite or collider, in world units.
215const MARK: f32 = 4.0;
216
217/// The last renders whose frames are kept, to give each the GPU's time
218/// over it when that is read back: twice the renderer's four renders in
219/// flight. A time read back 8 renders or more after its render is
220/// dropped.
221const RENDERS: usize = 8;
222
223/// What fills a window.
224#[derive(Clone, Copy)]
225enum Content {
226    /// A game's window.
227    Game(DebugWindow),
228    /// The engine's stats overlay.
229    Stats,
230    /// The engine's profiler.
231    Profiler,
232    /// The engine's inspector.
233    Inspector,
234    /// The engine's console.
235    Console,
236    /// The engine's debug drawing: the overlays it ticks.
237    DebugDraw,
238}
239
240/// A window of the debug UI: the engine's or a game's.
241struct Window {
242    toggle: Key,
243    title: &'static str,
244    first: Rect,
245    content: Content,
246    open: bool,
247}
248
249impl Window {
250    fn closed(toggle: Key, title: &'static str, first: Rect, content: Content) -> Self {
251        Self {
252            toggle,
253            title,
254            first,
255            content,
256            open: false,
257        }
258    }
259}
260
261/// The asset server's source in development builds: the engine's own
262/// files, the debug UI's font and white texel, made the first time one is
263/// read, and the game's loose files.
264pub(crate) struct EngineFiles {
265    loose: LooseSource,
266    files: OnceLock<Vec<(&'static str, Vec<u8>)>>,
267}
268
269impl EngineFiles {
270    /// The engine's files, and the loose files under `root`.
271    pub(crate) fn new(root: impl Into<PathBuf>) -> Self {
272        Self {
273            loose: LooseSource::new(root),
274            files: OnceLock::new(),
275        }
276    }
277}
278
279impl Source for EngineFiles {
280    fn read(&self, path: &AssetPath) -> Result<Vec<u8>, AssetError> {
281        if !font::is_file(path.as_str()) {
282            return self.loose.read(path);
283        }
284        self.files
285            .get_or_init(font::files)
286            .iter()
287            .find(|(name, _)| *name == path.as_str())
288            .map(|(_, bytes)| bytes.clone())
289            .ok_or(AssetError::NotFound)
290    }
291
292    /// `None` for the engine's files, which never change.
293    fn modified(&self, path: &AssetPath) -> Option<SystemTime> {
294        if font::is_file(path.as_str()) {
295            None
296        } else {
297            self.loose.modified(path)
298        }
299    }
300}
301
302/// The debug UI's state in the app: the engine's windows and the game's,
303/// the window's events for the UI, the UI itself once a window has been
304/// open, where its places are kept, and the profiler.
305pub(crate) struct DebugTools {
306    windows: Vec<Window>,
307    events: UiEvents,
308    input: DebugInput,
309    /// Made the first time a window is open, with the engine's font.
310    ui: Option<DebugUi>,
311    /// Whether making it failed, which the log said once.
312    failed: bool,
313    /// The free scale: the window's scale factor, whole and at least 1.
314    scale: f32,
315    /// What the debug UI held back from the game when it last changed it.
316    held: Capture,
317    /// Who holds the left button down, from where its press was: the debug
318    /// UI (`true`) or the game; `None` while it is up.
319    left: Option<bool>,
320    /// The places file, which [`App::run`](crate::App::run) names; and the
321    /// places read from it, given to the UI when it is made.
322    file: Option<PathBuf>,
323    places: Vec<places::Place>,
324    /// The UI's places revision when they were last read or written.
325    saved: u64,
326    /// The last frames' timings and scopes.
327    profiler: Profiler,
328    /// When the frame being run started, and how long the processor has
329    /// worked on it so far; how long it worked on the last one.
330    frame_start: Option<Instant>,
331    work: Duration,
332    last_work: Duration,
333    /// The renders so far, and for the last [`RENDERS`] of them, by their
334    /// number modulo that, the frame each drew and when it started.
335    renders: u64,
336    drawn: [Option<(u64, Instant)>; RENDERS],
337    /// The logs folder, which [`App::run`](crate::App::run) names: the
338    /// profiler's traces go into it, and the inspector's prefabs into its
339    /// [`PREFABS`].
340    logs: Option<PathBuf>,
341    /// The entity list and the components of the entity it shows.
342    inspector: Inspector,
343    /// The white texel, loaded with the UI's font, which the inspector's
344    /// outline and the debug drawing are drawn with; and the font.
345    white: Option<Handle<Texture>>,
346    font: Option<Handle<Font>>,
347    /// The console, and how many of the log's records it has read.
348    console: Console<Command>,
349    log_read: u64,
350    /// The game's time, as the time controls and `timescale` leave it, and
351    /// the corner label's text, written each frame it shows.
352    time: time::Time,
353    label: String,
354    /// The overlays the debug drawing ticks.
355    overlays: draw::Overlays,
356    /// The level `level` asked for, which the app loads after the frame.
357    level: Option<String>,
358    /// Whether `quit` asked [`App::run`](crate::App::run) to end.
359    quit: bool,
360}
361
362impl DebugTools {
363    pub(crate) fn new() -> Self {
364        let engine = |(toggle, title, first): (Key, &'static str, Rect), content| {
365            Window::closed(toggle, title, first, content)
366        };
367        let mut console = Console::new();
368        for (usage, help, builtin) in BUILTINS {
369            console
370                .register(usage, help, Command::Engine(builtin))
371                .expect("the engine's usages start with names");
372        }
373        Self {
374            windows: vec![
375                engine(STATS, Content::Stats),
376                engine(INSPECTOR, Content::Inspector),
377                engine(PROFILER, Content::Profiler),
378                engine(CONSOLE, Content::Console),
379                engine(DEBUG_DRAW, Content::DebugDraw),
380            ],
381            events: UiEvents::new(),
382            input: DebugInput::new(),
383            ui: None,
384            failed: false,
385            scale: 1.0,
386            held: Capture::NONE,
387            left: None,
388            file: None,
389            places: Vec::new(),
390            saved: 0,
391            profiler: Profiler::new(),
392            frame_start: None,
393            work: Duration::ZERO,
394            last_work: Duration::ZERO,
395            renders: 0,
396            drawn: [None; RENDERS],
397            logs: None,
398            inspector: Inspector::new(),
399            white: None,
400            font: None,
401            console,
402            log_read: 0,
403            time: time::Time::new(),
404            label: String::new(),
405            overlays: draw::Overlays::new(),
406            level: None,
407            quit: false,
408        }
409    }
410
411    /// Adds a game's window, closed.
412    pub(crate) fn add(&mut self, toggle: Key, title: &'static str, first: Rect, add: DebugWindow) {
413        self.windows
414            .push(Window::closed(toggle, title, first, Content::Game(add)));
415    }
416
417    /// Adds a game's command to the console, under `usage`, whose first
418    /// word is its name, with `help`; or, if the usage starts with no name,
419    /// logs why not.
420    pub(crate) fn add_command(&mut self, usage: &str, help: &str, command: ConsoleCommand) {
421        if let Err(cause) = self.console.register(usage, help, Command::Game(command)) {
422            error!("the console command is not added: {cause}");
423        }
424    }
425
426    /// The time the game's clock is given for a frame `elapsed` long, as
427    /// the time controls and `timescale` leave it: none while paused but a
428    /// tick for each step asked for since, otherwise `elapsed` at the
429    /// scale.
430    pub(crate) fn game_time(&mut self, elapsed: Duration) -> Duration {
431        self.time.game_time(elapsed)
432    }
433
434    /// The level `level` asked for in the frame, once.
435    pub(crate) fn take_level(&mut self) -> Option<String> {
436        self.level.take()
437    }
438
439    /// Says in the console why the level `name` that `level` asked for did
440    /// not load; the log says when one did.
441    pub(crate) fn level_loaded(&mut self, name: &str, result: Result<(), LevelError>) {
442        if let Err(cause) = result {
443            self.console
444                .print_error(format_args!("the level `{name}` is not loaded: {cause}"));
445        }
446    }
447
448    /// Whether `quit` asked the game to end.
449    pub(crate) fn quit(&self) -> bool {
450        self.quit
451    }
452
453    /// Writes the profiler's traces into `folder`, and the inspector's
454    /// prefabs into its folder [`PREFABS`].
455    pub(crate) fn write_traces_in(&mut self, folder: PathBuf) {
456        self.logs = Some(folder);
457    }
458
459    /// As a frame starts, at `now`: ends the frame before, if there was
460    /// one, and gives it to the profiler with `records`, the scopes
461    /// collected since it started.
462    pub(crate) fn start_profile(&mut self, now: Instant, records: &[ScopeRecord]) {
463        if let Some(start) = self.frame_start {
464            let length = now.saturating_duration_since(start);
465            self.profiler
466                .push(FrameTiming::new(start, length, self.work), records);
467            self.last_work = self.work;
468        }
469        self.frame_start = Some(now);
470        self.work = Duration::ZERO;
471    }
472
473    /// Counts `work` more of the processor's time on the frame being run.
474    pub(crate) fn add_work(&mut self, work: Duration) {
475        self.work += work;
476    }
477
478    /// After the frame being run was drawn, its drawing started at
479    /// `submitted`: gives the profiler `times`, the GPU's times that this
480    /// render read back ([`Renderer::gpu_times`](nadir_render::Renderer::gpu_times)),
481    /// each for the frame it was timed in. Each says how many renders
482    /// before this one it was, and a frame not drawn (a modal one) is no
483    /// render: so the frames of the last renders are kept by render. Call
484    /// it after each render of a renderer that times every render, and
485    /// after no other.
486    pub(crate) fn rendered(&mut self, submitted: Instant, times: &[GpuTimes]) {
487        let render = self.renders;
488        self.renders += 1;
489        let slot = |render: u64| (render % RENDERS as u64) as usize;
490        self.drawn[slot(render)] = Some((self.profiler.next_index(), submitted));
491        for time in times {
492            let ago = u64::from(time.renders_ago);
493            if ago == 0 || ago >= RENDERS as u64 || ago > render {
494                continue;
495            }
496            if let Some((frame, submitted)) = self.drawn[slot(render - ago)] {
497                let gpu = GpuTiming::new(submitted, time.world, time.output);
498                self.profiler.set_gpu(frame, gpu);
499            }
500        }
501    }
502
503    /// Keeps the windows' places in the file at `path`: reads them now, and
504    /// writes them when they change.
505    pub(crate) fn keep_places_in(&mut self, path: PathBuf) {
506        self.places = places::read(&path);
507        if let Some(ui) = &mut self.ui {
508            restore(ui, &mut self.places);
509            self.saved = ui.places_revision();
510        }
511        self.file = Some(path);
512    }
513
514    /// Before a frame's events reach `input`: holds the keys back if a
515    /// debug text field had the keyboard when the last frame ended. The
516    /// mouse is decided at each press and each turn of the wheel
517    /// ([`DebugTools::handle`]), never by where the pointer rests, so that
518    /// a button the game holds is not taken from it by the pointer passing
519    /// over a window.
520    pub(crate) fn start_frame(&mut self, input: &mut Input) {
521        let keyboard = self.ui.as_ref().is_some_and(DebugUi::wants_keyboard);
522        let mouse = self.held.mouse;
523        self.hold(input, Capture { keyboard, mouse });
524    }
525
526    /// Takes in `event`, before `input` does. A press of a mouse button, or
527    /// a turn of the wheel, is held back from the game while the debug UI
528    /// holds the left button from a press on one of its windows, and, while
529    /// nobody holds it, if the pointer is over a window the debug UI drew
530    /// in the last frame; a press of the left button decides who holds it,
531    /// until its release or a loss of the focus. The time controls take
532    /// their keys here, before the frame's clock, so that they act in the
533    /// frame they were pressed in.
534    pub(crate) fn handle(&mut self, input: &mut Input, event: &Event) {
535        match *event {
536            Event::Key {
537                key,
538                pressed,
539                repeat,
540            } => self.time.key(key, pressed, repeat),
541            Event::MouseButton {
542                button,
543                pressed: true,
544            } => {
545                let over = self.is_over(input.pointer());
546                let mouse = self.left.unwrap_or(over);
547                if button == MouseButton::Left && self.left.is_none() {
548                    self.left = Some(over);
549                }
550                self.hold_mouse(input, mouse);
551            }
552            Event::MouseButton {
553                button: MouseButton::Left,
554                pressed: false,
555            } => self.left = None,
556            Event::Focused(false) => {
557                self.left = None;
558                self.time.focus_lost();
559            }
560            Event::MouseWheel(_) => {
561                let mouse = self.left.unwrap_or_else(|| self.is_over(input.pointer()));
562                self.hold_mouse(input, mouse);
563            }
564            Event::ScaleFactorChanged(factor) => self.scale = whole_scale(factor),
565            _ => {}
566        }
567        self.events.handle(event);
568    }
569
570    /// Whether a window of the engine's whose content is `which` is open.
571    fn is_open(&self, which: impl Fn(Content) -> bool) -> bool {
572        self.windows
573            .iter()
574            .any(|window| window.open && which(window.content))
575    }
576
577    /// Whether `at` is over a window drawn in the last frame.
578    fn is_over(&self, at: Vec2) -> bool {
579        self.ui.as_ref().is_some_and(|ui| ui.is_over(at))
580    }
581
582    fn hold_mouse(&mut self, input: &mut Input, mouse: bool) {
583        let keyboard = self.held.keyboard;
584        self.hold(input, Capture { keyboard, mouse });
585    }
586
587    /// Holds `capture` back from the game's actions, if it changed. The
588    /// debug UI then touches the capture only while it wants something,
589    /// and once more to let go.
590    fn hold(&mut self, input: &mut Input, capture: Capture) {
591        if capture != self.held {
592            input.set_capture(capture);
593            self.held = capture;
594        }
595    }
596
597    /// After the frame stages: toggles the windows whose keys were pressed,
598    /// draws the open ones into the frame's UI, after the game's, and
599    /// writes the places if they changed. With the inspector open, it
600    /// outlines the entity it shows in the frame's sprites, drawn `alpha`
601    /// of the way from the last tick's place to this one's. With the
602    /// console open, it gives it the log's records since it last read
603    /// them, and runs the commands typed, which reach `schedule`. With the
604    /// debug drawing open, it draws the overlays ticked into the frame's
605    /// sprites and texts, as the inspector's outline is; and while the
606    /// game's time is not real, a label at the top-right says so.
607    pub(crate) fn frame(
608        &mut self,
609        world: &World,
610        schedule: &Schedule,
611        virtual_resolution: UVec2,
612        alpha: f32,
613    ) {
614        for event in self.events.events() {
615            if let UiEvent::Key {
616                key,
617                pressed: true,
618                repeat: false,
619            } = *event
620            {
621                for window in &mut self.windows {
622                    if window.toggle == key {
623                        window.open = !window.open;
624                    }
625                }
626            }
627        }
628        let wanted = self.windows.iter().any(|window| window.open) || !self.time.is_real();
629        if self.ui.is_none() && !self.failed && wanted {
630            match make_ui(world) {
631                Ok((mut ui, font, white)) => {
632                    restore(&mut ui, &mut self.places);
633                    self.saved = ui.places_revision();
634                    self.ui = Some(ui);
635                    self.font = Some(font);
636                    self.white = Some(white);
637                }
638                Err(cause) => {
639                    error!("the debug UI cannot be shown: its font did not load: {cause}");
640                    self.failed = true;
641                }
642            }
643        }
644        let windows = &self.windows;
645        feed(&mut self.input, self.events.events(), |key| {
646            windows.iter().any(|window| window.toggle == key)
647        });
648        self.events.clear();
649        if self.is_open(|content| matches!(content, Content::Console)) {
650            let console = &mut self.console;
651            self.log_read = log::since(self.log_read, |record| console.log_record(record));
652        }
653        let Some(ui) = &mut self.ui else {
654            // Nothing takes the events: keep only where they leave the
655            // pointer and what they leave held.
656            self.input.clear();
657            return;
658        };
659        ui.style_mut().scale = UiScale::Free(self.scale);
660        let output = world.resource::<WindowSize>().0;
661        // The time controls' label goes first, so that a window over the
662        // corner is drawn in front of it.
663        if !self.time.is_real()
664            && let (Some(white), Some(font)) = (self.white, self.font)
665        {
666            self.label.clear();
667            // Writing to a `String` cannot fail.
668            let _ = write!(self.label, "{}", self.time);
669            let style = *ui.style();
670            let size = UiSpace::new(style.scale, virtual_resolution, output).size;
671            corner(
672                &mut world.resource_mut::<RenderFrame>().ui,
673                &self.label,
674                (font, white),
675                &style,
676                size,
677            );
678        }
679        let mut frame = ui.frame(&mut self.input, virtual_resolution, output);
680        for window in self.windows.iter().filter(|window| window.open) {
681            let (title, first) = (window.title, window.first);
682            match window.content {
683                Content::Game(add) => frame.window(title, first, |ui| add(world, ui)),
684                Content::Stats => {
685                    let stats = stats(world, &self.profiler, self.last_work);
686                    frame.window(title, first, |ui| stats.show(ui))
687                }
688                Content::Profiler => frame.window(title, first, |ui| {
689                    if self.profiler.show(ui).write_trace {
690                        // The note and the log say how it went.
691                        let _ = write_trace(&mut self.profiler, self.logs.as_deref(), None);
692                    }
693                }),
694                Content::Inspector => frame.window(title, first, |ui| {
695                    let response = loading_context(world, INSPECTED, Scope::Level, |mut cx| {
696                        self.inspector.show(world, ui, &mut cx)
697                    });
698                    if response.save_prefab {
699                        save_prefab(world, &mut self.inspector, self.logs.as_deref());
700                    }
701                }),
702                Content::Console => frame.window(title, first, |ui| {
703                    let mut reach = Reach {
704                        world,
705                        schedule,
706                        profiler: &mut self.profiler,
707                        logs: self.logs.as_deref(),
708                        time: &mut self.time,
709                        level: &mut self.level,
710                        quit: &mut self.quit,
711                    };
712                    self.console
713                        .show(ui, |command, args, out| run(&mut reach, command, args, out));
714                }),
715                Content::DebugDraw => frame.window(title, first, |ui| self.overlays.show(ui)),
716            };
717        }
718        frame.finish(&mut world.resource_mut::<RenderFrame>().ui);
719        let drawing = self
720            .windows
721            .iter()
722            .any(|window| window.open && matches!(window.content, Content::DebugDraw));
723        if drawing && let (Some(white), Some(font)) = (self.white, self.font) {
724            self.overlays
725                .draw(world, white, font, virtual_resolution, alpha);
726        }
727        let inspecting = self
728            .windows
729            .iter()
730            .any(|window| window.open && matches!(window.content, Content::Inspector));
731        if inspecting
732            && let (Some(entity), Some(white)) = (self.inspector.selected(), self.white)
733            && let Some(rect) = outlined(world, entity, alpha)
734        {
735            outline(
736                &mut world.resource_mut::<RenderFrame>().sprites,
737                white,
738                rect,
739            );
740        }
741        if let Some(path) = &self.file
742            && ui.places_revision() != self.saved
743        {
744            self.saved = ui.places_revision();
745            save(path, ui);
746        }
747    }
748}
749
750/// The stats overlay's numbers: the frame rate and the last frame's
751/// processor time from the profiler, the rest from the world's resources:
752/// this frame's ticks, and the last frame's drawing and allocations.
753fn stats(world: &World, profiler: &Profiler, work: Duration) -> Stats {
754    let ticks = *world.resource::<TickStats>();
755    let drawn = *world.resource::<FrameStats>();
756    let allocs = world.resource::<FrameAllocs>().0;
757    let audio = world.resource::<Audio>().stats();
758    let mut stats = Stats::default();
759    stats.frame_rate = profiler.frame_rate();
760    stats.frame_time = work;
761    stats.tick_time = ticks.time;
762    stats.ticks = ticks.ticks;
763    stats.draw_calls = drawn.batches + drawn.chunks + drawn.ui_batches;
764    stats.sprites = drawn.sprites;
765    stats.entities = world.entity_count();
766    stats.allocations = allocs.allocations;
767    stats.allocated_bytes = allocs.bytes;
768    stats.voices = audio.active_voices;
769    stats.underruns = audio.underruns;
770    stats
771}
772
773/// Writes the prefab the inspector made of the entity it shows into
774/// `folder`'s [`PREFABS`], as `<name>.jsonc`, and says where in its note
775/// and the log; or why not. It leaves out [`NOT_IN_PREFABS`]. A name whose
776/// file in a game's assets, `data/prefabs/<name>.jsonc`, is no asset path,
777/// such as a Windows device's (`nul`), is not written.
778fn save_prefab(world: &World, inspector: &mut Inspector, folder: Option<&Path>) {
779    let Some(folder) = folder else {
780        inspector.set_note("Prefabs are written only by App::run.");
781        return;
782    };
783    let asset = format!("data/prefabs/{}.jsonc", inspector.prefab_name());
784    if let Err(cause) = AssetPath::new(&asset) {
785        warn!("the inspector's prefab is not written: {asset}: {cause}");
786        inspector.set_note(format_args!("Not written: {asset}: {cause}"));
787        return;
788    }
789    let text = reflect_context(world, INSPECTED, |mut cx| {
790        inspector.prefab(world, &NOT_IN_PREFABS, &mut cx)
791    });
792    let Some(text) = text else {
793        return;
794    };
795    let folder = folder.join(PREFABS);
796    let path = folder.join(format!("{}.jsonc", inspector.prefab_name()));
797    match fs::create_dir_all(&folder).and_then(|()| fs::write(&path, text)) {
798        Ok(()) => {
799            info!("the inspector saved the prefab {}", path.display());
800            inspector.set_note(format_args!("Wrote {}", path.display()));
801        }
802        Err(cause) => {
803            warn!(
804                "the inspector's prefab is not written: {} cannot be: {cause}",
805                path.display()
806            );
807            inspector.set_note(format_args!("Not written: {cause}"));
808        }
809    }
810}
811
812/// What the inspector outlines of `entity`, in the world: its sprite,
813/// unrotated, where it is drawn, `alpha` of the way from the last tick's
814/// place, by its parent's if it has one, as `nadir::extract_sprites` draws
815/// it; or its collider's bounds; or a box of [`MARK`] around its place.
816/// `None` for an entity with no place.
817fn outlined(world: &World, entity: Entity, alpha: f32) -> Option<Rect> {
818    let transforms = world.read::<Transform>();
819    let previous = world.read::<PrevTransform>();
820    let parents = world.read::<Parent>();
821    let drawn_at = |entity| {
822        let current = transforms.get(entity)?.position;
823        Some(
824            previous
825                .get(entity)
826                .map_or(current, |previous| previous.0.position.lerp(current, alpha)),
827        )
828    };
829    if let Some(sprite) = world.read::<Sprite>().get(entity) {
830        let parented = if parents.contains(entity) {
831            crate::glue::root(&parents, entity)
832                .and_then(|(root, offset)| Some(drawn_at(root)? + offset))
833        } else {
834            None
835        };
836        if let Some(position) = parented.or_else(|| drawn_at(entity)) {
837            // Mirrored about its pivot, as it is drawn.
838            let mut pivot = sprite.pivot;
839            if sprite.flip.x {
840                pivot.x = 1.0 - pivot.x;
841            }
842            if sprite.flip.y {
843                pivot.y = 1.0 - pivot.y;
844            }
845            let min = position - pivot * sprite.size;
846            return Some(Rect::new(min, min + sprite.size));
847        }
848    }
849    let position = drawn_at(entity)?;
850    if let Some(collider) = world.read::<Collider>().get(entity) {
851        return Some(collider.0.bounds(position));
852    }
853    Some(Rect::new(
854        position - Vec2::splat(MARK),
855        position + Vec2::splat(MARK),
856    ))
857}
858
859/// Pushes a line a world unit wide around `rect`, outside it, in front of
860/// every sprite: four of the white texel, in [`OUTLINE`].
861fn outline(sprites: &mut Vec<SpriteDraw>, white: Handle<Texture>, rect: Rect) {
862    let (min, max) = (rect.min.min(rect.max), rect.min.max(rect.max));
863    let edges = [
864        Rect::new(min - Vec2::ONE, Vec2::new(max.x + 1.0, min.y)),
865        Rect::new(Vec2::new(min.x - 1.0, max.y), max + Vec2::ONE),
866        Rect::new(Vec2::new(min.x - 1.0, min.y), Vec2::new(min.x, max.y)),
867        Rect::new(Vec2::new(max.x, min.y), Vec2::new(max.x + 1.0, max.y)),
868    ];
869    for edge in edges {
870        let mut draw = SpriteDraw::new(white, edge.min, edge.max - edge.min);
871        draw.pivot = Vec2::ZERO;
872        draw.color = OUTLINE;
873        draw.layer = u8::MAX;
874        draw.sort = SortMode::Fixed(u32::MAX);
875        sprites.push(draw);
876    }
877}
878
879/// Writes the profiler's trace to `path`, its folder made if need be, or
880/// with none into `folder`, as `trace-<UTC time>.json`, and says where in
881/// its note and the log, and returns it; or why not, which it returns too.
882fn write_trace(
883    profiler: &mut Profiler,
884    folder: Option<&Path>,
885    path: Option<&Path>,
886) -> Result<PathBuf, String> {
887    let path = match (path, folder) {
888        (Some(path), _) => path.to_path_buf(),
889        (None, Some(folder)) => folder.join(format!("trace-{}.json", DateTime::now().file_stamp())),
890        (None, None) => {
891            let note = "Traces are written only by App::run.";
892            profiler.set_note(note);
893            return Err(note.to_string());
894        }
895    };
896    let parent = path
897        .parent()
898        .filter(|parent| !parent.as_os_str().is_empty());
899    let written = parent
900        .map_or(Ok(()), fs::create_dir_all)
901        .and_then(|()| fs::write(&path, profiler.trace_json()));
902    match written {
903        Ok(()) => {
904            info!("the profiler's trace is in {}", path.display());
905            profiler.set_note(format_args!("Wrote {}", path.display()));
906            Ok(path)
907        }
908        Err(cause) => {
909            warn!(
910                "the profiler's trace is not written: {} cannot be: {cause}",
911                path.display()
912            );
913            let note = format!("Not written: {cause}");
914            profiler.set_note(&note);
915            Err(note)
916        }
917    }
918}
919
920/// What the engine's console commands reach beside the world.
921struct Reach<'a> {
922    world: &'a World,
923    schedule: &'a Schedule,
924    profiler: &'a mut Profiler,
925    logs: Option<&'a Path>,
926    time: &'a mut time::Time,
927    level: &'a mut Option<String>,
928    quit: &'a mut bool,
929}
930
931/// Runs a command of the console, its arguments checked against its usage.
932fn run(
933    reach: &mut Reach<'_>,
934    command: Command,
935    args: &Args<'_>,
936    out: &mut ConsoleOut<'_>,
937) -> Result<(), ConsoleError> {
938    let world = reach.world;
939    let builtin = match command {
940        Command::Game(command) => return command(world, args, out),
941        Command::Engine(builtin) => builtin,
942    };
943    match builtin {
944        Builtin::Schedule => {
945            for system in reach.schedule.describe() {
946                out.print(system);
947            }
948        }
949        Builtin::Spawn => spawn(world, args, out)?,
950        Builtin::Tp => teleport(world, args, out)?,
951        Builtin::Timescale => {
952            let scale = args.f32(0)?;
953            if !TIME_SCALES.contains(&scale) {
954                return Err(ConsoleError::InvalidArgument {
955                    usage: args.usage().to_string(),
956                    argument: "<scale>".to_string(),
957                    found: args.str(0)?.to_string(),
958                    expected: "from 0.25 to 4".to_string(),
959                });
960            }
961            reach.time.scale = scale;
962            out.print(reach.time.scale_note());
963        }
964        Builtin::Level => *reach.level = Some(args.str(0)?.to_string()),
965        Builtin::Reload => {
966            let reads = world.resource_mut::<AssetServer>().reload_all();
967            out.print(format_args!(
968                "reading {reads} assets' files again: each is swapped in once read"
969            ));
970        }
971        Builtin::Profile => {
972            let path = args.get(1).map(Path::new);
973            let path =
974                write_trace(reach.profiler, reach.logs, path).map_err(ConsoleError::Failed)?;
975            out.print(format_args!("Wrote {}", path.display()));
976        }
977        Builtin::Log => {
978            let target = args.str(1)?;
979            let level = match args.str(2)? {
980                "error" => Level::Error,
981                "warn" => Level::Warn,
982                "info" => Level::Info,
983                "debug" => Level::Debug,
984                "trace" => Level::Trace,
985                other => return Err(ConsoleError::Failed(format!("no log level `{other}`"))),
986            };
987            log::set_target_level(target, Some(level));
988            out.print(format_args!(
989                "`{target}` logs {level} and more severe records"
990            ));
991        }
992        Builtin::Quit => {
993            *reach.quit = true;
994            out.print("quitting");
995        }
996    }
997    Ok(())
998}
999
1000/// `spawn <prefab> [x] [y]`: loads the prefab into the library, if it is
1001/// not there, in the level's scope, and spawns it through the world's
1002/// commands at (x, y), or where the camera looks.
1003fn spawn(world: &World, args: &Args<'_>, out: &mut ConsoleOut<'_>) -> Result<(), ConsoleError> {
1004    let name = args.str(0)?;
1005    let at = match args.len() {
1006        3 => Vec2::new(args.f32(1)?, args.f32(2)?),
1007        1 => world.resource::<RenderFrame>().camera.position,
1008        _ => {
1009            return Err(ConsoleError::Failed(format!(
1010                "[x] and [y] go together: {}",
1011                args.usage()
1012            )));
1013        }
1014    };
1015    let failed =
1016        |cause: PrefabError| ConsoleError::Failed(format!("`{name}` is not spawned: {cause}"));
1017    let registry = world.resource::<TypeRegistry>();
1018    world
1019        .resource_mut::<PrefabLibrary>()
1020        .load(
1021            &mut world.resource_mut::<AssetServer>(),
1022            &registry,
1023            name,
1024            Scope::Level,
1025        )
1026        .map_err(failed)?;
1027    let library = world.resource::<PrefabLibrary>();
1028    let mut commands = world.commands();
1029    let entity = loading_context(world, TYPED, Scope::Level, |mut cx| {
1030        library.spawn(name, &[], &registry, &mut commands, &mut cx)
1031    })
1032    .map_err(failed)?;
1033    commands.insert(entity, Transform::at(at));
1034    out.print(format_args!(
1035        "spawned `{name}` as {}v{} at ({}, {}), from the next tick or frame",
1036        entity.index(),
1037        entity.generation(),
1038        at.x,
1039        at.y
1040    ));
1041    Ok(())
1042}
1043
1044/// `tp <x> <y>`: moves each entity with [`Player`] and a [`Transform`] to
1045/// (x, y), with no step between: its last place too.
1046fn teleport(world: &World, args: &Args<'_>, out: &mut ConsoleOut<'_>) -> Result<(), ConsoleError> {
1047    let at = Vec2::new(args.f32(0)?, args.f32(1)?);
1048    let players = world.read::<Player>();
1049    let mut transforms = world.write::<Transform>();
1050    let mut previous = world.write::<PrevTransform>();
1051    let mut moved = 0;
1052    for (entity, _) in players.iter() {
1053        if let Some(transform) = transforms.get_mut(entity) {
1054            transform.position = at;
1055            if let Some(previous) = previous.get_mut(entity) {
1056                previous.0.position = at;
1057            }
1058            moved += 1;
1059        }
1060    }
1061    if moved == 0 {
1062        return Err(ConsoleError::Failed(
1063            "nothing moved: no entity has `Player` and a `Transform`".to_string(),
1064        ));
1065    }
1066    out.print(format_args!(
1067        "moved {moved} player(s) to ({}, {})",
1068        at.x, at.y
1069    ));
1070    Ok(())
1071}
1072
1073/// Draws `text` on a panel at the top-right of a UI `size` units large, at
1074/// `style`'s scale, in the debug UI's `font` and `white` texel: the time
1075/// controls' label, pushed before the windows, which cover it. It puts the
1076/// list's view back.
1077fn corner(
1078    list: &mut UiList,
1079    text: &str,
1080    (font, white): (Handle<Font>, Handle<Texture>),
1081    style: &Style,
1082    size: Vec2,
1083) {
1084    let pad = style.padding;
1085    let width = text.chars().count() as f32 * font::ADVANCE as f32;
1086    let max = Vec2::new(
1087        size.x - CORNER,
1088        CORNER + font::LINE_HEIGHT as f32 + 2.0 * pad,
1089    );
1090    let min = Vec2::new(max.x - width - 2.0 * pad, CORNER);
1091    let before = list.view();
1092    list.set_view(UiView::new(style.scale));
1093    let mut panel = SpriteDraw::new(white, min, max - min);
1094    panel.pivot = Vec2::ZERO;
1095    panel.color = style.panel;
1096    panel.layer = u8::MAX;
1097    panel.sort = SortMode::Fixed(u32::MAX);
1098    list.sprite(panel);
1099    let mut draw = TextDraw::new(font, min + Vec2::splat(pad));
1100    draw.layout.markup = false;
1101    draw.color = style.text;
1102    draw.layer = u8::MAX;
1103    draw.sort = SortMode::Fixed(u32::MAX);
1104    list.text(draw, text);
1105    list.set_view(before);
1106}
1107
1108/// The debug UI, in the engine's font, which it loads in the global scope,
1109/// the font, and the white texel it draws with.
1110fn make_ui(world: &World) -> Result<(DebugUi, Handle<Font>, Handle<Texture>), AssetError> {
1111    let mut server = world.resource_mut::<AssetServer>();
1112    let font = Font::load_now_in(
1113        &mut server,
1114        font::FONT,
1115        Scope::Global,
1116        &mut FinalizeCtx::new(),
1117    )?;
1118    let white = server.load_in::<Texture>(font::WHITE, Scope::Global);
1119    let metrics = server
1120        .get(font)
1121        .map(|loaded| FontMetrics::new(loaded.clone()))
1122        .ok_or_else(|| AssetError::Invalid("the engine's font is not loaded".to_string()))?;
1123    Ok((DebugUi::new(font, metrics, white), font, white))
1124}
1125
1126/// Gives `ui` the places read from the file, by their names: each a
1127/// window's explicit ID or title, which `set_place` would cut at a `##` it
1128/// holds unless it comes after one.
1129fn restore(ui: &mut DebugUi, places: &mut Vec<places::Place>) {
1130    for place in places.drain(..) {
1131        ui.set_place(&format!("##{}", place.name), place.rect, place.collapsed);
1132    }
1133}
1134
1135/// Feeds the debug UI's input with `events`, in their order, but the
1136/// character a key that `toggles` a window types as it is pressed: each
1137/// system sends a key's press before its text (X11's `XLookupString`, a
1138/// `WM_CHAR` after its `WM_KEYDOWN`, `insertText:` after `keyDown:`), so
1139/// that is the text after the press, before another key's. No debug field
1140/// then takes the backtick that shows or hides the console.
1141fn feed(input: &mut DebugInput, events: &[UiEvent], toggles: impl Fn(Key) -> bool) {
1142    // The character a window's toggle types as it is pressed (the
1143    // backtick's), which no debug field takes: the next text, unless
1144    // another key is pressed first.
1145    let mut toggled = false;
1146    for event in events {
1147        match *event {
1148            UiEvent::PointerMoved(position) => input.pointer_moved(position),
1149            UiEvent::Button { button, pressed } => input.button(button, pressed),
1150            UiEvent::Wheel(lines) => input.wheel(lines),
1151            UiEvent::Key {
1152                key,
1153                pressed,
1154                repeat,
1155            } => {
1156                if pressed {
1157                    toggled = toggles(key);
1158                }
1159                input.key(key, pressed, repeat);
1160            }
1161            UiEvent::Text(_) if toggled => toggled = false,
1162            UiEvent::Text(character) => input.text(character.encode_utf8(&mut [0; 4])),
1163            UiEvent::FocusLost => input.focus_lost(),
1164        }
1165    }
1166}
1167
1168/// Writes the places of `ui` to `path`, or says why not.
1169fn save(path: &Path, ui: &DebugUi) {
1170    if let Err(cause) = places::write(path, &places::to_text(ui.places())) {
1171        warn!(
1172            "the debug UI's windows are not kept: {} cannot be written: {cause}",
1173            path.display()
1174        );
1175    }
1176}
1177
1178/// The free scale for a window's scale factor: the nearest whole number,
1179/// so that the pixel font stays sharp, and at least 1.
1180fn whole_scale(factor: f32) -> f32 {
1181    if factor.is_finite() {
1182        factor.round().max(1.0)
1183    } else {
1184        1.0
1185    }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190    use std::time::Duration;
1191    use std::{env, fs, process};
1192
1193    use nadir_codec::qoi;
1194    use nadir_core::time::Tick;
1195    use nadir_core::{GenIndex, Handle, MouseButton, Vec2};
1196    use nadir_ecs::{FixedStage, FrameStage};
1197    use nadir_input::{
1198        ActionKind, ActionMap, ActionSet, ActionState, Binding, InputPlayer, InputRecorder,
1199    };
1200    use nadir_render::{SpriteDraw, UiDraw};
1201
1202    use super::*;
1203    use crate::{App, Config};
1204
1205    /// One tick's length, as a frame.
1206    const TICK: Duration = Duration::from_nanos(16_666_667);
1207    const OUTPUT: UVec2 = UVec2::new(640, 360);
1208    /// The window: its title bar from y 10 to 24, its first row's middle
1209    /// at y 33 and its second's at y 49, both from x 12 (the engine's font
1210    /// is 10 a line, so a row is 14 high, 16 apart).
1211    const WINDOW: Rect = Rect::new(Vec2::new(10.0, 10.0), Vec2::new(210.0, 130.0));
1212    const FIELD: Vec2 = Vec2::new(50.0, 33.0);
1213    const BUTTON: Vec2 = Vec2::new(20.0, 49.0);
1214    const TITLE: Vec2 = Vec2::new(60.0, 17.0);
1215    const OUTSIDE: Vec2 = Vec2::new(400.0, 300.0);
1216
1217    /// What the debug window keeps.
1218    #[derive(Default)]
1219    struct Notes {
1220        text: String,
1221        clicks: u32,
1222    }
1223
1224    fn notes(world: &World, ui: &mut Ui<'_>) {
1225        let mut notes = world.resource_mut::<Notes>();
1226        ui.text_input("Name", &mut notes.text);
1227        if ui.button("Click").clicked {
1228            notes.clicks += 1;
1229        }
1230    }
1231
1232    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1233    enum Act {
1234        Fire,
1235        Jump,
1236        Aim,
1237    }
1238
1239    impl ActionSet for Act {
1240        const ALL: &'static [Self] = &[Act::Fire, Act::Jump, Act::Aim];
1241
1242        fn index(self) -> usize {
1243            self as usize
1244        }
1245
1246        fn name(self) -> &'static str {
1247            match self {
1248                Act::Fire => "fire",
1249                Act::Jump => "jump",
1250                Act::Aim => "aim",
1251            }
1252        }
1253
1254        fn kind(self) -> ActionKind {
1255            ActionKind::Button
1256        }
1257    }
1258
1259    /// The presses of each action the ticks saw, the ticks Jump was held,
1260    /// Aim's releases, and whether Fire and Aim are held now.
1261    #[derive(Default)]
1262    struct Seen {
1263        fire: u32,
1264        jump: u32,
1265        jump_held: u32,
1266        aim: u32,
1267        aim_released: u32,
1268        fire_down: bool,
1269        aim_down: bool,
1270    }
1271
1272    fn count(world: &World, _: &Tick) {
1273        let state = world.resource::<ActionState<Act>>();
1274        let mut seen = world.resource_mut::<Seen>();
1275        seen.fire += u32::from(state.just_pressed(Act::Fire));
1276        seen.jump += u32::from(state.just_pressed(Act::Jump));
1277        seen.jump_held += u32::from(state.pressed(Act::Jump));
1278        seen.aim += u32::from(state.just_pressed(Act::Aim));
1279        seen.aim_released += u32::from(state.just_released(Act::Aim));
1280        seen.fire_down = state.pressed(Act::Fire);
1281        seen.aim_down = state.pressed(Act::Aim);
1282    }
1283
1284    fn actions() -> ActionMap<Act> {
1285        let mut map = ActionMap::<Act>::new().expect("a valid set");
1286        map.bind(Act::Fire, 0, Binding::MouseButton(MouseButton::Left))
1287            .expect("a button");
1288        map.bind(Act::Jump, 0, Binding::Key(Key::Space))
1289            .expect("a key");
1290        map.bind(Act::Aim, 0, Binding::MouseButton(MouseButton::Right))
1291            .expect("a button");
1292        map
1293    }
1294
1295    /// A game with the window `Tools` on F8, which also draws a box of its
1296    /// own UI each frame.
1297    fn app() -> App {
1298        let mut app = App::new(Config::default())
1299            .insert_resource(Notes::default())
1300            .insert_resource(Seen::default())
1301            .add_actions(actions())
1302            .add_fixed_system(FixedStage::Gameplay, "count", count)
1303            .add_frame_system(FrameStage::Ui, "game_ui", |world, _| {
1304                let mut sprite = SpriteDraw::new(game_box(), Vec2::ZERO, Vec2::ONE);
1305                sprite.pivot = Vec2::ZERO;
1306                world.resource_mut::<RenderFrame>().ui.sprite(sprite);
1307            })
1308            .add_debug_window(Key::F8, "Tools", WINDOW, notes);
1309        *app.world_mut().resource_mut::<WindowSize>() = WindowSize(OUTPUT);
1310        app
1311    }
1312
1313    fn game_box() -> Handle<Texture> {
1314        Handle::new(GenIndex::new(99, std::num::NonZeroU32::MIN))
1315    }
1316
1317    fn key(key: Key, pressed: bool) -> Event {
1318        Event::Key {
1319            key,
1320            pressed,
1321            repeat: false,
1322        }
1323    }
1324
1325    fn tap(key: Key) -> [Event; 2] {
1326        [self::key(key, true), self::key(key, false)]
1327    }
1328
1329    fn click(at: Vec2) -> [Event; 3] {
1330        [
1331            Event::MouseMoved(at),
1332            Event::MouseButton {
1333                button: MouseButton::Left,
1334                pressed: true,
1335            },
1336            Event::MouseButton {
1337                button: MouseButton::Left,
1338                pressed: false,
1339            },
1340        ]
1341    }
1342
1343    /// The texts the frame's UI holds.
1344    fn texts(app: &App) -> Vec<String> {
1345        let frame = app.world().resource::<RenderFrame>();
1346        frame
1347            .ui
1348            .iter()
1349            .filter_map(|(draw, _)| match draw {
1350                UiDraw::Text(_, text) => Some(text.to_string()),
1351                _ => None,
1352            })
1353            .collect()
1354    }
1355
1356    fn seen(app: &App) -> (u32, u32) {
1357        let seen = app.world().resource::<Seen>();
1358        (seen.fire, seen.jump)
1359    }
1360
1361    #[test]
1362    fn a_window_shows_on_its_key_after_the_games_ui_and_hides_on_it_again() {
1363        let mut app = app();
1364        app.update(TICK, &[]);
1365        assert_eq!(app.world().resource::<RenderFrame>().ui.len(), 1);
1366        assert!(texts(&app).is_empty());
1367        app.update(TICK, &tap(Key::F8));
1368        {
1369            let frame = app.world().resource::<RenderFrame>();
1370            let mut items = frame.ui.iter();
1371            // The game's box first, then the debug window, at its own scale.
1372            assert!(matches!(
1373                items.next(),
1374                Some((UiDraw::Sprite(sprite), _)) if sprite.texture == game_box()
1375            ));
1376            assert!(items.len() > 4);
1377            assert!(items.all(|(_, view)| view.scale() == UiScale::Free(1.0)));
1378        }
1379        // The collapse box, the title, the field's text and its label, and
1380        // the button.
1381        assert_eq!(texts(&app), ["-", "Tools", "", "Name", "Click"]);
1382        // A repeat of the key does not toggle it.
1383        app.update(
1384            TICK,
1385            &[Event::Key {
1386                key: Key::F8,
1387                pressed: true,
1388                repeat: true,
1389            }],
1390        );
1391        assert_eq!(texts(&app), ["-", "Tools", "", "Name", "Click"]);
1392        app.update(TICK, &[key(Key::F8, false)]);
1393        app.update(TICK, &tap(Key::F8));
1394        assert!(texts(&app).is_empty());
1395        assert_eq!(app.world().resource::<RenderFrame>().ui.len(), 1);
1396    }
1397
1398    #[test]
1399    fn the_games_actions_miss_what_the_debug_window_takes() {
1400        let mut app = app();
1401        app.update(TICK, &tap(Key::F8));
1402        // A click outside every window is the game's.
1403        app.update(TICK, &click(OUTSIDE));
1404        assert_eq!(seen(&app), (1, 0));
1405        // On the button: the window's.
1406        app.update(TICK, &click(BUTTON));
1407        assert_eq!(seen(&app), (1, 0));
1408        assert_eq!(app.world().resource::<Notes>().clicks, 1);
1409        // The pointer comes over the window and clicks in one frame: the
1410        // window's, as the press was over it.
1411        app.update(TICK, &[Event::MouseMoved(OUTSIDE)]);
1412        app.update(TICK, &click(BUTTON));
1413        assert_eq!(seen(&app), (1, 0));
1414        assert_eq!(app.world().resource::<Notes>().clicks, 2);
1415        // It leaves the window and clicks in one frame: the game's.
1416        app.update(TICK, &click(OUTSIDE));
1417        assert_eq!(seen(&app), (2, 0));
1418        // The wheel over the window is the window's.
1419        app.update(
1420            TICK,
1421            &[
1422                Event::MouseMoved(BUTTON),
1423                Event::MouseWheel(Vec2::new(0.0, 1.0)),
1424            ],
1425        );
1426        assert_eq!(app.world().resource::<Input>().wheel(), Vec2::ZERO);
1427
1428        // Typed into the field, the keys are the window's, and so is the
1429        // Escape that leaves it.
1430        app.update(TICK, &click(FIELD));
1431        let mut typing = vec![key(Key::A, true), Event::Text('a'), key(Key::A, false)];
1432        typing.extend([
1433            key(Key::Space, true),
1434            Event::Text(' '),
1435            key(Key::Space, false),
1436        ]);
1437        typing.push(Event::Text('é'));
1438        app.update(TICK, &typing);
1439        assert_eq!(app.world().resource::<Notes>().text, "a é");
1440        assert_eq!(seen(&app), (2, 0));
1441        app.update(TICK, &tap(Key::Escape));
1442        app.update(TICK, &tap(Key::Space));
1443        assert_eq!(seen(&app), (2, 1));
1444        assert_eq!(app.world().resource::<Notes>().text, "a é");
1445
1446        // Hidden, it holds nothing back from the next frame on.
1447        app.update(TICK, &[Event::MouseMoved(BUTTON)]);
1448        assert!(app.world().resource::<Input>().capture().mouse);
1449        app.update(TICK, &tap(Key::F8));
1450        app.update(TICK, &click(BUTTON));
1451        assert_eq!(app.world().resource::<Input>().capture(), Capture::NONE);
1452        assert_eq!(seen(&app), (3, 1));
1453        assert_eq!(app.world().resource::<Notes>().clicks, 2);
1454    }
1455
1456    fn button(button: MouseButton, pressed: bool) -> Event {
1457        Event::MouseButton { button, pressed }
1458    }
1459
1460    #[test]
1461    fn a_release_and_a_press_in_one_frame_go_where_each_happened() {
1462        let mut app = app();
1463        app.update(TICK, &tap(Key::F8));
1464        // The game holds Left; in one frame it is released, and pressed and
1465        // released again over the window's button: the second press is
1466        // the window's alone.
1467        app.update(
1468            TICK,
1469            &[Event::MouseMoved(OUTSIDE), button(MouseButton::Left, true)],
1470        );
1471        assert_eq!(seen(&app), (1, 0));
1472        app.update(
1473            TICK,
1474            &[
1475                button(MouseButton::Left, false),
1476                Event::MouseMoved(BUTTON),
1477                button(MouseButton::Left, true),
1478                button(MouseButton::Left, false),
1479            ],
1480        );
1481        for _ in 0..2 {
1482            app.update(TICK, &[]);
1483        }
1484        assert_eq!(seen(&app), (1, 0));
1485        assert_eq!(app.world().resource::<Notes>().clicks, 1);
1486        // The window holds Left by its title bar; in one frame it is
1487        // released, and pressed again outside: that press is the game's.
1488        app.update(
1489            TICK,
1490            &[Event::MouseMoved(TITLE), button(MouseButton::Left, true)],
1491        );
1492        app.update(
1493            TICK,
1494            &[
1495                button(MouseButton::Left, false),
1496                Event::MouseMoved(OUTSIDE),
1497                button(MouseButton::Left, true),
1498                button(MouseButton::Left, false),
1499            ],
1500        );
1501        assert_eq!(seen(&app), (2, 0));
1502    }
1503
1504    #[test]
1505    fn a_button_the_game_holds_stays_its_as_the_pointer_passes_a_window() {
1506        let mut app = app();
1507        app.update(TICK, &tap(Key::F8));
1508        // Right held from outside, then over the window and away again.
1509        app.update(
1510            TICK,
1511            &[Event::MouseMoved(OUTSIDE), button(MouseButton::Right, true)],
1512        );
1513        for at in [BUTTON, FIELD, OUTSIDE] {
1514            app.update(TICK, &[Event::MouseMoved(at)]);
1515            app.update(TICK, &[]);
1516        }
1517        let seen = app.world().resource::<Seen>();
1518        assert_eq!((seen.aim, seen.aim_released, seen.aim_down), (1, 0, true));
1519    }
1520
1521    #[test]
1522    fn while_the_window_holds_left_another_button_is_its_too() {
1523        let mut app = app();
1524        app.update(TICK, &tap(Key::F8));
1525        // Left pressed on the window, then Right outside in the same frame.
1526        app.update(
1527            TICK,
1528            &[
1529                Event::MouseMoved(TITLE),
1530                button(MouseButton::Left, true),
1531                Event::MouseMoved(OUTSIDE),
1532                button(MouseButton::Right, true),
1533            ],
1534        );
1535        for _ in 0..3 {
1536            app.update(TICK, &[]);
1537        }
1538        app.update(
1539            TICK,
1540            &[
1541                button(MouseButton::Right, false),
1542                button(MouseButton::Left, false),
1543            ],
1544        );
1545        let seen = app.world().resource::<Seen>();
1546        assert_eq!((seen.aim, seen.aim_down), (0, false));
1547        assert_eq!(seen.fire, 0);
1548    }
1549
1550    #[test]
1551    fn opening_a_window_over_a_button_the_game_holds_leaves_it_the_game_s() {
1552        let mut app = app();
1553        // Left held by the game where the window will open.
1554        app.update(
1555            TICK,
1556            &[Event::MouseMoved(BUTTON), button(MouseButton::Left, true)],
1557        );
1558        app.update(TICK, &tap(Key::F8));
1559        for _ in 0..3 {
1560            app.update(TICK, &[Event::MouseMoved(FIELD)]);
1561        }
1562        let seen = app.world().resource::<Seen>();
1563        assert_eq!((seen.fire, seen.fire_down), (1, true));
1564    }
1565
1566    #[test]
1567    fn a_replay_plays_while_a_debug_field_has_the_keyboard() {
1568        // A recording of Jump held for 12 ticks.
1569        let mut recorder = InputRecorder::<Act>::new().expect("a valid set");
1570        let map = actions();
1571        let mut input = Input::new();
1572        let mut state = ActionState::new();
1573        input.handle(&key(Key::Space, true));
1574        for _ in 0..12 {
1575            input.latch(&map, &mut state);
1576            recorder.record(&state);
1577        }
1578        let bytes: &'static [u8] = Box::leak(recorder.into_bytes().into_boxed_slice());
1579        let player = InputPlayer::<Act>::new(bytes).expect("a replay of Act");
1580        let mut app = app().play_replay(player);
1581        app.update(TICK, &tap(Key::F8));
1582        app.update(TICK, &click(FIELD));
1583        for _ in 0..4 {
1584            app.update(TICK, &[]);
1585        }
1586        // The field has the keyboard, and the replay's Jump went on, tick
1587        // after tick.
1588        assert!(app.world().resource::<Input>().capture().keyboard);
1589        assert_eq!(app.world().resource::<Seen>().jump_held, 6);
1590    }
1591
1592    #[test]
1593    fn a_steady_frame_of_an_open_debug_window_allocates_nothing() {
1594        let mut app = app();
1595        app.world_mut().resource_mut::<Notes>().text = "hero".to_string();
1596        app.update(TICK, &tap(Key::F8));
1597        let moves = [Event::MouseMoved(BUTTON), Event::MouseMoved(OUTSIDE)];
1598        for index in 0..10 {
1599            app.update(TICK, &moves[index % 2..index % 2 + 1]);
1600        }
1601        let start = nadir_platform::thread_alloc_counts();
1602        for index in 0..20 {
1603            app.update(TICK, &moves[index % 2..index % 2 + 1]);
1604        }
1605        let allocated = nadir_platform::thread_alloc_counts().since(start);
1606        assert_eq!(texts(&app), ["-", "Tools", "hero", "Name", "Click"]);
1607        assert_eq!(allocated, nadir_platform::AllocCounts::default());
1608    }
1609
1610    /// A debug UI driven by hand over an app's world, so that its places
1611    /// can be read.
1612    struct Rig {
1613        app: App,
1614        tools: DebugTools,
1615    }
1616
1617    impl Rig {
1618        fn new() -> Self {
1619            let mut tools = DebugTools::new();
1620            tools.add(Key::F8, "Tools##tools", WINDOW, |_, ui| ui.label("Hello"));
1621            let mut app = App::new(Config::default());
1622            *app.world_mut().resource_mut::<WindowSize>() = WindowSize(OUTPUT);
1623            Self { app, tools }
1624        }
1625
1626        fn frame(&mut self, events: &[Event]) {
1627            let world = self.app.world();
1628            {
1629                let mut input = world.resource_mut::<Input>();
1630                self.tools.start_frame(&mut input);
1631                for event in events {
1632                    self.tools.handle(&mut input, event);
1633                    input.handle(event);
1634                }
1635            }
1636            world.resource_mut::<RenderFrame>().ui.clear();
1637            let schedule = self.app.schedule();
1638            self.tools.frame(world, schedule, UVec2::new(480, 270), 0.0);
1639        }
1640
1641        fn place(&self) -> Rect {
1642            let ui = self.tools.ui.as_ref().expect("made");
1643            let mut places = ui.places();
1644            places.next().expect("a window").rect
1645        }
1646    }
1647
1648    #[test]
1649    fn a_window_s_place_is_written_when_it_moves_and_read_on_the_next_run() {
1650        let dir = env::temp_dir().join(format!("nadir-engine-debug-places-{}", process::id()));
1651        let _ = fs::remove_dir_all(&dir);
1652        let path = dir.join(FILE_NAME);
1653        let mut rig = Rig::new();
1654        rig.tools.keep_places_in(path.clone());
1655        rig.frame(&tap(Key::F8));
1656        assert_eq!(rig.place(), WINDOW);
1657        assert!(!path.exists(), "nothing moved yet");
1658        // Dragged by its title bar 100 to the right and 100 down.
1659        let press = Event::MouseButton {
1660            button: MouseButton::Left,
1661            pressed: true,
1662        };
1663        let release = Event::MouseButton {
1664            button: MouseButton::Left,
1665            pressed: false,
1666        };
1667        rig.frame(&[Event::MouseMoved(TITLE), press]);
1668        rig.frame(&[Event::MouseMoved(TITLE + Vec2::splat(100.0))]);
1669        rig.frame(&[release]);
1670        let moved = Rect::new(
1671            WINDOW.min + Vec2::splat(100.0),
1672            WINDOW.max + Vec2::splat(100.0),
1673        );
1674        assert_eq!(rig.place(), moved);
1675        let text = fs::read_to_string(&path).expect("the places were written");
1676        assert!(text.contains("\"tools\""), "{text}");
1677
1678        // The next run puts it there, the first time it shows.
1679        let mut next = Rig::new();
1680        next.tools.keep_places_in(path.clone());
1681        next.frame(&tap(Key::F8));
1682        assert_eq!(next.place(), moved);
1683        let panel = next
1684            .app
1685            .world()
1686            .resource::<RenderFrame>()
1687            .ui
1688            .iter()
1689            .find_map(|(draw, _)| match draw {
1690                UiDraw::Sprite(sprite) => Some(sprite.position),
1691                _ => None,
1692            });
1693        assert_eq!(panel, Some(moved.min));
1694        fs::remove_dir_all(&dir).expect("remove the folder");
1695    }
1696
1697    #[test]
1698    fn an_explicit_id_with_hashes_in_it_gets_its_place_back() {
1699        let dir = env::temp_dir().join(format!("nadir-engine-debug-hashes-{}", process::id()));
1700        let _ = fs::remove_dir_all(&dir);
1701        fs::create_dir_all(&dir).expect("the folder");
1702        let path = dir.join(FILE_NAME);
1703        fs::write(
1704            &path,
1705            r#"{ "version": 1, "windows": [
1706                { "name": "a##b", "x": 300, "y": 40, "w": 100, "h": 60, "collapsed": false } ] }"#,
1707        )
1708        .expect("a places file");
1709        let mut tools = DebugTools::new();
1710        // The window `a##b`: its title is `Odd`.
1711        tools.add(Key::F8, "Odd##a##b", WINDOW, |_, ui| ui.label("odd"));
1712        let mut rig = Rig {
1713            app: Rig::new().app,
1714            tools,
1715        };
1716        rig.tools.keep_places_in(path);
1717        rig.frame(&tap(Key::F8));
1718        let ui = rig.tools.ui.as_ref().expect("made");
1719        let places: Vec<_> = ui.places().map(|place| (place.title, place.rect)).collect();
1720        assert_eq!(
1721            places,
1722            [(
1723                "a##b",
1724                Rect::from_min_size(Vec2::new(300.0, 40.0), Vec2::new(100.0, 60.0))
1725            )]
1726        );
1727        fs::remove_dir_all(&dir).expect("remove the folder");
1728    }
1729
1730    #[test]
1731    fn the_scale_is_the_window_s_whole_and_at_least_one() {
1732        assert_eq!(
1733            [0.5, 1.0, 1.25, 1.5, 2.0, 2.6, f32::NAN, f32::INFINITY].map(whole_scale),
1734            [1.0, 1.0, 1.0, 2.0, 2.0, 3.0, 1.0, 1.0]
1735        );
1736        let mut rig = Rig::new();
1737        rig.frame(&[Event::ScaleFactorChanged(2.0), tap(Key::F8)[0]]);
1738        let frame = rig.app.world().resource::<RenderFrame>();
1739        let (_, view) = frame.ui.iter().next().expect("the window");
1740        assert_eq!(view.scale(), UiScale::Free(2.0));
1741    }
1742
1743    #[test]
1744    fn the_engine_s_files_come_before_the_game_s_and_never_change() {
1745        let root = env::temp_dir().join(format!("nadir-engine-files-{}", process::id()));
1746        fs::create_dir_all(root.join("nadir/debug")).expect("the folder");
1747        fs::write(root.join("nadir/debug/white.qoi"), b"the game's").expect("a file");
1748        fs::write(root.join("nadir/debug/other.qoi"), b"the game's too").expect("a file");
1749        let source = EngineFiles::new(&root);
1750        let path = |path: &str| AssetPath::new(path).expect("a path");
1751        let white = source.read(&path(font::WHITE)).expect("the white texel");
1752        let image = qoi::decode(&white, nadir_codec::Limits::default()).expect("an image");
1753        assert_eq!((image.header.width, image.header.height), (1, 1));
1754        assert_eq!(image.pixels, [255; 4]);
1755        assert_eq!(source.modified(&path(font::WHITE)), None);
1756        assert_eq!(
1757            source.read(&path("nadir/debug/other.qoi")),
1758            Ok(b"the game's too".to_vec())
1759        );
1760        assert!(source.modified(&path("nadir/debug/other.qoi")).is_some());
1761        assert_eq!(source.read(&path("missing.qoi")), Err(AssetError::NotFound));
1762        fs::remove_dir_all(&root).expect("remove the folder");
1763    }
1764
1765    // -- the engine's windows ---------------------------------------------
1766
1767    /// Where the frame's UI drew `text`, in the UI's units: pixels here.
1768    fn text_at(app: &App, text: &str) -> Option<Vec2> {
1769        let frame = app.world().resource::<RenderFrame>();
1770        frame.ui.iter().find_map(|(draw, _)| match draw {
1771            UiDraw::Text(draw, shown) if shown == text => Some(draw.position),
1772            _ => None,
1773        })
1774    }
1775
1776    fn shows_starting(app: &App, start: &str) -> bool {
1777        texts(app).iter().any(|text| text.starts_with(start))
1778    }
1779
1780    #[test]
1781    fn f1_shows_the_frame_s_stats_and_f3_the_profiler_of_its_scopes() {
1782        let mut app = app();
1783        for _ in 0..3 {
1784            app.world_mut()
1785                .spawn()
1786                .with(crate::Transform::at(Vec2::ZERO));
1787        }
1788        for _ in 0..4 {
1789            app.update(TICK, &[]);
1790        }
1791        app.update(TICK, &tap(Key::F1));
1792        let shown = texts(&app);
1793        assert!(shown.iter().any(|text| text == "Stats"), "{shown:?}");
1794        assert!(shown.iter().any(|text| text == "entities 3"), "{shown:?}");
1795        assert!(shows_starting(&app, "ticks 1 in "), "{shown:?}");
1796        assert!(shown.iter().any(|text| text == "voices 0"), "{shown:?}");
1797        assert!(shown.iter().any(|text| text == "underruns 0"), "{shown:?}");
1798        app.update(TICK, &tap(Key::F1));
1799        assert!(texts(&app).is_empty());
1800
1801        // Each frame before this one, its scopes collected as the next
1802        // started: the first frame has none before it.
1803        app.update(TICK, &tap(Key::F3));
1804        let shown = texts(&app);
1805        assert!(shown.iter().any(|text| text == "Profiler"), "{shown:?}");
1806        assert!(shows_starting(&app, "6 frames, "), "{shown:?}");
1807        assert!(
1808            shown
1809                .iter()
1810                .any(|text| text == "Click a frame for its scopes.")
1811        );
1812
1813        // A click on the graph, from (218, 40) to (431.6, 100), selects a
1814        // frame: its scopes, the engine's and the systems', show.
1815        app.update(TICK, &click(Vec2::new(400.0, 70.0)));
1816        app.update(TICK, &[]);
1817        let shown = texts(&app);
1818        assert!(shows_starting(&app, "frame "), "{shown:?}");
1819        assert!(shows_starting(&app, "nadir::tick "), "{shown:?}");
1820        assert!(shows_starting(&app, "nadir::frame_stages "), "{shown:?}");
1821        assert!(shows_starting(&app, "  nadir::debug_ui "), "{shown:?}");
1822        let tick = shown
1823            .iter()
1824            .find(|text| text.starts_with("nadir::tick "))
1825            .expect("the tick");
1826        let at = text_at(&app, tick).expect("drawn");
1827        app.update(TICK, &click(at + Vec2::new(2.0, 2.0)));
1828        app.update(TICK, &[]);
1829        // The tick opened: the engine's systems and the game's in it.
1830        assert!(
1831            shows_starting(&app, "  nadir::snapshot "),
1832            "{:?}",
1833            texts(&app)
1834        );
1835        assert!(shows_starting(&app, "  count "), "{:?}", texts(&app));
1836
1837        // Without App::run there is no folder to write a trace to.
1838        let button = text_at(&app, "Write trace").expect("the button");
1839        app.update(TICK, &click(button + Vec2::new(2.0, 2.0)));
1840        app.update(TICK, &[]);
1841        let shown = texts(&app);
1842        assert!(
1843            shown
1844                .iter()
1845                .any(|text| text == "Traces are written only by App::run."),
1846            "{shown:?}"
1847        );
1848    }
1849
1850    #[test]
1851    fn a_steady_frame_of_the_stats_and_a_profiled_frame_s_tree_allocates_nothing() {
1852        let mut app = app();
1853        app.update(TICK, &tap(Key::F1));
1854        app.update(TICK, &tap(Key::F3));
1855        // Until the ring is full, the graph's lines grow the buffers that
1856        // hold them.
1857        for _ in 0..nadir_debug::PROFILER_FRAMES + 10 {
1858            app.update(TICK, &[]);
1859        }
1860        app.update(TICK, &click(Vec2::new(400.0, 70.0)));
1861        for _ in 0..10 {
1862            app.update(TICK, &[]);
1863        }
1864        assert!(shows_starting(&app, "nadir::tick "), "{:?}", texts(&app));
1865        let start = nadir_platform::thread_alloc_counts();
1866        for _ in 0..20 {
1867            app.update(TICK, &[]);
1868        }
1869        let allocated = nadir_platform::thread_alloc_counts().since(start);
1870        assert!(shows_starting(&app, "nadir::tick "), "{:?}", texts(&app));
1871        assert!(shows_starting(&app, "entities 0"), "{:?}", texts(&app));
1872        assert_eq!(allocated, nadir_platform::AllocCounts::default());
1873    }
1874
1875    /// The GPU's times over a render `renders_ago` renders back.
1876    fn gpu_times(renders_ago: u32, world_us: u64, output_us: u64) -> GpuTimes {
1877        let mut times = GpuTimes::default();
1878        times.renders_ago = renders_ago;
1879        times.world = Duration::from_micros(world_us);
1880        times.output = Duration::from_micros(output_us);
1881        times
1882    }
1883
1884    #[test]
1885    fn each_gpu_time_read_back_goes_to_the_frame_its_render_drew() {
1886        let mut tools = DebugTools::new();
1887        let base = Instant::now();
1888        let at = |frame: u32| base + frame * TICK;
1889        let drawn = |frame: u32| at(frame) + Duration::from_micros(500);
1890        // Each frame starts, then is drawn, but frame 2 (a modal one): so
1891        // render 2 is frame 3's, and so on. Frame 4 reads back render 1,
1892        // two renders back, frame 1's (two frames back is frame 2); frame 6
1893        // render 2, three back; frame 11, the eleventh render, render 3,
1894        // seven back, and one nine back, past what is kept: render 1, whose
1895        // slot now holds render 9, frame 10's. (Eight back would be the
1896        // slot of the render being drawn, whose frame is not held yet.)
1897        let mut read: [&[GpuTimes]; 12] = [&[]; 12];
1898        let (first, second, behind) = (
1899            [gpu_times(2, 100, 200)],
1900            [gpu_times(2, 300, 400)],
1901            [gpu_times(3, 500, 600)],
1902        );
1903        let late = [gpu_times(9, 1, 1), gpu_times(7, 700, 800)];
1904        read[3] = &first;
1905        read[4] = &second;
1906        read[6] = &behind;
1907        read[11] = &late;
1908        for (frame, times) in (0..).zip(read) {
1909            tools.start_profile(at(frame), &[]);
1910            if frame != 2 {
1911                tools.rendered(drawn(frame), times);
1912            }
1913        }
1914        tools.start_profile(at(12), &[]);
1915        let held: Vec<(u64, Option<GpuTiming>)> = tools
1916            .profiler
1917            .frames()
1918            .map(|frame| (frame.index, frame.gpu))
1919            .collect();
1920        let gpu = |frame: u32, world: u64, output: u64| {
1921            Some(GpuTiming::new(
1922                drawn(frame),
1923                Duration::from_micros(world),
1924                Duration::from_micros(output),
1925            ))
1926        };
1927        let mut expected: Vec<(u64, Option<GpuTiming>)> =
1928            (0..12).map(|index| (index, None)).collect();
1929        expected[0].1 = gpu(0, 100, 200);
1930        expected[1].1 = gpu(1, 300, 400);
1931        expected[3].1 = gpu(3, 500, 600);
1932        expected[4].1 = gpu(4, 700, 800);
1933        assert_eq!(held, expected);
1934    }
1935
1936    #[test]
1937    fn a_trace_written_holds_each_frame_and_its_scopes_and_parses() {
1938        use nadir_codec::json::{self, Value};
1939        use nadir_core::profile::{self, ScopeRecord};
1940
1941        let mut tools = DebugTools::new();
1942        let mut records: Vec<ScopeRecord> = Vec::new();
1943        for _ in 0..4 {
1944            {
1945                nadir_core::profile_scope!("outer");
1946                nadir_core::profile_scope!("inner");
1947            }
1948            profile::take_frame(&mut records);
1949            tools.start_profile(Instant::now(), &records);
1950        }
1951        let folder = env::temp_dir().join(format!("nadir-engine-traces-{}", process::id()));
1952        let _ = fs::remove_dir_all(&folder);
1953        write_trace(&mut tools.profiler, Some(&folder), None).expect("the trace is written");
1954        let files: Vec<PathBuf> = fs::read_dir(&folder)
1955            .expect("the folder was made")
1956            .map(|entry| entry.expect("an entry").path())
1957            .collect();
1958        let [file] = &files[..] else {
1959            panic!("one trace: {files:?}");
1960        };
1961        let name = file
1962            .file_name()
1963            .and_then(|name| name.to_str())
1964            .expect("a name");
1965        assert!(
1966            name.starts_with("trace-") && name.ends_with(".json"),
1967            "{name}"
1968        );
1969        let text = fs::read_to_string(file).expect("the trace");
1970        let value = json::parse(&text, nadir_codec::Limits::default()).expect("it parses");
1971        let events = value
1972            .get("traceEvents")
1973            .and_then(Value::as_array)
1974            .expect("its events");
1975        let names: Vec<&str> = events
1976            .iter()
1977            .filter(|event| event.get("ph").and_then(Value::as_str) == Some("X"))
1978            .filter_map(|event| event.get("name").and_then(Value::as_str))
1979            .collect();
1980        // Three frames: the first push only starts one. Each holds the
1981        // scopes collected as it ended, in the order they started.
1982        assert_eq!(names, ["frame", "outer", "inner"].repeat(3));
1983        fs::remove_dir_all(&folder).expect("remove the folder");
1984    }
1985
1986    /// The outline's sprites the frame holds, as one rect around them all.
1987    fn outline_of(app: &App) -> Option<Rect> {
1988        let frame = app.world().resource::<RenderFrame>();
1989        let edges: Vec<Rect> = frame
1990            .sprites
1991            .iter()
1992            .filter(|sprite| sprite.color == OUTLINE)
1993            .map(|sprite| Rect::new(sprite.position, sprite.position + sprite.size))
1994            .collect();
1995        if edges.is_empty() {
1996            return None;
1997        }
1998        assert_eq!(edges.len(), 4, "four edges: {edges:?}");
1999        let min = edges
2000            .iter()
2001            .fold(Vec2::splat(f32::MAX), |at, edge| at.min(edge.min));
2002        let max = edges
2003            .iter()
2004            .fold(Vec2::splat(f32::MIN), |at, edge| at.max(edge.max));
2005        Some(Rect::new(min, max))
2006    }
2007
2008    #[test]
2009    fn f2_inspects_an_entity_outlines_it_edits_it_and_saves_it_as_a_prefab() {
2010        use nadir_codec::json::{self, Value};
2011
2012        use crate::{Player, Velocity};
2013
2014        let mut app = app();
2015        // Wide enough for the inspector's first place.
2016        let screen = UVec2::new(1280, 720);
2017        *app.world_mut().resource_mut::<WindowSize>() = WindowSize(screen);
2018        let hero = app
2019            .world_mut()
2020            .spawn()
2021            .with(Transform::at(Vec2::new(100.0, 50.0)))
2022            .with(Velocity(Vec2::ZERO))
2023            .with(Player)
2024            .with(SaveId(7))
2025            .with(Sprite::new(game_box(), Vec2::new(16.0, 24.0)))
2026            .id();
2027        let folder = env::temp_dir().join(format!("nadir-engine-prefabs-{}", process::id()));
2028        let _ = fs::remove_dir_all(&folder);
2029        app.debug_tools().write_traces_in(folder.clone());
2030
2031        app.update(TICK, &tap(Key::F2));
2032        assert!(texts(&app).iter().any(|text| text == "1 entities"));
2033        let row = "  0v1 Transform Velocity Player SaveId Sprite";
2034        let at = text_at(&app, row).expect("the hero's row");
2035        app.update(TICK, &click(at + Vec2::new(1.0, 2.0)));
2036        assert_eq!(app.debug_tools().inspector.selected(), Some(hero));
2037
2038        // Outlined in the world, a unit outside its sprite, whose feet are
2039        // at its place.
2040        app.update(TICK, &[]);
2041        let expected = Rect::new(Vec2::new(91.0, 25.0), Vec2::new(109.0, 51.0));
2042        assert_eq!(outline_of(&app), Some(expected));
2043
2044        // Its place, dragged in the window through the engine's context: 100
2045        // units right is 10 world units.
2046        let at = text_at(&app, "Transform").expect("its node");
2047        app.update(TICK, &click(at + Vec2::new(1.0, 2.0)));
2048        app.update(TICK, &[]);
2049        let position = text_at(&app, "position").expect("its position");
2050        let x = position + Vec2::new(-126.0, 2.0);
2051        let press = Event::MouseButton {
2052            button: MouseButton::Left,
2053            pressed: true,
2054        };
2055        let release = Event::MouseButton {
2056            button: MouseButton::Left,
2057            pressed: false,
2058        };
2059        app.update(TICK, &[Event::MouseMoved(x), press]);
2060        app.update(TICK, &[Event::MouseMoved(x + Vec2::new(100.0, 0.0))]);
2061        app.update(TICK, &[release]);
2062        let moved = app
2063            .world()
2064            .read::<Transform>()
2065            .get(hero)
2066            .map(|at| at.position);
2067        assert_eq!(moved, Some(Vec2::new(110.0, 50.0)));
2068
2069        // Saved as a prefab named in its field, the button's text 48 after
2070        // the field's middle: without its place or its save number.
2071        let button = text_at(&app, "Save as prefab").expect("the button");
2072        let typed = |text: &str| -> Vec<Event> {
2073            let mut events = vec![key(Key::LeftControl, true)];
2074            events.extend(tap(Key::A));
2075            events.push(key(Key::LeftControl, false));
2076            events.extend(text.chars().map(Event::Text));
2077            events
2078        };
2079        // A Windows device's name is no file: not written.
2080        app.update(TICK, &click(button + Vec2::new(-48.0, 2.0)));
2081        app.update(TICK, &typed("nul"));
2082        app.update(TICK, &click(button + Vec2::new(1.0, 2.0)));
2083        app.update(TICK, &[]);
2084        assert!(
2085            shows_starting(&app, "Not written: data/prefabs/nul.jsonc: "),
2086            "{:?}",
2087            texts(&app)
2088        );
2089        assert!(!folder.join(PREFABS).join("nul.jsonc").exists());
2090        app.update(TICK, &click(button + Vec2::new(-48.0, 2.0)));
2091        app.update(TICK, &typed("hero"));
2092        app.update(TICK, &click(button + Vec2::new(1.0, 2.0)));
2093        app.update(TICK, &[]);
2094        let path = folder.join(PREFABS).join("hero.jsonc");
2095        let text = fs::read_to_string(&path).expect("the prefab was written");
2096        assert!(texts(&app).contains(&format!("Wrote {}", path.display())));
2097        let prefab = json::parse(&text, nadir_codec::Limits::default()).expect("JSONC");
2098        assert_eq!(prefab.get("name").and_then(Value::as_str), Some("hero"));
2099        let names: Vec<&str> = prefab
2100            .get("components")
2101            .and_then(Value::as_object)
2102            .expect("components")
2103            .iter()
2104            .map(|(name, _)| name.as_str())
2105            .collect();
2106        assert_eq!(names, ["Velocity", "Player", "Sprite"]);
2107
2108        // Closed, the inspector outlines nothing.
2109        app.update(TICK, &tap(Key::F2));
2110        assert_eq!(outline_of(&app), None);
2111        fs::remove_dir_all(&folder).expect("remove the folder");
2112    }
2113
2114    #[test]
2115    fn an_entity_with_no_sprite_is_outlined_by_its_collider_or_a_box_at_its_place() {
2116        use nadir_collision::Shape;
2117
2118        let mut app = app();
2119        let crate_box = app
2120            .world_mut()
2121            .spawn()
2122            .with(Transform::at(Vec2::new(40.0, 40.0)))
2123            .with(Collider::solid(Shape::Aabb {
2124                half: Vec2::new(5.0, 3.0),
2125            }))
2126            .id();
2127        let marker = app
2128            .world_mut()
2129            .spawn()
2130            .with(Transform::at(Vec2::new(-10.0, 0.0)))
2131            .id();
2132        let nowhere = app.world_mut().spawn().id();
2133        app.update(TICK, &tap(Key::F2));
2134        app.debug_tools().inspector.select(Some(crate_box));
2135        app.update(TICK, &[]);
2136        let expected = Rect::new(Vec2::new(34.0, 36.0), Vec2::new(46.0, 44.0));
2137        assert_eq!(outline_of(&app), Some(expected));
2138        app.debug_tools().inspector.select(Some(marker));
2139        app.update(TICK, &[]);
2140        let expected = Rect::new(Vec2::new(-15.0, -5.0), Vec2::new(-5.0, 5.0));
2141        assert_eq!(outline_of(&app), Some(expected));
2142        app.debug_tools().inspector.select(Some(nowhere));
2143        app.update(TICK, &[]);
2144        assert_eq!(outline_of(&app), None);
2145    }
2146    /// What the game's `god` command flips.
2147    #[derive(Default)]
2148    struct God(bool);
2149
2150    fn god(world: &World, args: &Args<'_>, out: &mut ConsoleOut<'_>) -> Result<(), ConsoleError> {
2151        let mut god = world.resource_mut::<God>();
2152        god.0 = match args.get(0) {
2153            Some("on") => true,
2154            Some(_) => false,
2155            None => !god.0,
2156        };
2157        out.print(format_args!("god {}", if god.0 { "on" } else { "off" }));
2158        Ok(())
2159    }
2160
2161    /// The backtick, as a window gives it: a key, and the text it types.
2162    fn backtick() -> [Event; 3] {
2163        [
2164            key(Key::Grave, true),
2165            Event::Text('`'),
2166            key(Key::Grave, false),
2167        ]
2168    }
2169
2170    /// Types `line` in a frame and presses Enter, then runs a frame more,
2171    /// for the commands queued to apply.
2172    fn enter(app: &mut App, line: &str) {
2173        let mut events: Vec<Event> = line.chars().map(Event::Text).collect();
2174        events.extend(tap(Key::Enter));
2175        app.update(TICK, &events);
2176        app.update(TICK, &[]);
2177    }
2178
2179    /// Whether `line` is a record of the log, which the tests running beside
2180    /// this one may add at any time: `<time> <LEVEL> <target>: <message>`,
2181    /// its time `2026-11-14T10:00:00.000Z`.
2182    fn is_record(line: &str) -> bool {
2183        line.len() > 25 && line.as_bytes()[10] == b'T' && line.as_bytes()[23] == b'Z'
2184    }
2185
2186    /// The console's lines from the last `> line` echoed on, but the log's
2187    /// records.
2188    fn after(app: &mut App, line: &str) -> Vec<String> {
2189        let lines: Vec<String> = app
2190            .debug_tools()
2191            .console
2192            .lines()
2193            .map(String::from)
2194            .collect();
2195        let echo = format!("> {line}");
2196        let start = lines
2197            .iter()
2198            .rposition(|shown| *shown == echo)
2199            .unwrap_or_else(|| panic!("`{echo}` is not in the console: {lines:?}"));
2200        lines[start + 1..]
2201            .iter()
2202            .filter(|line| !is_record(line))
2203            .cloned()
2204            .collect()
2205    }
2206
2207    /// A console app: the `god` command, a player at (1, 2), and the
2208    /// prefab `rock` in the library.
2209    fn console_app() -> (App, Entity) {
2210        let mut app = app()
2211            .insert_resource(God::default())
2212            .add_console_command("god [on|off]", "makes the player invulnerable", god)
2213            // Starts with no name: logged, not added.
2214            .add_console_command("<god>", "nothing", god);
2215        *app.world_mut().resource_mut::<WindowSize>() = WindowSize(UVec2::new(1280, 720));
2216        let player = app
2217            .world_mut()
2218            .spawn()
2219            .with(Transform::at(Vec2::new(1.0, 2.0)))
2220            .with(Player)
2221            .id();
2222        let rock = r#"{"name": "rock", "components": {"Velocity": [3, 4]}}"#;
2223        let value = nadir_codec::json::parse(rock, nadir_codec::Limits::default()).expect("JSON");
2224        let file = nadir_codec::prefab::read(&value).expect("a prefab");
2225        app.world_mut()
2226            .resource_mut::<PrefabLibrary>()
2227            .insert("data/prefabs/rock.kbj", file);
2228        (app, player)
2229    }
2230
2231    #[test]
2232    fn the_backtick_shows_the_console_whose_line_runs_the_engine_s_commands() {
2233        use crate::Velocity;
2234
2235        let (mut app, player) = console_app();
2236        app.update(TICK, &backtick());
2237        assert!(texts(&app).iter().any(|text| text == "Console"));
2238        assert_eq!(
2239            app.debug_tools().console.line(),
2240            "",
2241            "the backtick is not typed"
2242        );
2243        // The game's keys are held back from the next frame on.
2244        assert!(
2245            app.debug_tools()
2246                .ui
2247                .as_ref()
2248                .is_some_and(DebugUi::wants_keyboard)
2249        );
2250        app.update(TICK, &[]);
2251        assert!(app.world().resource::<Input>().capture().keyboard);
2252
2253        enter(&mut app, "tp 10 -20");
2254        let at = app
2255            .world()
2256            .read::<Transform>()
2257            .get(player)
2258            .map(|at| at.position);
2259        assert_eq!(at, Some(Vec2::new(10.0, -20.0)));
2260        assert_eq!(
2261            after(&mut app, "tp 10 -20"),
2262            ["moved 1 player(s) to (10, -20)"]
2263        );
2264
2265        enter(&mut app, "spawn rock 5 6");
2266        let rocks: Vec<(Vec2, Vec2)> = {
2267            let world = app.world();
2268            let velocities = world.read::<Velocity>();
2269            let transforms = world.read::<Transform>();
2270            velocities
2271                .iter()
2272                .filter_map(|(entity, velocity)| {
2273                    Some((transforms.get(entity)?.position, velocity.0))
2274                })
2275                .collect()
2276        };
2277        // Spawned, then moved a tick at its velocity.
2278        assert_eq!(rocks.len(), 1, "{rocks:?}");
2279        assert_eq!(rocks[0].1, Vec2::new(3.0, 4.0));
2280        assert!(
2281            (rocks[0].0 - Vec2::new(5.0, 6.0)).length() < 0.2,
2282            "{rocks:?}"
2283        );
2284        assert!(after(&mut app, "spawn rock 5 6")[0].starts_with("spawned `rock` as "));
2285        // Both coordinates, or neither.
2286        enter(&mut app, "spawn rock 5");
2287        assert_eq!(
2288            after(&mut app, "spawn rock 5"),
2289            ["[x] and [y] go together: spawn <prefab> [x] [y]"]
2290        );
2291        enter(&mut app, "spawn boulder");
2292        let refused = after(&mut app, "spawn boulder");
2293        assert!(
2294            refused[0].starts_with("`boulder` is not spawned: "),
2295            "{refused:?}"
2296        );
2297
2298        // Twice the time: two ticks a frame.
2299        enter(&mut app, "timescale 2");
2300        app.update(TICK, &[]);
2301        assert_eq!(app.world().resource::<TickStats>().ticks, 2);
2302        enter(&mut app, "timescale 9");
2303        assert_eq!(
2304            after(&mut app, "timescale 9"),
2305            ["<scale>: `9` is not from 0.25 to 4: timescale <scale>"]
2306        );
2307        enter(&mut app, "timescale 1");
2308        app.update(TICK, &[]);
2309        assert_eq!(app.world().resource::<TickStats>().ticks, 1);
2310
2311        enter(&mut app, "schedule");
2312        let systems = after(&mut app, "schedule");
2313        assert!(
2314            systems.iter().any(|line| line.ends_with("nadir::movement")),
2315            "{systems:?}"
2316        );
2317        assert!(
2318            systems.iter().any(|line| line.ends_with(" count")),
2319            "{systems:?}"
2320        );
2321
2322        enter(&mut app, "level nowhere");
2323        let refused = after(&mut app, "level nowhere");
2324        assert!(
2325            refused
2326                .iter()
2327                .any(|line| line.starts_with("the level `nowhere` is not loaded: ")),
2328            "{refused:?}"
2329        );
2330
2331        enter(&mut app, "reload");
2332        assert!(after(&mut app, "reload")[0].starts_with("reading "));
2333
2334        let folder = env::temp_dir().join(format!("nadir-engine-console-{}", process::id()));
2335        let _ = fs::remove_dir_all(&folder);
2336        let trace = folder.join("deep").join("t.json");
2337        let line = format!("profile dump \"{}\"", trace.display());
2338        enter(&mut app, &line);
2339        assert_eq!(
2340            after(&mut app, &line)[0],
2341            format!("Wrote {}", trace.display())
2342        );
2343        assert!(
2344            fs::read_to_string(&trace)
2345                .expect("the trace")
2346                .contains("traceEvents")
2347        );
2348        fs::remove_dir_all(&folder).expect("remove the folder");
2349        // Without App::run, no folder for a trace without a path.
2350        enter(&mut app, "profile dump");
2351        assert_eq!(
2352            after(&mut app, "profile dump"),
2353            ["Traces are written only by App::run."]
2354        );
2355
2356        let target = "nadir_engine::debug_ui::tests::console";
2357        assert!(!log::enabled(Level::Debug, target));
2358        enter(&mut app, &format!("log level {target} DEBUG"));
2359        assert!(log::enabled(Level::Debug, target));
2360        log::set_target_level(target, None);
2361
2362        // The game's command, with its own usage.
2363        enter(&mut app, "god");
2364        assert!(app.world().resource::<God>().0);
2365        enter(&mut app, "god off");
2366        assert!(!app.world().resource::<God>().0);
2367        enter(&mut app, "god maybe");
2368        assert_eq!(
2369            after(&mut app, "god maybe"),
2370            ["[on|off]: `maybe` is not one of on, off: god [on|off]"]
2371        );
2372
2373        assert!(!app.debug_tools().quit());
2374        enter(&mut app, "quit");
2375        assert!(app.debug_tools().quit());
2376    }
2377
2378    #[test]
2379    fn the_console_shows_the_log_s_records_and_its_help_lists_every_command() {
2380        let (mut app, _) = console_app();
2381        warn!("a warning from before the console showed");
2382        app.update(TICK, &backtick());
2383        warn!("a warning while it shows");
2384        app.update(TICK, &[]);
2385        let lines: Vec<String> = app
2386            .debug_tools()
2387            .console
2388            .lines()
2389            .map(String::from)
2390            .collect();
2391        let before = lines
2392            .iter()
2393            .position(|line| line.ends_with("a warning from before the console showed"));
2394        let while_shown = lines
2395            .iter()
2396            .position(|line| line.ends_with("a warning while it shows"));
2397        assert!(before.is_some() && before < while_shown, "{lines:?}");
2398        assert!(
2399            lines.iter().any(|line| line.contains(" ERROR ")
2400                && line.contains("the console command is not added: `<god>`")),
2401            "{lines:?}"
2402        );
2403
2404        enter(&mut app, "help");
2405        let help = after(&mut app, "help");
2406        let names: Vec<&str> = help
2407            .iter()
2408            .filter_map(|line| line.split_whitespace().next())
2409            .collect();
2410        assert_eq!(
2411            names,
2412            [
2413                "help",
2414                "schedule",
2415                "spawn",
2416                "tp",
2417                "timescale",
2418                "level",
2419                "reload",
2420                "profile",
2421                "log",
2422                "quit",
2423                "god"
2424            ]
2425        );
2426        // Tab completes from the engine's commands and the game's.
2427        app.update(
2428            TICK,
2429            &[Event::Text('g'), key(Key::Tab, true), key(Key::Tab, false)],
2430        );
2431        assert_eq!(app.debug_tools().console.line(), "god ");
2432        // Closed by the backtick, which it does not type.
2433        app.update(TICK, &backtick());
2434        assert_eq!(app.debug_tools().console.line(), "god ");
2435        assert!(!texts(&app).iter().any(|text| text == "Console"));
2436    }
2437
2438    #[test]
2439    fn the_backtick_is_typed_into_no_debug_field_as_it_shows_or_hides_the_console() {
2440        let (mut app, _) = console_app();
2441        // The game's window, its field with the keyboard.
2442        app.update(TICK, &tap(Key::F8));
2443        app.update(TICK, &click(FIELD));
2444        app.update(TICK, &[Event::Text('a')]);
2445        assert_eq!(app.world().resource::<Notes>().text, "a");
2446        // The backtick shows the console, which takes the keyboard.
2447        app.update(TICK, &backtick());
2448        app.update(TICK, &[Event::Text('b')]);
2449        assert_eq!(app.world().resource::<Notes>().text, "a");
2450        assert_eq!(app.debug_tools().console.line(), "b");
2451        // Back in the game's field, the backtick hides the console.
2452        app.update(TICK, &click(FIELD));
2453        app.update(TICK, &backtick());
2454        app.update(TICK, &[Event::Text('c')]);
2455        assert_eq!(app.world().resource::<Notes>().text, "ac");
2456        assert!(!texts(&app).iter().any(|text| text == "Console"));
2457        // Text that comes after another key's press is typed: a key
2458        // pressed after the toggle, or a dead key's accent with it.
2459        app.update(TICK, &backtick());
2460        app.update(TICK, &click(FIELD));
2461        app.update(
2462            TICK,
2463            &[
2464                key(Key::Grave, true),
2465                key(Key::Grave, false),
2466                key(Key::E, true),
2467                Event::Text('e'),
2468                key(Key::E, false),
2469            ],
2470        );
2471        assert_eq!(app.world().resource::<Notes>().text, "ace");
2472        assert!(!texts(&app).iter().any(|text| text == "Console"));
2473    }
2474
2475    /// The frame's sprites of `color`: where each is, how large, and how
2476    /// turned.
2477    fn colored(app: &App, color: Color) -> Vec<(Vec2, Vec2, f32)> {
2478        let frame = app.world().resource::<RenderFrame>();
2479        frame
2480            .sprites
2481            .iter()
2482            .filter(|sprite| sprite.color == color)
2483            .map(|sprite| (sprite.position, sprite.size, sprite.rotation))
2484            .collect()
2485    }
2486
2487    /// The rect around unturned sprites with their pivots at their
2488    /// top-left corners.
2489    fn around(sprites: &[(Vec2, Vec2, f32)]) -> Option<Rect> {
2490        let mut rects = sprites
2491            .iter()
2492            .map(|&(at, size, _)| Rect::new(at, at + size));
2493        let first = rects.next()?;
2494        Some(rects.fold(first, |all, rect| {
2495            Rect::new(all.min.min(rect.min), all.max.max(rect.max))
2496        }))
2497    }
2498
2499    /// The tile layer a frame system of the test draws.
2500    struct Chunked(Handle<nadir_render::TileLayer>);
2501
2502    fn draw_chunked(world: &World, _: &nadir_core::time::Frame) {
2503        let tiles = world.resource::<Chunked>().0;
2504        let mut frame = world.resource_mut::<RenderFrame>();
2505        frame
2506            .tile_layers
2507            .push(nadir_render::TileLayerDraw::new(tiles));
2508    }
2509
2510    #[test]
2511    fn f4_draws_the_overlays_ticked_into_the_world_and_nothing_once_closed() {
2512        use nadir_collision::{Shape, TileGrid};
2513        use nadir_core::IVec2;
2514        use nadir_render::{TileLayer, TileLayers, TileSet};
2515
2516        use crate::Collisions;
2517
2518        let mut app = app().add_frame_system(FrameStage::Extract, "chunked", draw_chunked);
2519        *app.world_mut().resource_mut::<WindowSize>() = WindowSize(UVec2::new(1280, 720));
2520        let world = app.world_mut();
2521        world
2522            .spawn()
2523            .with(Transform::at(Vec2::new(40.0, 40.0)))
2524            .with(Collider::solid(Shape::Aabb {
2525                half: Vec2::new(5.0, 3.0),
2526            }));
2527        world
2528            .spawn()
2529            .with(Transform::at(Vec2::new(-100.0, 50.0)))
2530            .with(Collider::trigger(Shape::Circle { radius: 8.0 }));
2531        // Out of the view, (-240, -135) to (240, 135): not drawn.
2532        world
2533            .spawn()
2534            .with(Transform::at(Vec2::new(1000.0, 0.0)))
2535            .with(Collider::solid(Shape::Aabb {
2536                half: Vec2::splat(4.0),
2537            }));
2538        let mut grid = TileGrid::new(4, 4, 16.0, Vec2::new(-64.0, -64.0));
2539        grid.set_solid(IVec2::new(1, 2), true);
2540        world.resource_mut::<Collisions>().set_grid(grid);
2541        let tileset = TileSet {
2542            texture: game_box(),
2543            columns: 1,
2544            rows: 1,
2545        };
2546        let layer = TileLayer::new(tileset, UVec2::new(40, 10), 16.0, Vec2::new(-200.0, -100.0));
2547        let tiles = world.resource_mut::<TileLayers>().add(layer);
2548        world.insert_resource(Chunked(tiles));
2549
2550        app.update(TICK, &[]);
2551        assert!(colored(&app, draw::SOLID).is_empty(), "closed");
2552        app.update(TICK, &tap(Key::F4));
2553        app.update(TICK, &[]);
2554        // The colliders, the triggers and the grid, at first: a box's edges
2555        // inside it, a line wide; a circle's sides; a solid cell, filled.
2556        let solid = colored(&app, draw::SOLID);
2557        assert_eq!(solid.len(), 4, "the box out of view is not drawn");
2558        let expected = Rect::new(Vec2::new(35.0, 37.0), Vec2::new(45.0, 43.0));
2559        assert_eq!(around(&solid), Some(expected));
2560        assert!(
2561            solid
2562                .iter()
2563                .all(|&(_, size, _)| size.x == 1.0 || size.y == 1.0)
2564        );
2565        assert_eq!(colored(&app, draw::TRIGGER).len(), 24);
2566        let grid = colored(&app, draw::GRID);
2567        let cell = Rect::new(Vec2::new(-48.0, -32.0), Vec2::new(-32.0, -16.0));
2568        assert_eq!(around(&grid), Some(cell));
2569        assert_eq!(grid.len(), 1);
2570        for color in [draw::HASH, draw::CHUNK, draw::CAMERA] {
2571            assert!(colored(&app, color).is_empty());
2572        }
2573
2574        // A click on the colliders' box, the first row's, unticks them.
2575        app.update(TICK, &click(Vec2::new(960.0, 31.0)));
2576        app.update(TICK, &[]);
2577        assert!(colored(&app, draw::SOLID).is_empty());
2578        assert_eq!(colored(&app, draw::TRIGGER).len(), 24);
2579
2580        let overlays = &mut app.debug_tools().overlays;
2581        overlays.hash = true;
2582        overlays.chunks = true;
2583        overlays.camera = true;
2584        app.update(TICK, &[]);
2585        // The hash's cells of 64 that hold a collider in the view, and how
2586        // many each holds.
2587        let hash = colored(&app, draw::HASH);
2588        assert_eq!(hash.len(), 8);
2589        let counts: Vec<(Vec2, String)> = app
2590            .world()
2591            .resource::<RenderFrame>()
2592            .texts
2593            .iter()
2594            .filter(|(draw, _)| draw.color == draw::HASH)
2595            .map(|(draw, text)| (draw.position, text.to_string()))
2596            .collect();
2597        assert_eq!(
2598            counts,
2599            [
2600                (Vec2::new(-126.0, 2.0), "1".to_string()),
2601                (Vec2::new(2.0, 2.0), "1".to_string())
2602            ]
2603        );
2604        // The layer's first chunk of 32 tiles; the second is out of view.
2605        let chunk = colored(&app, draw::CHUNK);
2606        let expected = Rect::new(Vec2::new(-200.0, -100.0), Vec2::new(312.0, 60.0));
2607        assert_eq!((chunk.len(), around(&chunk)), (4, Some(expected)));
2608        // The camera's cross, two lines turned, and its view.
2609        let camera = colored(&app, draw::CAMERA);
2610        let (cross, view): (Vec<_>, Vec<_>) = camera
2611            .iter()
2612            .partition(|&&(_, size, _)| size == Vec2::new(12.0, 1.0));
2613        assert_eq!(cross.len(), 2);
2614        let expected = Rect::new(Vec2::new(-240.0, -135.0), Vec2::new(240.0, 135.0));
2615        assert_eq!((view.len(), around(&view)), (4, Some(expected)));
2616
2617        // Closed, it draws nothing.
2618        app.update(TICK, &tap(Key::F4));
2619        for color in [
2620            draw::TRIGGER,
2621            draw::GRID,
2622            draw::HASH,
2623            draw::CHUNK,
2624            draw::CAMERA,
2625        ] {
2626            assert!(colored(&app, color).is_empty());
2627        }
2628    }
2629
2630    #[test]
2631    fn a_box_off_the_pixel_grid_is_a_closed_ring_on_it_and_a_thin_one_a_fill() {
2632        use nadir_collision::Shape;
2633
2634        let mut app = app();
2635        app.world_mut()
2636            .spawn()
2637            .with(Transform::at(Vec2::new(40.2, 40.2)))
2638            .with(Collider::solid(Shape::Aabb {
2639                half: Vec2::new(5.74, 3.74),
2640            }));
2641        app.world_mut()
2642            .spawn()
2643            .with(Transform::at(Vec2::new(-20.0, 0.0)))
2644            .with(Collider::trigger(Shape::Aabb {
2645                half: Vec2::new(0.4, 5.0),
2646            }));
2647        app.update(TICK, &tap(Key::F4));
2648        app.update(TICK, &[]);
2649        // Its corners on whole pixels, its four edges meeting and never
2650        // overlapping: the renderer, which puts each sprite's corner on a
2651        // whole pixel, draws them as they are.
2652        let ring = colored(&app, draw::SOLID);
2653        assert_eq!(ring.len(), 4);
2654        let whole = |v: Vec2| v.x.fract() == 0.0 && v.y.fract() == 0.0;
2655        assert!(ring.iter().all(|&(at, size, _)| whole(at) && whole(size)));
2656        let expected = Rect::new(Vec2::new(34.0, 36.0), Vec2::new(46.0, 44.0));
2657        assert_eq!(around(&ring), Some(expected));
2658        let area: f32 = ring.iter().map(|&(_, size, _)| size.x * size.y).sum();
2659        assert_eq!(area, 12.0 * 8.0 - 10.0 * 6.0);
2660        // Too thin for two edges: one sprite, a pixel wide at least.
2661        let thin = colored(&app, draw::TRIGGER);
2662        let expected = Rect::new(Vec2::new(-20.0, -5.0), Vec2::new(-19.0, 5.0));
2663        assert_eq!((thin.len(), around(&thin)), (1, Some(expected)));
2664    }
2665
2666    #[test]
2667    fn a_child_s_collider_is_drawn_where_its_root_is_drawn_with_its_offset() {
2668        use nadir_collision::Shape;
2669
2670        use crate::{Parent, Velocity};
2671
2672        let mut app = app();
2673        let root = app
2674            .world_mut()
2675            .spawn()
2676            .with(Transform::at(Vec2::ZERO))
2677            .with(Velocity(Vec2::new(120.0, 0.0)))
2678            .with(Sprite::new(game_box(), Vec2::new(8.0, 8.0)))
2679            .id();
2680        app.world_mut()
2681            .spawn()
2682            .with(Transform::at(Vec2::ZERO))
2683            .with(Parent {
2684                entity: root,
2685                offset: Vec2::new(20.0, 0.0),
2686            })
2687            .with(Collider::trigger(Shape::Circle { radius: 4.0 }));
2688        app.update(TICK, &tap(Key::F4));
2689        // Three frames a tick: the root is drawn between its last two
2690        // ticks, and so is its child's collider.
2691        for _ in 0..7 {
2692            app.update(TICK / 3, &[]);
2693            let drawn = app
2694                .world()
2695                .resource::<RenderFrame>()
2696                .sprites
2697                .iter()
2698                .find(|sprite| sprite.texture == game_box())
2699                .map(|sprite| sprite.position)
2700                .expect("the root's sprite");
2701            let sides = colored(&app, draw::TRIGGER);
2702            assert_eq!(sides.len(), 24);
2703            let center = sides.iter().fold(Vec2::ZERO, |sum, &(at, _, _)| sum + at) / 24.0;
2704            let expected = drawn + Vec2::new(20.0, 0.0);
2705            assert!(
2706                (center - expected).length() < 1e-3,
2707                "{center:?} {expected:?}"
2708            );
2709        }
2710    }
2711
2712    #[test]
2713    fn f5_pauses_f6_steps_and_f7_scales_the_game_s_time_saying_so_in_a_corner() {
2714        let mut app = app();
2715        let ticks = |app: &App| app.world().resource::<TickStats>().ticks;
2716        let time = |app: &App| app.world().resource::<RenderFrame>().time;
2717        let label = |app: &App| -> Vec<String> {
2718            texts(app)
2719                .into_iter()
2720                .filter(|text| text.starts_with("paused") || text.starts_with("time x"))
2721                .collect()
2722        };
2723        app.update(TICK, &[]);
2724        app.update(TICK, &[]);
2725        assert_eq!(ticks(&app), 1);
2726        assert!(label(&app).is_empty());
2727        // F5 pauses in the frame it is pressed: no tick, the frame's time
2728        // held, which holds the tiles and the clips.
2729        let held = time(&app);
2730        app.update(TICK, &tap(Key::F5));
2731        assert_eq!((ticks(&app), time(&app)), (0, held));
2732        assert_eq!(label(&app), ["paused"]);
2733        // Under the windows, which cover the corner if they reach it.
2734        app.update(TICK, &tap(Key::F1));
2735        let shown = texts(&app);
2736        let at = |text: &str| {
2737            shown
2738                .iter()
2739                .position(|shown| shown == text)
2740                .unwrap_or_else(|| panic!("no {text:?} in {shown:?}"))
2741        };
2742        assert!(at("paused") < at("Stats"), "{shown:?}");
2743        app.update(TICK, &tap(Key::F1));
2744        app.update(TICK, &[]);
2745        assert_eq!((ticks(&app), time(&app)), (0, held));
2746        // F6 steps a tick, and a held F6's repeats step on.
2747        app.update(TICK, &tap(Key::F6));
2748        assert_eq!(ticks(&app), 1);
2749        assert!(time(&app) > held);
2750        let repeat = Event::Key {
2751            key: Key::F6,
2752            pressed: true,
2753            repeat: true,
2754        };
2755        app.update(
2756            TICK,
2757            &[key(Key::F6, true), repeat, repeat, key(Key::F6, false)],
2758        );
2759        assert_eq!(ticks(&app), 3);
2760        // F5 runs it again, and the label goes.
2761        app.update(TICK, &tap(Key::F5));
2762        assert_eq!(ticks(&app), 1);
2763        assert!(label(&app).is_empty());
2764        // F7 doubles it, and Shift+F7 halves it again.
2765        app.update(TICK, &tap(Key::F7));
2766        assert_eq!(ticks(&app), 2);
2767        assert_eq!(label(&app), ["time x2"]);
2768        app.update(
2769            TICK,
2770            &[
2771                key(Key::LeftShift, true),
2772                key(Key::F7, true),
2773                key(Key::F7, false),
2774                key(Key::LeftShift, false),
2775            ],
2776        );
2777        assert_eq!(ticks(&app), 1);
2778        assert!(label(&app).is_empty());
2779        // The console's `timescale` sets the same scale.
2780        app.debug_tools().time.scale = 0.5;
2781        app.update(TICK, &[]);
2782        assert_eq!(label(&app), ["time x0.5"]);
2783    }
2784
2785    #[test]
2786    fn a_step_takes_the_replay_s_next_tick() {
2787        use crate::Replay;
2788
2789        // A recording of Jump held for 12 ticks.
2790        let mut recorder = InputRecorder::<Act>::new().expect("a valid set");
2791        let map = actions();
2792        let mut input = Input::new();
2793        let mut state = ActionState::new();
2794        input.handle(&key(Key::Space, true));
2795        for _ in 0..12 {
2796            input.latch(&map, &mut state);
2797            recorder.record(&state);
2798        }
2799        let bytes: &'static [u8] = Box::leak(recorder.into_bytes().into_boxed_slice());
2800        let player = InputPlayer::<Act>::new(bytes).expect("a replay of Act");
2801        let mut app = app().play_replay(player);
2802        let played = |app: &App| match *app.world().resource::<Replay>() {
2803            Replay::Playing { ticks } => ticks,
2804            ref other => panic!("{other:?}"),
2805        };
2806        app.update(TICK, &[]);
2807        app.update(TICK, &tap(Key::F5));
2808        let at = played(&app);
2809        let held = app.world().resource::<Seen>().jump_held;
2810        for step in 1..=3 {
2811            app.update(TICK, &tap(Key::F6));
2812            app.update(TICK, &[]);
2813            assert_eq!(played(&app), at + step);
2814            assert_eq!(app.world().resource::<Seen>().jump_held, held + step as u32);
2815        }
2816    }
2817
2818    #[test]
2819    fn a_steady_frame_of_every_overlay_and_the_label_allocates_nothing() {
2820        use nadir_collision::Shape;
2821
2822        let mut app = app();
2823        for at in [Vec2::new(40.0, 40.0), Vec2::new(-60.0, 10.0)] {
2824            app.world_mut()
2825                .spawn()
2826                .with(Transform::at(at))
2827                .with(crate::Velocity(Vec2::new(5.0, 0.0)))
2828                .with(Collider::solid(Shape::Circle { radius: 6.0 }));
2829        }
2830        app.update(TICK, &tap(Key::F4));
2831        let overlays = &mut app.debug_tools().overlays;
2832        overlays.hash = true;
2833        overlays.chunks = true;
2834        overlays.camera = true;
2835        app.update(TICK, &tap(Key::F7));
2836        for _ in 0..10 {
2837            app.update(TICK, &[]);
2838        }
2839        let start = nadir_platform::thread_alloc_counts();
2840        for _ in 0..20 {
2841            app.update(TICK, &[]);
2842        }
2843        let allocated = nadir_platform::thread_alloc_counts().since(start);
2844        assert!(!colored(&app, draw::SOLID).is_empty());
2845        assert!(texts(&app).iter().any(|text| text == "time x2"));
2846        assert_eq!(allocated, nadir_platform::AllocCounts::default());
2847    }
2848
2849    #[test]
2850    fn the_time_scale_scales_each_frame_s_length() {
2851        let mut tools = DebugTools::new();
2852        assert_eq!(tools.game_time(TICK), TICK);
2853        tools.time.scale = 0.5;
2854        assert_eq!(
2855            tools.game_time(Duration::from_millis(20)),
2856            Duration::from_millis(10)
2857        );
2858        tools.time.scale = 4.0;
2859        assert_eq!(tools.game_time(Duration::MAX), Duration::MAX);
2860    }
2861}