Architecture overview¶
Aegis2D is split into small libraries with one job each. A game links only what it needs: the server never loads rendering, audio or windowing code, and game rules never live inside the engine.
Status
This page describes the target architecture. The module boundaries, build targets and dependencies already exist; the module contents are being implemented ticket by ticket (see the changelog).
Layers¶
flowchart TB
subgraph game["Game (project-rtype)"]
server["r-type_server<br/>authoritative simulation"]
client["r-type_client<br/>input, prediction, display"]
end
subgraph engine["Aegis2D engine"]
direction TB
ui["ui<br/>widgets, focus"]
render["render<br/>OpenGL context, renderer"]
audio["audio<br/>sounds, music"]
platform["platform<br/>window, input"]
shmup["shmup<br/>player ships, weapons, shots"]
script["script<br/>Lua behaviors"]
ecs["ecs<br/>entities, components, systems"]
net["net<br/>serialization, UDP/TCP, net thread"]
core["core<br/>log, time, loop, events, config"]
end
subgraph deps["Third-party (CPM)"]
sdl["SDL3"]
gl["glad · stb_image"]
glm["GLM"]
asio["Asio"]
json["nlohmann-json"]
lz4["LZ4"]
lua["Lua · sol2"]
end
server --> shmup & ecs & net & core
client --> ui & render & audio & platform & shmup & ecs & net & core
ui --> render
shmup --> ecs
script --> lua
render --> platform
render --> gl
platform --> core
platform --> sdl
audio --> core
audio --> sdl
ecs --> core
net --> core
net --> asio & lz4
core --> json
core --> glm
What each module offers and costs, and which ones to link, is in the Modules reference.
| Module | Library | Depends on | Built for |
|---|---|---|---|
| core | aegis2d::core |
GLM (public), nlohmann-json | server, client |
| ecs | aegis2d::ecs |
core | server, client |
| shmup | aegis2d::shmup |
ecs | server, client |
| net | aegis2d::net |
core, Asio, LZ4 | server, client |
| platform | aegis2d::platform |
core, SDL3 | client |
| render | aegis2d::render |
platform, glad, stb_image, SDL3 | client |
| audio | aegis2d::audio |
core, SDL3 | client |
| ui | aegis2d::ui |
render | client |
Rules that keep the layers apart:
- Dependencies point down.
coredepends on no other module; nothing in the engine depends on the game. - Third-party libraries stay private. Modules link SDL3, glad, Asio and the others
privately, so their headers never leak into game code: the game sees engine types only.
The one exception is GLM, the engine's maths library:
corelinks it publicly, behind theaegis2d::Vec2,Vec3,Vec4andMat4aliases, so the server, the client and every render backend share the same vector and matrix types. - Server builds stop at
net. WithAEGIS2D_BUILD_CLIENT=OFF,platform,render,audioanduiare not even configured, and SDL3 and glad are not downloaded.
How the subsystems talk¶
flowchart LR
subgraph clientproc["Client process"]
input["platform<br/>input actions"] --> cgame["game systems"]
cgame --> cecs[("ECS world")]
cecs --> renderer["render"]
cgame -. events .-> sound["audio"]
cnet["network<br/>(ClientSession)"] <-->|"world, inputs"| cgame
end
subgraph serverproc["Server process"]
snet["network<br/>(main thread)"] <-->|posted tasks| sim["simulation thread<br/>60 Hz fixed step"]
sim --> secs[("ECS world")]
end
cnet <-->|"UDP: inputs, snapshots, events<br/>TCP: login"| snet
- ECS as the shared world model. Gameplay, networking and rendering read and write
components (
Transform,Velocity,Sprite,NetworkId...). Rendering only needs a position and a sprite; it never sees health or damage. - Event bus for decoupling. Gameplay publishes typed events (
shmup::ShotFired,ecs::Explosion,ecs::LifeLost...) on thecoreevent bus; audio plays sounds by listening to them (audio::EventSounds), so gameplay code never calls audio. - Network and game threads. Sockets run on a network context (Asio), and the simulation on a thread of its own: messages cross between them as posted tasks, so the simulation never blocks on the network. How R-Type splits its threads, and its rates and timeouts, are in Networking architecture.
- Fixed time step.
coredrives the simulation at a fixed 60 Hz with an accumulator, independent of the frame rate; rendering interpolates between steps. Nothing depends on CPU speed. - Authoritative server. Clients send inputs; the server simulates, then broadcasts snapshots and reliable events. Clients display the server's world, interpolating remote entities between snapshots.
Core module¶
aegis2d::core is in place; every other module builds on it.
| Header | Provides |
|---|---|
aegis2d/core/paths.hpp |
executable_dir(), asset_dir(), asset_path("sprites/ship.png"): files next to the running program, whatever the working directory; pairs with the aegis2d_copy_assets() CMake function |
aegis2d/core/math.hpp |
Vec2, Vec3, Vec4, Mat4: GLM types under engine names, zero (or identity) by default, column-major like GLSL and HLSL constant buffers |
aegis2d/core/hot_reload.hpp |
HotReload{enabled, interval}: files reloaded while the game runs; watch(path, reload) registers what to do when a file changes (watching it again replaces that) (a texture through TextureManager::watch(), a JSON file with Config::from_file()...); update(), once per frame, looks at the files at most every interval (250 ms) and calls the reload of each one whose time or size changed; a reload that throws is logged and retried at the next save, the game keeping what it had; a missing file waits for its return. hot_reload_by_default is on in debug builds, off with NDEBUG, taken from the game's own build; off, it does nothing |
aegis2d/core/memory.hpp |
memory_use(): the memory of the process in RAM now, its resident set on Linux (/proc/self/statm) and macOS (task_info) or its working set on Windows, in bytes, or nothing if the system does not tell; asked to the system at each call |
aegis2d/core/profiler.hpp |
Profiler: timers around the parts of a frame, for developers; begin_frame() and end_frame() bound a frame, scope(name) times the code its ProfileScope lives in (begin(name) and end() without one), scopes nest, and one entered several times at the same place in a frame adds up (calls); last_frame() gives the breakdown of the last frame ended, each ProfileEntry (name, depth, ms, calls) after its parent, and last_frame_ms() its duration; off (set_enabled(false)) or outside a frame, scopes time nothing; profile_lines(profiler, most) writes the breakdown as lines of the metrics overlay (FRAME 16.4 MS, MOVEMENT 0.31 MS X2), the slowest most kept. ecs::Scheduler::set_profiler() times each of its systems in a scope named after it. start_trace(capacity) records every scope and frame as a TraceEvent (name, start_us on a clock shared by the threads, duration_us) until stop_trace() or the capacity (dropped() counts the rest); write_chrome_trace(out, threads, process) and save_chrome_trace(file, threads, process) write them in the Chrome trace format, a TraceThread per thread, which Perfetto (ui.perfetto.dev) and chrome://tracing open |
aegis2d/core/log.hpp |
Logger with levels (Debug to Error, Off), console and file output, ISO 8601 UTC timestamps, thread-safe; log_info("port {}", port) and friends on the global logger |
aegis2d/core/clock.hpp |
FixedTimestep (accumulator, 250 ms frame cap, interpolation alpha), step_from_rate(60), Stopwatch on steady_clock |
aegis2d/core/loop.hpp |
MainLoop: fixed-rate update, then one render(alpha) per frame; sleeps between steps when there is no renderer (server); stop() from any thread |
aegis2d/core/event_bus.hpp |
EventBus: subscribe<Event>, publish, unsubscribe; immediate dispatch in subscription order, game thread only. Use for reactions that must happen now (audio, effects) |
aegis2d/core/event_queue.hpp |
EventQueue: push<Event>(event, priority), dispatch(bus), clear(); deferred dispatch in priority order (stable: same priority → push order). Use when the order across event types matters, or when handlers must not run mid-tick |
aegis2d/core/console_variables.hpp |
ConsoleVariables: settings a console reads and changes by name while the game runs; add(name, default, description, flags) declares a variable whose type is its default's (bool, a 64-bit integer, a double or a text), its name lower case letters, digits, _ and . from a letter (r_vsync, net.rate); VarFlags{.saved, .cheat, .read_only}; get<T>(name), text(name), info(name) (value, default, description, flags), names(); set(name, value) in its type (an integer sets a number too) and set_text(name, text) as a console or a command line gives it (1/0, true/false, on/off; whole numbers; decimal numbers, read the same in every locale and standard library), both returning a VarResult (Changed, or Unknown, ReadOnly, Cheat, WrongType, BadText, told by to_string()); reset(name), reset_all(); a read-only variable keeps its default and a cheat changes only after set_cheats(true); to_text(value) writes what set_text() reads back, and read_value(text, like) reads it as set_text() does; is_console_name(name) |
aegis2d/core/commands.hpp |
Commands: the commands a console runs from a line (spawn bydos 3); add(name, arguments, description, handler) declares one, its name as a variable's, its CommandArgs typed (ArgType::Text, Integer, Number, Boolean, read as set_text() reads them), optional ones last, and a last text that may take the rest of the words; double quotes keep blanks; run(line) checks the arguments before the handler runs and returns a CommandResult (Done, Empty, Unknown, WrongArguments with the usage, Failed with the message of what the handler threw) and the text to show; the handler reads its CommandCall by name (text(), integer(), number(), boolean(), has()); add_variables(variables) makes console variables commands too (r_vsync shows it, r_vsync off sets it); help lists every name, help <name> shows usage(name) and the description |
aegis2d/core/variable_settings.hpp |
Console variables set at start, so that a value changes without recompiling: settings_from_arguments() reads the +set name value of a command line (main()'s argc/argv or views), the game's other arguments left alone; settings_from_text() and settings_from_file() read name value lines (set name value too, a quoted value keeping its spaces, # and // comment lines); each VarSetting keeps its origin ("command line", "game.cfg:3"), and the lines that do not read are in errors; apply_settings(variables, settings) sets them in order through set_text(), so types and flags are kept, a later setting winning, and returns one line per refusal |
aegis2d/core/config.hpp |
Config: JSON file with comments, dotted paths ("server.udp_port", "levels.0.name"), typed getters, value_or and value() (any type, such as an array); set(path, value) creates the objects on its path, to_string() and save(file) write it back (members in document order, atomic replace through <file>.tmp); errors throw ConfigError |
aegis2d/core/resource_cache.hpp |
ResourceCache<Resource>{loader}: resources shared by name; load(name) gives a std::shared_ptr handle, the cached resource while handles live, a fresh call of the loader otherwise, so each resource is loaded once, counted by its handles (uses()) and freed with the last one; find() without loading, loaded(), size(), clear(); safe between threads, the loader running outside the cache's lock: while one thread loads a name, the others load other names and find() answers at once, so a preloading thread can fill the cache while the game reads it; threads asking for a name being loaded wait for that load and share its resource or its error, so each name is loaded once; loader errors reach the callers and cache nothing |
aegis2d/core/preloader.hpp |
Preloader<Resource>{cache, names}: loads a list of resources through a ResourceCache in its own thread, started at once, for loading screens; progress() from 0 to 1, processed() of total(), done(), wait(); the handles are kept, so the resources stay cached until release(); handle(name); a loader's error is recorded in failures() (PreloadFailure: name and reason, "unknown error" for one that is not an std::exception) and the rest still loads; the destructor waits for the thread |
aegis2d/core/spsc_queue.hpp |
SpscQueue<T>: lock-free queue from one producer thread to one consumer thread, fixed capacity allocated once; try_push() / try_emplace() return false when full and try_pop() nothing when empty, so neither thread ever waits; drain(consume, limit) takes up to limit values; head and tail on separate cache lines. Carries messages between the network thread and the game thread |
aegis2d/core/random.hpp |
Random: seeded PCG32 generator whose numbers are the same on every compiler and standard library (std distributions are not): next(), below(bound) without bias, uniform() in [0, 1) and uniform(low, high); a stream picks one of 2^63 independent sequences; meets std::uniform_random_bit_generator. For gameplay the server must replay, not for cryptography |
aegis2d/core/shared_library.hpp |
SharedLibrary: a .so, .dylib or .dll opened at run time (dlopen or LoadLibraryExW, the DLLs it needs also looked for in its folder) and closed when destroyed; symbol(name), function<int(int)>(name) (null when not exported). load_library(path) opens an Aegis2D library: it calls its C entry point aegis2d_library_entry(), which returns a LibraryInfo (api_version, name), and refuses a library built for another library_api_version before running any other of its code. Failures throw LibraryError with the path and the reason (the system's, a missing entry point, both versions) |
using namespace aegis2d::core;
const Config config = Config::from_file("server.json");
const auto port = config.value_or<std::uint16_t>("server.udp_port", 4242);
Logger::global().set_level(LogLevel::Debug);
Logger::global().open_file("server.log");
log_info("server listening on UDP port {}", port);
struct EnemyDestroyed { int score; };
EventBus events;
events.subscribe<EnemyDestroyed>([](const EnemyDestroyed& event) { /* play a sound */ });
MainLoop loop{FixedTimestep{step_from_rate(60)}};
loop.set_update([&events](Duration step) {
/* simulate one step */
events.publish(EnemyDestroyed{.score = 100});
});
loop.set_render([](double alpha) { /* draw, interpolating with alpha */ });
loop.run(); // until loop.stop()
A library the engine loads at run time, such as a plugin, exports a C entry point that tells its version; another version is refused with a reason instead of crashing:
// In the library, exported (__declspec(dllexport) on Windows):
extern "C" MY_PLUGIN_EXPORT const aegis2d::core::LibraryInfo* aegis2d_library_entry() {
static constexpr aegis2d::core::LibraryInfo info{
.api_version = aegis2d::core::library_api_version, .name = "my_plugin"};
return &info;
}
// In the game:
const auto plugin = load_library(executable_dir() / "plugins" / "libmy_plugin.so");
log_info("loaded {}", plugin.name); // LibraryError if not loadable, with the reason
ECS module¶
aegis2d::ecs is in place. Game code works with the Registry, describes entities with
the shared components and runs its logic in systems; the allocator and the pools are the
registry's building blocks.
How the storage works, how to iterate over the entities that own several components and
the rules to follow while doing it are explained in ECS design.
ecs::Registry registry;
const ecs::Entity ship = registry.create();
registry.emplace<Velocity>(ship, Vec2{120.0F, 0.0F});
registry.emplace<Health>(ship, 3);
registry.get<Health>(ship).points -= 1;
registry.has<Health, Velocity>(ship); // true
for (Health& health : registry.pool<Health>().components()) { /* every Health */ }
// Movement system: every entity that owns both a Transform and a Velocity.
registry.view<Transform, Velocity>().each([dt](Transform& transform, const Velocity& velocity) {
transform.position += velocity.value * dt;
});
registry.destroy(ship); // removes the Velocity and the Health too
registry.alive(ship); // false: the handle is stale
The components both binaries use live in one header, aegis2d/ecs/components.hpp. They
are plain data: positions and sizes in logical pixels (origin top-left, y down), speeds per
second, and no render type, so the server builds them without the render module:
const ecs::Entity ship = registry.create();
registry.emplace<ecs::Transform>(ship, Vec2{64.0F, 240.0F}); // center of the ship
registry.emplace<ecs::Velocity>(ship, Vec2{0.0F, 0.0F}); // pixels per second
registry.emplace<ecs::Sprite>(ship, ecs::Sprite{.texture = ships, .size = {32.0F, 16.0F}, .frame = slot});
registry.emplace<ecs::Collider>(ship, ecs::Collider{.size = {28.0F, 12.0F},
.layer = player_layer, .mask = enemy_layer});
registry.emplace<ecs::Health>(ship, 1); // health.depleted() at 0
registry.emplace<ecs::NetworkId>(ship, ecs::NetworkId::of(ship)); // server side
std::unordered_map<ecs::NetworkId, ecs::Entity> replicated; // client side: server id
// to local entity
Systems hold the game logic. Each binary registers its own in a Scheduler, in the order
they must run, and the fixed-step callback of the main loop updates them all once per tick:
class InputSystem final : public ecs::ISystem { // a system with its own state
public:
explicit InputSystem(InputQueue& inputs) : inputs_{inputs} {}
void update(ecs::Registry& registry, const ecs::Tick& tick) override { /* apply inputs */ }
private:
std::reference_wrapper<InputQueue> inputs_;
};
ecs::Scheduler systems; // server: inputs, then movement...
systems.add<InputSystem>("input", inputs); // built in place, owned by systems
systems.add("movement", [](ecs::Registry& world, const ecs::Tick& tick) {
world.view<Transform, Velocity>().each([&tick](Transform& t, const Velocity& v) {
t.position += v.value * tick.delta(); // tick.delta(): the step in seconds
});
});
systems.add("collision", collision_system); // any function (Registry&, const Tick&)
MainLoop loop{FixedTimestep{step_from_rate(60)}};
loop.set_update([&](Duration step) { systems.update(registry, step); });
systems.set_enabled("collision", false); // skipped, keeps its place
Player ships are steered by the actions their client holds (one byte per tick), at a fixed speed per second whatever the tick rate; the engine's movement systems fit the scheduler as they are:
const ecs::Entity ship = shmup::spawn_player_ship(registry, Vec2{80.0F, 360.0F}, 300.0F);
registry.get<ecs::PlayerInput>(ship).set(ecs::Action::Right, true); // from the client
systems.add("steering", shmup::steer_player_ships); // Velocity = direction * speed
systems.add("movement", ecs::apply_velocity); // Transform += Velocity * delta
systems.add("sine_motion", ecs::apply_sine_motion); // SineMotion: a wave on top of it
const ecs::Aabb area{.min = {0.0F, 0.0F}, .max = {1280.0F, 720.0F}}; // the play area
systems.add("clamp", [area](ecs::Registry& world, const ecs::Tick&) {
shmup::clamp_player_ships(world, area); // ships stop at the edges
});
registry.emplace<shmup::Weapon>(ship, shmup::Weapon{.cooldown = 0.25F}); // four shots a second
std::vector<ecs::Entity> shooters;
systems.add("weapons", [&shooters](ecs::Registry& world, const ecs::Tick& tick) {
shmup::trigger_weapons(world, tick, shooters); // fire held and weapon reloaded
for (const ecs::Entity ship : shooters) { /* the game spawns its missile */ }
});
registry.emplace<shmup::Weapon>(enemy, shmup::Weapon{.cooldown = 2.0F, .reload = 1.2F});
registry.emplace<shmup::AutoTrigger>(enemy); // fires on its own, first in 1.2 s
std::vector<ecs::Entity> gunners;
systems.add("enemy_fire", [&gunners](ecs::Registry& world, const ecs::Tick& tick) {
shmup::trigger_auto_weapons(world, tick, gunners); // reloaded automatic weapons
for (const ecs::Entity enemy : gunners) { /* the game spawns its missile */ }
});
ecs::RandomSpawner spawner{ecs::SpawnSettings{.from = {1296.0F, 64.0F}, .to = {1296.0F, 656.0F},
.min_interval = 0.8F, .max_interval = 2.0F},
seed}; // same seed, same spawns
std::vector<Vec2> points;
systems.add("spawn", [&spawner, &points](ecs::Registry& world, const ecs::Tick& tick) {
spawner.update(tick, points); // points due this tick
for (const Vec2 point : points) { /* the game spawns its enemy */ }
});
auto waves = ecs::WaveSchedule::from_file(core::asset_path("waves/stage1.json"),
known_types); // a typo fails here, not in game
std::vector<ecs::WaveSpawn> due;
systems.add("waves", [&waves, &due](ecs::Registry& world, const ecs::Tick& tick) {
waves.update(tick, due); // spawns due this tick
for (const auto& spawn : due) { /* the game creates spawn.type at spawn.position */ }
});
registry.emplace<ecs::Timer>(tower, ecs::Timer::every(0.8F)); // fires every 0.8 s
std::vector<ecs::Entity> fired;
systems.add("timers", [&fired](ecs::Registry& world, const ecs::Tick& tick) {
ecs::fire_timers(world, tick, fired); // timers due this tick
for (const ecs::Entity tower : fired) { /* the game does what the timer is for */ }
});
std::vector<ecs::Entity> gone; // missiles and enemies get
systems.add("despawn", [area, &gone](ecs::Registry& world, const ecs::Tick&) {
ecs::despawn_outside(world, area, gone); // OffscreenDespawn: destroyed once
}); // they left the screen for good
Collisions run in two phases. The broad phase, a uniform grid over the play area, returns the pairs of entities that share a cell; the narrow phase keeps the pairs whose layers interact and whose boxes overlap, and tells who hits whom:
constexpr std::uint32_t player = 1, player_missile = 2, enemy = 4, enemy_missile = 8;
ecs::Collider{.size = {12.0F, 4.0F}, .layer = player_missile, .mask = enemy}; // hits enemies only
ecs::Collider{.size = {24.0F, 24.0F}, .layer = enemy, .mask = player | player_missile};
registry.emplace<ecs::Health>(bydo, 2); // two hits to kill
registry.emplace<ecs::Damage>(missile, 1); // consumed by its first hit
registry.emplace<ecs::Damage>(ship, ecs::Damage{.amount = 1, .consumed_on_hit = false});
registry.emplace<ecs::Owner>(missile, ship); // kills are credited to the ship
registry.emplace<ecs::Score>(ship); // the ship's points
registry.emplace<ecs::ScoreValue>(bydo, 100); // what killing the Bydo is worth
registry.emplace<ecs::Lives>(ship, ecs::Lives{.count = 3, .spawn = {80.0F, 360.0F}});
ecs::CollisionGrid grid{Vec2{1280.0F, 720.0F}, 64.0F}; // once: play area, cell size
std::vector<ecs::Contact> contacts; // reused every tick
ecs::DamageReport damage; // reused every tick
std::vector<ecs::Award> awards; // reused every tick
std::vector<ecs::LifeLost> lost; // reused every tick
systems.add("collision", [&](ecs::Registry& world, const ecs::Tick&) {
grid.build(world); // every Transform + Collider
ecs::find_contacts(world, grid.pairs(), contacts); // overlap + layer masks
ecs::apply_damage(world, contacts, damage); // Health -= Damage, nothing destroyed
ecs::publish_explosions(events, world, damage); // an ecs::Explosion per kill
ecs::credit_kills(world, damage, awards); // ScoreValue -> the shooter's Score
ecs::handle_player_deaths(world, damage, lost); // a life lost: respawn, or out
ecs::publish_deaths(events, lost); // an ecs::LifeLost per death
ecs::remove_casualties(world, damage); // dead entities, out players, missiles
if (ecs::game_over(world)) { /* tell the clients, stop the game */ }
});
The building blocks, usable on their own:
ecs::EntityAllocator entities;
const ecs::Entity bullet = entities.create(); // Entity(0, 0)
entities.destroy(bullet); // index 0 goes to the free list
const ecs::Entity next = entities.create(); // Entity(0, 1): same index, new generation
entities.alive(bullet); // false: the old handle is stale
ecs::SparseSet<Health> health; // one pool per component type
health.emplace(next, 3); // Health{3}
health.get(next).points -= 1;
for (Health& component : health.components()) {
/* packed: only entities that have a Health; entities()[i] owns components()[i] */
}
health.remove(next); // the last component fills the hole
| Header | Provides |
|---|---|
aegis2d/ecs/entity.hpp |
Entity: 32-bit handle, 24-bit index and 8-bit generation, so a handle kept after its entity was destroyed is detected as stale; null by default, comparable, hashable, id()/from_id() for the network, to_string() for logs |
aegis2d/ecs/entity_allocator.hpp |
EntityAllocator: create() and destroy() entities, alive() rejects null, stale and forged handles; a destroyed index gets a new generation and goes to a first-in, first-out free list, so reuses are spread over all free indices; clear() keeps generations; throws std::length_error past Entity::max_index |
aegis2d/ecs/sparse_set.hpp |
SparseSet<Component>: one component pool, components packed in a dense array next to their entities, found through a sparse array indexed by entity index; emplace(), get() (throws std::out_of_range), try_get() (std::optional of a reference), contains(), remove() (swap with the last, O(1)), entities() and components() spans; stale handles never reach the component of a recycled index; SparseSetBase erases the type so the registry can remove a destroyed entity from every pool |
aegis2d/ecs/registry.hpp |
Registry: owns the entities and one SparseSet per component type, created on first use; create(), destroy() (removes every component of the entity, whatever its type), alive(), clear(); emplace<C>() (throws std::invalid_argument for a dead entity, std::logic_error if it already has C), emplace_or_replace<C>(), remove<C>(), has<C...>(), get<C>() (throws std::out_of_range), try_get<C>(), count<C>(), pool<C>() and find_pool<C>() for iteration, view<C...>() |
aegis2d/ecs/view.hpp |
View<C...>: visits the entities that own all of C... with each(), the callback taking (C&...) or (Entity, C&...); walks the smallest pool and checks the others in O(1); the callback may destroy or strip the entity it visits; contains(), get<C>(), size_hint(); types must be distinct (checked at compile time) |
aegis2d/ecs/components.hpp |
Components shared by client and server, all plain data: Transform (center, logical pixels), Velocity (pixels per second), Sprite (texture id, size, sprite-sheet frame, layer, RGBA tint as Vec4; turned into a render::Sprite by the client), Animation (a clip of a sprite sheet: first frame, count, frame_time in seconds, loop, elapsed; frame(), duration(), finished()), Collider (box size and offset around the position, layer and mask bit masks), Health (points, depleted() at zero or less), Damage (amount, consumed_on_hit), Owner (the entity that fired a missile), Score (a player's points), ScoreValue (points for killing the entity, 100 by default), Lives (count 3 by default, spawn position, health given back on respawn), PlayerInput (held Actions, one bit each: Up, Down, Left, Right, Fire; holds(), set()), DestroyAfterAnimation (empty marker: a visual effect, such as an explosion, destroyed once its clip has played), OffscreenDespawn (margin beyond the play area before the entity is destroyed), SineMotion (amplitude vector, period and elapsed seconds of a wave added to the movement), NetworkId (the server entity's Entity::id(), of(entity), comparable and hashable) |
aegis2d/ecs/system.hpp |
ISystem: update(registry, tick), the interface of game logic; FunctionSystem wraps a function with the same signature; Tick: the step, its number and delta() in seconds; Scheduler: named systems run in the order they were added, once per update(registry, step), built in place with add<S>(name, args...) or from a function; remove(), set_enabled() (a disabled system keeps its place), names(), ticks(); names must be unique and non-empty (std::invalid_argument); adding, removing or updating from inside a system throws std::logic_error; an exception from a system stops the tick, which is not counted |
aegis2d/ecs/collision.hpp |
Collision detection. Broad phase: CollisionGrid, a uniform grid of square cells over the play area; insert(entity, box) or build(registry) (every entity with a Transform and a Collider), pairs() returns the entities sharing at least one cell, each pair once, in a deterministic order; query(area, out) lists each entity recorded in the cells an area touches once; boxes outside the area (or not finite) stay in the border cells; clear() keeps the cells' memory. Narrow phase: find_contacts(registry, pairs, out) (or find_contacts(registry, grid)) keeps the pairs whose layers interact and whose boxes overlap, as Contacts (first, second, first_hits_second, second_hits_first), skipping entities destroyed or changed since the grid was built; hits(attacker, target) (attacker.mask & target.layer, one-way); Aabb (min, max, of(transform, collider), overlaps(), touching edges do not count), CollisionPair (first < second, of(a, b), comparable) |
aegis2d/ecs/pathfinding.hpp |
Grid pathfinding: NavGrid(columns, rows, cell_size, origin), cells walkable with a cost of 1 by default; set_walkable(cell, bool), set_cost(cell, cost) (at least 1: the cost of entering the cell), mark_tiles(tiles, Painted::Walkable or Painted::Blocked) from a Tiled layer's tile ids; find_path(from, to) runs A* over the four neighbours and returns the centers of a cheapest path, both ends included, empty when there is none; cell_at(position), center(cell), contains(), walkable(); version() goes up at each change, so NavPath (from, to, points) finds its path again in update(grid) only after a cell changed. Out-of-range cells throw std::out_of_range, invalid sizes and costs std::invalid_argument; at most max_cells (one million) cells |
aegis2d/ecs/path_following.hpp |
Path following: PathFollower (waypoints, speed in pixels per second, progress walked from the first waypoint, arrived); follow_paths(registry, tick, arrived) adds speed * tick.delta() to the progress and puts the Transform at that distance along the waypoints, corners included, so an entity is at the same place at any tick rate; it stops on the last waypoint and is listed once, on the tick it arrives. publish_path_ends(events, registry, arrived) publishes a PathEnded (entity, last waypoint) for each. progress tells who is ahead on one path, remaining(follower) across paths; path_length(waypoints), point_along(waypoints, distance). Inline, so that the view is made in the caller's code |
aegis2d/ecs/targeting.hpp |
Targets in range: find_targets<Component>(registry, grid, center, radius, order, out) lists the entities with Component whose Transform is at most radius from center, testing only the candidates of CollisionGrid::query() over the square around the circle (the grid built this tick, so targets need a Collider); TargetOrder::Nearest puts the closest first, TargetOrder::MostAdvanced the least remaining() of its PathFollower (then the closest; entities that follow no path last); ties in handle order, entities destroyed since the grid was built skipped, a negative or NaN radius finds nothing. Inline, so that the components are read in the caller's code |
aegis2d/ecs/damage.hpp |
Damage on hit: apply_damage(registry, contacts, report) removes Damage::amount from the target's Health for each direction of each contact, records Hits, Kills (victim and the attacker of the last hit) and attackers consumed by their hit; an entity consumed or killed takes no part in the next contacts of the tick (one missile, one hit; no missile wasted on a dead enemy), both directions of one contact happen at once; targets without Health still consume missiles. Nothing is destroyed until remove_casualties(registry, report), which keeps a victim whose health was restored (a player with lives left). DamageReport (hits, kills, consumed, clear()) |
aegis2d/ecs/score.hpp |
Score: credit_kills(registry, report, awards) adds each killed entity's ScoreValue to the Score of the player who killed it, found by shooter_of(registry, killer) (the killer's Owner, or the killer itself for a ship that rams); kills without a value or without a living player with a Score give nothing; scores stop at the largest value instead of wrapping; one Award (player, victim, points) per credited kill. Call it between apply_damage() and remove_casualties() |
aegis2d/ecs/lives.hpp |
Player deaths: handle_player_deaths(registry, report, lost) takes a life from each killed entity with Lives; while lives remain, the player respawns (health back to Lives::health, moved to Lives::spawn, velocity zero) and remove_casualties() keeps it; with no life left it is out and destroyed like any casualty. One LifeLost (player, lives left, score, out()) per death. players_left(registry) and game_over(registry) (no entity with Lives left), to check after remove_casualties() |
aegis2d/ecs/movement.hpp |
Movement: direction_of(input) gives the direction a PlayerInput points to (opposite actions cancel, diagonals normalized); apply_velocity(registry, tick) adds velocity * tick.delta() to every Transform; apply_sine_motion(registry, tick) moves each entity with SineMotion by the change of sine_offset(motion, elapsed) (amplitude * sin(2π * elapsed / period)) over the tick, so the wave stacks with the velocity and reaches the same offsets at any tick rate; both have the (Registry&, const Tick&) signature of a system. clamp_into(position, half, area) keeps a box inside an area and half_extent_of(registry, entity) gives the half size of what must stay visible (its Sprite, else its Collider) |
aegis2d/ecs/animation.hpp |
Animation: animate_sprites(registry, tick) advances each Animation by the tick and sets its entity's Sprite::frame, so animations run at the same speed at any tick or frame rate; advance(animation, seconds); a looping clip wraps, another stops on its last frame; destroy_finished_animations(registry, destroyed) destroys the entities with DestroyAfterAnimation whose clip does not loop and is finished, so one-shot effects go away after their last frame |
aegis2d/ecs/despawn.hpp |
Off-screen despawn, so missiles and enemies never leak: despawn_outside(registry, area, despawned) destroys each entity with OffscreenDespawn whose box (its Sprite, else its Collider, else its center) is entirely outside the area grown by its margin and whose Velocity does not bring it back, and lists them for the clients; left_for_good(position, half, velocity, area) is the test, so an enemy created beyond the right edge and flying in is kept |
aegis2d/ecs/timers.hpp |
Timers, for anything that happens every few seconds or once after a delay (a tower that shoots, a message that goes away): Timer (period, left before the next fire, repeat, running, done; Timer::every(seconds), Timer::after(seconds)); fire_timers(registry, tick, fired) counts each timer down and lists its entity at each fire, a repeating timer keeping the time left over so it fires exactly every period at any tick rate, and once per period elapsed after a long tick; advance(timer, seconds) returns the number of fires |
aegis2d/ecs/spawner.hpp |
Random spawns from a seed: RandomSpawner(settings, seed) with SpawnSettings (a line from/to, min_interval and max_interval in seconds); update(tick, spawns) lists the points due this tick, each at a random point of the line, and the game creates its entities there; random() draws anything else about them (a phase, a type) from the same seeded sequence. The same seed gives the same points, at any tick rate |
aegis2d/ecs/waves.hpp |
Enemy waves from a data file, so a level changes without recompiling: WaveSchedule::from_file(path, types) (or from_string, from_config) reads waves that follow each other (delay after the previous wave's last spawn) made of groups (type, position, optional at, count, every, step) and an optional loop; unknown types and invalid values throw core::ConfigError naming the file and the path (waves.1.spawns.0.type). update(tick, due) lists the WaveSpawns (type, position, wave, time) due this tick, the game creating them by type; finished(), restart(), spawns(), duration() |
aegis2d/ecs/events.hpp |
Gameplay events, published on the core::EventBus so that audio and effects react without gameplay code knowing them: Explosion (entity, killer, where it was hit) and LifeLost for deaths. publish_explosions(events, registry, report) right after apply_damage(), before handle_player_deaths() moves a revived player back to its spawn point; publish_deaths(events, lost) after handle_player_deaths(). Inline, so that they publish in the caller's code, where the bus finds the handlers by typeid |
aegis2d/ecs/plugins.hpp |
Plugins: shared libraries that add systems and assets to a game when it starts, without recompiling it. A plugin is a core::load_library() library that also exports aegis2d_plugin_start(PluginContext&) with C linkage; PluginContext(systems) gives it the game's Scheduler (systems()) and add_asset_folder(). Plugins::load(path, context) checks and starts one and returns its name, load_folder(folder, context) loads every library of a folder in file-name order (none for a missing folder); the libraries stay loaded as long as the Plugins, which must outlive the scheduler. A plugin with no start function, or whose start throws, gives a core::LibraryError |
A plugin adds a system to a game that was not built with it. The game loads the plugins of a folder at start; each one's start function adds to the scheduler:
// The plugin, a shared library (plus its aegis2d_library_entry(), see core):
extern "C" MY_PLUGIN_EXPORT void aegis2d_plugin_start(aegis2d::ecs::PluginContext& game) {
game.systems().add("drift", [](ecs::Registry& registry, const ecs::Tick&) { /* ... */ });
game.add_asset_folder("plugins/drift/assets");
}
// The game:
ecs::Plugins plugins; // first: it outlives the systems running its code
ecs::Scheduler systems;
ecs::PluginContext context{systems};
plugins.load_folder(core::executable_dir() / "plugins", context);
Shoot'em up module¶
aegis2d::shmup holds what only a shoot'em up needs, on top of the ECS: player ships, their
controls, weapons and their shots. A game of another genre links ecs without it, and no
other module mentions ships (the shmup_genre_free test checks it). Its code reads
components, so it is header-only, like the ECS systems.
| Header | Provides |
|---|---|
aegis2d/shmup/components.hpp |
PlayerShip (speed in pixels per second, 300 by default), Weapon (cooldown between shots, 0.25 s by default, and reload left) and AutoTrigger (empty marker: the weapon fires on its own when reloaded, for enemies) |
aegis2d/shmup/weapons.hpp |
Fire rate enforced by the server: trigger_weapons(registry, tick, shooters) counts each Weapon's reload down and lists the entities that hold Action::Fire with a reloaded weapon, adding the cooldown to the reload (time left over is kept, so the rate is exact at any tick rate); an idle weapon does not store shots and tapping faster than the cooldown does not shoot faster; trigger_auto_weapons(registry, tick, shooters) does the same for entities with AutoTrigger (and no PlayerInput), which fire as soon as they are reloaded, every cooldown seconds after a first reload; both use pull_trigger(weapon, delta, pulled); the game creates the missiles. ShotFired (shooter, position, player for a player's ship), published by publish_shots(events, registry, shooters) after trigger_weapons() or trigger_auto_weapons() |
aegis2d/shmup/ships.hpp |
steer_player_ships(registry, tick) sets the Velocity of each PlayerShip from its PlayerInput (ecs::direction_of(input) * speed, stops when released); clamp_player_ships(registry, area) keeps every PlayerShip inside the play area, its Sprite (else its Collider) fully visible, so holding a direction stops the ship at the edge; spawn_player_ship(registry, position, speed) creates a ship with Transform, Velocity, PlayerInput and PlayerShip, the game adding its collider, health, lives and sprite |
aegis2d/shmup/ship_controls.hpp |
ShipControls (client side: needs aegis2d::platform, which the shmup library does not link, so a server never depends on it): the actions up, down, left, right and fire of a player ship with the default arrows and Space, and on a gamepad the D-pad or the left stick and South (A, Cross) or the right trigger; id(ecs::Action); auto-fire on the fire action (auto_fire()), update(keyboard) or update(keyboard, gamepad) returning the held actions as ecs::Action bits, the byte of ecs::PlayerInput::held; load() and save() for the player's keys, buttons (in their own section) and auto-fire |
The ECS headers still give the old names (ecs::Weapon, ecs::trigger_weapons(),
ecs::ShotFired...) as aliases of the shmup ones, until the games use the new headers.
The player ships and their controls moved without aliases (ecs::PlayerShip,
ecs::steer_player_ships(), platform::ShipControls, platform::ShipAction are gone; the
latter is ecs::Action), so that no other module mentions ships.
Script module¶
aegis2d::script runs entity behaviors in Lua, so that new enemies and patterns need no
recompilation. It builds on servers and clients alike, the behaviors running where the game
is simulated. Lua 5.4 (the Lua team's sources, built as a static library without the
interpreter) and sol2 3.5 (header-only C++ bindings) are pinned in
cmake/Dependencies.cmake and private to the module: no Lua header reaches the games, which
link aegis2d::script like any module.
| Header | Provides |
|---|---|
aegis2d/script/module.hpp |
name(); lua_version(), the _VERSION of a new Lua state read through sol2 ("Lua 5.4"), which checks that both are linked and run |
aegis2d/script/state.hpp |
ScriptState: a sandboxed Lua state, only the base functions, coroutine, math, string, table and utf8 open (no io, os, debug, package nor require; dofile and loadfile removed; load reads text only, never precompiled chunks; finalizers (__gc) refused and the collector never stopped); run(code, chunk), run_file(path), call(function) run the script on a thread of its own and return false when it fails, by a syntax error, an error at run time, more instructions than set_instruction_limit() allows (10 million by default, shared by the script's coroutines, each step of the pattern matcher counting as one, so an endless loop or a costly pattern stops, and a pcall cannot catch the stop) or more memory than set_memory_limit() allows (64 MB by default); the error is logged as chunk:line: message and kept in last_error() (ScriptError: chunk, line, message), and the state goes on; has(), number(), text(), boolean() read globals without their metamethods; print writes to the engine's log |
aegis2d/script/components.hpp |
bind_components(state, registry): a global table ecs for the scripts of a state: ecs.get(entity, "Transform"), ecs.add(entity, "Velocity", {x = -120}), ecs.has(), ecs.remove(), ecs.alive(), ecs.entities("Transform", "Velocity"); entities are their Entity::id(), components are read and written by field, vectors flattened (Transform.x, Sprite.width, Sprite.r), for Transform, Velocity, Sprite, Animation, Collider, Health, Damage, Score and SineMotion (component_names(), component_fields()); a component held by a script is found again at each access, so it never points to freed memory, and a gone component, an unknown field or a value of the wrong type is an error of the script; inline, so that the registry is reached from the caller's code (its pools are found by typeid) |
aegis2d/script/events.hpp |
emit(state, name, fields): an event to the scripts of a state, whose listeners (events.on(name, function(event) ... end), events.off(id)) get a table of its EventFields (whole numbers as integers), each listener's error kept apart from the others, under the state's budgets; scripts send events to each other with events.emit(name, {...}); EventBridge{state, bus}: the gameplay events of a core::EventBus sent to the scripts while it lives, ecs::Explosion as "Explosion" (entity, killer, x, y) and ecs::LifeLost as "LifeLost" (player, lives_left, score), inline, the bus finding its handlers by typeid; with the components, ecs.create({Transform = {...}, Sprite = {...}}) (all or nothing) and ecs.destroy(entity) |
The scripted enemy behaviors build on the sandboxed state and its bindings (the Engine: scripting epic). Script entity behaviors in Lua shows how to write one.
Network module¶
aegis2d::net provides the sockets, the framing, the packet header, the acknowledgements and
the reliable events; R-Type builds its server and client sessions on it (see
Networking architecture). The bytes it exchanges are specified in the
protocol RFC. Every packet is built and parsed field by field, so the bytes
on the wire are the same on every platform and untrusted input is never read past its end.
Asio stays private to the module: the public headers only show engine types.
net::BinaryWriter writer;
writer.write_u32(0x52545950); // magic
writer.write_u16(42); // sequence
writer.write_string("player one"); // u16 length, then the UTF-8 bytes
// send writer.data()
net::BinaryReader reader{datagram}; // received, untrusted bytes
const auto magic = reader.read_u32();
const auto sequence = reader.read_u16();
const auto name = reader.read_string();
if (!magic || !sequence || !name || !reader.at_end()) {
return; // truncated, forged or trailing bytes: drop the packet
}
net::NetworkContext context; // run by the network thread
net::UdpSocket socket{context, 4242}; // every interface, port 4242
socket.start_receiving([&](const net::Endpoint& from, std::span<const std::byte> datagram) {
// called on the context's thread, datagram <= 1200 bytes
});
socket.send_to(*net::Endpoint::parse("192.168.1.10", 4242), writer.data()); // any thread
context.run(); // until context.stop()
The login goes over TCP, which delivers a stream: a connection sends each message behind its length and hands the receiver whole messages, however the stream was split.
net::TcpListener listener{context, 4242}; // server
std::vector<net::TcpConnection> players;
listener.start_accepting([&](net::TcpConnection player) {
player.start([](std::span<const std::byte> message) { /* a whole message */ },
[](net::TcpCloseReason reason) { /* the player left: end the session */ });
players.push_back(std::move(player));
});
net::TcpConnection server{context}; // client
server.connect(*net::Endpoint::parse("192.168.1.10", 4242), [&](const std::error_code& error) {
if (error) { /* show error.message() on the connect screen */ return; }
server.start([](std::span<const std::byte> message) { /* session token */ });
server.send(writer.data()); // any thread, <= 4096 bytes
});
The sockets run on a network thread, and the game thread never waits on them: the two
threads exchange messages through two core::SpscQueue, one in each direction.
struct Datagram { net::Endpoint peer; std::vector<std::byte> data; };
core::SpscQueue<Datagram> incoming{1024}; // network thread -> game thread
core::SpscQueue<Datagram> outgoing{1024}; // game thread -> network thread
net::NetworkContext context;
net::UdpSocket socket{context, 4242};
socket.start_receiving([&](const net::Endpoint& from, std::span<const std::byte> datagram) {
if (!incoming.try_push({from, {datagram.begin(), datagram.end()}})) { /* full: drop */ }
});
net::NetworkThread network{context}; // after the sockets: stops before they go
loop.set_update([&](core::Duration step) { // game thread, 60 times a second
incoming.drain([](Datagram&& datagram) { /* decode, apply to the world */ });
systems.update(registry, step);
if (!outgoing.try_push({client, snapshot})) { /* full: the network is behind */ }
context.post([&] { // run by the network thread
outgoing.drain([&](Datagram&& d) { socket.send_to(d.peer, d.data); });
});
});
Each datagram acknowledges the last 33 datagrams of the peer in its header, and events
that must arrive (spawns, deaths...) are resent until a datagram that carried them is
acknowledged (RFC section 5). A ReliableChannel per peer does both:
net::ReliableChannel channel; // one per peer: the server has one per session
const auto now = net::ReliableChannel::Clock::now();
channel.send(death_event); // queued until the peer acknowledges it
net::BinaryWriter writer;
if (channel.write_events(writer, session, now) > 0) { // new events, and those lost
socket.send_to(peer, writer.data()); // an Event datagram
}
writer.clear();
net::write_header(writer, channel.next_header(net::PacketType::Snapshot, session));
/* the snapshot */ // every datagram carries the acks
// For each datagram received from the peer, after read_header():
if (header.type == net::PacketType::Event) {
std::vector<std::vector<std::byte>> events;
if (channel.read_events(header, reader, events)) { /* each event once, never twice */ }
} else if (payload_valid && channel.receive(header)) { // false: a duplicate
/* apply the input or the snapshot */
}
| Header | Provides |
|---|---|
aegis2d/net/binary.hpp |
BinaryWriter: explicit-size little-endian u8 to u64, i8 to i64, f32, f64 (IEEE 754 bits), bool, raw bytes and length-prefixed strings; BinaryReader: the same reads on untrusted bytes, each returning an empty std::optional instead of reading past the end; the first failure sticks, booleans other than 0 and 1 are rejected, string lengths are checked before allocating, at_end() rejects trailing bytes |
aegis2d/net/bits.hpp |
BitWriter: write_bits() for values of 0 to 64 bits, write_signed() in two's complement, write_bool() on one bit, packed from the least significant bit of each byte, the end of the last byte completed with 0 bits. BitReader: the same reads, bounds-checked with std::optional; the first failure (too few bits, invalid width) sticks, and at_end() rejects trailing data. Throwing on what cannot be written, like BinaryWriter. |
aegis2d/net/packet.hpp |
PacketHeader: the 18-byte header of every UDP datagram (magic, version, type, sequence, ack, ack bits, session, RFC section 2); PacketType (Connect, Accept, Input, Snapshot, Event, Heartbeat, Disconnect); write_header(), and read_header(), which checks the size, magic, version and type and returns the header or a HeaderError; compressed, the high bit of the type byte; max_datagram_size (1200) |
aegis2d/net/compression.hpp |
Optional LZ4 compression of payloads (RFC section 2.6): compress_payload() gives the size (u16) and the LZ4 block, or nothing when the payload does not shrink; decompress_payload() refuses a size of 0 or above 1182 and a block that is invalid or does not give that size; write_datagram(writer, header, payload, threshold) compresses from threshold bytes (default_compression_threshold, 128) when that pays and sets compressed; read_payload(header, reader) gives the payload, decompressed when the header says so |
aegis2d/net/sequence.hpp |
sequence_greater_than() and sequence_less_than(): compare two 16-bit sequence numbers across their wrap from 65535 to 0 (RFC 1982 serial number arithmetic, RFC section 2.2): a sequence 1 to 32767 steps ahead is more recent, so 0 is more recent than 65535; two sequences 32768 apart are not ordered; constexpr, header-only |
aegis2d/net/reliability.hpp |
Acknowledgements and reliable events (RFC section 5). AckTracker: the ack and ack_bits to send, from the sequences received (record() tells a new datagram from a duplicate or one too old; 65535 and 0 before anything arrived). ReliableChannel, one per peer: next_header(type, session) numbers each datagram from 0 and fills its acks; send(event) queues an event (at most max_event_size, 1177 bytes; nothing when max_events_in_flight, 256, are unacknowledged); write_events(writer, session, now) writes an Event datagram with the events due, oldest first: never sent, or sent resend_delay (100 ms) ago and not acknowledged; receive(header) records a valid datagram and the acknowledgements it carries; read_events(header, reader, events) checks an Event payload whole and hands each event over once, however many copies arrive; pending(), has_due_events(), stats(); given the times datagrams are sent and received (the optional now of next_header(), receive() and read_events()), rtt() estimates the round trip time. Game thread only |
aegis2d/net/rtt.hpp |
RttEstimator: the round trip time smoothed as in RFC 6298 (smoothed(), 7/8 of the previous estimate and 1/8 of each sample) and its jitter (jitter(), RTTVAR), from add_sample(); ReliableChannel::rtt() feeds it with one sample per datagram acknowledged for the first time in the ack field of the peer, which includes the time the peer waited before sending it |
aegis2d/net/traffic.hpp |
TrafficCounters, one per peer: record(direction, type, bytes, now) counts each datagram sent or received (record(direction, bytes, now) for one of unknown type); total() since the start and last_second() (the last whole second, 0 after a second without traffic), for a direction or a direction and a packet type, as a TrafficCount (datagrams, and bytes with the 18-byte header but without the IP and UDP headers). Thread that sends and receives only |
aegis2d/net/endpoint.hpp |
Endpoint: IPv4 or IPv6 address and port, built from bytes or parsed from a numeric address (no name resolution), comparable and hashable to key sessions and per-address counters; IPv4 peers seen through an IPv6 socket are stored as IPv4 |
aegis2d/net/context.hpp |
NetworkContext: the event loop that runs the network operations, poll(), run_for(), run() until stop() (thread-safe), restart(), post(task) runs a task on the context's thread (thread-safe) |
aegis2d/net/network_thread.hpp |
NetworkThread: runs a context on a thread of its own from construction until stop() (or destruction), which waits for the running handler and the thread; an exception escaping a handler is logged and counted (errors()) and the thread goes on; running(), is_network_thread(); stop() from the network thread itself throws std::logic_error |
aegis2d/net/udp_socket.hpp |
UdpSocket: bound to a port or an endpoint (SocketError if taken), start_receiving(handler) hands every datagram and its sender to the handler on the context's thread, send_to() copies the datagram and is thread-safe; datagrams over 1200 bytes are refused on send and dropped on receive, receiving goes on after errors (including Windows' "port unreachable"); stats() |
aegis2d/net/tcp_connection.hpp |
TcpConnection: TCP stream carrying messages behind a little-endian u16 length (RFC section 1.3), so the handler always gets a message whole, however the stream was split; connect(endpoint, handler) (asynchronous, errors comparable with std::errc, close() cancels it), start(on_message, on_close) on the context's thread, send() copies the message and is thread-safe, messages leave in order; over 4096 bytes is refused on send, and a peer announcing more is closed before anything is allocated; the close handler tells why a connection closed by itself (PeerClosed, Error, MessageTooLarge), never after close(); remote_endpoint() kept after the close, stats(). TcpListener: bound to a port or an endpoint (SocketError if taken), start_accepting(handler) hands every accepted peer over as a TcpConnection, accepting goes on after errors; closing it keeps the accepted connections. SocketError lives in socket_error.hpp, shared with UdpSocket |
Platform and render modules¶
The client modules are being written; the window, keyboard input actions, the mouse, the OpenGL context, the renderer interface and its camera, Tiled maps, shader programs, textures, the sprite batcher, bitmap font text and the players' colors and markers are in place.
| Header | Provides |
|---|---|
aegis2d/platform/window.hpp |
Window: SDL3 window, independent of the graphics API: size and high-density framebuffer size, title() and set_title(), quit requests, keyboard(), mouse() and text_input() fed by poll_events() (keys and mouse buttons released when the focus is lost; set_text_input() starts or stops the collection of typed text), gamepad(): every gamepad plugged in, opened and closed as they come and go, their states merged so any of them drives the player (gamepad_count(); buttons released when a pad is unplugged or the focus is lost; without SDL gamepad support the game goes on with the keyboard), id() for the render backends; no SDL type in the header; errors throw WindowError |
aegis2d/platform/keyboard.hpp |
Key: engine keys (letters, digits, F1 to F12, arrows, editing keys, modifiers, symbols, keypad) following the user's layout, with the US position as fallback; key_name() and key_from_name() (case-insensitive), stable names for settings files; Keyboard: keys held(), and pressed() or released() during the frame (a tap within one frame still counts, repeats do not), pressed_keys() in order |
aegis2d/platform/text_input.hpp |
TextInput: the UTF-8 text typed during the frame, following the user's keyboard layout (Shift, AltGr and dead keys applied), so an address typed on an AZERTY keyboard has its own punctuation; collected only while text input is on (Window::set_text_input()), text() is the frame's text in order; editing keys stay on the Keyboard; pop_back_utf8(text) removes the last code point, as Backspace does |
aegis2d/platform/mouse.hpp |
MouseButton (Left, Middle, Right, X1, X2); Mouse: like Keyboard, buttons held(), and pressed() or released() during the frame (a click within one frame still counts), position() in window coordinates and moved(), wheel() turned during the frame (y above 0 away from the player, natural scrolling undone); render::opengl::Renderer::to_logical() turns the position into logical pixels |
aegis2d/platform/gamepad.hpp |
GamepadButton: buttons named by position (South is A, Cross or B), with the triggers and the stick directions as buttons too, so actions bind to them; GamepadAxis (sticks from -1 to 1, y down; triggers from 0 to 1); button_name() and button_from_name() for settings files; button_label(button, style) as printed on the pad (GamepadStyle: "A", "Cross", "ZR", "D-pad up", "Left stick left"); Gamepad: like Keyboard, buttons held(), pressed(), released() during the frame, plus axis(); set_axis() presses a stick direction or a trigger past press_threshold (0.5) and releases it below release_threshold (0.35), so a stick resting near the edge does not flicker; merge() for several pads, connected(), style() |
aegis2d/platform/actions.hpp |
ActionMap: named actions (add("fire", {Key::Space}, {GamepadButton::South}) returns an ActionId) with their default keys and gamepad buttons; held(), pressed(), released() against a Keyboard, or a Keyboard and a Gamepad together; rebindable in code: bind(), rebind(), unbind() for a key or a button (rebinding one keeps the other), clear(), reset(), reset_all(); a key or a button triggers one action, binding it takes it from the other; save(settings, "input") writes each action as an array of key names, load() reads them back (actions missing or unreadable keep their keys); save_buttons(settings, "gamepad") and load_buttons() do the same for the buttons, in their own section |
aegis2d/platform/key_capture.hpp |
KeyCapture: the "press a key for Fire" step of a settings menu: start(action, keyboard), then update(actions, keyboard) each frame binds the next key pressed (rebind()), Escape cancels; returns a CapturedKey (action, key, action that lost it) |
aegis2d/platform/latched_action.hpp |
LatchedAction: an action held without holding its key, such as auto-fire: with the option on, a press holds the action and the next press releases it (update(actions, keyboard) or update(actions, keyboard, gamepad) once per frame, held(), release()), with it off the action follows its key; save() and load() keep the option in the player's settings |
aegis2d/platform/controls.hpp |
The controls in words: control_lines(actions, labels) lists each action with the keys that trigger it now (after the player's remap), control_lines(actions, style, labels) with the gamepad buttons as printed on the player's pad; keys_label() ("Up / W", "not bound"), buttons_label() ("A / RT", "Cross / R2"), action_label() ("move-up" → "Move up"); key_label() in keyboard.hpp names keys for players ("Left Shift", "Keypad 5") |
aegis2d/platform/settings.hpp |
settings_dir(organization, application): per-user folder for the player's settings (SDL pref path, created if needed); read_settings(file): a missing file, or one that cannot be parsed (logged), gives an empty Config, so a broken file never stops the game |
aegis2d/render/opengl/context.hpp |
opengl::Context: OpenGL core context of a window (4.5, or 4.1 with AEGIS2D_MACOS_GL41), functions loaded with glad, version checked against the driver, OpenGL errors logged in debug builds (KHR_debug callback, or glGetError at each frame on macOS), vsync, clear and swap_buffers; errors throw ContextError |
aegis2d/render/color.hpp |
Color: RGBA color; rgb(0x0072B2) from a hexadecimal code |
aegis2d/render/color_vision.hpp |
simulate(color, vision): a color as seen with protanopia, deuteranopia, tritanopia (Machado 2009) or achromatopsia; relative_luminance() and contrast_ratio() (WCAG 2), lightness() (CIE L*), color_difference() (CIE76 ΔE): to check that a palette stays readable for everyone |
aegis2d/render/player_style.hpp |
player_styles: color and MarkerShape (circle, triangle, square, diamond) of each of the max_players (4) players, colorblind-safe and distinct in grayscale; player_style(index); marker_image(shape, size): the marker as RGBA pixels, white outlined in black, to load as a texture and tint |
aegis2d/render/screen_effects.hpp |
ScreenEffects: full-screen flash(color, seconds) that fades out (at most 3 started per second, WCAG 2.3.1) and camera shake(strength, seconds) that calms down (seeded directions); update(seconds) each step, then overlay(screen) (a full-screen sprite on the top layer), tint(background) and offset() for the camera (Camera::set_shake()); EffectSettings (flashes, shake) turns either off, saved with save() and load() in the player's settings |
aegis2d/render/metrics_overlay.hpp |
FrameMetrics: tick(now) once a frame keeps the durations of the last 120 frames (record(seconds) for a known one), fps() over the last second, last_ms(), average_ms(), worst_ms(), frame_ms(index) oldest first; MetricsOverlay: a panel for developers, hidden until toggle() or set_visible(true), with the frames per second, the mean and longest frame times, the entities given to draw(renderer, font, metrics, entities, lines) and the sprites and draw calls of the frame before, the memory of the process (memory(), read twice a second while shown), the game's own lines (its network numbers while connected...), and a bar per frame kept, a line marking the budget (MetricsOverlayStyle::budget_ms, 60 frames per second) and the slower frames in another color; drawn once a frame, shown or not, its counts leave out its own sprites and draw calls (game_stats(renderer), with batching or without); metrics_text() its text. The ship and stress examples and the tower defense sample show it with F12 (--metrics from the start) |
aegis2d/render/renderer.hpp |
IRenderer: what the game draws with, whatever the backend: create_texture(image), update_texture(texture, image) (a new image, of any size, under the same identifier, so every sprite drawn with it shows it) and texture_size(), begin_frame(clear), draw(Sprite), end_frame(), stats() (sprites and draw calls), set_camera() (the sprites drawn after it are in world coordinates, placed by the camera; std::nullopt for the HUD, in screen coordinates); Sprite (texture id, position, size, source rectangle, tint, layer), Rect, TextureSize; positions are aegis2d::Vec2 |
aegis2d/render/camera.hpp |
Camera(view): the part of a world larger than the screen that is shown, a view of a fixed size on screen (such as the logical screen) centered on a world point; follow(target) each frame scrolls with the player, kept within set_bounds(rect) (centered on bounds smaller than the view), set_zoom() (screen pixels per world pixel), set_shake(offset) moves the picture without moving the camera; visible() (the world area shown, for culling), to_screen() for a point or a Sprite, to_world() for the mouse |
aegis2d/render/tile_map.hpp |
TileMap::load(path): an orthogonal map made in Tiled, saved as JSON (.tmj), with its tilesets, embedded or in .tsj files (Tileset: image resolved from the file that names it, tile size, tile(index) as a PixelRect); layers from the bottom one (MapLayer): the tiles of a tile layer (global tile ids row by row, 0 for none, with the flip_horizontal, flip_vertical and flip_diagonal bits; tile_id_mask removes them) or the objects of an object layer (TileObject: id, name, class, position, size, rotation, optional tile); the layers of a group in its place, its offset, opacity and visibility applied; custom properties (TileProperties) on the map, tilesets, layers and objects; tileset(gid), layer(name); a broken map (missing field, tile id that no tileset has, tiles that do not fit in the image) or an unsupported one (base64 or compressed data, infinite, isometric, image layers) throws TileMapError with the file and the reason |
aegis2d/render/tile_map_view.hpp |
TileMapView(map, textures): a TileMap ready to draw, the image of each tileset loaded once; draw(renderer, first_layer) draws every visible tile layer, layer i of the map on sprite layer first_layer + i, draw_layer() one of them; each tile is a sprite placed as Tiled shows it (in its cell, bottom-left aligned when larger than the cells, with the layer's offset and opacity, flipped by the bits of its id; tiles rotated in Tiled are drawn unrotated); with a camera, only the cells around Camera::visible() are drawn, so a map of any size costs one screen of tiles, one draw call per tileset and layer |
aegis2d/render/image.hpp |
Image: RGBA pixels from the top left; Image::load() (PNG, JPEG, BMP, TGA... through stb_image, UTF-8 paths), from_pixels() for generated images, save_png(), pixel(x, y); errors throw ImageError with the path |
aegis2d/render/texture_manager.hpp |
TextureManager: textures found by name (load("ship", path), add(name, image), get(), find()); a file is read and sent to the GPU once, even under another name or path; sprite sheets: load_sheet(name, path, frame_size), set_sheet(), sheet(), and source(texture, frame), the rectangle that ecs::Sprite::frame draws; reload(path) reads a loaded file again into the same texture, at the same size, so sheets, tile maps and sprite sizes stay right (another size, or a file that does not decode, leaves the texture as it was), and watch(hot) reloads every loaded file with a core::HotReload |
aegis2d/render/starfield.hpp |
Starfield(area, layers, seed): a parallax background, layers of stars (StarLayer: count, speed in pixels a second, size, color; default_star_layers: three, the far ones small, dim and slow) spread from a seed; update(seconds) or update(step) adds time and draw(renderer, layer) draws them all, farthest first, wrapping around the screen. Positions depend only on the time spent (elapsed(), positions(layer)), so the stars scroll at the same speed at any frame rate |
aegis2d/render/particles.hpp |
ParticleEmitter(config, seed): sparks, smoke and trails; EmitterConfig: rate per second (the fraction of a step carried over, so the count is the same at any frame rate), lifetime and speed as Ranges, direction and spread (radians, y down), start_size and end_size, start_color and end_color (fade out with an alpha of 0), max_particles; set_position(), set_emitting(), burst(count) for explosions, update(seconds) ages, moves and removes the particles then spawns the step's; particles() (position, velocity, age, lifetime), size(particle) and color(particle) over its life; the same seed gives the same particles; draw(renderer, layer, texture) draws every particle in the sprite batch, a square centered on its position with its size and color now (plain or textured), all in one draw call per layer |
aegis2d/render/sprite_sheet.hpp |
SpriteSheet: how a texture is cut into frames, numbered from 0: SpriteSheet::grid(texture, frame_size, count, spacing) for frames of one size, left to right then top to bottom, or explicit PixelRects for packed sheets; frame(index) in pixels, source(index) as the normalized Sprite::source |
aegis2d/render/sprite_batch.hpp |
batch_sprites(sprites): sorts a frame's sprites by layer then texture (stable) and returns the runs that share both, one draw call each |
aegis2d/render/bitmap_font.hpp |
BitmapFont: monospaced text drawn as sprites of an atlas (one draw call for all the text of a layer); builtin(textures), the engine's own 5 x 8 font for printable ASCII; draw(renderer, text, position, {scale, color, layer}), measure(), line_height(), wrap(text, width, scale) (word wrap, UTF-8 aware); \n breaks lines, unknown and non-ASCII characters show as ?; GlyphGrid for other atlases |
aegis2d/render/text_layout.hpp |
TextSize: the player's text size, 100% to 200% by steps of 25% (larger(), smaller(), apply(style), save(), load()); flow_layout(sizes, area, gap): boxes left to right, a new row when one does not fit, so larger text never overlaps; overlaps() and contains() for rectangles |
aegis2d/render/controls_table.hpp |
draw_controls(renderer, font, lines, position, style) and measure_controls(): control lines as a two-column table (actions, then their keys aligned), with ControlsTableStyle (text styles, column and row gaps) |
aegis2d/render/sound_cues.hpp |
SoundCues: captions for important sounds (show(SoundCue{caption, source, color, seconds}), update(), draw(renderer, font, screen, style)); a cue with a source sits on the nearest screen edge with an arrow toward it, one without is a caption at the bottom center; cues fade out, never overlap, a repeated caption is refreshed; off by default, save() and load() keep the option |
aegis2d/render/letterbox.hpp |
LogicalScreen: a fixed screen size (1280 x 720 by default) the game lays out on, with its ScaleMode (Fit: as large as the window allows; Integer: whole scales only, so pixel art stays even) and the color of its bars; letterbox(logical, width, height, mode): where it goes in a framebuffer, centered, aspect ratio kept, as a Letterbox (area in pixels and scale); to_logical(box, point): the logical pixel under a framebuffer point, outside the screen on a bar |
aegis2d/render/opengl/renderer.hpp |
opengl::Renderer: IRenderer owning the window's OpenGL context; set_logical_screen() draws at a fixed logical size, scaled to the window with bars (letterbox() tells where), or, by default, at the window's size; to_logical(window_point) turns a point of the window, such as the mouse, into logical pixels; one opengl::Texture per create_texture(), sampled with the nearest texel, sprites batched (batch_sprites()), the whole frame's vertices sent at once, alpha blending that keeps the screen opaque; capture_next_frame() and captured() read a frame back as an Image (screenshots, tests); set_draw_mode(DrawMode::Naive) sends each sprite on its own (one upload, bind and draw call per sprite, the same picture) to measure what batching saves; set_gpu_timing(true) measures the GPU time of each frame with OpenGL timer queries, read back a few frames later without waiting for the GPU (gpu_time()) |
aegis2d/render/headless_renderer.hpp |
HeadlessRenderer: IRenderer without window, which records each frame's sprites and the sizes of its textures, and counts the draw calls a GPU backend would make, for tests and tools |
aegis2d/render/opengl/texture.hpp |
opengl::Texture: an image on the GPU (RGBA8), from an Image or Texture::load(path) (PNG and the other formats of Image::load()); sampled with the nearest texel, so pixel art scaled up stays sharp and sprite-sheet frames do not blend into each other, with clamped edges; size(), id(), bind(unit), pixels() to read it back (tests, tools); move-only, deleted with the object |
aegis2d/render/opengl/shader.hpp |
opengl::ShaderProgram: vertex and fragment GLSL compiled and linked, #version added to match the context (450, or 410 on macOS), cached uniform locations, set_uniform for int, float, Vec2, Vec4, Color and Mat4; errors throw ShaderError with the driver's log |
The window does not know which graphics API draws into it: WindowConfig::graphics
only prepares it (SDL needs OpenGL windows to be created as such). Each render backend
owns its context or swapchain and finds the window through Window::id(), so a Direct3D
or Vulkan backend would sit next to rendersystem/opengl/ without touching platform.
Game code only sees render::IRenderer: the same drawing code runs with the OpenGL
backend in the client and with HeadlessRenderer in unit tests.
A world larger than the screen is drawn in world coordinates through a camera, which the renderer applies to each sprite as it is drawn; the HUD is drawn after it, without one:
render::Camera camera{{1280.0F, 720.0F}}; // the logical screen
camera.set_bounds(render::Rect{.width = 4000.0F, .height = 720.0F}); // the level
...
camera.follow(player_position); // each frame: scrolls, stops at the edges
camera.set_shake(effects.offset()); // render::ScreenEffects shake the camera
renderer.begin_frame(background);
renderer.set_camera(camera);
map_view.draw(renderer); // a render::TileMapView: the level's tiles
... draw the entities, in world coordinates, on sprite layers above the map's ...
renderer.set_camera(std::nullopt);
... draw the HUD, in screen coordinates ...
renderer.end_frame();
The game lays out its screen once, at a fixed logical size: the renderer scales it to the window, keeping its aspect ratio, and fills the rest with bars. A player who resizes the window, or plays on a screen of another shape, sees the same picture, larger or smaller, never stretched:
opengl::Renderer renderer{window}; // window resizable or not
renderer.set_logical_screen(render::LogicalScreen{.size = {1280.0F, 720.0F}});
renderer.draw({.position = {1200.0F, 40.0F}, ...}); // logical pixels, whatever the window
renderer.letterbox(); // where the screen is in the window

Animated sprites come from sprite sheets: a texture cut into frames of the same size. The
ECS plays a clip of frames with an ecs::Animation, at a rate set in seconds, so it runs
at the same speed whatever the tick or frame rate; the client draws the frame the sprite
shows:
// ship.png: four 16x9 frames side by side, the engine flame flickering.
const auto ship = textures.load_sheet("ship", core::asset_path("ship.png"), {.width = 16, .height = 9});
registry.emplace<ecs::Animation>(entity, ecs::Animation{.count = 4, .frame_time = 0.06F});
ecs::animate_sprites(registry, tick); // each tick: Sprite::frame follows
renderer.draw({.texture = sprite.texture, .position = ..., .size = sprite.size,
.source = textures.source(sprite.texture, sprite.frame)});
Effects are client-side: gameplay publishes what happened on the event bus, and each client turns it into something to see. An explosion is a clip that plays once, on an entity destroyed after its last frame, so every kill shows one and none is left behind:
events.subscribe<ecs::Explosion>([&](const ecs::Explosion& explosion) {
const ecs::Entity blast = registry.create();
registry.emplace<ecs::Transform>(blast, explosion.position);
registry.emplace<ecs::Sprite>(blast, ecs::Sprite{.texture = explosion_sheet, .size = {64.0F, 64.0F}});
registry.emplace<ecs::Animation>(blast, ecs::Animation{.count = 6, .frame_time = 0.06F, .loop = false});
registry.emplace<ecs::DestroyAfterAnimation>(blast);
});
ecs::animate_sprites(registry, tick);
ecs::destroy_finished_animations(registry, faded); // effects whose clip has ended

Gameplay reads actions, never raw keys or buttons. shmup::ShipControls declares the
actions of a player ship with the subject's default keys (arrows to move, Space to fire)
and their gamepad buttons (D-pad or left stick, A or the right trigger), and gives, each
frame, the byte the client sends in its ecs::PlayerInput; changing a key or playing with
a pad changes no gameplay code:
shmup::ShipControls controls; // up, down, left, right, fire
controls.load(settings, "input", "accessibility.auto_fire", "gamepad"); // keys, buttons
controls.actions().bind(controls.id(ecs::Action::Up), platform::Key::W);
controls.actions().bind(controls.id(ecs::Action::Fire),
platform::GamepadButton::RightShoulder);
window.poll_events(); // once per frame
registry.get<ecs::PlayerInput>(ship).held =
controls.update(window.keyboard(), window.gamepad()); // either, or both
Players can change their keys (see Accessibility). The bindings live in
the player's settings file, read at start and written at each change; a settings menu binds
the next key pressed with KeyCapture:
const auto file = platform::settings_dir("Aegis2D", "RType") / "settings.json";
actions.load(platform::read_settings(file), "input"); // after the actions are declared
platform::KeyCapture capture;
capture.start(fire, window.keyboard()); // "Press a key for Fire"
// each frame, after window.poll_events():
if (const auto captured = capture.update(actions, window.keyboard())) {
if (captured->key) { // not cancelled with Escape
auto settings = platform::read_settings(file); // keeps the other settings
actions.save(settings, "input");
settings.save(file);
}
}
using namespace aegis2d;
platform::Window window{{.title = "R-Type", .width = 1280, .height = 720}};
render::opengl::Renderer renderer{window};
render::TextureManager textures{renderer};
const render::TextureId ship = textures.load("ship", core::asset_path("sprites/ship.png"));
const auto font = render::BitmapFont::builtin(textures);
std::uint32_t score = 0;
core::MainLoop loop{core::FixedTimestep{core::step_from_rate(60)}};
loop.set_render([&](double /*alpha*/) {
window.poll_events();
if (window.close_requested()) {
loop.stop();
return;
}
renderer.begin_frame({.r = 0.02F, .g = 0.02F, .b = 0.08F});
renderer.draw({.texture = ship, .position = {100.0F, 200.0F}, .size = {32.0F, 16.0F}});
font.draw(renderer, std::format("SCORE {:06}", score), {16.0F, 16.0F},
{.scale = 3.0F, .layer = 100}); // over the scene
renderer.end_frame(); // 2 draw calls: ship, then text
});
loop.run();
UI module¶
aegis2d::ui holds the widgets of menus and forms and moves the focus between them with
the keyboard, a gamepad or the mouse, so every menu can be used with any of the three.
| Header | Provides |
|---|---|
aegis2d/ui/widget_tree.hpp |
WidgetTree: widgets (add(bounds, group), rectangles at 100% in logical pixels, which can take the focus) in groups (add_group(), which never do), from the root group; set_enabled() on a widget or a whole group (a disabled widget is skipped and loses the focus to the next one); focused(), focus(), clear_focus(); focus_next() and focus_previous() in the tree's order, wrapping around; move_focus(Direction) to the nearest widget in a direction (distance along it plus twice the offset across it, so the widget straight ahead wins); at(point), the widget under the mouse; set_scale(scale, origin) follows the player's text size, bounds() gives the scaled rectangle; scaled(point) places a point given at 100%; update(navigation) applies a frame's Navigation (next, previous, direction, pointer, click, activate, held): the mouse, then Tab, then a direction |
aegis2d/ui/navigation.hpp |
NavigationInput: its own ActionMap, so the menus keep their keys whatever the game binds: ui-up to ui-right on the arrows, the D-pad and the left stick, ui-next on Tab and the right shoulder, ui-previous on the left shoulder and Shift+Tab, ui-activate on Enter, Space and South, all remappable (actions()); read(keyboard, gamepad, mouse, pointer) returns the frame's Navigation, with the mouse's logical position as the pointer when it moved or clicked, and held while activate or the main mouse button is down |
aegis2d/ui/menu.hpp |
Menu: buttons (add_button(text, bounds, group), widgets of its tree(), text centered) and labels (add_label(text, position), never focused), set_text(), set_label(); update(navigation) moves the focus and returns the button used: the focused one when activate is pressed, or the one clicked, never a disabled one; state(button): WidgetState Normal, Focused, Pressed (focused and held) or Disabled; draw(renderer, font) at the tree's scale, the focused button outlined as well as colored; MenuStyle: colors (text at least 4.5:1 against every background, WCAG AA), outline, text scale and layer |
aegis2d/ui/widgets.hpp |
Slider(tree, bounds, config, group): a value between min and max as a widget of the tree; focused, Left and Right move it by step and are consumed, so the focus stays; the mouse presses or drags the handle; value(), set_value(); draw() shows the track, its filled part and the handle, the focused slider outlined. ListView(tree, bounds, items, visible, group): a scrollable list, one widget; focused, Up and Down move the selection (consumed, except at the ends, where the focus walks out) and the list scrolls to keep it visible; a click selects and chooses a row, activate chooses the selected one (update() returns it); draw() shows the visible rows, the selection, the focus outline and a scrollbar when items are off screen. SliderStyle and ListStyle: colors, outline, layer |
aegis2d/ui/text_field.hpp |
TextField(tree, bounds, config, group): an editable line of text as a widget of the tree, on the platform's text input, so typed characters follow the keyboard layout; the frame's text is inserted at the cursor up to max_length characters (code points: accents and emoji whole), Backspace and Delete remove one, Left and Right move the cursor (consumed, so the focus stays), Home and End jump, Space types instead of activating, and gaining the focus puts the cursor at the end; text(), set_text(), cursor(); draw() shows the field, its text or dimmed placeholder and the cursor, the focused field outlined, and a text longer than the field scrolls to keep the cursor in view (nothing is drawn past its edges); TextFieldStyle. The caller starts the window's text input while a field is focused |
aegis2d/ui/console.hpp |
Console: the in-game console, for developers; toggle_key (Key::Grave, the key under Escape whatever the layout) opens and closes it, and while it is open update(keyboard, text) takes the keyboard (it returns true then, for the game to ignore it): the typed text goes to the input line, Backspace removes a character, Up and Down bring back the lines run before (history(), the last history_capacity, a line kept once when run twice in a row; recall_previous(), recall_next()), Tab completes the first word, or the name after help, with the names of the commands and variables (complete(): one name whole, several as far as they agree, then listed), Enter runs the line through its own core::Commands (commands(), where the game adds its commands and add_variables() its console variables; the console adds clear), Page Up and Page Down scroll, Escape closes; submit(line) runs a line as typed, echoed after > with what the command shows, or the error; print(), clear(), lines() (the last capacity, as ConsoleLines: input, output or error), input(), set_input(), scroll(), scroll_by(); draw(renderer, font, screen, ConsoleStyle) shows it over the top of the screen, the output wrapped to its width above the input line and its cursor. The caller starts the window's text input while it is open |
ui::WidgetTree form; // a connect form
const auto name = form.add({.x = 40, .y = 40, .width = 200, .height = 24});
const auto join = form.add({.x = 40, .y = 72, .width = 96, .height = 24});
form.set_scale(text_size.scale(), {40.0F, 40.0F}); // grows with the player's text size
ui::NavigationInput navigation;
navigation.actions().load(settings, "ui"); // the player's keys for menus
// Once per frame, after window.poll_events():
form.update(navigation.read(window.keyboard(), window.gamepad(), window.mouse(),
renderer.to_logical(window.mouse().position())));
if (form.focused() == join) { /* draw Join highlighted */ }
ui::Menu menu; // buttons and labels on a tree
menu.add_label("AEGIS2D", {440.0F, 100.0F});
const auto start = menu.add_button("Start", {.x = 440, .y = 160, .width = 280, .height = 40});
const auto quit = menu.add_button("Quit", {.x = 440, .y = 208, .width = 280, .height = 40});
const auto used = menu.update(navigation.read(window.keyboard(), window.gamepad(), window.mouse(),
renderer.to_logical(window.mouse().position())));
if (used == quit) { window.request_close(); }
menu.draw(renderer, font); // states, focus outline, labels
Audio module¶
aegis2d::audio plays sounds and looping background music, and plays the sounds of
gameplay events by itself.
| Header | Provides |
|---|---|
aegis2d/audio/audio.hpp |
AudioDevice: the default audio output (SDL3); load(wav) returns a SoundId, play(sound, channel) mixes it with the sounds already playing (SDL converts every sound to the device format on its own thread, at most max_voices (32) at a time, the oldest stopped first), play(sound, channel, pan, gain_scale) plays with stereo panning (-1 left, 0 center, 1 right) and distance attenuation (0–1); positional(position, camera_center, view_half_width) converts a world position to {pan, gain_scale}; stop(channel), stop_all(), update() frees finished sounds once per frame, playing() and playing(channel); set_volumes() applies the gain of each channel to new and playing sounds; play_music(sound, loop) plays the background music on Channel::Music, looping without a gap (SDL's audio thread asks for the next samples as it needs them), never stopped to make room for effects, stop_music(), music_playing(); Channel (Effects, Music); errors throw AudioError, so a game without an audio device can go on silently |
aegis2d/audio/volume.hpp |
Volumes: master, music and effects sliders from 0 to 1; gain(channel) is master² × channel² (equal steps sound like equal changes of loudness), so each slider changes only its channel and master changes both; clamped(); save(settings, "audio") and load() keep them in the player's settings |
aegis2d/audio/event_sounds.hpp |
EventSounds(device, events): the game says once which sound each event plays, and gameplay never calls audio. play_on<Event>(sound, filter, options) plays sound each time an Event (any type published on the core::EventBus, such as shmup::ShotFired) is published, if the optional filter accepts it; several rules can listen to one event type. SoundOptions: channel, and min_interval (50 ms by default), the shortest time between two starts by one rule, so ten explosions in one tick are heard once, not ten times louder. A sound that cannot start is logged and skipped. clear() and the destructor remove the rules from the bus; rules() |
audio::AudioDevice audio; // AudioError if there is no output
const audio::SoundId click = audio.load(core::asset_path("click.wav"));
audio.play(click); // Channel::Effects by default
audio.update(); // once per frame
audio::EventSounds sounds{audio, events}; // gameplay events play their sounds:
sounds.play_on<shmup::ShotFired>(audio.load(core::asset_path("shot.wav")));
sounds.play_on<ecs::Explosion>(audio.load(core::asset_path("explosion.wav")));
sounds.play_on<ecs::LifeLost>(audio.load(core::asset_path("death.wav")));
sounds.play_on<shmup::ShotFired>(enemy_shot, [](const shmup::ShotFired& shot) {
return !shot.player; // only the enemies' shots
}, {.min_interval = std::chrono::milliseconds{100}});
audio.play_music(audio.load(core::asset_path("music.wav"))); // loops until stop_music()
audio::Volumes volumes; // the player's sliders
volumes.load(platform::read_settings(file), "audio");
audio.set_volumes(volumes); // also changes playing sounds
Build structure¶
- Every module is declared with
aegis2d_module(<name> <sources>)(cmake/Modules.cmake): a shared library with hidden symbol visibility, a generatedaegis2d/<name>/export.hpp, public headers inpublic/aegis2d/<name>/and theaegis2d::<name>alias. aegis2d_copy_assets(<target> <folder>...)copies a game's assets, from one folder or several, next to its binary at each build;aegis2d_stage_runtime(<target>)does the same for the engine DLLs on Windows.aegis2d_install(TARGETS … ASSETS …)andaegis2d_package(NAME …)(cmake/Install.cmake) install a game with the engine libraries and SDL3 (relative run paths, no system libraries needed) and package it with CPack:.tar.gz, or.zipon Windows.aegis2d::warnings(strict warnings, optionally as errors) andaegis2d::sanitizers(ASan and UBSan whenAEGIS2D_SANITIZE=ON; withAEGIS2D_FUZZ=ON, also the coverage libFuzzer steers by) are attached to every module.aegis2d::enginelinks every built module, for games that want all of them.aegis2d_install_development()(cmake/Package.cmake) installs the engine for games that build against it withfind_package(Aegis2D COMPONENTS ...): modules, headers, GLM's headers, SDL3 and theAegis2DTargetspackage with one component per module, all in thedevelopmentcomponent, left out of the games' installs and packages.- Dependencies are declared once in
cmake/Dependencies.cmake, pinned, and fetched by CPM.
Repositories and delivery¶
flowchart LR
engine["Aegis2D-Dev/aegis2d<br/>engine"] -->|FetchContent| game["Aegis2D-Dev/project-rtype<br/>game"]
engine -->|"push to master"| mirror["Epitech mirror workflow"]
game -->|"push to master<br/>(dispatch)"| mirror
mirror -->|"build + validated sources"| epitech["Epitech delivery repository"]
The game fetches the engine with CMake FetchContent. On delivery, the
mirror workflow assembles both repositories, builds them, and
publishes the validated sources to the Epitech repository.