Aegis2D
Modular C++26 2D game engine for networked games
Loading...
Searching...
No Matches
aegis2d::core Namespace Reference

Logging, time, main loop, events and configuration shared by client and server. More...

Classes

struct  CommandArg
 An argument a command takes: {.name = "count", .type = ArgType::Integer}. More...
 
class  CommandCall
 The arguments of a command being run, read in their types. More...
 
struct  CommandResult
 What running a line gave. More...
 
class  Commands
 The commands a console runs: each has a name, its arguments and a help. More...
 
class  Config
 JSON configuration file (server port, window size...) read through typed getters. More...
 
class  ConfigError
 Thrown when a configuration cannot be read or parsed. More...
 
struct  ConfigMember
 One member of a JSON object. More...
 
struct  ConfigValue
 One value of a configuration document, independent of the JSON library. More...
 
class  ConsoleVariables
 The settings a console reads and changes by name while the game runs. More...
 
struct  EngineLibrary
 An Aegis2D library, opened and checked by load_library(). More...
 
class  EventBus
 Lets systems react to events without knowing who sends them. More...
 
class  EventQueue
 Deferred event queue dispatched by priority at a chosen point in the tick. More...
 
class  FixedTimestep
 Turns variable frame times into a whole number of fixed simulation steps. More...
 
class  HotReload
 Watches files and reloads each one with its own function when it changes. More...
 
class  LibraryError
 A shared library could not be opened or is not one the engine can load. More...
 
struct  LibraryInfo
 What an Aegis2D library tells about itself, from its C entry point. More...
 
class  Logger
 Writes timestamped messages to the console (std::clog) and to an optional file. More...
 
class  MainLoop
 Drives a game: fixed-rate updates, then one render per frame. More...
 
class  Preloader
 Loads a list of resources in the background, telling how far it is. More...
 
struct  PreloadFailure
 A resource a Preloader could not load, and why. More...
 
struct  ProfileEntry
 Time a named part of a frame took, as Profiler::last_frame() gives it. More...
 
class  Profiler
 Timers around the parts of a frame (its phases, each system of a ecs::Scheduler...), and the breakdown of the last frame for the metrics overlay. More...
 
class  ProfileScope
 Times a scope while it lives: from Profiler::scope() to its destruction. More...
 
class  Random
 Seeded pseudo-random generator (PCG32), for gameplay the server must replay. More...
 
class  ResourceCache
 Shares resources by name: each is loaded once, counted, and freed when unused. More...
 
class  SharedLibrary
 A shared library opened at run time (.so, .dylib or .dll), closed when destroyed. More...
 
class  SpscQueue
 Fixed-capacity FIFO queue passing values from one thread to another without locks. More...
 
class  Stopwatch
 Measures elapsed time with the monotonic std::chrono::steady_clock. More...
 
struct  TraceEvent
 A scope timed while tracing (Profiler::start_trace()), for write_chrome_trace(). More...
 
struct  TraceThread
 The trace of one thread, as write_chrome_trace() writes it. More...
 
struct  VarFlags
 What a console variable allows: {.saved = true, .cheat = true}. More...
 
struct  VarInfo
 A console variable as declared, with its value now. More...
 
struct  VarSetting
 A variable to set, as a command line or a settings file gives it. More...
 
struct  VarSettings
 Settings read from a command line or a file, and what could not be read. More...
 

Typedefs

using Duration = std::chrono::nanoseconds
 Duration type used for simulation time (nanoseconds).
 
using CommandHandler = std::function< std::string(const CommandCall &call)>
 What a command does with its arguments.
 
using VarValue = std::variant< bool, std::int64_t, double, std::string >
 Value of a console variable: a boolean, an integer, a number or a text.
 
using SubscriptionId = std::uint64_t
 Handle returned by EventBus::subscribe(), used to unsubscribe. Never 0.
 

Enumerations

enum class  ArgType : std::uint8_t { Text , Integer , Number , Boolean }
 Type of an argument of a command, read from its text as a console variable's. More...
 
