Expand description
The Nadir game engine: App and its main loop, the engine’s
components and systems, and the subsystems a game uses.
Nadir is a 2D engine for
top-down games on Windows, macOS and Linux, written in Rust with no
third-party crates. This crate is its facade, the one a game depends on:
its package is nadir_engine, and code names it nadir. It re-exports
the subsystems as modules, and prelude holds what most games use. A
game needs only this crate:
use nadir::prelude::*;
fn main() -> Result<(), nadir::Error> {
App::new(Config::default())
.add_fixed_system(FixedStage::Gameplay, "hello", |_, tick| {
if tick.index == 0 {
nadir::log::info!("the first tick");
}
})
.run()
}This is version 0.4, and the API will change before 1.0. The engine
draws and plays sound on Linux (X11, ALSA). On Windows and macOS a game
runs, but its window stays empty until roadmap tasks M2.6 and M2.7, and
it plays no sound until M6.4 and M6.5. Text is drawn in the world
(nadir::render::Font, RenderFrame::texts), and on the window with
the UI’s sprites (RenderFrame::ui); development builds show a
debug UI of the game’s own windows and the engine’s
debug tools; gamepads and saves are not built yet. The
README
is a guide to how the parts fit together, with a game that walks a hero
about a tile map.
§The app and the main loop
App holds the game’s Config, its world and its systems. A game
adds resources, actions and systems with its builder methods, sets its
world up through App::world_mut, and calls App::run, which opens
the log file, the window and the audio output and runs the main loop
until the window is closed. Each frame, the loop:
- hands the window’s
Events toInput; - runs the ticks that are due,
TICK_HZa second however fast the frames come: each latches the game’s actions, then runs the tick stages; - sets
TickStats, and runs the frame stages, which fill theRenderFrame; - draws it, and makes the assets that the workers have loaded.
A frame counts for at most 250 ms: after a stall the simulation falls behind real time rather than running a burst of ticks.
App::updateruns steps 1 to 3 without a window: tests, benchmarks and headless runs call it themselves.App::offscreendraws frames with no window:Offscreen::framereturns each frame’s pixels, for recordings.Erroris what endsApp::run.
§The world, systems and stages
The game’s state is a World of entities, components and
resources, from ecs. Systems are plain functions: a
FixedSystem, fn(&World, &Tick), runs in a
FixedStage of each tick, added with
App::add_fixed_system; a FrameSystem,
fn(&World, &Frame), in a FrameStage of each
frame, added with App::add_frame_system. They run in stage order,
then in the order they were added, after the engine’s own, which
App lists with the resources the engine adds.
App::insert_resourceadds a resource; systems read it withWorld::resourceand write it withWorld::resource_mut.- A component implements
Component, and is registered before use: withApp::register_componentif it is reflected (defined withscene::reflect_struct!and its siblings), or withWorld::register. - Systems spawn, despawn, add and remove through
Commands, which apply after the tick’s stages or the frame’s. App::add_eventadds an event type, the resourceEvents: tick systems read a tick’s events, and frame systems all those since the last frame.
§The engine’s components
| Component | What it is |
|---|---|
Transform | Where an entity is, in world pixels, +Y down |
Velocity | How fast it moves, in pixels a second: the engine moves it each tick |
Collider | What it collides with, solid or a trigger |
Sprite | What it looks like, drawn at its Transform |
Animator | Plays a Clip on its Sprite |
Facing | Which way it faces: facing left mirrors its Sprite |
Parent | Puts it at another entity’s position, plus an offset |
Player | A tag for the entity the player controls |
SaveId | Its id in saves, which come with roadmap M9.4 |
PrevTransform | Where it was at the start of the last tick, for drawing between ticks: the engine keeps it |
AudioListener | Where the game hears from, in place of the camera |
AudioEmitter | A sound that plays at it, and follows it |
MusicArea | A box whose music plays while the listener is in it |
Transform, Velocity, Player, SaveId, Facing,
Sprite, Collider and Animator are reflected, so prefabs and
levels can give them; Parent, AudioListener, AudioEmitter
and MusicArea are not yet (M9.4 brings Parent), and
PrevTransform is the engine’s own, and is never in data. A
Sprite is written with its texture’s path, and a prefab may name a
frame of a cooked atlas instead, {"atlas": "atlas/sprites.kbj", "sprite": "sprites/hero", "frame": 0}; a Collider’s layers by the
names App::collision_layers gives them, ["World", "People"]; an
Animator as its clip’s name in the Clips. The world hash leaves
out what nadir::animate writes: a sprite’s texture, uv, size, pivot
and flip.x (ADR-0038).
§Prefabs
A prefab is a set of component values, cooked from
assets/data/prefabs/<name>.jsonc to data/prefabs/<name>.kbj, that
may extend another. The PrefabLibrary
resource loads prefabs and their bases, and spawns entities of them;
loading_context gives it a reflect context with what the engine’s
components need, the asset server, the clips and the collision layers,
and reflect_context one for writing them, as a hash or a save
does.
§Levels
The cook makes a level file, levels/<name>.klvl, of each level of an
LDtk project. App::load_level (or load_level on a world) loads
one in place of the last: its prefabs are read and checked before it
returns, its assets load in Scope::Level, its tall tiles and entities
spawn, its tile layers go into the TileLayers
and its grid into the Collisions, and the engine draws its tile
layers each frame, its background the clear colour. CurrentLevel
says what it made, and the next load removes it whole; a
LevelError says why one did not load (ADR-0038).
§Collision
Collisions is the resource of the colliders, which the engine
rebuilds and moves each tick: systems query its
world, a CollisionWorld,
and turn the collider indices it gives into entities with
Collisions::entity. Its tile grid, Collisions::set_grid, is how
tiles collide. TriggerEnter and TriggerExit are the events of
colliders that start and stop overlapping a trigger. collision has
the shapes, the layers and the queries.
§Animation
A Clip is a list of ClipFrames, each a region of a texture shown
for a time, maybe with its own Placement. It loops or plays once
(Playback). The resource Clips keeps the clips by handle and
name, and Clips::add_atlas adds a cooked atlas’s, from Aseprite’s
tags. An Animator plays one on its entity’s Sprite, and sends
AnimationFinished when a clip that plays once ends. ClipError
says why a clip could not be made or added.
§Sound
The resource Audio, from audio, is the game’s
handle on the mixer: it plays a Sound, cooked to a
.kpcm or .qoa file, on a Bus, at a position in the
world or not, and crossfades from one Music track to
another. Config::volumes sets each bus’s volume as the game starts
(Volumes). App::run opens the audio output with it, while
App::update and App::offscreen play nothing, and
App::take_mixer hands a test the mixer to render itself.
The engine’s nadir::sound plays the world’s sound each frame. An
AudioEmitter plays its sound at its entity, panned and fading by
where it is from the listener: the first AudioListener, or else the
camera. When the listener comes into a MusicArea, the music
crossfades to its track, and AudioState says whose track was sent
last. An emitter and an area wait for what they play to load; a sound
played once as something happens, a footstep say, is lost if it has
not loaded, so load it first with
AssetServer::load_now.
§Input, drawing and assets
input: the game’s actions. AnActionSetnames them, anActionMapbinds keys and mouse buttons to them, andApp::add_actionsadds both; tick systems read the resourceActionState.render: the resourceRenderFrame, with itsCamera2D, which frame systems fill and the loop draws; the resourceTileLayers, whose layers a frame names inRenderFrame::tile_layers; the texts a frame draws in the world, inRenderFrame::texts; the UI it draws on the window, inRenderFrame::ui; and theTexture,AtlasandFontassets.assets: the resourceAssetServer, which loads fromConfig::assetson worker threads, and frees assets byScope.
§Hot reload
With the dev feature, App::run reloads the files that change while
the game runs, such as those cargo xtask cook --watch cooks again, and
nadir-render’s shaders, from its shaders/ folder
(SHADER_DIR). Watchers look at the files’ times
of change every 250 ms, and an edit is drawn a frame or two after it is
seen; a shader edited before the loop starts is seen at its next save.
The handles the game holds stay good (ADR-0043):
- a texture’s handle draws its new texels;
- an atlas’s clips are replaced by name under their handles, so its animators play the new frames on from their time;
- a prefab is replaced in the
PrefabLibraryunder its name; - the current level is made again from its files, behind the handles of its assets, tile layers and clips, once its file, an atlas or a prefab changed; its entities are spawned anew;
- a program is rebuilt from its shader files.
A file that fails to load, a level that cannot be made again, or shaders
that do not compile or fit their program are logged, and what they
would replace stays. Each reload is logged with its time. What the game
copied out of an asset, such as an atlas’s regions into its own sprites,
and the entities it spawned of prefabs itself, do not change.
App::offscreen and App::update never reload, so recordings stay
the same, and builds without dev hold none of the reload.
§The debug UI
With the dev feature, a game adds windows of its own to a debug UI
with App::add_debug_window, each shown and hidden by a key, and fills
them each frame with the widgets of nadir::debug, the nadir-debug
crate: labels, buttons, checkboxes, sliders, text fields, lists, trees,
plots. They are drawn over the game’s UI in the engine’s own pixel
font; they drag, collapse, resize and scroll; while one has the
pointer, or one of their text fields the keys, the game’s actions do not
see them; and App::run keeps their places in debug_ui.jsonc in the
game’s settings folder. The resource WindowSize is the window’s size.
The engine’s own windows are the stats overlay (F1), the inspector (F2),
the profiler (F3), the debug drawing (F4), whose overlays draw into the
world, and the console (the backtick), which runs the engine’s commands
and those a game adds with App::add_console_command. F5 pauses the
game’s time and runs it again, F6 steps it a tick, and F7 and Shift+F7
scale it, a label at the top-right saying so.
use nadir::prelude::*;
/// A note the developer types in.
#[derive(Default)]
struct Note(String);
let app = App::new(Config::default())
.insert_resource(Note::default())
.add_debug_window(
Key::F8,
"Notes",
Rect::new(Vec2::new(16.0, 16.0), Vec2::new(216.0, 116.0)),
|world, ui| {
ui.text_input("Note", &mut world.resource_mut::<Note>().0);
let ticks = world.resource::<TickStats>().ticks;
ui.label(format_args!("{ticks} ticks this frame"));
},
);§Replays and determinism
App::play_replay plays a recording of the game’s actions, made with
an InputRecorder, in place of the live input,
and the resource Replay says how far it got. world_hash and
App::world_hash hash the reflected components, so that a test can
check that a replay reaches the same world, tick after tick.
§The modules
| Module | Crate | What it holds |
|---|---|---|
assets | nadir-assets | Handles, the asset server, sources and scopes |
audio | nadir-audio | Sounds, music, the mixer, its buses and voices |
collision | nadir-collision | Shapes, layers, the tile grid, move-and-slide, triggers, queries |
ecs | nadir-ecs | The world, components, resources, events, commands, the schedule |
input | nadir-input | Actions, bindings, their state, replays |
render | nadir-render | The frame to draw, sprites, tiles, the camera, textures, atlases |
scene | nadir-scene | Reflection: the macros that define reflected types, and the type registry |
log | nadir-core | The log macros, error! to trace! |
cli | nadir-core | A small parser of command lines |
Vec2, IVec2, UVec2,
Rect, Color, Key,
MouseButton, Pcg32 and the
time types Tick, Frame and
Stopwatch are in the prelude; the rest of
nadir-core, such as its matrices and linear colours, is a dependency
of its own. The OS
layer, the GPU layer and the codecs are the engine’s own, and a game
does not use them, except for the window’s Events, which
App::update takes.
§Examples
A frame of one tick moves an entity by its velocity, with no window:
use std::time::Duration;
use nadir::prelude::*;
let mut app = App::new(Config::default());
let ball = app
.world_mut()
.spawn()
.with(Transform::at(Vec2::ZERO))
.with(Velocity(Vec2::new(60.0, 0.0)))
.id();
// 1/60 of a second, rounded up to the nanosecond: one tick.
app.update(Duration::from_nanos(16_666_667), &[]);
let at = app.world().read::<Transform>().get(ball).map(|it| it.position);
assert_eq!(at, Some(Vec2::new(1.0, 0.0)));A trigger counts who steps on it, in a tick system after the engine’s
nadir::triggers:
use std::time::Duration;
use nadir::prelude::*;
/// How many times something stepped on the plate.
#[derive(Default)]
struct Steps(usize);
fn count_steps(world: &World, _tick: &Tick) {
let entered = world.resource::<Events<TriggerEnter>>().tick_events().len();
world.resource_mut::<Steps>().0 += entered;
}
let mut app = App::new(Config::default())
.insert_resource(Steps::default())
.add_fixed_system(FixedStage::PostMovement, "count_steps", count_steps);
let world = app.world_mut();
// A plate 8 pixels across at x = 20.
world
.spawn()
.with(Transform::at(Vec2::new(20.0, 0.0)))
.with(Collider::trigger(Shape::Aabb { half: Vec2::splat(4.0) }));
// Someone who walks right across it, at 2 pixels a tick.
world
.spawn()
.with(Transform::at(Vec2::ZERO))
.with(Velocity(Vec2::new(120.0, 0.0)))
.with(Collider::solid(Shape::Aabb { half: Vec2::splat(2.0) }));
for _ in 0..30 {
app.update(Duration::from_nanos(16_666_667), &[]);
}
assert_eq!(app.world().resource::<Steps>().0, 1);An animator shows the frame of its clip that the simulated time has reached. The texture need not have loaded: the clip writes its regions into the sprite all the same.
use std::time::Duration;
use nadir::prelude::*;
let mut app = App::new(Config::default());
let world = app.world_mut();
let sheet = world.resource_mut::<AssetServer>().load::<Texture>("hero.qoi");
// The sheet's left and right halves, 100 ms each, over and over.
let half = |x: f32| {
let uv = Rect::new(Vec2::new(x, 0.0), Vec2::new(x + 0.5, 1.0));
ClipFrame::new(sheet, uv, Duration::from_millis(100))
};
let clip = Clip::new(vec![half(0.0), half(0.5)], Playback::Loop);
let walk = world.resource_mut::<Clips>().add(clip);
let hero = world
.spawn()
.with(Transform::at(Vec2::ZERO))
.with(Sprite::new(sheet, Vec2::new(16.0, 16.0)))
.with(Animator::new(walk))
.id();
// 9 ticks, 150 ms: the second frame shows.
for _ in 0..9 {
app.update(Duration::from_nanos(16_666_667), &[]);
}
let uv = app.world().read::<Sprite>().get(hero).map(|it| it.uv.min.x);
assert_eq!(uv, Some(0.5));§Using it well
- Threads. The world, the systems, the window and the GPU all live
on the thread that runs the app, and systems run one at a time. The
asset server reads and decodes files on 1 to 4 worker threads of its
own, and the mixer runs on the audio output’s thread, which
Audio’s commands reach through a queue. CallApp::runon the main thread: macOS opens windows only there. - Borrows. Storages and resources are borrowed at run time. A system that borrows one mutably while it is borrowed panics, with the system’s name and the type.
- Determinism. Ticks have a fixed length, and the clock counts
frames’ lengths exactly, so the same frames give the same ticks. Keep
gameplay in tick systems. What frames set, such as an
Animator’s time, whether an asset has loaded, and the pointer and the wheel differ from run to run:world_hashgives the conditions under which a replay reproduces the world. - Assets. Loads finish only in drawn frames, so
App::updatefinishes none, and a tick system must not depend on whether an asset has loaded. Before the window opens there is no GPU device, so only assets that need none, such as anAtlas, can be made then, withAssetServer::load_now. - Allocation. The engine’s own systems and drawing do not allocate in
a steady frame: its tests count a frame of 10,000 animated sprites and
a tile layer with the
devfeature’s counter. Systems are function pointers; keep their buffers in resources and reuse them. - Errors and logs.
App::runlogs anErrorand shows it to the player before it returns it: on standard error on Linux, and in a message box on Windows or an alert on macOS. Thelogmacros write to standard error, andApp::runalso writes the log tonadir.login the game’s logs folder, named byConfig::studioandConfig::game. - Platforms. On Linux the engine needs X11, or XWayland, and OpenGL
3.3, which it loads at run time, and plays sound through ALSA’s
libasound.so.2, loaded at run time too: without it the game is silent. On Windows and macOS it has no OpenGL context yet:App::runlogs that and runs the game without drawing, and so without reloading, andApp::offscreenfails; nor has it audio output, so the game is silent there.
§Features
dev: development builds. The assets are the loose files ofConfig::assets, not the cook’s pack there, which builds withoutdevread when it is there (ADR-0041). A texture that failed to load shows a placeholder rather than nothing, and the global allocator counts allocations: the resourceFrameAllocsholds the last frame’s, andthread_alloc_countsandprocess_alloc_countsgive the counts so far, asAllocCounts. No other crate in the program may then declare a#[global_allocator].App::runreloads what changes while it runs (“Hot reload”, above), and the game’s debug windows show (“The debug UI”, above), withnadir::debug,App::add_debug_window,DebugWindowandWindowSize. Turn it on from a feature of the game, never from a normal dependency, so that release builds leave it out.
Re-exports§
pub use nadir_debug as debug;pub use nadir_assets as assets;pub use nadir_audio as audio;pub use nadir_collision as collision;pub use nadir_ecs as ecs;pub use nadir_input as input;pub use nadir_render as render;pub use nadir_scene as scene;
Modules§
- cli
- A minimal command-line argument parser for
xtask, the cook tool and the game binary. - log
- Logging: the [
error!], [warn!], [info!], [debug!] and [trace!] macros, a level filter, and three sinks. - prelude
- What most games use, for one
use nadir::prelude::*.
Structs§
- Alloc
Counts - Counts of heap use, on one thread or in the whole process.
- Animation
Finished - A clip that plays once reached its end in this frame:
nadir::animatesends it, first in the frame stageAnimate. - Animator
- Plays a
Clipon its entity’sSprite. - App
- A game: its configuration, its
Worldof entities and resources, and its systems in stages.App::runopens the log file and the window, and runs the main loop;App::updateruns one frame without them. - Audio
Emitter - A sound that plays at its entity, and follows it as it moves: the system
nadir::soundstarts it once its sound has loaded, while the entity has aTransformand is withinAudioConfig::max_distof the listener (AudioListener), 800 pixels, where it can be heard. It stops, fading out over 100 ms, when the entity is despawned or loses the emitter or itsTransform, or is more than 64 pixels past that distance; back within it, it starts again. A sound that does not loop plays once each time it starts. - Audio
Listener - Where the game hears from: the first entity with one and a
Transform, where it is drawn, between ticks part of the way from itsPrevTransform. With none, the camera’s position (RenderFrame::camera) is. - Audio
State - What the engine’s
nadir::soundkeeps of the game’s sound from frame to frame: a resource of everyApp, for the game to read. - Clip
- An animation: frames shown one after another, looping or once.
- Clip
Frame - One frame of a
Clip: a region of a texture, shown forduration, and maybe the size and pivot of its quad. - Clips
- The clips, by handle, and by name for those that have one: a resource
that the engine adds. An
Animatornames its clip by the handle thatClips::add,Clips::add_namedorClips::add_atlasgives. - Collider
- What an entity collides with: a
nadir_collision::Collider, offset from itsTransform. The engine builds theCollisionsworld from these each tick. - Collision
Layers - The names of the game’s collision layers: the layer of bit
nof aLayerMaskis named by then-th, so that prefabs and levels write["World", "People"]for a collider’s layers. A resource of everyApp, with no names untilApp::collision_layersgives them. - Collisions
- The colliders of the entities that have a
Colliderand aTransform, in aCollisionWorld: a resource that the engine rebuilds each tick, in the systemnadir::movement. - Config
- What a game asks of the engine.
- Current
Level - The level the world holds, if any: what
load_levelmade of it. A resource of everyApp, empty until a level loads. - Frame
Allocs - What the main thread allocated in the last frame: a resource of
development builds (feature
dev). - Music
Area - A box, its entity’s position ±
halfin pixels, whose music plays while the listener (AudioListener) is in it: the systemnadir::soundcrossfades tomusicovercrossfade_mswhen the listener comes into it. Where areas overlap, the one playing stays while the listener is in it, and otherwise the first of them that holds it plays. Outside every area, the music plays on; coming back into the area of the track that plays, it goes on as it is (ADR-0046). - Offscreen
- A game drawn offscreen, a frame at a time, with no window. Made by
App::offscreen. - Parent
- Puts an entity at another’s position plus
offset: the systemnadir::parent_offsetswrites itsTransformafter each tick’s movement, and frames draw it at its parent’s drawn position plus the offset. - Placement
- The size and pivot of a frame’s quad, as
Sprite::sizeandSprite::pivothold them. - Player
- The entity the player controls: a tag.
- Prev
Transform - Where an entity was at the start of the last tick: a frame between two
ticks draws it part of the way from there to its
Transform, by the frame’salpha. - SaveId
- An entity’s id in saves, which stays the same from one run to the
next, unlike its
Entity. Saves (roadmap M9.4) store only entities that have one. - Sprite
- What an entity looks like: a sprite drawn at its
Transform, between ticks part of the way from itsPrevTransform. - Tick
Stats - How many ticks the frame ran, and how long they took: a resource.
- Transform
- Where an entity is, in world pixels (+Y down), as the last tick left it. For a sprite, it is where its pivot is: its feet.
- Trigger
Enter - A collider began to overlap a trigger, in this tick. The system
nadir::triggerssends it, in the tick stagePostMovement. - Trigger
Exit - A collider stopped overlapping a trigger, in this tick, or one of the
two left: lost its collider or its
Transform, or was despawned. The systemnadir::triggerssends it, in the tick stagePostMovement. Either entity may be dead by then: check withWorld::is_alive. - Velocity
- How fast an entity moves, in pixels a second. The system
nadir::movementmoves it byvelocity × dteach tick: with aCollider, it slides along what it meets. - Volumes
- The volume of each of the mixer’s buses, in percent of full: 0 to 100,
and more counts as 100. A percent is heard as its square
(
Volumes::gain), so 50 is −12 dB, nearer half as loud than the −6 dB of half the gain. - Window
Size - The size of the inside of the window, in physical pixels: what the
frame is drawn into, and what the UI’s views
(
RenderFrame::ui) cover. A resource of development builds (featuredev).
Enums§
- Clip
Error - Why a clip could not be made or added.
- Error
- Errors that end
App::run. - Event
- Something that happened to the window or to an input device.
- Facing
- Which way an entity faces. Art is drawn facing right: the system
nadir::animatemirrors theSpriteof an entity that faces left (flip.x), and unmirrors it whichever other way it faces. Only the entity’s own Sprite: aParent’s children need their own. - Level
Error - Why a level could not be loaded. The previous level is gone then, and
nothing of the new one is in the world but the prefabs it read, which
the
PrefabLibrarykeeps. - Playback
- What a
Clipdoes at its end. - Replay
- How the replay that
App::play_replayplays is going: a resource that it adds.
Constants§
- TICK_HZ
- How many times a second the simulation steps.
Functions§
- load_
level - Loads the level
nameintoworld, the world of anApp, in place of the one it holds (ADR-0038): - loading_
context - Runs
fwith aReflectContextforsourcethat reads the engine’s components too: asreflect_context, with theAssetServerto load each handle read inscope(ReflectContext::loading). For spawning prefabs and a level’s entities (PrefabLibrary). - process_
alloc_ counts - The heap use of every thread since the process started.
- reflect_
context - Runs
fwith aReflectContextforsourcethat has what the engine’s components need to be written: theAssetServer, theClipsand theCollisionLayersofworld, each ifworldhas it. For writing values, such as a save’s, or, withReflectContext::hashing, a hash’s, asworld_hashdoes; it never loads, so it cannot read a handle. - thread_
alloc_ counts - The heap use of this thread since it started.
- unload_
level - Removes the level
worldholds, if any, and returns whether there was one: despawns the entities it spawned, takes its tile layers out ofTileLayers, lets go of its atlases’ clips inClips(Clips::release_atlas), empties the grid it set, puts back the clear colour it replaced, and unloadsScope::Level. The prefabs it read stay in thePrefabLibrary. - world_
hash - A hash of every reflected component of
world, asTypeRegistry::hash_worldtakes it, with the context the engine gives it. Determinism tests compare it run against run, tick after tick.
Type Aliases§
- Console
Command - A command of the game’s in the debug console: a function of the world,
the arguments typed, checked against the command’s usage, and where to
print, added with
App::add_console_command. An error it returns (ConsoleError::Failedwith why) is printed in red. - Debug
Window - A window of the debug UI, which fills it with widgets each frame it is
open: a function of the world and the window’s
Ui, added withApp::add_debug_window.