enum class  CommandStatus : std::uint8_t {
  Done , Empty , Unknown , WrongArguments ,
  Failed
}
 How running a line went. More...
 
enum class  VarResult : std::uint8_t {
  Changed , Unknown , ReadOnly , Cheat ,
  WrongType , BadText
}
 What became of a change of a console variable. More...
 
enum class  LogLevel : std::uint8_t {
  Debug , Info , Warn , Error ,
  Off
}
 Severity of a log message, from the most verbose to the most severe. More...
 

Functions

constexpr Duration step_from_rate (std::uint32_t ticks_per_second) noexcept
 Length of one step for a given update rate.
 
std::string_view to_string (VarResult result) noexcept
 Sentence for a VarResult, as a console shows it.
 
std::string to_text (const VarValue &value)
 A value as text, as ConsoleVariables::set_text() reads it.
 
std::optional< VarValue > read_value (std::string_view text, const VarValue &like)
 Reads a value from text, in the type of another one, as ConsoleVariables::set_text() does.
 
bool is_console_name (std::string_view name) noexcept
 Tells whether a name is valid for a console variable or a command.
 
std::string_view to_string (LogLevel level) noexcept
 Short upper-case name of a level.
 
template<typename... Args>
void log_debug (std::format_string< Args... > format, Args &&... args)
 Logs a Debug message with the global logger.
 
template<typename... Args>
void log_info (std::format_string< Args... > format, Args &&... args)
 Logs an Info message with the global logger.
 
template<typename... Args>
void log_warn (std::format_string< Args... > format, Args &&... args)
 Logs a Warn message with the global logger.
 
template<typename... Args>
void log_error (std::format_string< Args... > format, Args &&... args)
 Logs an Error message with the global logger.
 
std::optional< std::size_t > memory_use () noexcept
 Memory of the process in RAM now: its resident set (Linux, macOS) or working set (Windows), in bytes.
 
std::string_view name () noexcept
 Name of the module, used to check that it is linked.
 
std::filesystem::path executable_dir ()
 Folder containing the running executable.
 
std::filesystem::path asset_dir ()
 Folder of the assets copied next to the executable by aegis2d_copy_assets().
 
std::filesystem::path asset_path (const std::filesystem::path &relative)
 Path of one asset.
 
void write_chrome_trace (std::ostream &out, std::span< const TraceThread > threads, std::string_view process="aegis2d")
 Writes traces in the Chrome trace format, which Perfetto (ui.perfetto.dev) and chrome://tracing open.
 
void save_chrome_trace (const std::filesystem::path &file, std::span< const TraceThread > threads, std::string_view process="aegis2d")
 Writes traces to a file in the Chrome trace format (write_chrome_trace()).
 
std::vector< std::string > profile_lines (const Profiler &profiler, std::size_t most=12)
 The breakdown of the last frame as lines of the metrics overlay.
 
EngineLibrary load_library (const std::filesystem::path &path, std::uint32_t api_version=library_api_version)
 Opens an Aegis2D library and checks that the engine can use it.
 
VarSettings settings_from_arguments (std::span< const std::string_view > arguments)
 Reads the +set name value of a command line.
 
VarSettings settings_from_arguments (int argc, char **argv)
 Reads the +set name value of main()'s arguments.
 
VarSettings settings_from_text (std::string_view text, std::string_view origin)
 Reads settings from text, one per line.
 
VarSettings settings_from_file (const std::filesystem::path &file)
 Reads settings from a file, as settings_from_text() reads text.
 
std::vector< std::string > apply_settings (ConsoleVariables &variables, std::span< const VarSetting > settings)
 Sets variables, in order: a later setting wins over an earlier one.
 

Variables

constexpr bool hot_reload_by_default = true
 Whether to turn hot reload on: in debug builds (NDEBUG not defined).
 
constexpr std::uint32_t library_api_version = 1
 Version of the interface between the engine and the libraries it loads.
 
constexpr std::string_view library_entry = "aegis2d_library_entry"
 Name of the C function every Aegis2D library exports (see LibraryInfo).
 

Detailed Description

Logging, time, main loop, events and configuration shared by client and server.

Typedef Documentation

◆ CommandHandler

using aegis2d::core::CommandHandler = typedef std::function<std::string(const CommandCall& call)>

What a command does with its arguments.

It returns what the console shows, or nothing. It throws an exception derived from std::exception to fail: the line fails with its message.

◆ Duration

using aegis2d::core::Duration = typedef std::chrono::nanoseconds

Duration type used for simulation time (nanoseconds).

◆ SubscriptionId

using aegis2d::core::SubscriptionId = typedef std::uint64_t

Handle returned by EventBus::subscribe(), used to unsubscribe. Never 0.

◆ VarValue

using aegis2d::core::VarValue = typedef std::variant<bool, std::int64_t, double, std::string>

Value of a console variable: a boolean, an integer, a number or a text.

Enumeration Type Documentation

◆ ArgType

enum class aegis2d::core::ArgType : std::uint8_t
strong

Type of an argument of a command, read from its text as a console variable's.

Enumerator
Text 

A word, or words between double quotes.

Integer 

A whole number.

Number 

Any number.

Boolean 

1, 0, true, false, on or off.

◆ CommandStatus

enum class aegis2d::core::CommandStatus : std::uint8_t
strong

How running a line went.

Enumerator
Done 

The command ran.

Empty 

The line has no command (blank).

Unknown 

No command and no variable has this name.

WrongArguments 

An argument is missing, too many are given, or one does not read in its type.

Failed 

The command failed, or a variable refused its new value.

◆ LogLevel

enum class aegis2d::core::LogLevel : std::uint8_t
strong

Severity of a log message, from the most verbose to the most severe.

Off is only meant for Logger::set_level(): it disables every message.

Enumerator
Debug 
Info 
Warn 
Error 
Off 

◆ VarResult

enum class aegis2d::core::VarResult : std::uint8_t
strong

What became of a change of a console variable.

Enumerator
Changed 

The variable has its new value.

Unknown 

No variable has this name.

ReadOnly 

The variable is read-only.

Cheat 

The variable is a cheat, and cheats are off.

WrongType 

The value is of another type than the variable's.

BadText 

The text does not read as a value of the variable's type.

Function Documentation

◆ apply_settings()

std::vector< std::string > aegis2d::core::apply_settings ( ConsoleVariables &  variables,
std::span< const VarSetting >  settings 
)

Sets variables, in order: a later setting wins over an earlier one.

Each value is read by ConsoleVariables::set_text(), so it follows the variable's type and flags: an unknown, read-only or cheat variable (while cheats are off) is not changed. Apply a settings file first, then the command line, so the command line wins.

Parameters
variablesVariables to set.
settingsSettings to apply.
Returns
One line per setting that was refused, such as "game.cfg:3: player_speed: not a value of the variable's type"; empty when all were applied.

◆ asset_dir()

std::filesystem::path aegis2d::core::asset_dir ( )

Folder of the assets copied next to the executable by aegis2d_copy_assets().

Returns
executable_dir() / "assets".
Exceptions
std::runtime_errorif executable_dir() fails.

◆ asset_path()

std::filesystem::path aegis2d::core::asset_path ( const std::filesystem::path &  relative)

Path of one asset.

Parameters
relativePath inside the assets folder, e.g. "sprites/player.png".
Returns
asset_dir() / relative; the file is not required to exist.
Exceptions
std::runtime_errorif executable_dir() fails.

◆ executable_dir()

std::filesystem::path aegis2d::core::executable_dir ( )

Folder containing the running executable.

Independent of the working directory: a game started from a shortcut, an IDE or another folder still finds its files. Read once from the operating system (/proc/self/exe, _NSGetExecutablePath or GetModuleFileNameW), then cached.

Returns
Absolute path of the folder.
Exceptions
std::runtime_errorif the operating system does not tell.

◆ is_console_name()

bool aegis2d::core::is_console_name ( std::string_view  name)
noexcept

Tells whether a name is valid for a console variable or a command.

Parameters
nameName to check.
Returns
true for lower case letters, digits, _ and ., starting with a letter, at most 64 characters.

◆ load_library()

EngineLibrary aegis2d::core::load_library ( const std::filesystem::path &  path,
std::uint32_t  api_version = library_api_version 
)

Opens an Aegis2D library and checks that the engine can use it.

Calls its entry point (library_entry) and compares the version it was built with to api_version: a library built for another version of the engine is refused before any of its code runs, other than the entry point.

Parameters
pathPath of the library file.
api_versionVersion the library must have, library_api_version by default.
Returns
The library and its name.
Exceptions
LibraryErrorif it cannot be opened, has no entry point, gives no information or was built for another version; the message gives both versions.

◆ log_debug()

template<typename... Args>
void aegis2d::core::log_debug ( std::format_string< Args... >  format,
Args &&...  args 
)

Logs a Debug message with the global logger.

Parameters
formatstd::format format string.
argsValues to format.

◆ log_error()

template<typename... Args>
void aegis2d::core::log_error ( std::format_string< Args... >  format,
Args &&...  args 
)

Logs an Error message with the global logger.

Parameters
formatstd::format format string.
argsValues to format.

◆ log_info()

template<typename... Args>
void aegis2d::core::log_info ( std::format_string< Args... >  format,
Args &&...  args 
)

Logs an Info message with the global logger.

Parameters
formatstd::format format string.
argsValues to format.

◆ log_warn()

template<typename... Args>
void aegis2d::core::log_warn ( std::format_string< Args... >  format,
Args &&...  args 
)

Logs a Warn message with the global logger.

Parameters
formatstd::format format string.
argsValues to format.

◆ memory_use()

std::optional< std::size_t > aegis2d::core::memory_use ( )
noexcept

Memory of the process in RAM now: its resident set (Linux, macOS) or working set (Windows), in bytes.

Asks the system each time (a file read on Linux, a system call elsewhere): call it a few times a second at most, as the metrics overlay does.

Returns
The bytes, or nothing if the system does not tell.

◆ name()

std::string_view aegis2d::core::name ( )
noexcept

Name of the module, used to check that it is linked.

Returns
"core", a view of a static string.

◆ profile_lines()

std::vector< std::string > aegis2d::core::profile_lines ( const Profiler &  profiler,
std::size_t  most = 12 
)

The breakdown of the last frame as lines of the metrics overlay.

Parameters
profilerProfiler whose last_frame() to show.
mostMost scopes shown; the slowest are kept, in their order.
Returns
"FRAME 16.4 MS", then a line per scope indented by its depth, such as " MOVEMENT 0.31 MS X2" (the calls when more than one), in capitals for the pixel font.

◆ read_value()

std::optional< VarValue > aegis2d::core::read_value ( std::string_view  text,
const VarValue &  like 
)

Reads a value from text, in the type of another one, as ConsoleVariables::set_text() does.

Parameters
textSuch as "on", "42" or "0.5"; blanks around it are ignored, but for a text.
likeValue of the type to read.
Returns
The value, or nothing if text does not read in that type.

◆ save_chrome_trace()

void aegis2d::core::save_chrome_trace ( const std::filesystem::path &  file,
std::span< const TraceThread >  threads,
std::string_view  process = "aegis2d" 
)

Writes traces to a file in the Chrome trace format (write_chrome_trace()).

Parameters
fileFile to write, created or replaced; a .json file opens in Perfetto.
threadsThe trace of each thread.
processName of the process in the viewer.
Exceptions
std::runtime_errorif the file cannot be written; the message names it.

◆ settings_from_arguments() [1/2]

VarSettings aegis2d::core::settings_from_arguments ( int  argc,
char **  argv 
)

Reads the +set name value of main()'s arguments.

Parameters
argcNumber of arguments, the program's name included.
argvArguments; the first, the program's name, is skipped.
Returns
As the overload taking views.

◆ settings_from_arguments() [2/2]

VarSettings aegis2d::core::settings_from_arguments ( std::span< const std::string_view >  arguments)

Reads the +set name value of a command line.

Every other argument is left to the game, so the engine's settings mix with its own options: my_game --port 4242 +set player_speed 450 +set r_vsync off. The shell keeps a value with spaces in one argument when it is quoted.

Parameters
argumentsArguments, without the program's name.
Returns
The settings, and a +set without a name and a value as an error.

◆ settings_from_file()

VarSettings aegis2d::core::settings_from_file ( const std::filesystem::path &  file)

Reads settings from a file, as settings_from_text() reads text.

Parameters
filePath of the file.
Returns
The settings, or an error if the file cannot be read.

◆ settings_from_text()

VarSettings aegis2d::core::settings_from_text ( std::string_view  text,
std::string_view  origin 
)

Reads settings from text, one per line.

A line is name value or set name value, the value being the rest of the line, or the text between double quotes when it is quoted. Blank lines, and lines starting with # or //, are skipped.

# Faster, louder.
player_speed 450
set player_name "Ace Pilot"
Parameters
textText of the settings.
originName of the text in the errors, such as a file name.
Returns
The settings, each with its origin and line, and the lines that do not read.

◆ step_from_rate()

constexpr Duration aegis2d::core::step_from_rate ( std::uint32_t  ticks_per_second)
constexprnoexcept

Length of one step for a given update rate.

Parameters
ticks_per_secondUpdate rate in hertz, e.g. 60; must not be 0.
Returns
1s / ticks_per_second, rounded down to the nanosecond.

◆ to_string() [1/2]

std::string_view aegis2d::core::to_string ( LogLevel  level)
noexcept

Short upper-case name of a level.

Parameters
levelLevel to name.
Returns
"DEBUG", "INFO", "WARN", "ERROR" or "OFF".

◆ to_string() [2/2]

std::string_view aegis2d::core::to_string ( VarResult  result)
noexcept

Sentence for a VarResult, as a console shows it.

Parameters
resultResult of a change.
Returns
Such as "unknown variable", a view of a static string.

◆ to_text()

std::string aegis2d::core::to_text ( const VarValue &  value)

A value as text, as ConsoleVariables::set_text() reads it.

Parameters
valueValue.
Returns
"true" or "false", the integer, the shortest text of the number that reads back the same, or the text.

◆ write_chrome_trace()

void aegis2d::core::write_chrome_trace ( std::ostream &  out,
std::span< const TraceThread >  threads,
std::string_view  process = "aegis2d" 
)

Writes traces in the Chrome trace format, which Perfetto (ui.perfetto.dev) and chrome://tracing open.

A JSON object whose traceEvents are the names of the process and of each thread, then a complete event ("ph": "X") per scope and frame, in microseconds.

Parameters
outStream to write to.
threadsThe trace of each thread, numbered from 1 in this order.
processName of the process in the viewer.

Variable Documentation

◆ hot_reload_by_default

constexpr bool aegis2d::core::hot_reload_by_default = true
constexpr

Whether to turn hot reload on: in debug builds (NDEBUG not defined).

Not inline, so each file that includes this header gets the value of its own build type: the game's, whatever the engine was built with. Pass it to HotReload.

◆ library_api_version

constexpr std::uint32_t aegis2d::core::library_api_version = 1
inlineconstexpr

Version of the interface between the engine and the libraries it loads.

Raised whenever what an engine library exchanges with the engine changes, so a library built for another engine is refused by load_library() instead of crashing.

◆ library_entry

constexpr std::string_view aegis2d::core::library_entry = "aegis2d_library_entry"
inlineconstexpr

Name of the C function every Aegis2D library exports (see LibraryInfo).