openage c++/python reference

class PrintVersion

Public Functions

__call__(self self, parser parser, namespace namespace, values values, option_string option_string = None)
class ActionMode : public openage::OutputMode
#include <game_control.h>

This is the main game UI.

Used to control units, issue commands, basically this is where you sink your time in when playing.

Public Functions

ActionMode(qtsdl::GuiItemLink *gui_link)
bool available() const

Is this mode able to be used?

void on_enter()

Called when switching to this mode.

void on_exit()

Called when the mode is left.

void render()

Display this mode.

std::string name() const

Used for displaying the current mode.

void on_game_control_set()

Called after GameControl has been set by QML from set_game_control.

Public Members

ActionModeSignals gui_signals

Private Functions

void announce()

sends to gui the properties that it needs

void announce_resources()

sends to gui the amounts of resources

void announce_buttons_type()

sends to gui the buttons it should use for the action buttons (if changed)

void announce_current_selection()
Command get_action(const coord::phys3 &pos) const

decides which type of right mouse click command to issue based on position.

if a unit is at the position the command should target the unit, otherwise target ground position

void create_binds()

Register the keybindings.

bool place_selection(coord::phys3 point)

places hovering building

Private Members

friend openage::ActionMode::ActionModeSignals
InputContext build_menu_context

used after opening the build menu

InputContext build_menu_mil_context

used after opening the military build menu

InputContext building_context

used when selecting the building placement

UnitSelection *selection
bool use_set_ability
ability_type ability
UnitType *type_focus
coord::phys3 mousepos_phys3 = {0, , }
coord::tile mousepos_tile = {0, }
bool selecting
ActionButtonsType buttons_type
rng::RNG rng
class ActionModeSignals : public QObject
#include <game_control.h>

Public Functions

ActionModeSignals(ActionMode *action_mode)

Public Slots

void on_action(const std::string &action_name)

Signals

void resource_changed(game_resource resource, int amount)
void population_changed(int demand, int capacity, bool warn)
void selection_changed(const UnitSelection *unit_selection, const Player *player)
void ability_changed(const std::string &ability)
void buttons_type_changed(const ActionButtonsType type)

Private Members

ActionMode *action_mode
class AssetManager
#include <assetmanager.h>

Container class for all available assets.

Responsible for loading, providing and updating requested files.

Public Functions

AssetManager(qtsdl::GuiItemLink *gui_link)
const util::Path &get_asset_dir()

Return the path where assets are found in.

void set_asset_dir(const util::Path &asset_dir)

Set the asset search path.

void set_engine(Engine *engine)

Set the game engine of this asset manager.

Called from QML.

Engine *get_engine() const

Return the engine responsible for this asset manager.

Texture *get_texture(const std::string &name, bool use_metafile = true, bool null_if_missing = false)

Query the Texture for a given filename.

Return

the queried texture handle.

Parameters
  • name: the asset file name relative to the asset root.

  • use_metafile: load subtexture information from meta file

  • null_if_missing: instead of providing the “missing texture”, return nullptr.

void check_updates()

Ask the kernel whether there were updates to watched files.

Public Members

qtsdl::GuiItemLink *gui_link

Protected Functions

std::shared_ptr<Texture> load_texture(const std::string &name, bool use_metafile = true, bool null_if_missing = false)

Create an internal texture handle.

std::shared_ptr<Texture> get_missing_tex()

Retrieves the texture for missing textures.

Private Functions

void clear()

Private Members

Engine *engine

The engine this asset manager is attached to.

util::Path asset_path

The root directory for the available assets.

std::shared_ptr<Texture> missing_tex

The replacement texture for missing textures.

std::unordered_map<std::string, std::shared_ptr<Texture>> textures

Map from texture filename to texture instance ptr.

class AttackAbility : public openage::UnitAbility
#include <ability.h>

initiates an attack action when given a valid target

Public Functions

AttackAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class AttackAction : public openage::TargetAction
#include <action.h>

attacks another unit

Public Functions

AttackAction(Unit *e, UnitReference tar)
~AttackAction()
void update_in_range(unsigned int int, Unit *)

Control units action when in range of the target.

void on_completion_in_range(int)
bool completed_in_range(Unit *target_ptr) const
std::string name() const

debug string to identify action types

Private Functions

void attack(Unit &target)

use attack action

void fire_projectile(const Attribute<attr_type::attack> &att, const coord::phys3 &target)

add a projectile game object which moves towards the target

Private Members

IntervalTimer timer
template<attr_type T>
class Attribute
#include <attribute.h>

this type gets specialized for each attribute

template<>
class Attribute<attr_type::armor> : public openage::SharedAttributeContainer
#include <attribute.h>

Public Functions

Attribute(typeamount_map a)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

typeamount_map armor
template<>
class Attribute<attr_type::attack> : public openage::SharedAttributeContainer
#include <attribute.h>

TODO can a unit have multiple attacks such as villagers hunting map target classes onto attacks TODO remove the first constructor and the default values after (keep for now for compatibility)

Public Functions

Attribute(UnitType *type, coord::phys_t r, coord::phys_t h, unsigned int d)
Attribute(UnitType *type, coord::phys_t r, coord::phys_t h, typeamount_map d, coord::phys_t min_range = 0, bool friendly_fire = false, coord::phys_t area_of_effect = 0)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

UnitType *ptype

The projectile’s unit type.

coord::phys_t min_range

The min range of the attack TODO not used.

coord::phys_t max_range

The max range of the attack.

coord::phys_t init_height

The height from which the projectile starts.

typeamount_map damage
bool friendly_fire

If the attack can damage allied (friendly) units.

TODO not used

coord::phys_t area_of_effect

The radius of the area of effect of the attack or 0 if there is no area_of_effect.

TODO not used

template<>
class Attribute<attr_type::building> : public openage::UnsharedAttributeContainer
#include <attribute.h>

TODO revisit after unit training is improved.

Public Functions

Attribute(int foundation_terrain, UnitType *pp, coord::phys3 gather_point)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

float completed
int foundation_terrain
object_state completion_state
UnitType *pp
coord::phys3 gather_point

The go to point after a unit is created.

template<>
class Attribute<attr_type::damaged> : public openage::UnsharedAttributeContainer
#include <attribute.h>

The current hitpoints.

TODO add last damage taken timestamp

Public Functions

Attribute(unsigned int i)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

unsigned int hp

The current hitpoint.

template<>
class Attribute<attr_type::direction> : public openage::UnsharedAttributeContainer
#include <attribute.h>

Public Functions

Attribute(coord::phys3_delta dir)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

coord::phys3_delta unit_dir
template<>
class Attribute<attr_type::dropsite> : public openage::SharedAttributeContainer
#include <attribute.h>

The resources that are accepted to be dropped.

Public Functions

Attribute(std::vector<game_resource> types)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

bool accepting_resource(game_resource res) const

Public Members

std::vector<game_resource> resource_types
template<>
class Attribute<attr_type::formation> : public openage::UnsharedAttributeContainer
#include <attribute.h>

The attack stance and formation TODO store patrol and follow command information.

Public Functions

Attribute()
Attribute(attack_stance stance)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

attack_stance stance
attack_formation formation
template<>
class Attribute<attr_type::garrison> : public openage::UnsharedAttributeContainer
#include <attribute.h>

Units put inside a building.

TODO add capacity per type of unit

Public Functions

Attribute()
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

std::vector<UnitReference> content

The units that are garrisoned.

template<>
class Attribute<attr_type::heal> : public openage::SharedAttributeContainer
#include <attribute.h>

Healing capabilities.

Public Functions

Attribute(coord::phys_t r, unsigned int l, unsigned int ra)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

coord::phys_t range

The max range of the healing.

unsigned int life

Life healed in each cycle.

unsigned int rate

The period of each heal cycle.

template<>
class Attribute<attr_type::hitpoints> : public openage::SharedAttributeContainer
#include <attribute.h>

The max hitpoints and health bar information.

TODO change bar information stucture

Public Functions

Attribute(unsigned int i)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

unsigned int hp

The max hitpoints.

float hp_bar_height
template<>
class Attribute<attr_type::multitype> : public openage::SharedAttributeContainer
#include <attribute.h>

Stores the collection of unit types based on a unit class.

It is used mostly for units with multiple graphics (villagers, trebuchets).

Public Functions

Attribute()
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

void switchType(const gamedata::unit_classes cls, Unit *unit) const

Switch the type of a unit based on a given unit class.

Public Members

std::unordered_map<gamedata::unit_classes, UnitType *> types

The collection of unit class to unit type pairs.

template<>
class Attribute<attr_type::owner> : public openage::SharedAttributeContainer
#include <attribute.h>

Public Functions

Attribute(Player &p)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

Player &player
template<>
class Attribute<attr_type::population> : public openage::SharedAttributeContainer
#include <attribute.h>

The population capacity and the population demand.

Public Functions

Attribute(int demand, int capacity)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

int demand
int capacity
template<>
class Attribute<attr_type::projectile> : public openage::UnsharedAttributeContainer
#include <attribute.h>

Public Functions

Attribute(float arc)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

float projectile_arc
UnitReference launcher
bool launched
template<>
class Attribute<attr_type::resource> : public openage::UnsharedAttributeContainer
#include <attribute.h>

Resource capacity of a trees, mines, animal, worker etc.

Public Functions

Attribute()
Attribute(game_resource type, double init_amount, double decay = 0.0, double gather_rate = 1.0)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

game_resource resource_type
double amount
double decay

The rate of decay.

double gather_rate

The gather rate multiplier (1.0 is the identity)

template<>
class Attribute<attr_type::resource_generator> : public openage::SharedAttributeContainer
#include <attribute.h>

Resource generator eg.

relic. While a unit is idle and contains this attribute, it will generate resources for its owner.

A rate of zero means that the generation is continuously and not in intervals.

Public Functions

Attribute(ResourceBundle resources, double rate = 0)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

ResourceBundle resources
double rate
template<>
class Attribute<attr_type::speed> : public openage::SharedAttributeContainer
#include <attribute.h>

Public Functions

Attribute(coord::phys_t sp)
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

coord::phys_t unit_speed
template<>
class Attribute<attr_type::storage> : public openage::SharedAttributeContainer
#include <attribute.h>

The worker’s capacity and gather rates.

Public Functions

Attribute()
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

ResourceBundle capacity

The capacity for each resource.

template<>
class Attribute<attr_type::worker> : public openage::SharedAttributeContainer
#include <attribute.h>

The worker’s capacity and gather rates.

Public Functions

Attribute()
std::shared_ptr<AttributeContainer> copy() const

Produces an copy of the attribute.

Public Members

double capacity

The max number of resources that can be carried.

ResourceBundle gather_rate

The gather rate for each resource.

The ResourceBundle class is used but instead of amounts it stores gather rates.

class AttributeContainer
#include <attribute.h>

Wraps a templated attribute.

Subclassed by openage::SharedAttributeContainer, openage::UnsharedAttributeContainer

Public Functions

AttributeContainer()
AttributeContainer(attr_type t)
virtual ~AttributeContainer()
virtual bool shared() const = 0

shared attributes are common across all units of one type, such as max hp, and gather rates

non shared attributes include a units current hp, and the amount a villager is carrying

virtual std::shared_ptr<AttributeContainer> copy() const = 0

Produces an copy of the attribute.

Public Members

attr_type type
class Attributes
#include <attributes.h>

Contains a group of attributes.

Can contain only one attribute of each type.

Public Functions

Attributes()
void add(const std::shared_ptr<AttributeContainer> attr)

Add an attribute or replace any attribute of the same type.

void add_copies(const Attributes &attrs)

Add copies of all the attributes from the given Attributes.

void add_copies(const Attributes &attrs, bool shared, bool unshared)

Add copies of all the attributes from the given Attributes.

If shared is false, shared attributes are ignored. If unshared is false, unshared attributes are ignored.

bool remove(const attr_type type)

Remove an attribute based on the type.

bool has(const attr_type type) const

Check if the attribute of the given type exists.

std::shared_ptr<AttributeContainer> get(const attr_type type) const

Get the attribute based on the type.

template<attr_type T>
Attribute<T> &get() const

Get the attribute.

Private Members

std::map<attr_type, std::shared_ptr<AttributeContainer>> attrs
struct audio_chunk_t
#include <types.h>

A piece of raw audio data.

special values: (nullptr, *) no data in the chunk (*, 0) end of stream

Public Members

const int16_t *data
size_t length
class AudioManager
#include <audio_manager.h>

This class provides audio functionality for openage.

Public Functions

AudioManager(job::JobManager *job_manager, const std::string &device_name = "")

Initializes the audio manager with the given device name.

If the name is empty, the default device is used.

~AudioManager()
AudioManager(const AudioManager&)
AudioManager(AudioManager&&)
AudioManager &operator=(const AudioManager&)
AudioManager &operator=(AudioManager&&)
void load_resources(const std::vector<resource_def> &sound_files)

Loads all audio resources, that are specified in the sound_files vector.

Parameters
  • sound_files: a list of all sound resources

Sound get_sound(category_t category, int id)

Returns a sound object with the given category and the given id.

If no such sound exists an Error will be thrown.

Parameters
  • category: the sound’s category

  • id: the sound’s id

void audio_callback(int16_t *stream, int length)

Called from the audio system once to request new data.

SDL_AudioSpec get_device_spec() const

Returns the currently used audio output format.

job::JobManager *get_job_manager() const

Return the game engine the audio manager is attached to.

bool is_available() const

If this audio manager is available.

It’s not available if

Public Static Functions

std::vector<std::string> get_devices()

Returns a vector of all available device names.

std::vector<std::string> get_drivers()

Returns a vector of all available driver names.

std::string get_current_driver()

Returns the name of the currently used driver.

Private Functions

void add_sound(std::shared_ptr<SoundImpl> sound)
void remove_sound(std::shared_ptr<SoundImpl> sound)

Private Members

bool available

If no audio device was found, this audio manager will be unavailable.

job::JobManager *job_manager

The job manager used in this audio manager for job queuing.

std::string device_name

the used audio device’s name

SDL_AudioSpec device_spec

the audio output format

SDL_AudioDeviceID device_id

the used audio device’s id

std::unique_ptr<int32_t[]> mix_buffer

Buffer used for mixing audio to one stream.

std::unordered_map<std::tuple<category_t, int>, std::shared_ptr<Resource>> resources
std::unordered_map<category_t, std::vector<std::shared_ptr<SoundImpl>>> playing_sounds

Friends

friend openage::audio::AudioManager::Sound
struct chunk_info_t
#include <dynamic_resource.h>

information storage about a piece of raw audio data.

Public Types

enum state_t

Values:

EMPTY

The chunk is currently empty and unused.

LOADING

The chunk is currently loading.

READY

The chunk is loaded and ready to be used.

Public Functions

chunk_info_t(chunk_info_t::state_t state, size_t buffer_size)
~chunk_info_t()

Public Members

std::atomic<state_t> state

The chunk’s current state.

size_t size

The chunk’s actual size.

std::unique_ptr<int16_t[]> buffer

The chunk’s buffer.

class DynamicLoader
#include <dynamic_loader.h>

A DynamicLoader loads pcm chunks without loading the whole resource.

A chunk is a int16_t buffer with a fixed size that contains 16 bit signed integer pcm data.

Subclassed by openage::audio::OpusDynamicLoader

Public Functions

DynamicLoader(const util::Path &path)

Initializes a new DynamicLoader.

Parameters
  • path: the resource’s location in the filesystem

virtual ~DynamicLoader()
virtual size_t load_chunk(int16_t *chunk_buffer, size_t offset, size_t chunk_size) = 0

Loads a chunk of stereo pcm data from the resource.

The chunk of data begins at the given offset from the beginning of the resource. The actual read number of int16_t values is returned. TODO: Returns zero if the end of resource is reached.

Parameters
  • chunk_buffer: the buffer to save the chunk into

  • offset: the offset from the resource’s beginning

  • chunk_size: the number of int16_t values that fit in one chunk

Public Static Functions

std::unique_ptr<DynamicLoader> create(const util::Path &path, format_t format)

Creates a DynamicLoader instance that supports the given format.

Parameters
  • path: the resource’s location in the filesystem

  • format: the resource’s audio format

Protected Attributes

util::Path path

the resource’s location in the filesystem

class DynamicResource : public openage::audio::Resource
#include <dynamic_resource.h>

Audio data that is loaded dynamically when used.

Public Functions

DynamicResource(AudioManager *manager, category_t category, int id, const util::Path &path, format_t format = format_t::OPUS, int preload_amount = DEFAULT_PRELOAD_AMOUNT, size_t chunk_size = DEFAULT_CHUNK_SIZE, size_t max_chunks = DEFAULT_MAX_CHUNKS)
virtual ~DynamicResource()
void use()

Tells the resource, that it will be used by a sound object, so it can preload some pcm samples.

void stop_using()

Tells the resource, that one sound object does not use this resource any longer.

audio_chunk_t get_data(size_t position, size_t data_length)

Returns a pointer to the sample buffer at the given position and the number of int16_t values that are actually available.

If the end of the resource is reached, 0 will be returned. If the resource is not ready yet, a nullptr with a length, different to zero, will be returned.

Parameters
  • position: the current position in the resource

  • data_length: the number of int16_t values that should be returned

  • data_length: the number of bytes of audio data that is requested

Public Static Attributes

constexpr int DEFAULT_PRELOAD_AMOUNT = 10

The number of chunks that have to be loaded, before a sound actually starts playing.

constexpr size_t DEFAULT_CHUNK_SIZE = 9600 * 2

The default used chunk size in bytes (100ms).

constexpr size_t DEFAULT_MAX_CHUNKS = 100

The default number of chunks, that can be loaded at the same time.

Private Functions

void start_preloading(size_t resource_chunk_index)

Start to load audio chunks beginning at the given chunk index.

Continues to do so until the preload_amount is reached.

void load_chunk_async(std::shared_ptr<chunk_info_t> chunk_info, size_t resource_chunk_offset)

Load a single chunk in the background (through the job manager).

First, the given chunk_info is invalidated. Then, after loading, it’s pushed into the decay_queue so it can decay again.

Private Members

util::Path path

The resource’s path.

format_t format

The resource’s audio format.

int preload_amount

The number of chunks that should be preloaded.

size_t chunk_size

The size of one audio chunk in bytes.

size_t max_chunks

The maximum number of chunks that are used to store audio data.

This is the maximum amount stored in the chunks map.

std::atomic_int use_count

The number of sounds that currently use this resource.

std::unique_ptr<DynamicLoader> loader

The background audio loader.

datastructure::ConcurrentQueue<std::shared_ptr<chunk_info_t>> decay_queue

Queue of audio chunk information that manages the decay of buffer data.

This implements “forget least-recently-used chunks” when a new one shall be loaded. This must never run empty! Otherwise the audio system will lock up.

std::unordered_map<size_t, std::shared_ptr<chunk_info_t>> chunks

Resource chunk index to chunk mapping.

Loading and usage state is reached through this.

job::JobGroup loading_job_group

The background loading job group.

class Error : public openage::error::Error
#include <error.h>

Public Functions

Error(const log::message &msg)
class InMemoryLoader
#include <in_memory_loader.h>

A InMemoryLoader loads a audio file into memory and converts it into 16 bit signed integer pcm data.

Subclassed by openage::audio::OpusInMemoryLoader

Public Functions

InMemoryLoader(const util::Path &path)

Initializes a new InMemoryLoader.

Parameters
  • path: the resource’s location in the filesystem

virtual ~InMemoryLoader()
virtual pcm_data_t get_resource() = 0

Returns the resource as pcm data buffer.

Public Static Functions

std::unique_ptr<InMemoryLoader> create(const util::Path &path, format_t format)

Create a InMemoryLoader instance that supports the given format.

Parameters
  • path: the resource’s location in the filesystem

  • format: the resource’s audio format

Protected Attributes

util::Path path
class InMemoryResource : public openage::audio::Resource
#include <in_memory_resource.h>

An InMemoryResource loads the whole pcm data into memory and keeps it there.

Public Functions

InMemoryResource(AudioManager *manager, category_t category, int id, const util::Path &path, format_t format = format_t::OPUS)
virtual ~InMemoryResource()
void use()

Tells the resource, that it will be used by a sound object, so it can preload some pcm samples.

void stop_using()

Tells the resource, that one sound object does not use this resource any longer.

audio_chunk_t get_data(size_t position, size_t data_length)

Returns a pointer to the sample buffer at the given position and the number of int16_t values that are actually available.

If the end of the resource is reached, 0 will be returned. If the resource is not ready yet, a nullptr with a length, different to zero, will be returned.

Parameters
  • position: the current position in the resource

  • data_length: the number of int16_t values that should be returned

  • data_length: the number of bytes of audio data that is requested

Private Members

pcm_data_t buffer

The resource’s internal buffer.

struct opus_file_t
#include <opus_loading.h>

opusfile handle storage.

Public Members

std::unique_ptr<OggOpusFile, std::function<void(OggOpusFile *)>> handle

The opusfile handle, with a custom deleter that frees the opusfile memory.

std::unique_ptr<util::File> file

File used to supply the data.

This is unused if the file is a real file.

class OpusDynamicLoader : public openage::audio::DynamicLoader
#include <opus_dynamic_loader.h>

A OpusDynamicLoader load’s opus encoded data.

Public Functions

OpusDynamicLoader(const util::Path &path)

Creates a new OpusDynamicLoader.

Parameters
  • path: the resource’s location in the filesystem

virtual ~OpusDynamicLoader()
size_t load_chunk(int16_t *chunk_buffer, size_t offset, size_t chunk_size)

Loads a chunk of stereo pcm data from the resource.

The chunk of data begins at the given offset from the beginning of the resource. The actual read number of int16_t values is returned. TODO: Returns zero if the end of resource is reached.

Parameters
  • chunk_buffer: the buffer to save the chunk into

  • offset: the offset from the resource’s beginning

  • chunk_size: the number of int16_t values that fit in one chunk

Private Members

opus_file_t source

The source file.

size_t length

The resource’s length in int16_t values.

int channels

The resource’s pcm channels.

class OpusInMemoryLoader : public openage::audio::InMemoryLoader
#include <opus_in_memory_loader.h>

A OpusInMemoryLoader load’s opus encoded data from opus files.

A opus file is loaded completely at once and the loaded data will be kept in memory.

Public Functions

OpusInMemoryLoader(const util::Path &path)

Creates a new OpusInMemoryLoader.

Parameters
  • path: the resource’s location in the filesystem

virtual ~OpusInMemoryLoader()
pcm_data_t get_resource()

Returns the resource as pcm data buffer.

class Resource
#include <resource.h>

A Resource contains 16 bit signed integer pcm data, that can be played by sounds.

Each Resource has an unique id within it’s category. The category specifies the type of sound, e. g. game sounds, background music, etc. The id is a unique integer value.

Subclassed by openage::audio::DynamicResource, openage::audio::InMemoryResource

Public Functions

Resource(AudioManager *manager, category_t category, int id)
virtual ~Resource()
Resource(const Resource&)
Resource &operator=(const Resource&)
Resource(Resource&&)
Resource &operator=(Resource&&)
category_t get_category() const
int get_id() const
virtual void use() = 0

Tells the resource, that it will be used by a sound object, so it can preload some pcm samples.

virtual void stop_using() = 0

Tells the resource, that one sound object does not use this resource any longer.

virtual audio_chunk_t get_data(size_t position, size_t data_length) = 0

Returns a pointer to the sample buffer at the given position and the number of int16_t values that are actually available.

If the end of the resource is reached, 0 will be returned. If the resource is not ready yet, a nullptr with a length, different to zero, will be returned.

Parameters
  • position: the current position in the resource

  • data_length: the number of int16_t values that should be returned

  • data_length: the number of bytes of audio data that is requested

Public Static Functions

std::shared_ptr<Resource> create_resource(AudioManager *manager, const resource_def &def)

create an audio resource, this produces a DynamicResource or a InMemoryResource

Protected Attributes

AudioManager *manager

Audiomanager in charge of this resource.

Private Members

category_t category

The resource’s category.

int id

The resource’s id.

struct resource_def
#include <resource_def.h>

Definition of a single sound resource file to load.

Public Members

category_t category
int id
util::Path location
format_t format
loader_policy_t loader_policy
class SDLDeviceLock

Wrapper class for the sdl audio device locking so the device doesn’t deadlock because of funny exceptions.

Public Functions

SDLDeviceLock(const SDL_AudioDeviceID &id)
~SDLDeviceLock()
SDLDeviceLock(SDLDeviceLock&&)
SDLDeviceLock(const SDLDeviceLock&)
SDLDeviceLock &operator=(SDLDeviceLock&&)
SDLDeviceLock &operator=(const SDLDeviceLock&)

Private Members

SDL_AudioDeviceID dev_id
class Sound
#include <sound.h>

A sound object is the direct interface to the user.

It provides methods to control the sound, e.g. play, stop, etc. It is a lightweight object that stores a shared_ptr to its internal SoundImpl and a pointer to its AudioManager.

Public Functions

category_t get_category() const

Returns this sound’s category.

int get_id() const

Returns this sound’s id.

void set_volume(int32_t volume)

Sets this sound’s volume.

The volume should be a value in range [0,256], where 0 means silence and 256 the original pcm volume. A volume greater than 256 could lead to overmodulation.

Parameters
  • volume: the new volume

int32_t get_volume() const

Returns this sound’s volume.

void set_looping(bool looping)

Sets whether this sound should be looping or not.

A looping sound restarts automatically after it has finishes.

Parameters
  • looping: true, if this sound should be looping, otherwise false

bool is_looping() const

Returns whether this sound is looping.

void play()

Resets the sound to it’s beginning and starts playing it.

void pause()

Pauses the sound at it’s current playing offset.

void resume()

Resumes the sound at it’s current playing offset.

void stop()

Resets the sound to it’s beginning and stops playing it.

bool is_playing() const

Returns whether this sound is currently playing.

Private Functions

Sound(AudioManager *audio_manager, std::shared_ptr<SoundImpl> sound_impl)

Private Members

AudioManager *audio_manager

The audio manager that manages this sound.

std::shared_ptr<SoundImpl> sound_impl

The internal sound implementation.

This is where the internal state, e.g. current playing offset, volume, etc., is stored.

Friends

friend openage::audio::Sound::AudioManager
class SoundImpl
#include <sound.h>

A SoundImpl is the internal implementation of a sound.

It stores the sound’s complete state. It is passed around as a shared_ptr, such that the same SoundImpl instance can be shared between the Sound objects themselves and the AudioManager.

Public Functions

SoundImpl(std::shared_ptr<Resource> resource, int32_t volume = 128)
~SoundImpl()
category_t get_category() const

Returns this sound’s category.

int get_id() const

Returns this sound’s id.

bool mix_audio(int32_t *stream, int length)

Public Members

std::shared_ptr<Resource> resource

The shared audio resource, which provides the pcm data to play.

bool in_use

Whether this sound currently actively uses it’s shared audio resource.

int32_t volume

The sound’s volume.

uint32_t offset

The sound’s playing offset.

bool playing

Whether this sound is currently playing.

bool looping

Whether this sound is currently looping.

class BuildAbility : public openage::UnitAbility
#include <ability.h>

villagers build new buildings

Public Functions

BuildAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class BuildAction : public openage::TargetAction
#include <action.h>

builds a building

Public Functions

BuildAction(Unit *e, UnitReference foundation)
virtual ~BuildAction()
void update_in_range(unsigned int int, Unit *)

Control units action when in range of the target.

void on_completion_in_range(int)
bool completed_in_range(Unit *) const
void on_completion()

action to perform when popped from a units action stack

std::string name() const

debug string to identify action types

float get_progress() const

Private Members

float complete
float build_rate

Private Static Attributes

constexpr float search_tile_distance = 9.0f
class BuildingProducer : public openage::UnitType
#include <producer.h>

Stores graphics and attributes for a building type Will be replaced with nyan system in future in aoe buildings are derived from living units.

Public Functions

BuildingProducer(const Player &owner, const GameSpec &spec, const gamedata::building_unit *ud)
~BuildingProducer()
int id() const

gets the unique id of this unit type

int parent_id() const

gets the parent id of this unit type which is used for village base and gather types

std::string name() const

gets the name of the unit type being produced

void initialise(Unit *, Player&)

Initialize units attributes to this type spec.

This can be called using existing units to modify type Ensure that the unit has been placed before seting the units type

TODO: make const

TerrainObject *place(Unit *, std::shared_ptr<Terrain>, coord::phys3) const

set unit in place return if placement was successful

This should be used when initially creating a unit or when a unit is ungarrsioned from a building or object TODO: make const

Private Functions

std::vector<game_resource> get_accepted_resources()
TerrainObject *make_annex(Unit &u, std::shared_ptr<Terrain> t, int annex_id, coord::phys3 annex_pos, bool c) const

Private Members

const gamedata::building_unit unit_data
const Sound *on_create

Sound id played when object is created or destroyed.

const Sound *on_destroy
std::shared_ptr<Texture> terrain_outline
std::shared_ptr<UnitTexture> texture
std::shared_ptr<UnitTexture> destroyed
int projectile
int foundation_terrain
bool enable_collisions

used for objects like town centers or gates where the base does not apply collision checks

class CABFile

The actual file system-like CAB object.

Constructor arguments:

The constructor reads the entire header, including the folder and file descriptions. Most CAB file issues should cause the constructor to fail.

Parameters
  • cab: A file-like object that must implement read() and seek() with whence=os.SEEK_SET.

Public Functions

__init__(self self, cab cab)
__repr__(self self)
read_folder_headers(self self, cab cab)

Called during the constructor run.

Reads the folder headers and initializes the folder’s plain stream file-like objects.

Yields all folders.

read_file_headers(self self, cab cab)

Called during the constructor run.

Reads the headers for all files and yields CFFile objects.

Public Members

header
folders
rootdir
class CABFolderStream

Public Functions

__init__(self self, fileobj fileobj, offset offset, blockcount blockcount, blockreserved blockreserved)
next_block_size(self self, payloadsize payloadsize)

adds metadata for the next block

read_block_data(self self, block_id block_id)

reads the data of block block_id.

if necessary, the metadata info in self.blockvalues and self.blockoffsets is updated.

returns the block data.

read_blocks(self self, size size = -1)
read(self self, size size = -1)
get_size(self self)
close(self self)

Public Members

fileobj
blockcount
blockreserved
blockoffsets
streamindex
closed
class CFData

Public Functions

verify_checksum(self self)

Public Static Attributes

string openage.cabextract.cab.CFData.endianness = "<"
string openage.cabextract.cab.CFData.csum = "I"
string openage.cabextract.cab.CFData.cbData = "H"
string openage.cabextract.cab.CFData.cbUncomp = "H"
openage.cabextract.cab.CFData.reserved = None
openage.cabextract.cab.CFData.payload = None
class CFFile

Header for a single file.

Describes the file’s metadata, as well as the location of its content (which CAB folder, at what offset).

Public Static Attributes

string openage.cabextract.cab.CFFile.endianness = "<"
string openage.cabextract.cab.CFFile.size = "I"
string openage.cabextract.cab.CFFile.pos = "I"
string openage.cabextract.cab.CFFile.folderid = "H"
string openage.cabextract.cab.CFFile.date = "H"
string openage.cabextract.cab.CFFile.time = "H"
openage.cabextract.cab.CFFile.attribs = CFFileAttributes
openage.cabextract.cab.CFFile.path = None
openage.cabextract.cab.CFFile.continued = None
openage.cabextract.cab.CFFile.continues = None
openage.cabextract.cab.CFFile.folder = None
openage.cabextract.cab.CFFile.timestamp = None
class CFFileAttributes

File flags; found in the CFFile struct.

Public Static Attributes

string openage.cabextract.cab.CFFileAttributes.specstr = "H"
int openage.cabextract.cab.CFFileAttributes.rdonly = 0
int openage.cabextract.cab.CFFileAttributes.hidden = 1
int openage.cabextract.cab.CFFileAttributes.system = 2
int openage.cabextract.cab.CFFileAttributes.arch = 5
int openage.cabextract.cab.CFFileAttributes.exec = 6
int openage.cabextract.cab.CFFileAttributes.name_is_utf = 7
class CFFolder

Public Static Attributes

string openage.cabextract.cab.CFFolder.endianness = "<"
string openage.cabextract.cab.CFFolder.coffCabStart = "I"
string openage.cabextract.cab.CFFolder.cCFData = "H"
string openage.cabextract.cab.CFFolder.typeCompress = "H"
openage.cabextract.cab.CFFolder.reserved = None
openage.cabextract.cab.CFFolder.comp_name = None
openage.cabextract.cab.CFFolder.plain_stream = None
class CFHeader

Global CAB file header; found at the very beginning of the file.

Public Static Attributes

string openage.cabextract.cab.CFHeader.endianness = "<"
string openage.cabextract.cab.CFHeader.signature = "4s"
string openage.cabextract.cab.CFHeader.reserved1 = "I"
string openage.cabextract.cab.CFHeader.cbCabinet = "I"
string openage.cabextract.cab.CFHeader.reserved2 = "I"
string openage.cabextract.cab.CFHeader.coffFiles = "I"
string openage.cabextract.cab.CFHeader.reserved3 = "I"
string openage.cabextract.cab.CFHeader.versionMinor = "B"
string openage.cabextract.cab.CFHeader.versionMajor = "B"
string openage.cabextract.cab.CFHeader.cFolders = "H"
string openage.cabextract.cab.CFHeader.cFiles = "H"
openage.cabextract.cab.CFHeader.flags = CFHeaderFlags
string openage.cabextract.cab.CFHeader.setID = "H"
string openage.cabextract.cab.CFHeader.iCabinet = "H"
openage.cabextract.cab.CFHeader.reserved_data = None
openage.cabextract.cab.CFHeader.reserved = None
openage.cabextract.cab.CFHeader.prev_cab = None
openage.cabextract.cab.CFHeader.prev_disk = None
openage.cabextract.cab.CFHeader.next_cab = None
openage.cabextract.cab.CFHeader.next_disk = None
class CFHeaderFlags

Cabinet file option indicators.

Found in the header.

Public Static Attributes

string openage.cabextract.cab.CFHeaderFlags.specstr = "H"
int openage.cabextract.cab.CFHeaderFlags.prev_cabinet = 0
int openage.cabextract.cab.CFHeaderFlags.next_cabinet = 1
int openage.cabextract.cab.CFHeaderFlags.reserve_present = 2
class CFHeaderReservedFields

Public Static Attributes

string openage.cabextract.cab.CFHeaderReservedFields.endianness = "<"
string openage.cabextract.cab.CFHeaderReservedFields.cbCFHeader = "H"
string openage.cabextract.cab.CFHeaderReservedFields.cbCFFolder = "B"
string openage.cabextract.cab.CFHeaderReservedFields.cbCFData = "B"
class LZXDStream

Read-only stream object that wraps LZXDecompressor.

Constructor arguments:

Defaults to 21.

Parameters
  • compressed_file: The compressed file-like object; must implement only read(). If seek(0) works on it, reset() works on this object.

  • window_bits: Provided as metadata in MSCAB files; see LZXDecompressor.

Theoretically, if reset_interval > 0, efficient

seek() could be implemented. However, it isn’t.
Parameters
  • reset_interval: Zero for MSCAB files; see LZXDecompressor.

Defaults to 0.

Public Functions

__init__(self self, sourcestream sourcestream, window_bits window_bits = 21, reset_interval reset_interval = 0)
reset(self self)

Resets the decompressor back to the start of the file.

read(self self, size size = -1)
get_size(self self)
seek(self self, offset offset, whence whence = os.SEEK_SET)
seekable(self self)
tell(self self)
close(self self)

Public Members

sourcestream
window_bits
reset_interval
pos
buf
decompressor
closed
struct chunk_neighbors
#include <terrain_chunk.h>

adjacent neighbors of a chunk.

neighbor ids: 0 7 1 6 @ 2 5 3 4

Public Members

TerrainChunk *neighbor[8]
class Civilisation
#include <civilisation.h>

contains the initial tech structure for one civilisation

Public Functions

Civilisation(const GameSpec &spec, int id)
std::vector<std::shared_ptr<UnitTypeMeta>> object_meta() const

return all the objects available to this civ

std::vector<index_t> get_category(const std::string &c) const

return all types in a particular named category

std::vector<std::string> get_type_categories() const

return all used categories, such as living, building or projectile

const gamedata::building_unit *get_building_data(index_t unit_id) const

gamedata for a building

void initialise_unit_types(const GameSpec &spec)

initialise the unit meta data

Public Members

const int civ_id

civ index

const std::string civ_name

civ name

Private Functions

void add_to_category(const std::string &c, index_t type)

creates and adds items to categories

Private Members

std::vector<std::shared_ptr<UnitTypeMeta>> civ_objects

unit types which can be produced by this civilisation.

std::vector<std::string> all_categories

all available categories of units

std::unordered_map<std::string, std::vector<index_t>> categories

category lists

std::unordered_map<index_t, const gamedata::building_unit *> buildings

used for annex creation

class ClassicResources : public openage::Resources
#include <resource.h>

Public Functions

ClassicResources()
unsigned int get_count() const
const Resource &get_resource(int id) const

Private Members

const ResourceProducer resources[4]
class CodegenDirWrapper

Only allows pure-read and pure-write operations;.

Intercepts all writes for later inspection, and logs all reads.

The constructor takes the to-be-wrapped fslike object.

Public Functions

__init__(self self, obj obj)
open_r(self self, parts parts)
open_w(self self, parts parts)
get_reads(self self)
get_writes(self self)
__repr__(self self)

Public Members

writes
reads
class CodegenMode

Modus operandi.

Public Static Attributes

string openage.codegen.codegen.CodegenMode.codegen = "codegen"
string openage.codegen.codegen.CodegenMode.dryrun = "dryrun"
string openage.codegen.codegen.CodegenMode.clean = "clean"
class WriteCatcher

Public Functions

close(self self)
read(self self, size size = -1)

Public Members

eof
class Namespace

Represents a C++ namespace, which contains other namespaces and functions.

gen_prototypes() generates the code for the namespace.

Public Functions

__init__(self self)
add_functionname(self self, path path)

Adds a function to the namespace.

Path is the qualified function “path” (e.g., openage::test::foo) has the path [“openage”, “test”, “foo”].

Descends recursively, creating subnamespaces as required.

gen_prototypes(self self)
get_functionnames(self self)

Public Members

namespaces
functions
class Command
#include <command.h>

Public Functions

Command(const Player &p, Unit *unit)

target another unit

Command(const Player &p, coord::phys3 position)

target a position

Command(const Player &p, Unit *unit, coord::phys3 position)

target another unit or a position

Command(const Player &p, UnitType *t)

select a type

Command(const Player &p, Research *res)

select a research

Command(const Player &p, UnitType *t, coord::phys3 position)

place building foundation

bool has_unit() const
bool has_position() const
bool has_type() const
bool has_research() const
Unit *unit() const
coord::phys3 position() const
UnitType *type() const
Research *research() const
void set_ability(ability_type t)

sets invoked ability type, no other type may be used if this gets set

Parameters
  • type: allows a specific ability type to be used for example to set a unit to patrol rather than the default move

void set_ability_set(ability_set set)

restricts action to a set of possible ability types

const ability_set &ability() const

the ability types allowed to use this command

void add_flag(command_flag flag)

add addition option to this command

bool has_flag(command_flag flag) const

read the range setting

Public Members

const Player &player

player who created the command

Private Functions

Command(const Player &p, Unit *unit, bool haspos, UnitType *t, Research *res)

basic constructor, which shouldnt be used directly

Private Members

bool has_pos
Unit *u
coord::phys3 pos = {0, , }
UnitType *unit_type
Research *res
std::unordered_set<command_flag> flags

additional options

ability_set modifiers

select actions to use when targeting

class Buf
#include <buf.h>

Public Functions

Buf(coord::term dims, coord::term_t scrollback_lines, coord::term_t min_width, buf_char default_char_fmt = {0x20, , , })
~Buf()
Buf &operator=(const Buf&)
Buf(const Buf&)
void reset()

resets the buffer to its constructor defaults

void write(const char *c, ssize_t len = -1)

write a byte string to the buffer

the string is assumed to be UTF-8 encoded.

if len >= 0, it describes the length of the string. otherwise, the string is assumed to be null-terminated.

void write(char c)

write a single byte to the buffer.

assumed to be UTF-8 encoded.

void pop_last_char()

Pop the last char of the current line.

Will correctly handle UTF-8 chars and wrapped lines.

void resize(coord::term new_dims)

resizes the screen buffer

void scroll(coord::term_t lines)

scrolls up or down by the given number of lines

lines amount of lines to scroll up - may be negative if the upper or lower limit is reached, this is capped.

void process_codepoint(int cp)

processes one unicode codepoint internally called by write(char) after feeding the char into streamdecoder

void print_codepoint(int cp)

prints one unicode codepoint interally called by process_codepoint(int cp) after sorting out escape sequences, and by some escape sequences such as CSI @

void escape_sequence_aborted()

aborts the current escape sequence (e.g.

because it contained an illegal character, or is not implemented)

void escape_sequence_processed()

called when a escape sequence has been successfully processed, clears the sequence.

either this or abort_escape_sequence is called for each escape sequence.

void process_csi_escape_sequence()

processes the CSI escape sequence currently stored in escape_sequence.

invalid sequences are ignored.

void process_escaped_cp(int cp)

processes a single-codepoint escape sequence.

invalid codepoints are ignored.

void process_text_escape_sequence()

processes a text escape sequence that is one of OSC, DCS, APC or PM

void process_sgr_code(const std::vector<int> &params)

sets graphics rendition parameters; called by process_escape_sequence

params: numerical params list from escape sequence

void advance(unsigned linecount = 1)

advances the buffer by the specified number of lines.

the top lines are moved to the scrollback buffer. the top lines of the scrollback buffer are discarded. the bottom lines of the buffer are empty after this. the cursor position is not changed by this.

linecount: the number of lines to advance the buffer; defaults to one. may be > buffer height.

void clear(coord::term start, coord::term end, bool clear_end = false)

clears the screen character and line buffers.

lines are cleared iff all of their characters are cleared.

if start >= end, nothing happens.

inputs are not sanitized.

start screen buffer coordinates of first character to be deleted negative values of y indicate scrollback buffer -scrollback_lines <= y < dims.y 0 <= x < dims.x end screen buffer coordinates of first character not to be deleted negative values of y indicate scrollback buffer -scrollback_lines <= y < dims.y 0 <= x < dims.x {x, y} = {0, dims.y} is allowed. clear_end if true, end is incremented by 1. this affects all constraints.

void chrdata_clear(buf_char *start, buf_char *end)

clears a range of the data buffer.

end is the first character that is not cleared. end and start both must be valid pointers within data.

void linedata_clear(buf_line *start, buf_line *end)

clears a range of the linedata buffer.

end is the first line that is not cleared. end and start both must be valid pointers within data.

buf_char *chrdataptr(coord::term pos)

returns a valid pointer to the character info for the character designated by pos

pos screen buffer coordinates negative values of y indicate scrollback buffer -scrollback_lines <= pos.y <= dims.y 0 <= pos.x < dims.x if y == dims.y, the return ptr is not guaranteed to be valid.

buf_line *linedataptr(coord::term_t lineno)

returns a valid pointer to the line info for the line designated by lineno

lineno number of line in screen buffer negative numbers indicate scrollback buffer -scrollback_lines <= lineno <= dims.y if lineno == dims.y, the return ptr is not guaranteed to be valid.

const coord::term &get_dims() const

Return the dimensions of the visible console area.

Public Members

util::utf8_decoder streamdecoder

utf-8 state-machine that reads input bytes and outputs unicode codepoints

buf_char *chrdata

the complete (2-dimensional) terminal output buffer content

contains the screen buffer (where the cursor may move), and the scrollback buffer (which is invisible while not scrolled back)

thus, its size is always screen buffer size + scrollback buffer size (dims.x * dims.y + dims.x * scrollback_lines)

on resize, this buffer is completely re-created.

the first entry of data is not neccesarily the first character of the screen or scrollback buffer; see screen_chrdata.

size_t chrdata_size

stores the (array) size of data, for performance and convenience reasons.

always has the value dims.x * (dims.y + scrollback_lines)

buf_char *chrdata_end

stores the end of the region allocated for data, for performance and convenience reasons.

points to the first memory region outside the data buffer.

always has the value data + chrdata_size

buf_char *screen_chrdata

points to the first character that belongs to the screen buffer, inside the data buffer.

this pointer is changed when the terminal buffer advances one line.

note that screen_chrdata may NOT be directly indexed, as *screen_chrdata[k] might be >= chrdata_end. in this case, the correct memory location will be *screen_chrdata[k - chrdata_size].

*screen_chrdata[0] always is the correct memory location of the screen buffer top left corner.

*screen_chrdata[dims.x * dims.y] is the memory location of the scrollback buffer top left corner, but it might be neccesary to subtract chrdata_size to get an actually valid memory location.

buf_line *linedata

similar to how data holds information about all characters, linedata holds information about all lines.

currently, the only held information is whether the line has been started by wrapping an existing line (and thus is not a ‘real’ new line)

size_t linedata_size

see chrdata_size

buf_line *linedata_end

see chrdata_end

buf_line *screen_linedata

as an analog to screen_chrdata, this points to the entry in linedata that holds metadata about the top line of the screen buffer.

coord::term_t min_width

minimum screen buffer width

coord::term dims

screen buffer dimensions (in characters)

coord::term_t scrollback_lines

scrollback buffer height; scrollback buffer width is identical to screen buffer width.

coord::term cursorpos

cursor position

coord::term saved_cursorpos

saved cursor position

bool cursor_visible

true if the cursor is visible

bool cursor_special_lastcol

true if cursor is in the last column while whole line is filled this is very special.

this allows CR after fully-filled lines to return to the same line, instead of being in the next line.

bool escaped

true if we are currently reading an escape sequence

std::vector<int> escape_sequence

current escape sequence

bool bell

true if an bell (‘’) has been received, but not cleared

std::vector<int> title

window title

buf_char current_char_fmt

surrently selected formatting (colors, flags).

all printed chars, as well as all buffer clearing, will use this until it is changed by an SGR escape sequence.

the codepoint is the codepoint used for filling empty chars (e.g. 0x20 (‘space’))

const buf_char default_char_fmt

the default buf char, which will be used for filling new lines, or determining whether a line is empty.

should have space (0x20) as its char, and the desired default values for fgcol and bgcol.

coord::term_t scrollback_possible

how far it’s currently possible to scroll back.

this value steadily increases when the buffer advances.

if this is 0, all lines outside the screen buffer are empty.

must be >= 0 and <= scrollback_lines

coord::term_t scrollback_pos

how many lines the buffer is currently scrolled back.

if 0, the screen buffer is wholly rendered. if the terminal is being advanced, this stays 0. this makes the terminal follow newly printed text. if > 0, the bottom lines of the screen buffer are not rendered, and the bottom lines of the scrollback buffer are rendered instead. if screen buffer advances, this is increased accordingly (unless it would become >= scrollback_lines). this causes the currently scrolled-to position to remain scrolled-to even when new text is printed.

must be >= 0 and <= scrollback_possible.

Friends

friend openage::console::Buf::NewBuf
struct buf_char
#include <buf.h>

a single character in the buffer

Public Functions

buf_char(int cp, chrcol_t fgcol, chrcol_t bgcol, chrflags_t flags)

Default copy constructor.

buf_char()
bool operator==(const buf_char &other) const
bool operator!=(const buf_char &other) const

Public Members

int cp

unicode codepoint of the character

chrcol_t fgcol

(256-col) color of the character

chrcol_t bgcol

(256-col) background color

chrflags_t flags

flags of the character

struct buf_line
#include <buf.h>

metadata for a single line in the buffer

Public Members

linetype_t type
class Console : private openage::InputHandler, private openage::TickHandler, private openage::HudHandler, private openage::ResizeHandler
#include <console.h>

Public Functions

Console(Engine *engine)
~Console()
void load_colors(std::vector<gamedata::palette_color> &colortable)

load the consoles color table

void register_to_engine()

register this console to the engine.

this leads to the drawing calls, and input handling.

void set_visible(bool make_visible)
void write(const char *text)

prints the given text on the console.

void interpret(const std::string &command)

a temporary console command interpreter

bool on_drawhud()

execute the drawing action.

bool on_tick()

execute the tick action.

bool on_input(SDL_Event *event)

execute the input handler.

bool on_resize(coord::viewport_delta new_size)

execute the resize handler.

Public Members

coord::camhud bottomleft
coord::camhud topright
coord::camhud charsize
std::vector<util::col> termcolors
bool visible
Buf buf
renderer::Font font
input::InputContext input_context
std::string command

Protected Attributes

Engine *engine
class NewBuf

Public Functions

NewBuf(term dims, term_t scrollback_lines, buf_char default_char_fmt)
~NewBuf()
void apply_to_buf(Buf *b)
void move_ptrs_to_next_line()
void new_line(bool part_of_screen_buf)

starts a new line (as by newline character)

void new_chr(buf_char c)

writes a char

Public Members

term dims
term_t scrollback_lines
buf_line *linedata
size_t linedata_size
buf_line *linedata_end
buf_line *linedata_ptr
buf_char *chrdata
size_t chrdata_size
buf_char *chrdata_end
buf_char *chrdata_ptr
term_t screen_buf_start
size_t screen_buf_size
term_t scrollback_buf_start
size_t scrollback_buf_size
bool current_line_is_screen_buf
term current_pos
const buf_char default_char_fmt
class BestPacker

Chooses the best result from all the given packers.

Public Functions

__init__(self self, packers packers)
pack(self self, blocks blocks)
best_packer(self self)
pos(self self, block block)
width(self self)
height(self self)

Public Members

packers
current_best
class BinaryTreePacker

Binary tree bin packing strategy.

Very close to http://codeincomplete.com/posts/2011/5/7/bin_packing/.

Aditionally can target a given aspect ratio. 97/49 is optimal for terrain textures.

Public Functions

__init__(self self, margin margin, aspect_ratio aspect_ratio = 1, heuristic heuristic = maxside_heuristic)
pack(self self, blocks blocks)
pos(self self, block block)
fit(self self, block block)
find_node(self self, root root, width width, height height)
split_node(self self, node node, width width, height height)
grow_node(self self, width width, height height)
grow_right(self self, width width, height height)
grow_down(self self, width width, height height)

Public Members

aspect_ratio
heuristic
root
mapping
class ColumnPacker

Packs blocks into columns, greedily trying to minimize the maximum height.

Public Functions

pack(self self, blocks blocks)

Public Members

mapping
class Packer

Packs blocks.

Subclassed by openage.convert.binpack.BinaryTreePacker, openage.convert.binpack.ColumnPacker, openage.convert.binpack.RowPacker

Public Functions

__init__(self self, margin margin)
pack(self self, blocks blocks)

Pack all the blocks.

Each block must have a width and height attribute.

pos(self self, block block)
width(self self)

Gets the total width of the packing.

height(self self)

Gets the total height of the packing.

Public Members

margin
mapping
class PackerNode

A node in a binary packing tree.

Public Functions

__init__(self self, x x, y y, width width, height height)

Public Members

x
y
width
height
used
down
right
class RowPacker

Packs blocks into rows, greedily trying to minimize the maximum width.

Public Functions

pack(self self, blocks blocks)

Public Members

mapping
class BlendingMode

Public Functions

__init__(self self, idx idx, data_file data_file, tile_count tile_count, header header)
get_tile_from_data(self self, data data)

get the data pixels, interprete them in isometric tile format

….*…. ..*****..

..*****.. ….*…. like this, only bigger..

we end up drawing the rhombus with 49 rows. the space indicated by . is added by the function.

Public Members

pxcount
row_count
alphamasks
bitmasks
class BlendingTile

Public Functions

__init__(self self, row_data row_data, width width, height height)
get_picture_data(self self)

Return a numpy array of image data for a blending tile.

Public Members

row_data
width
height
class Blendomatic

Public Functions

__init__(self self, fileobj fileobj)
get_textures(self self)

generate a list of textures.

one atlas per blending mode is generated, each atlas contains all blending masks merged on one texture

dump(self self, filename filename)
structs(cls cls)
save(self self, fslikeobj fslikeobj, path path, save_format save_format)

Save the blending mask textures to disk.

__str__(self self)

Public Members

header
blending_modes

Public Static Attributes

string openage.convert.blendomatic.Blendomatic.name_struct = "blending_mode"
string openage.convert.blendomatic.Blendomatic.name_struct_file = "blending_mode"
tuple openage.convert.blendomatic.Blendomatic.struct_description= ("describes one blending mode, " "a blending transition shape " "between two different terrain types.")
tuple openage.convert.blendomatic.Blendomatic.data_format= ( (True, "blend_mode", "int32_t"), )
openage.convert.blendomatic.Blendomatic.blendomatic_header = Struct("< I I")
class ColorTable

Subclassed by openage.convert.colortable.PlayerColorTable

Public Functions

__init__(self self, data data)
fill_from_array(self self, ar ar)
fill(self self, data data)
__getitem__(self self, index index)
__len__(self self)
__repr__(self self)
__str__(self self)
gen_image(self self, draw_text draw_text = True, squaresize squaresize = 100)

writes this color table (palette) to a png image.

save_visualization(self self, fileobj fileobj)
dump(self self, filename filename)
structs(cls cls)

Public Members

palette
header
version

Public Static Attributes

string openage.convert.colortable.ColorTable.name_struct = "palette_color"
string openage.convert.colortable.ColorTable.name_struct_file = "color"
string openage.convert.colortable.ColorTable.struct_description = "indexed color storage."
tuple openage.convert.colortable.ColorTable.data_format= ( (True, "idx", "int32_t"), (True, "r", "uint8_t"), (True, "g", "uint8_t"), (True, "b", "uint8_t"), (True, "a", "uint8_t"), )
class PlayerColorTable

this class represents stock player color values.

each player has 8 subcolors, where 0 is the darkest and 7 is the lightest

Public Functions

__init__(self self, base_table base_table)
__repr__(self self)

Public Members

header
version
palette
class ContentSnippet

one part of text for generated files to be saved in “file_name”

before whole source files can be written, it’s content snippets have to be ordered according to their dependency chain.

also, each snipped can have import requirements that have to be included in top of the source.

Subclassed by openage.convert.dataformat.header_snippet.HeaderSnippet, openage.convert.dataformat.struct_snippet.StructSnippet

Public Functions

__init__(self self, data data, file_name file_name, section section, orderby orderby = None, reprtxt reprtxt = None)
get_data(self self)
generate_content(self self)
add_required_snippets(self self, snippet_list snippet_list)
get_required_snippets(self self)
__hash__(self self)

hash all relevant snippet properties

__lt__(self self, other other)

comparison of two snippets for their ordering

__eq__(self self, other other)

equality check for text snippets

__repr__(self self)
__str__(self self)

Public Members

data
file_name
typerefs
typedefs
includes
section
orderby
reprtxt
required_snippets
data_ready
class SectionType

Public Static Attributes

string openage.convert.dataformat.content_snippet.SectionType.section_header = "header"
string openage.convert.dataformat.content_snippet.SectionType.section_body = "body"
class DataDefinition

Public Functions

__init__(self self, target target, data data, name_data_file name_data_file)
generate_csv(self self, genfile genfile)

create a text snippet to represent the csv data

__str__(self self)
__repr__(self self)

Public Members

data
name_data_file
target
class DataFormatter

Public Functions

__init__(self self)
add_data(self self, data_set_pile data_set_pile, prefix prefix = None, single_output single_output = None)

add a given StructDefinition to the storage, so it can be exported later.

other exported data structures are collected from the given input.

export(self self, projectdir projectdir, requested_formats requested_formats)

Generates files in the requested formats to projectdir.

projectdir is a util.fslike.path.Path.

Public Members

data
typedefs

Public Static Attributes

string openage.convert.dataformat.data_formatter.DataFormatter.DELIMITER = ","
dictionary openage.convert.dataformat.data_formatter.DataFormatter.member_methods
class EntryParser

An entry parser for reading a single column value from a data file.

Public Functions

__init__(self self, lines lines, headers headers, typerefs typerefs, destination destination = "fill")
get_code(self self, indentlevel indentlevel = 1)

Return the parser code, indented correctly.

Public Members

lines
headers
typerefs
destination
class ParserMemberFunction

Public Functions

__init__(self self, templates templates, func_name func_name)
get_template(self self, lookup lookup)
get_snippet(self self, parser_list parser_list, file_name file_name, class_name class_name, data data)
get_signature(self self)

return the function signature for this member function.

get_headers(self self)

return the needed headers for the function signature of this member function.

Public Members

templates
func_name
class ParserTemplate

Tempalte for a data parser function, its content is generated.

Public Functions

__init__(self self, signature signature, template template, impl_headers impl_headers, headers headers)
get_signature(self self, class_name class_name)

Return the function signature of this parser.

get_text(self self, class_name class_name, data data)

Public Members

signature
template
impl_headers
headers
class Exportable

superclass for all exportable data members

exportable classes shall inherit from this.

Subclassed by openage.convert.blendomatic.Blendomatic, openage.convert.colortable.ColorTable, openage.convert.dataformat.multisubtype_base.MultisubtypeBaseFile, openage.convert.gamedata.civ.Civ, openage.convert.gamedata.empiresdat.EmpiresDat, openage.convert.gamedata.empiresdat.EmpiresDatWrapper, openage.convert.gamedata.graphic.Graphic, openage.convert.gamedata.graphic.GraphicAttackSound, openage.convert.gamedata.graphic.GraphicDelta, openage.convert.gamedata.graphic.SoundProp, openage.convert.gamedata.maps.Map, openage.convert.gamedata.maps.MapElevation, openage.convert.gamedata.maps.MapInfo, openage.convert.gamedata.maps.MapLand, openage.convert.gamedata.maps.MapTerrain, openage.convert.gamedata.maps.MapUnit, openage.convert.gamedata.playercolor.PlayerColor, openage.convert.gamedata.research.Research, openage.convert.gamedata.research.ResearchResourceCost, openage.convert.gamedata.sound.Sound, openage.convert.gamedata.sound.SoundItem, openage.convert.gamedata.tech.AgeTechTree, openage.convert.gamedata.tech.BuildingConnection, openage.convert.gamedata.tech.Effect, openage.convert.gamedata.tech.Mode, openage.convert.gamedata.tech.ResearchConnection, openage.convert.gamedata.tech.Tech, openage.convert.gamedata.tech.UnitConnection, openage.convert.gamedata.terrain.FrameData, openage.convert.gamedata.terrain.Terrain, openage.convert.gamedata.terrain.TerrainAnimation, openage.convert.gamedata.terrain.TerrainBorder, openage.convert.gamedata.terrain.TerrainPassGraphic, openage.convert.gamedata.terrain.TerrainRestriction, openage.convert.gamedata.terrain.TileSize, openage.convert.gamedata.unit.BuildingAnnex, openage.convert.gamedata.unit.DamageGraphic, openage.convert.gamedata.unit.HitType, openage.convert.gamedata.unit.ResourceCost, openage.convert.gamedata.unit.ResourceStorage, openage.convert.gamedata.unit.UnitCommand, openage.convert.gamedata.unit.UnitHeader, openage.convert.gamedata.unit.UnitLine, openage.convert.gamedata.unit.UnitObject

Public Functions

__init__(self self, args args)
dump(self self, filename filename)

main data dumping function, the magic happens in here.

recursively dumps all object members as DataDefinitions.

returns [DataDefinition, ..]

read(self self, raw raw, offset offset, cls cls = None, members members = None)

recursively read defined binary data from raw at given offset.

this is used to fill the python classes with data from the binary input.

structs(cls cls)

create struct definitions for this class and its subdata references.

format_hash(cls cls, hasher hasher = None)

provides a deterministic hash of all exported structure members

used for determining changes in the exported data, which requires data reconversion.

get_effective_type(cls cls)
get_data_format(cls cls, allowed_modes allowed_modes = False, flatten_includes flatten_includes = False, is_parent is_parent = False)

return all members of this exportable (a struct.)

can filter by export modes and can also return included members: inherited members can either be returned as to-be-included, or can be fetched and displayed as if they weren’t inherited.

Public Static Attributes

openage.convert.dataformat.exportable.Exportable.name_struct = None
openage.convert.dataformat.exportable.Exportable.name_struct_file = None
openage.convert.dataformat.exportable.Exportable.struct_description = None
openage.convert.dataformat.exportable.Exportable.game_versions = list()
openage.convert.dataformat.exportable.Exportable.data_format = list()
class GeneratedFile

represents a writable file that was generated automatically.

it’s filled by many ContentSnippets before its contents are generated.

Public Functions

namespacify(cls cls, var_type var_type)
__init__(self self, file_name file_name, format_ format_)
add_snippet(self self, snippet snippet, inherit_typedefs inherit_typedefs = True)
get_include_snippet(self self, file_name file_name = True)

return a snippet with a header entry for this file to be able to include it.

create_xref_headers(self self, file_pool file_pool)

discover and add needed header snippets for type references accross files.

create_forward_declarations(self self, file_pool file_pool)

create forward declarations for this generated file.

a forward declatation is needed when a referenced type is defined in an included header, that includes a header that includes the first one.

generate(self self)

actually generate the content for this file.

__repr__(self self)

Public Members

snippets
typedefs
typerefs
file_name
format_
included_typedefs

Public Static Attributes

tuple openage.convert.dataformat.generated_file.GeneratedFile.namespaces = ("openage", "gamedata")
dictionary openage.convert.dataformat.generated_file.GeneratedFile.default_preferences= { "folder": "", "file_suffix": "", "process": True, "content_prefix": Template(""), "content_suffix": Template(""), }
dictionary openage.convert.dataformat.generated_file.GeneratedFile.output_preferences
class HeaderSnippet

represents an includable C header

Public Functions

__init__(self self, header_name header_name, file_name file_name = True, is_global is_global = False)
get_file_name(self self)
__hash__(self self)
__eq__(self self, other other)
__repr__(self self)

Public Members

is_global
name
class MemberAccess

Public Static Attributes

string openage.convert.dataformat.member_access.MemberAccess.READ = "binary-read_member"
string openage.convert.dataformat.member_access.MemberAccess.READ_EXPORT = "binary-read-export_member"
string openage.convert.dataformat.member_access.MemberAccess.NOREAD_EXPORT = "noread-export_member"
string openage.convert.dataformat.member_access.MemberAccess.READ_UNKNOWN = "read-unknown_member"
class ArrayMember

subdata member for C-type arrays like float[8].

Public Functions

__init__(self self, raw_type raw_type, length length)
__repr__(self self)

Public Members

raw_type
class CharArrayMember

struct member/column type that allows to store equal-length char[n].

Subclassed by openage.convert.dataformat.members.StringMember

Public Functions

__init__(self self, length length)
get_parsers(self self, idx idx, member member)
get_headers(self self, output_target output_target)
get_effective_type(self self)
get_empty_value(self self)
__repr__(self self)

Public Members

raw_type
class ContinueReadMember

Public Functions

entry_hook(self self, data data)
get_empty_value(self self)
get_parsers(self self, idx idx, member member)

Public Static Attributes

openage.convert.dataformat.members.ContinueReadMember.Result = ContinueReadMemberResult
class ContinueReadMemberResult

Public Functions

__str__(self self)

Public Static Attributes

string openage.convert.dataformat.members.ContinueReadMemberResult.ABORT = "data_absent"
string openage.convert.dataformat.members.ContinueReadMemberResult.CONTINUE = "data_exists"
class DataMember

member variable of data files and generated structs.

equals:

  • one column in a csv file.

  • member in the C struct

  • data field in the .dat file

Subclassed by openage.convert.dataformat.members.DynLengthMember, openage.convert.dataformat.members.GroupMember, openage.convert.dataformat.members.NumberMember, openage.convert.dataformat.members.RefMember

Public Functions

__init__(self self)
get_parsers(self self, idx idx, member member)
get_headers(self self, output_target output_target)
get_typerefs(self self)
entry_hook(self self, data data)

allows the data member class to modify the input data

is used e.g. for the number => enum lookup

get_effective_type(self self)
get_empty_value(self self)

when this data field is not filled, use the returned value instead.

get_length(self self, obj obj = None)
verify_read_data(self self, obj obj, data data)

gets called for each entry.

used to check for storage validity (e.g. 0 expected)

get_struct_entries(self self, member_name member_name)

return the lines to put inside the C struct.

format_hash(self self, hasher hasher)

hash these member’s settings.

used to determine data format changes.

__repr__(self self)

Public Members

length
raw_type
do_raw_read
class DynLengthMember

a member that can have a dynamic length.

Subclassed by openage.convert.dataformat.members.ArrayMember, openage.convert.dataformat.members.CharArrayMember, openage.convert.dataformat.members.MultisubtypeMember

Public Functions

__init__(self self, length length)
get_length(self self, obj obj = None)
is_dynamic_length(self self, target target = None)
format_hash(self self, hasher hasher)

Public Members

length

Public Static Attributes

string openage.convert.dataformat.members.DynLengthMember.any_length = "any_length"
class EnumLookupMember

enum definition, does lookup of raw datfile data => enum value

Public Functions

__init__(self self, type_name type_name, lookup_dict lookup_dict, raw_type raw_type, file_name file_name = None)
entry_hook(self self, data data)

perform lookup of raw data -> enum member name

Public Members

lookup_dict
raw_type
class EnumMember

this struct member/data column is a enum.

Subclassed by openage.convert.dataformat.members.EnumLookupMember

Public Functions

__init__(self self, type_name type_name, values values, file_name file_name = None)
get_parsers(self self, idx idx, member member)
get_headers(self self, output_target output_target)
get_typerefs(self self)
get_effective_type(self self)
validate_value(self self, value value)
get_snippets(self self, file_name file_name, format_ format_)

generate enum snippets from given data

input EnumMember output ContentSnippet

format_hash(self self, hasher hasher)
__repr__(self self)

Public Members

values
resolved
class GroupMember

Subclassed by openage.convert.dataformat.members.IncludeMembers

Public Functions

__init__(self self, cls cls)
get_headers(self self, output_target output_target)
get_typerefs(self self)
get_effective_type(self self)
get_parsers(self self, idx idx, member member)
format_hash(self self, hasher hasher)
__repr__(self self)

Public Members

cls
class IncludeMembers

Public Functions

get_parsers(self self, idx idx, member member)
__repr__(self self)
class MultisubtypeMember

Subclassed by openage.convert.dataformat.members.SubdataMember

Public Functions

__init__(self self, type_name type_name, subtype_definition subtype_definition, class_lookup class_lookup, length length, passed_args passed_args = None, ref_to ref_to = None, offset_to offset_to = None, file_name file_name = None, ref_type_params ref_type_params = None)
get_headers(self self, output_target output_target)
get_effective_type(self self)
get_empty_value(self self)
get_contained_types(self self)
get_parsers(self self, idx idx, member member)
get_typerefs(self self)
get_snippets(self self, file_name file_name, format_ format_)

return struct definitions for this type

format_hash(self self, hasher hasher)
__repr__(self self)

Public Members

subtype_definition
class_lookup
passed_args
ref_to
offset_to
ref_type_params
resolved
class NumberMember

this struct member/data column contains simple numbers

Subclassed by openage.convert.dataformat.members.ContinueReadMember, openage.convert.dataformat.members.ZeroMember

Public Functions

__init__(self self, number_def number_def)
get_parsers(self self, idx idx, member member)
get_headers(self self, output_target output_target)
get_effective_type(self self)
format_hash(self self, hasher hasher)
__repr__(self self)

Public Members

number_type
raw_type

Public Static Attributes

dictionary openage.convert.dataformat.members.NumberMember.type_scan_lookup= { "char": "hhd", "int8_t": "hhd", "uint8_t": "hhu", "int16_t": "hd", "uint16_t": "hu", "int": "d", "int32_t": "d", "uint": "u", "uint32_t": "u", "float": "f", }
class RefMember

a struct member that can be referenced/references another struct.

Subclassed by openage.convert.dataformat.members.EnumMember, openage.convert.dataformat.members.MultisubtypeMember

Public Functions

__init__(self self, type_name type_name, file_name file_name)
format_hash(self self, hasher hasher)

Public Members

type_name
file_name
resolved
class StringMember

member with unspecified string length, aka std::string

Public Functions

__init__(self self)
class SubdataMember

Public Functions

__init__(self self, ref_type ref_type, length length, offset_to offset_to = None, ref_to ref_to = None, ref_type_params ref_type_params = None, passed_args passed_args = None)
get_headers(self self, output_target output_target)
get_subtype(self self)
get_effective_type(self self)
get_parsers(self self, idx idx, member member)
get_snippets(self self, file_name file_name, format_ format_)
get_typerefs(self self)
get_subdata_type_name(self self)
__repr__(self self)
class ZeroMember

Public Functions

__init__(self self, raw_type raw_type, length length = 1)
verify_read_data(self self, obj obj, data data)

Public Members

length
class MultisubtypeBaseFile

Public Static Attributes

string openage.convert.dataformat.multisubtype_base.MultisubtypeBaseFile.name_struct_file = "util"
string openage.convert.dataformat.multisubtype_base.MultisubtypeBaseFile.name_struct = "multisubtype_ref"
string openage.convert.dataformat.multisubtype_base.MultisubtypeBaseFile.struct_description = "format for multi-subtype references"
tuple openage.convert.dataformat.multisubtype_base.MultisubtypeBaseFile.data_format= ( (NOREAD_EXPORT, "subtype", "std.string"), (NOREAD_EXPORT, "filename", "std.string"), )
class StructDefinition

input data read from the data files.

one data set roughly represents one struct in the gamedata dat file. it consists of multiple DataMembers, they define the struct members.

Subclassed by openage.convert.dataformat.data_definition.DataDefinition

Public Functions

__init__(self self, target target)

create a struct definition from an Exportable

dynamic_ref_update(self self, lookup_ref_data lookup_ref_data)

update ourself the with the given reference data.

data members can be cross references to definitions somewhere else. this symbol resolution is done here by replacing the references.

generate_struct(self self, genfile genfile)
generate_struct_implementation(self self, genfile genfile)
__str__(self self)
__repr__(self self)

Public Members

name_struct_file
name_struct
struct_description
prefix
single_output
target
members
inherited_members
parent_classes
class StructSnippet

text snippet for generating C++ structs.

it can generate all struct members and inheritance annotations.

Public Functions

__init__(self self, file_name file_name, struct_name struct_name, comment comment = None, parents parents = None)
set_comment(self self, comment comment)

Add a comment to the struct definition.

set_parents(self self, parent_types parent_types)

Add inheritance partents to the struct definition.

add_member(self self, member member)

Add a data member to the struct definition.

add_members(self self, members members)

Add multiple data members to the struct definition.

generate_content(self self)
__hash__(self self)
__eq__(self self, other other)
__str__(self self)

Public Members

data_ready
struct_name
member_list
reprtxt
members
comment
inheritance
data
file_name
section
typedefs
typerefs

Public Static Attributes

openage.convert.dataformat.struct_snippet.StructSnippet.struct_base = Template()
class DRS

represents a file archive in DRS format.

Public Functions

__init__(self self, fileobj fileobj)
read_tables(self self)

Public Members

fileobj
header
tables
class DRSFileInfo

DRS file header.

Public Static Attributes

string openage.convert.drs.DRSFileInfo.endianness = "<"
string openage.convert.drs.DRSFileInfo.file_id = "i"
string openage.convert.drs.DRSFileInfo.file_data_offset = "i"
string openage.convert.drs.DRSFileInfo.file_size = "i"
class DRSHeader

DRS file header; see doc/media/drs-files.

Public Static Attributes

string openage.convert.drs.DRSHeader.endianness = "<"
string openage.convert.drs.DRSHeader.copyright = str(COPYRIGHT_SIZE) + "s"
string openage.convert.drs.DRSHeader.version = "4s"
string openage.convert.drs.DRSHeader.ftype = "12s"
string openage.convert.drs.DRSHeader.table_count = "i"
string openage.convert.drs.DRSHeader.file_offset = "i"
class DRSTableInfo

DRS table header.

Public Static Attributes

string openage.convert.drs.DRSTableInfo.endianness = "<"
string openage.convert.drs.DRSTableInfo.file_extension = "4s"
string openage.convert.drs.DRSTableInfo.file_info_offset = "i"
string openage.convert.drs.DRSTableInfo.file_count = "i"
class GameVersion

Public Functions

__init__(self self, engine_version engine_version, description description, support support, required_files required_files = None)
__str__(self self)

Public Members

engine_version
description
support
required_files

Public Static Attributes

tuple openage.convert.game_versions.GameVersion.age_1= ( 7.2, "Age of Empires 1", Support.nope, {'empires.exe', 'data/empires.dat'}, )
tuple openage.convert.game_versions.GameVersion.age_ror= ( 7.24, "Age of Empires 1: The Rise of Rome", Support.nope, {'empiresx.exe', 'data2/empires2.dat'}, )
tuple openage.convert.game_versions.GameVersion.age2_aok= ( 11.5, "Age of Empires 2: The Age of Kings", Support.nope, {'empires2.exe', 'data/empires2.dat'}, )
tuple openage.convert.game_versions.GameVersion.age2_tc= ( 11.76, "Age of Empires 2: The Conquerors", Support.yes, {'age2_x1/age2_x1.exe', 'data/empires2_x1.dat'}, )
tuple openage.convert.game_versions.GameVersion.age2_tc_10c= ( 12.0, "Age of Empires 2: The Conquerors, Patch 1.0c", Support.yes, {'age2_x1/age2_x1.exe', 'data/empires2_x1_p1.dat'}, )
tuple openage.convert.game_versions.GameVersion.swgb_10= ( 12.1, "Star Wars: Galactic Battlegrounds", Support.nope, {'Game/Battlegrounds.exe', 'Game/Data/GENIE.DAT'}, )
tuple openage.convert.game_versions.GameVersion.swgb_cc= ( 12.2, "Star Wars: Galactic Battlegrounds: Clone Campaigns", Support.nope, {'Game/battlegrounds_x1.exe', 'Game/Data/genie_x1.dat'}, )
tuple openage.convert.game_versions.GameVersion.age2_tc_fe= ( 12.0, "Age of Empires 2: Forgotten Empires", Support.yes, {'age2_x1/age2_x2.exe', 'games/forgotten empires/data/empires2_x1_p1.dat'}, )
tuple openage.convert.game_versions.GameVersion.age2_hd_3x= ( 12.0, "Age of Empires 2: HD Edition (Version 3.0+)", Support.yes, {'AoK HD.exe', 'data/empires2_x1_p1.dat'}, )
tuple openage.convert.game_versions.GameVersion.age2_hd_fe= ( 12.0, "Age of Empires 2: HD + Forgotten Empires (Version 4.0+)", Support.yes, {'AoK HD.exe', 'resources/_common/dat/empires2_x1_p1.dat'}, )
tuple openage.convert.game_versions.GameVersion.age2_hd_ak= ( 12.0, "Age of Empires 2: HD + African Kingdoms (Version 4.7+)", Support.yes, {'AoK HD.exe', 'resources/_common/dat/empires2_x2_p1.dat', 'resources/_packages/african-kingdoms/config.json'}, )
tuple openage.convert.game_versions.GameVersion.age2_hd_rajas= ( 12.0, "Age of Empires 2: HD + Rise of the Rajas (Version 5.x)", Support.breaks, {'AoK HD.exe', 'resources/_common/dat/empires2_x2_p1.dat', 'resources/_packages/rise-of-the-rajas/config.json'}, )
class Support

Support state of a game version.

Public Static Attributes

string openage.convert.game_versions.Support.nope = "not supported"
string openage.convert.game_versions.Support.yes = "supported"
string openage.convert.game_versions.Support.breaks = "presence breaks conversion"
class Civ

Public Static Attributes

string openage.convert.gamedata.civ.Civ.name_struct = "civilisation"
string openage.convert.gamedata.civ.Civ.name_struct_file = name_struct
string openage.convert.gamedata.civ.Civ.struct_description = "describes a civilisation."
list openage.convert.gamedata.civ.Civ.data_format= [ (READ, "player_type", "int8_t"), # always 1 (READ_EXPORT, "name", "char[20]"), (READ, "resources_count", "uint16_t"), (READ_EXPORT, "tech_tree_id", "int16_t"), # links to tech id (to apply its effects) ]
class EmpiresDat

class for fighting and beating the compressed empires2*.dat

represents the main game data file.

Public Functions

get_hash(cls cls)

return the unique hash for the data format tree

Public Static Attributes

string openage.convert.gamedata.empiresdat.EmpiresDat.name_struct_file = "gamedata"
string openage.convert.gamedata.empiresdat.EmpiresDat.name_struct = "empiresdat"
string openage.convert.gamedata.empiresdat.EmpiresDat.struct_description = "empires2_x1_p1.dat structure"
list openage.convert.gamedata.empiresdat.EmpiresDat.data_format = [(READ, "versionstr", "char[8]")]
class EmpiresDatWrapper

Public Static Attributes

string openage.convert.gamedata.empiresdat.EmpiresDatWrapper.name_struct_file = "gamedata"
string openage.convert.gamedata.empiresdat.EmpiresDatWrapper.name_struct = "gamedata"
string openage.convert.gamedata.empiresdat.EmpiresDatWrapper.struct_description = "wrapper for empires2_x1_p1.dat structure"
list openage.convert.gamedata.empiresdat.EmpiresDatWrapper.data_format= [ (READ_EXPORT, "empiresdat", SubdataMember( ref_type=EmpiresDat, length=1, )), ]
class Graphic

Public Static Attributes

string openage.convert.gamedata.graphic.Graphic.name_struct = "graphic"
string openage.convert.gamedata.graphic.Graphic.name_struct_file = name_struct
string openage.convert.gamedata.graphic.Graphic.struct_description = "metadata for ingame graphics files."
list openage.convert.gamedata.graphic.Graphic.data_format = []
class GraphicAttackSound

Public Static Attributes

string openage.convert.gamedata.graphic.GraphicAttackSound.name_struct = "graphic_attack_sound"
string openage.convert.gamedata.graphic.GraphicAttackSound.name_struct_file = "graphic"
string openage.convert.gamedata.graphic.GraphicAttackSound.struct_description = "attack sounds for a given graphics file."
list openage.convert.gamedata.graphic.GraphicAttackSound.data_format= [ (READ, "sound_props", SubdataMember( ref_type=SoundProp, length=3, )), ]
class GraphicDelta

Public Static Attributes

string openage.convert.gamedata.graphic.GraphicDelta.name_struct = "graphic_delta"
string openage.convert.gamedata.graphic.GraphicDelta.name_struct_file = "graphic"
string openage.convert.gamedata.graphic.GraphicDelta.struct_description = "delta definitions for ingame graphics files."
list openage.convert.gamedata.graphic.GraphicDelta.data_format= [ (READ_EXPORT, "graphic_id", "int16_t"), (READ, "padding_1", "int16_t"), (READ, "sprite_ptr", "int32_t"), (READ_EXPORT, "offset_x", "int16_t"), (READ_EXPORT, "offset_y", "int16_t"), (READ, "display_angle", "int16_t"), (READ, "padding_2", "int16_t"), ]
class SoundProp

Public Static Attributes

string openage.convert.gamedata.graphic.SoundProp.name_struct = "sound_prop"
string openage.convert.gamedata.graphic.SoundProp.name_struct_file = "graphic"
string openage.convert.gamedata.graphic.SoundProp.struct_description = "sound id and delay definition for graphics sounds."
list openage.convert.gamedata.graphic.SoundProp.data_format= [ (READ, "sound_delay", "int16_t"), (READ, "sound_id", "int16_t"), ]
class Map

Public Static Attributes

string openage.convert.gamedata.maps.Map.name_struct_file = "randommap"
string openage.convert.gamedata.maps.Map.name_struct = "map"
string openage.convert.gamedata.maps.Map.struct_description = "random map information data"
list openage.convert.gamedata.maps.Map.data_format
class MapElevation

Public Static Attributes

string openage.convert.gamedata.maps.MapElevation.name_struct_file = "randommap"
string openage.convert.gamedata.maps.MapElevation.name_struct = "map_elevation"
string openage.convert.gamedata.maps.MapElevation.struct_description = "random map elevation data"
list openage.convert.gamedata.maps.MapElevation.data_format= [ (READ, "proportion", "int32_t"), (READ, "terrain", "int32_t"), (READ, "clump_count", "int32_t"), (READ, "base_terrain", "int32_t"), (READ, "base_elevation", "int32_t"), (READ, "tile_spacing", "int32_t"), ]
class MapInfo

Public Static Attributes

string openage.convert.gamedata.maps.MapInfo.name_struct_file = "randommap"
string openage.convert.gamedata.maps.MapInfo.name_struct = "map_header"
string openage.convert.gamedata.maps.MapInfo.struct_description = "random map information header"
list openage.convert.gamedata.maps.MapInfo.data_format= [ (READ, "map_id", "int32_t"), (READ, "border_south_west", "int32_t"), (READ, "border_north_west", "int32_t"), (READ, "border_north_east", "int32_t"), (READ, "border_south_east", "int32_t"), (READ, "border_usage", "int32_t"), (READ, "water_shape", "int32_t"), (READ, "base_terrain", "int32_t"), (READ, "land_coverage", "int32_t"), (READ, "unused_id", "int32_t"), (READ, "base_zone_count", "uint32_t"), (READ, "base_zone_ptr", "int32_t"), (READ, "map_terrain_count", "uint32_t"), (READ, "map_terrain_ptr", "int32_t"), (READ, "map_unit_count", "uint32_t"), (READ, "map_unit_ptr", "int32_t"), (READ, "map_elevation_count", "uint32_t"), (READ, "map_elevation_ptr", "int32_t"), ]
class MapLand

Public Static Attributes

string openage.convert.gamedata.maps.MapLand.name_struct_file = "randommap"
string openage.convert.gamedata.maps.MapLand.name_struct = "map"
string openage.convert.gamedata.maps.MapLand.struct_description = "random map information data"
list openage.convert.gamedata.maps.MapLand.data_format= [ (READ, "land_id", "int32_t"), (READ, "terrain", "int32_t"), (READ, "land_spacing", "int32_t"), (READ, "base_size", "int32_t"), (READ, "zone", "int8_t"), (READ, "placement_type", "int8_t"), (READ, "padding1", "int16_t"), (READ, "base_x", "int32_t"), (READ, "base_y", "int32_t"), (READ, "land_proportion", "int8_t"), (READ, "by_player_flag", "int8_t"), (READ, "padding2", "int16_t"), (READ, "start_area_radius", "int32_t"), (READ, "terrain_edge_fade", "int32_t"), (READ, "clumpiness", "int32_t"), ]
class MapTerrain

Public Static Attributes

string openage.convert.gamedata.maps.MapTerrain.name_struct_file = "randommap"
string openage.convert.gamedata.maps.MapTerrain.name_struct = "map_terrain"
string openage.convert.gamedata.maps.MapTerrain.struct_description = "random map terrain information data"
list openage.convert.gamedata.maps.MapTerrain.data_format= [ (READ, "proportion", "int32_t"), (READ, "terrain", "int32_t"), (READ, "number_of_clumps", "int32_t"), (READ, "edge_spacing", "int32_t"), (READ, "placement_zone", "int32_t"), (READ, "clumpiness", "int32_t"), ]
class MapUnit

Public Static Attributes

string openage.convert.gamedata.maps.MapUnit.name_struct_file = "randommap"
string openage.convert.gamedata.maps.MapUnit.name_struct = "map_unit"
string openage.convert.gamedata.maps.MapUnit.struct_description = "random map unit information data"
list openage.convert.gamedata.maps.MapUnit.data_format= [ (READ, "unit", "int32_t"), (READ, "host_terrain", "int32_t"), (READ, "group_placing", "int8_t"), (READ, "scale_flag", "int8_t"), (READ, "padding1", "int16_t"), (READ, "objects_per_group", "int32_t"), (READ, "fluctuation", "int32_t"), (READ, "groups_per_player", "int32_t"), (READ, "group_radius", "int32_t"), (READ, "own_at_start", "int32_t"), (READ, "set_place_for_all_players", "int32_t"), (READ, "min_distance_to_players", "int32_t"), (READ, "max_distance_to_players", "int32_t"), ]
class PlayerColor

Public Static Attributes

string openage.convert.gamedata.playercolor.PlayerColor.name_struct = "player_color"
string openage.convert.gamedata.playercolor.PlayerColor.name_struct_file = name_struct
string openage.convert.gamedata.playercolor.PlayerColor.struct_description = "describes player color settings."
list openage.convert.gamedata.playercolor.PlayerColor.data_format= [ (READ_EXPORT, "id", "int32_t"), (READ_EXPORT, "player_color_base", "int32_t"), # palette index offset, where the 8 player colors start (READ_EXPORT, "outline_color", "int32_t"), # palette index (READ, "unit_selection_color1", "int32_t"), (READ, "unit_selection_color2", "int32_t"), (READ_EXPORT, "minimap_color1", "int32_t"), # palette index (READ, "minimap_color2", "int32_t"), (READ, "minimap_color3", "int32_t"), (READ_EXPORT, "statistics_text_color", "int32_t"), ]
class Research

Public Static Attributes

string openage.convert.gamedata.research.Research.name_struct = "research"
string openage.convert.gamedata.research.Research.name_struct_file = "research"
string openage.convert.gamedata.research.Research.struct_description = "one researchable technology."
list openage.convert.gamedata.research.Research.data_format= [ (READ, "required_techs", "int16_t[6]"), # research ids of techs that are required for activating the possible research (READ, "research_resource_costs", SubdataMember( ref_type=ResearchResourceCost, length=3, )), (READ, "required_tech_count", "int16_t"), # a subset of the above required techs may be sufficient, this defines the minimum amount ]
class ResearchResourceCost

Public Static Attributes

string openage.convert.gamedata.research.ResearchResourceCost.name_struct = "research_resource_cost"
string openage.convert.gamedata.research.ResearchResourceCost.name_struct_file = "research"
string openage.convert.gamedata.research.ResearchResourceCost.struct_description = "amount definition for a single type resource for researches."
list openage.convert.gamedata.research.ResearchResourceCost.data_format= [ (READ, "resource_id", "int16_t"), # see unit/resource_cost, TODO: type xref (READ, "amount", "int16_t"), (READ, "enabled", "int8_t"), ]
class Sound

Public Static Attributes

string openage.convert.gamedata.sound.Sound.name_struct = "sound"
string openage.convert.gamedata.sound.Sound.name_struct_file = "sound"
string openage.convert.gamedata.sound.Sound.struct_description = "describes a sound, consisting of several sound items."
list openage.convert.gamedata.sound.Sound.data_format= [ (READ_EXPORT, "id", "int16_t"), (READ, "play_delay", "int16_t"), (READ_EXPORT, "file_count", "uint16_t"), (READ, "cache_time", "int32_t"), # always 300000 (READ_EXPORT, "sound_items", SubdataMember( ref_type=SoundItem, ref_to="id", length="file_count", )), ]
class SoundItem

Public Static Attributes

string openage.convert.gamedata.sound.SoundItem.name_struct = "sound_item"
string openage.convert.gamedata.sound.SoundItem.name_struct_file = "sound"
string openage.convert.gamedata.sound.SoundItem.struct_description = "one possible file for a sound."
list openage.convert.gamedata.sound.SoundItem.data_format = []
class AgeTechTree

Public Static Attributes

string openage.convert.gamedata.tech.AgeTechTree.name_struct = "age_tech_tree"
string openage.convert.gamedata.tech.AgeTechTree.name_struct_file = "tech"
string openage.convert.gamedata.tech.AgeTechTree.struct_description = "items available when this age was reached."
list openage.convert.gamedata.tech.AgeTechTree.data_format= [ (READ, "total_unit_tech_groups", "int32_t"), (READ, "id", "int32_t"), # 0=generic # 1=TODO # 2=default # 3=marks as not available # 4=upgrading, constructing, creating # 5=research completed, building built (READ, "status", "int8_t"), ]
class BuildingConnection

Public Static Attributes

string openage.convert.gamedata.tech.BuildingConnection.name_struct = "building_connection"
string openage.convert.gamedata.tech.BuildingConnection.name_struct_file = "tech"
string openage.convert.gamedata.tech.BuildingConnection.struct_description = "new available buildings/units/researches when this building was created."
list openage.convert.gamedata.tech.BuildingConnection.data_format= [ (READ_EXPORT, "id", "int32_t"), # unit id of the current building # 0=generic # 1=TODO # 2=default # 3=marks as not available # 4=upgrading, constructing, creating # 5=research completed, building built (READ, "status", "int8_t"), # maybe always 2 because we got 2 of them hardcoded below (unit_or_research, mode) ]
class Effect

Public Static Attributes

string openage.convert.gamedata.tech.Effect.name_struct = "tech_effect"
string openage.convert.gamedata.tech.Effect.name_struct_file = "tech"
string openage.convert.gamedata.tech.Effect.struct_description = "applied effect for a research technology."
list openage.convert.gamedata.tech.Effect.data_format
class Mode

Public Static Attributes

string openage.convert.gamedata.tech.Mode.name_struct = "age_tech_tree"
string openage.convert.gamedata.tech.Mode.name_struct_file = "tech"
string openage.convert.gamedata.tech.Mode.struct_description = "items available when this age was reached."
list openage.convert.gamedata.tech.Mode.data_format= [ (READ, "mode", EnumLookupMember( # mode for unit_or_research0 raw_type = "int32_t", type_name = "building_connection_mode", lookup_dict = { 0: "NOTHING", 1: "BUILDING", 2: "UNIT", 3: "RESEARCH", } )), ]
class ResearchConnection

Public Static Attributes

string openage.convert.gamedata.tech.ResearchConnection.name_struct = "research_connection"
string openage.convert.gamedata.tech.ResearchConnection.name_struct_file = "tech"
string openage.convert.gamedata.tech.ResearchConnection.struct_description = "research updates to apply when activating the technology."
list openage.convert.gamedata.tech.ResearchConnection.data_format= [ (READ, "id", "int32_t"), # 0=generic # 1=TODO # 2=default # 3=marks as not available # 4=upgrading, constructing, creating # 5=research completed, building built (READ, "status", "int8_t"), (READ, "upper_building", "int32_t"), ]
class Tech
class UnitConnection

Public Static Attributes

string openage.convert.gamedata.tech.UnitConnection.name_struct = "unit_connection"
string openage.convert.gamedata.tech.UnitConnection.name_struct_file = "tech"
string openage.convert.gamedata.tech.UnitConnection.struct_description = "unit updates to apply when activating the technology."
list openage.convert.gamedata.tech.UnitConnection.data_format= [ (READ, "id", "int32_t"), # 0=generic # 1=TODO # 2=default # 3=marks as not available # 4=upgrading, constructing, creating # 5=research completed, building built (READ, "status", "int8_t"), # always 2: default (READ, "upper_building", "int32_t"), # building, where this unit is created (READ, "slots_used", "int32_t"), (READ, "unit_researches", "int32_t[10]"), (READ, "modes", SubdataMember( ref_type=Mode, length=10, # number of tile types * 12 )), (READ, "vertical_lines", "int32_t"), ]
class FrameData

Public Static Attributes

string openage.convert.gamedata.terrain.FrameData.name_struct_file = "terrain"
string openage.convert.gamedata.terrain.FrameData.name_struct = "frame_data"
string openage.convert.gamedata.terrain.FrameData.struct_description = "specification of terrain frames."
list openage.convert.gamedata.terrain.FrameData.data_format= [ (READ_EXPORT, "frame_count", "int16_t"), (READ_EXPORT, "angle_count", "int16_t"), (READ_EXPORT, "shape_id", "int16_t"), # frame index ]
class Terrain

Public Static Attributes

string openage.convert.gamedata.terrain.Terrain.name_struct = "terrain_type"
string openage.convert.gamedata.terrain.Terrain.name_struct_file = "terrain"
string openage.convert.gamedata.terrain.Terrain.struct_description = "describes a terrain type, like water, ice, etc."
list openage.convert.gamedata.terrain.Terrain.data_format= [ (READ_EXPORT, "enabled", "int8_t"), (READ, "random", "int8_t"), ]
class TerrainAnimation

Public Static Attributes

string openage.convert.gamedata.terrain.TerrainAnimation.name_struct = "terrain_animation"
string openage.convert.gamedata.terrain.TerrainAnimation.name_struct_file = "terrain"
string openage.convert.gamedata.terrain.TerrainAnimation.struct_description = "describes animation properties of a terrain type"
list openage.convert.gamedata.terrain.TerrainAnimation.data_format= [ (READ, "is_animated", "int8_t"), (READ, "animation_frame_count", "int16_t"), # number of frames to animate (READ, "pause_frame_count", "int16_t"), # pause n * (frame rate) after last frame draw (READ, "interval", "float"), # time between frames (READ, "pause_between_loops", "float"), # pause time between frames (READ, "frame", "int16_t"), # current frame (including animation and pause frames) (READ, "draw_frame", "int16_t"), # current frame id to draw (READ, "animate_last", "float"), # last time animation frame was changed (READ, "frame_changed", "int8_t"), # has the drawframe changed since terrain was drawn (READ, "drawn", "int8_t") ]
class TerrainBorder

Public Static Attributes

string openage.convert.gamedata.terrain.TerrainBorder.name_struct = "terrain_border"
string openage.convert.gamedata.terrain.TerrainBorder.name_struct_file = "terrain"
string openage.convert.gamedata.terrain.TerrainBorder.struct_description = "one inter-terraintile border specification."
list openage.convert.gamedata.terrain.TerrainBorder.data_format= [ (READ, "enabled", "int8_t"), (READ, "random", "int8_t"), (READ, "name0", "char[13]"), (READ, "name1", "char[13]"), (READ, "slp_id", "int32_t"), (READ, "shape_ptr", "int32_t"), (READ, "sound_id", "int32_t"), (READ, "color", "uint8_t[3]"), (READ_EXPORT, None, IncludeMembers(cls=TerrainAnimation)), (READ, "frames", SubdataMember( ref_type=FrameData, length=19 * 12, # number of tile types * 12 )), (READ, "draw_tile", "int16_t"), # always 0 (READ, "underlay_terrain", "int16_t"), (READ, "border_style", "int16_t"), ]
class TerrainPassGraphic

Public Static Attributes

string openage.convert.gamedata.terrain.TerrainPassGraphic.name_struct_file = "terrain"
string openage.convert.gamedata.terrain.TerrainPassGraphic.name_struct = "terrain_pass_graphic"
openage.convert.gamedata.terrain.TerrainPassGraphic.struct_description = None
list openage.convert.gamedata.terrain.TerrainPassGraphic.data_format= [ # when this restriction in unit a was selected, can the unit be placed on this terrain id? 0=no, -1=yes (READ, "slp_id_exit_tile", "int32_t"), (READ, "slp_id_enter_tile", "int32_t"), (READ, "slp_id_walk_tile", "int32_t"), ]
class TerrainRestriction

access policies for units on specific terrain.

Public Static Attributes

string openage.convert.gamedata.terrain.TerrainRestriction.name_struct_file = "terrain"
string openage.convert.gamedata.terrain.TerrainRestriction.name_struct = "terrain_restriction"
string openage.convert.gamedata.terrain.TerrainRestriction.struct_description = "løl TODO"
class TileSize

Public Static Attributes

string openage.convert.gamedata.terrain.TileSize.name_struct = "tile_size"
string openage.convert.gamedata.terrain.TileSize.name_struct_file = "terrain"
string openage.convert.gamedata.terrain.TileSize.struct_description = "size definition of one terrain tile."
list openage.convert.gamedata.terrain.TileSize.data_format= [ (READ_EXPORT, "width", "int16_t"), (READ_EXPORT, "height", "int16_t"), (READ_EXPORT, "delta_z", "int16_t"), ]
class ActionUnit

Subclassed by openage.convert.gamedata.unit.ProjectileUnit

Public Static Attributes

string openage.convert.gamedata.unit.ActionUnit.name_struct = "action_unit"
string openage.convert.gamedata.unit.ActionUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.ActionUnit.struct_description = "adds search radius and work properties, as well as movement sounds."
list openage.convert.gamedata.unit.ActionUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=MovingUnit)), # callback unit action id when found. # monument and sheep: 107 = enemy convert. # all auto-convertible units: 0, most other units: -1 (READ, "default_task_id", "int16_t"), # e.g. when sheep are discovered (READ, "search_radius", "float"), (READ_EXPORT, "work_rate", "float"), (READ_EXPORT, "drop_site0", "int16_t"), # unit id where gathered resources shall be delivered to (READ_EXPORT, "drop_site1", "int16_t"), # alternative unit id (READ_EXPORT, "task_by_group", "int8_t"), # if a task is not found in the current unit, other units with the same group id are tried. # 1: male villager; 2: female villager; 3+: free slots # basically this creates a "swap group id" where you can place different-graphic units together. (READ_EXPORT, "command_sound_id", "int16_t"), # sound played when a command is instanciated (READ_EXPORT, "stop_sound_id", "int16_t"), # sound when the command is done (e.g. unit stops at target position) (READ, "run_pattern", "int8_t"), # how animals run around randomly ]
class AnimatedUnit

Subclassed by openage.convert.gamedata.unit.DoppelgangerUnit

Public Static Attributes

string openage.convert.gamedata.unit.AnimatedUnit.name_struct = "animated_unit"
string openage.convert.gamedata.unit.AnimatedUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.AnimatedUnit.struct_description = "adds speed property to units."
list openage.convert.gamedata.unit.AnimatedUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=UnitObject)), (READ_EXPORT, "speed", "float"), ]
class BuildingAnnex

Public Static Attributes

string openage.convert.gamedata.unit.BuildingAnnex.name_struct = "building_annex"
string openage.convert.gamedata.unit.BuildingAnnex.name_struct_file = "unit"
string openage.convert.gamedata.unit.BuildingAnnex.struct_description = "a possible building annex."
list openage.convert.gamedata.unit.BuildingAnnex.data_format= [ (READ_EXPORT, "unit_id", "int16_t"), (READ_EXPORT, "misplaced0", "float"), (READ_EXPORT, "misplaced1", "float"), ]
class BuildingUnit

type_id >= 80

Public Static Attributes

string openage.convert.gamedata.unit.BuildingUnit.name_struct = "building_unit"
string openage.convert.gamedata.unit.BuildingUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.BuildingUnit.struct_description = "construction graphics and garrison building properties for units."
list openage.convert.gamedata.unit.BuildingUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=LivingUnit)), (READ_EXPORT, "construction_graphic_id", "int16_t"), ]
class DamageGraphic

Public Static Attributes

string openage.convert.gamedata.unit.DamageGraphic.name_struct = "damage_graphic"
string openage.convert.gamedata.unit.DamageGraphic.name_struct_file = "unit"
string openage.convert.gamedata.unit.DamageGraphic.struct_description = "stores one possible unit image that is displayed at a given damage percentage."
list openage.convert.gamedata.unit.DamageGraphic.data_format= [ (READ_EXPORT, "graphic_id", "int16_t"), (READ_EXPORT, "damage_percent", "int8_t"), (READ, "old_apply_mode", "int8_t"), # gets overwritten in aoe memory by the real apply_mode: (READ_EXPORT, "apply_mode", EnumLookupMember( raw_type = "int8_t", type_name = "damage_draw_type", lookup_dict = { 0: "TOP", # adds graphics on top (e.g. flames) 1: "RANDOM", # adds graphics on top randomly 2: "REPLACE", # replace original graphics (e.g. damaged walls) }, )), ]
class DoppelgangerUnit

type_id >= 25

Subclassed by openage.convert.gamedata.unit.MovingUnit

Public Static Attributes

string openage.convert.gamedata.unit.DoppelgangerUnit.name_struct = "doppelganger_unit"
string openage.convert.gamedata.unit.DoppelgangerUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.DoppelgangerUnit.struct_description = "weird doppelganger unit thats actually the same as an animated unit."
list openage.convert.gamedata.unit.DoppelgangerUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=AnimatedUnit)), ]
class HitType

Public Static Attributes

string openage.convert.gamedata.unit.HitType.name_struct = "hit_type"
string openage.convert.gamedata.unit.HitType.name_struct_file = "unit"
string openage.convert.gamedata.unit.HitType.struct_description = "stores attack amount for a damage type."
list openage.convert.gamedata.unit.HitType.data_format
class LivingUnit

type_id >= 70

Subclassed by openage.convert.gamedata.unit.BuildingUnit

Public Static Attributes

string openage.convert.gamedata.unit.LivingUnit.name_struct = "living_unit"
string openage.convert.gamedata.unit.LivingUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.LivingUnit.struct_description = "adds creation location and garrison unit properties."
list openage.convert.gamedata.unit.LivingUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=ProjectileUnit)), (READ_EXPORT, "resource_cost", SubdataMember( ref_type=ResourceCost, length=3, )), (READ_EXPORT, "creation_time", "int16_t"), # in seconds (READ_EXPORT, "creation_location_id", "int16_t"), # e.g. 118 = villager # where to place the button with the given icon # creation page: # +------------------------+ # | 01 | 02 | 03 | 04 | 05 | # |----|----|----|----|----| # | 06 | 07 | 08 | 09 | 10 | # |----|----|----|----|----| # | 11 | 12 | 13 | 14 | 15 | # +------------------------+ # # additional page (dock): # +------------------------+ # | 21 | 22 | 23 | 24 | 25 | # |----|----|----|----|----| # | 26 | 27 | 28 | 29 | 30 | # |----|----|----|----|----| # | 31 | 32 | 33 | 34 | 35 | # +------------------------+ (READ, "creation_button_id", "int8_t"), ]
class MissileUnit

Public Static Attributes

string openage.convert.gamedata.unit.MissileUnit.name_struct = "missile_unit"
string openage.convert.gamedata.unit.MissileUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.MissileUnit.struct_description = "adds missile specific unit properties."
list openage.convert.gamedata.unit.MissileUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=ProjectileUnit)), (READ, "projectile_type", "int8_t"), # 0 = default; 1 = projectile falls vertically to the bottom of the map; 3 = teleporting projectiles (READ, "smart_mode", "int8_t"), # "better aiming". tech attribute 19 changes this: 0 = shoot at current pos; 1 = shoot at predicted pos (READ, "drop_animation_mode", "int8_t"), # 1 = disappear on hit (READ, "penetration_mode", "int8_t"), # 1 = pass through hit object; 0 = stop projectile on hit; (only for graphics, not pass-through damage) (READ, "area_of_effect_special", "int8_t"), (READ_EXPORT, "projectile_arc", "float"), ]
class MovingUnit

Subclassed by openage.convert.gamedata.unit.ActionUnit

Public Static Attributes

string openage.convert.gamedata.unit.MovingUnit.name_struct = "moving_unit"
string openage.convert.gamedata.unit.MovingUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.MovingUnit.struct_description = "adds walking graphics, rotations and tracking properties to units."
list openage.convert.gamedata.unit.MovingUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=DoppelgangerUnit)), (READ_EXPORT, "walking_graphics0", "int16_t"), (READ_EXPORT, "walking_graphics1", "int16_t"), (READ, "turn_speed", "float"), (READ, "old_size_class", "int8_t"), (READ, "trail_unit_id", "int16_t"), # unit id for the ground traces (READ, "trail_opsions", "uint8_t"), # ground traces: -1: no tracking present, 2: projectiles with tracking unit (READ, "trail_spacing", "float"), # ground trace spacing: 0: no tracking, 0.5: trade cart, 0.12: some projectiles, 0.4: other projectiles (READ, "old_move_algorithm", "int8_t"), ]
class ProjectileUnit

Subclassed by openage.convert.gamedata.unit.LivingUnit, openage.convert.gamedata.unit.MissileUnit

Public Static Attributes

string openage.convert.gamedata.unit.ProjectileUnit.name_struct = "projectile_unit"
string openage.convert.gamedata.unit.ProjectileUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.ProjectileUnit.struct_description = "adds attack and armor properties to units."
list openage.convert.gamedata.unit.ProjectileUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=ActionUnit)), ]
class ResourceCost

Public Static Attributes

string openage.convert.gamedata.unit.ResourceCost.name_struct = "resource_cost"
string openage.convert.gamedata.unit.ResourceCost.name_struct_file = "unit"
string openage.convert.gamedata.unit.ResourceCost.struct_description = "stores cost for one resource for creating the unit."
list openage.convert.gamedata.unit.ResourceCost.data_format
class ResourceStorage

Public Static Attributes

string openage.convert.gamedata.unit.ResourceStorage.name_struct = "resource_storage"
string openage.convert.gamedata.unit.ResourceStorage.name_struct_file = "unit"
string openage.convert.gamedata.unit.ResourceStorage.struct_description = "determines the resource storage capacity for one unit mode."
list openage.convert.gamedata.unit.ResourceStorage.data_format= [ (READ, "type", "int16_t"), (READ, "amount", "float"), (READ, "used_mode", EnumLookupMember( raw_type = "int8_t", type_name = "resource_handling", lookup_dict = { 0: "DECAYABLE", 1: "KEEP_AFTER_DEATH", 2: "RESET_ON_DEATH_INSTANT", 4: "RESET_ON_DEATH_WHEN_COMPLETED", }, )), ]
class TreeUnit

type_id == 90

Public Static Attributes

string openage.convert.gamedata.unit.TreeUnit.name_struct = "tree_unit"
string openage.convert.gamedata.unit.TreeUnit.name_struct_file = "unit"
string openage.convert.gamedata.unit.TreeUnit.struct_description = "just a tree unit."
list openage.convert.gamedata.unit.TreeUnit.data_format= [ (READ_EXPORT, None, IncludeMembers(cls=UnitObject)), ]
class UnitCommand

Public Static Attributes

string openage.convert.gamedata.unit.UnitCommand.name_struct = "unit_command"
string openage.convert.gamedata.unit.UnitCommand.name_struct_file = "unit"
string openage.convert.gamedata.unit.UnitCommand.struct_description = "a command a single unit may receive by script or human."
class UnitHeader

Public Static Attributes

string openage.convert.gamedata.unit.UnitHeader.name_struct = "unit_header"
string openage.convert.gamedata.unit.UnitHeader.name_struct_file = "unit"
string openage.convert.gamedata.unit.UnitHeader.struct_description = "stores a bunch of unit commands."
list openage.convert.gamedata.unit.UnitHeader.data_format= [ (READ, "exists", ContinueReadMember("uint8_t")), (READ, "unit_command_count", "uint16_t"), (READ_EXPORT, "unit_commands", SubdataMember( ref_type=UnitCommand, length="unit_command_count", )), ]
class UnitLine

Public Static Attributes

string openage.convert.gamedata.unit.UnitLine.name_struct = "unit_header"
string openage.convert.gamedata.unit.UnitLine.name_struct_file = "unit"
string openage.convert.gamedata.unit.UnitLine.struct_description = "stores a bunch of unit commands."
list openage.convert.gamedata.unit.UnitLine.data_format= [ (READ, "name_length", "uint16_t"), (READ, "name", "char[name_length]"), (READ, "unit_ids_counter", "uint16_t"), (READ, "unit_ids", "int16_t[unit_ids_counter]"), ]
class UnitObject

base properties for every unit entry.

Subclassed by openage.convert.gamedata.unit.AnimatedUnit, openage.convert.gamedata.unit.TreeUnit

Public Static Attributes

string openage.convert.gamedata.unit.UnitObject.name_struct = "unit_object"
string openage.convert.gamedata.unit.UnitObject.name_struct_file = "unit"
string openage.convert.gamedata.unit.UnitObject.struct_description = "base properties for all units."
list openage.convert.gamedata.unit.UnitObject.data_format
class InterfaceCutter

Cuts interface textures into repeatable parts.

Public Functions

__init__(self self, idx idx)
cut(self self, image image)

Create subtextures by searching for patterns at hardcoded positions.

cut_strip(self self, img_array img_array, pattern_corners pattern_corners, search_area_corners search_area_corners)

Finds a horizontally tilable piece of the strip (ex.

the top of the HUD).

   ||----///////////-------------///////////-------------///////////-------------///////////||
             ^      pattern_corners     ^                    ^  where it is found last  ^
             ^           this piece is tileable              ^

   so, cut out a subtexture:
             ///////-------------///////////-------------////

Public Members

idx
class PECOFFHeader

The new (win32) PE and object file header.

Public Static Attributes

string openage.convert.pefile.PECOFFHeader.endianness = "<"
string openage.convert.pefile.PECOFFHeader.signature = "4s"
string openage.convert.pefile.PECOFFHeader.machine = "H"
string openage.convert.pefile.PECOFFHeader.number_of_sections = "H"
string openage.convert.pefile.PECOFFHeader.time_stamp = "I"
string openage.convert.pefile.PECOFFHeader.symbol_table_ptr = "I"
string openage.convert.pefile.PECOFFHeader.symbol_count = "I"
string openage.convert.pefile.PECOFFHeader.opt_header_size = "H"
string openage.convert.pefile.PECOFFHeader.characteristics = "H"
class PEDataDirectory

Public Static Attributes

string openage.convert.pefile.PEDataDirectory.endianness = "<"
string openage.convert.pefile.PEDataDirectory.rva = "I"
string openage.convert.pefile.PEDataDirectory.size = "I"
class PEDOSHeader

The (legacy) DOS-compatible PE header.

In all modern PE files, only the ‘lfanew’ pointer is relevant.

Public Static Attributes

string openage.convert.pefile.PEDOSHeader.endianness = "<"
string openage.convert.pefile.PEDOSHeader.signature = "2s"
string openage.convert.pefile.PEDOSHeader.bytes_lastpage = "H"
string openage.convert.pefile.PEDOSHeader.count_pages = "H"
string openage.convert.pefile.PEDOSHeader.crlc = "H"
string openage.convert.pefile.PEDOSHeader.cparhdr = "H"
string openage.convert.pefile.PEDOSHeader.minalloc = "H"
string openage.convert.pefile.PEDOSHeader.maxalloc = "H"
string openage.convert.pefile.PEDOSHeader.initial_ss = "H"
string openage.convert.pefile.PEDOSHeader.initial_sp = "H"
string openage.convert.pefile.PEDOSHeader.checksum = "H"
string openage.convert.pefile.PEDOSHeader.initial_ip = "H"
string openage.convert.pefile.PEDOSHeader.initial_cs = "H"
string openage.convert.pefile.PEDOSHeader.lfarlc = "H"
string openage.convert.pefile.PEDOSHeader.ovno = "H"
string openage.convert.pefile.PEDOSHeader.reserved0 = "8s"
string openage.convert.pefile.PEDOSHeader.oemid = "H"
string openage.convert.pefile.PEDOSHeader.oeminfo = "H"
string openage.convert.pefile.PEDOSHeader.reserved1 = "20s"
string openage.convert.pefile.PEDOSHeader.coffheaderpos = "I"
class PEFile

Reads Microsoft PE files.

The constructor takes a file-like object.

Public Functions

__init__(self self, fileobj fileobj)
open_section(self self, section_name section_name)

Returns a tuple of data, va for the given section.

data is a file-like object (StreamFragment), and va is the RVA of the section start.

resources(self self)

Returns a PEResources object for self.

Public Members

fileobj
doshdr
coffhdr
opthdr
sections
class PEOptionalHeader

This “optional” header is required for linked files (but not object files).

Public Static Attributes

string openage.convert.pefile.PEOptionalHeader.endianness = "<"
string openage.convert.pefile.PEOptionalHeader.signature = "H"
string openage.convert.pefile.PEOptionalHeader.major_linker_ver = "B"
string openage.convert.pefile.PEOptionalHeader.minor_linker_ver = "B"
string openage.convert.pefile.PEOptionalHeader.size_of_code = "I"
string openage.convert.pefile.PEOptionalHeader.size_of_data = "I"
string openage.convert.pefile.PEOptionalHeader.size_of_bss = "I"
string openage.convert.pefile.PEOptionalHeader.entry_point_addr = "I"
string openage.convert.pefile.PEOptionalHeader.base_of_code = "I"
string openage.convert.pefile.PEOptionalHeader.base_of_data = "I"
string openage.convert.pefile.PEOptionalHeader.image_base = "I"
string openage.convert.pefile.PEOptionalHeader.section_alignment = "I"
string openage.convert.pefile.PEOptionalHeader.file_alignment = "I"
string openage.convert.pefile.PEOptionalHeader.major_os_ver = "H"
string openage.convert.pefile.PEOptionalHeader.minor_os_ver = "H"
string openage.convert.pefile.PEOptionalHeader.major_img_ver = "H"
string openage.convert.pefile.PEOptionalHeader.minor_img_ver = "H"
string openage.convert.pefile.PEOptionalHeader.major_subsys_ver = "H"
string openage.convert.pefile.PEOptionalHeader.minor_subsys_ver = "H"
string openage.convert.pefile.PEOptionalHeader.reserved = "I"
string openage.convert.pefile.PEOptionalHeader.size_of_image = "I"
string openage.convert.pefile.PEOptionalHeader.size_of_headers = "I"
string openage.convert.pefile.PEOptionalHeader.checksum = "I"
string openage.convert.pefile.PEOptionalHeader.subsystem = "H"
string openage.convert.pefile.PEOptionalHeader.dll_characteristics = "H"
string openage.convert.pefile.PEOptionalHeader.stack_reserve_size = "I"
string openage.convert.pefile.PEOptionalHeader.stack_commit_size = "I"
string openage.convert.pefile.PEOptionalHeader.heap_reserve_size = "I"
string openage.convert.pefile.PEOptionalHeader.heap_commit_size = "I"
string openage.convert.pefile.PEOptionalHeader.loader_flags = "I"
string openage.convert.pefile.PEOptionalHeader.data_directory_count = "I"
openage.convert.pefile.PEOptionalHeader.data_directories = None
class PESection

Describes a section in a PE file (like an ELF section).

Public Static Attributes

string openage.convert.pefile.PESection.endianness = "<"
string openage.convert.pefile.PESection.name = "8s"
string openage.convert.pefile.PESection.virtual_size = "I"
string openage.convert.pefile.PESection.virtual_address = "I"
string openage.convert.pefile.PESection.size_on_disk = "I"
string openage.convert.pefile.PESection.file_offset = "I"
string openage.convert.pefile.PESection.reserved = "12s"
string openage.convert.pefile.PESection.flags = "I"
class PEResources

.rsrc section of a PE file

The constructor takes a PEFile object.

Public Functions

__init__(self self, pefile pefile)
__getitem__(self self, key key)
read_directory(self self)

reads the directory that’s currently pointed at by self.data.

descends recursively for subdirectories.

returns a ResourceDirectory object with both subdirs and leaves filled in.

read_strings(self self)

Public Members

datava
rootdir
strings
class ResourceDirectory

Resource directory header.

Public Static Attributes

string openage.convert.peresource.ResourceDirectory.endianness = "<"
string openage.convert.peresource.ResourceDirectory.characteristics = "I"
string openage.convert.peresource.ResourceDirectory.timestamp = "I"
string openage.convert.peresource.ResourceDirectory.version_major = "H"
string openage.convert.peresource.ResourceDirectory.version_minor = "H"
string openage.convert.peresource.ResourceDirectory.named_entry_count = "H"
string openage.convert.peresource.ResourceDirectory.id_entry_count = "H"
openage.convert.peresource.ResourceDirectory.subdirs = None
openage.convert.peresource.ResourceDirectory.leaves = None
class ResourceDirectoryEntry

these follow immediately after the directory.

Public Static Attributes

string openage.convert.peresource.ResourceDirectoryEntry.endianness = "<"
string openage.convert.peresource.ResourceDirectoryEntry.name = "I"
string openage.convert.peresource.ResourceDirectoryEntry.data = "I"
openage.convert.peresource.ResourceDirectoryEntry.name_is_str = None
openage.convert.peresource.ResourceDirectoryEntry.is_subdir = None
class ResourceLeaf

header for a leaf node in the resource tree.

Public Functions

open(self self)

Returns a file-like object for this resource.

Public Static Attributes

string openage.convert.peresource.ResourceLeaf.endianness = "<"
string openage.convert.peresource.ResourceLeaf.data_ptr = "I"
string openage.convert.peresource.ResourceLeaf.data_size = "I"
string openage.convert.peresource.ResourceLeaf.codepage = "I"
string openage.convert.peresource.ResourceLeaf.reserved = "I"
openage.convert.peresource.ResourceLeaf.fileobj = None
class StringLiteral

A simple length-prefixed little-endian utf-16 string.

Public Functions

readall(cls cls, fileobj fileobj)

In addition to the static data, reads the string.

Public Static Attributes

string openage.convert.peresource.StringLiteral.endianness = "<"
string openage.convert.peresource.StringLiteral.length = "H"
openage.convert.peresource.StringLiteral.value = None
class SLPConverterPool

Multiprocessing-based pool of SLP converter processes.

Public Functions

__init__(self self, palette palette, jobs jobs = None)
close(self self)

Closes the converter pool, quitting all the processes.

convert(self self, slpdata slpdata, custom_cutter custom_cutter = None)
__enter__(self self)
__exit__(self self, exctype exctype, value value, traceback traceback)

Public Members

palette
fake
idle
job_mutex
processes
class StringResource

Public Functions

__init__(self self)
fill_from(self self, stringtable stringtable)

stringtable is a dict {langcode: {id: string}}

dump(self self, filename filename)
structs(cls cls)

Public Members

strings

Public Static Attributes

string openage.convert.stringresource.StringResource.name_struct = "string_resource"
string openage.convert.stringresource.StringResource.name_struct_file = "string_resource"
string openage.convert.stringresource.StringResource.struct_description = "string id/language to text mapping,"\
tuple openage.convert.stringresource.StringResource.data_format= ( (True, "id", "int32_t"), (True, "lang", "char[16]"), (True, "text", "std.string"), )
class Texture

Public Functions

__init__(self self, input_data input_data, palette palette = None, custom_cutter custom_cutter = None)
save(self self, targetdir targetdir, filename filename, meta_formats meta_formats = None)
dump(self self, filename filename)
structs(cls cls)

Public Static Attributes

string openage.convert.texture.Texture.image_format = "png"
string openage.convert.texture.Texture.name_struct = "subtexture"
string openage.convert.texture.Texture.name_struct_file = "texture"
tuple openage.convert.texture.Texture.struct_description= ( "one sprite, as part of a texture atlas.n" "n" "this struct stores information about positions and sizesn" "of sprites included in the 'big texture'." )
tuple openage.convert.texture.Texture.data_format= ( (True, "x", "int32_t"), (True, "y", "int32_t"), (True, "w", "int32_t"), (True, "h", "int32_t"), (True, "cx", "int32_t"), (True, "cy", "int32_t"), )
int openage.convert.texture.Texture.player_id = 1

Private Functions

_slp_to_subtextures(self self, frame frame, palette palette = None, custom_cutter custom_cutter = None)

convert slp to subtexture or subtextures, use a palette.

class TextureImage

represents a image created from a (r,g,b,a) matrix.

Public Functions

__init__(self self, picture_data picture_data, hotspot hotspot = None)
get_pil_image(self self)
get_data(self self)

Public Members

width
height
hotspot
data
class ConvertAbility : public openage::UnitAbility
#include <ability.h>

initiates a convert action when given a valid target

Public Functions

ConvertAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class ConvertAction : public openage::TargetAction
#include <action.h>

convert an object

Public Functions

ConvertAction(Unit *e, UnitReference tar)
virtual ~ConvertAction()
void update_in_range(unsigned int int, Unit *)

Control units action when in range of the target.

void on_completion_in_range(int)
bool completed_in_range(Unit *) const
std::string name() const

debug string to identify action types

Private Members

float complete
struct camgame : public CoordXYAbsolute<pixel_t, camgame, camgame_delta>
#include <pixel.h>

Public Functions

viewport to_viewport(const CoordManager &mgr) const

See the comments for camgame_delta::to_phys3.

TODO: Once we have terrain elevation, ‘up’ will not mean the absolute elevation, but instead the returned phys3 coordinate will be the intersection between the camgame line and the 3d terrain + up altitude.

camhud to_camhud(const CoordManager &mgr) const
phys3 to_phys3(const CoordManager &mgr, phys_t up = phys_t::zero()) const
tile to_tile(const CoordManager &mgr, phys_t up = phys_t::zero()) const
struct camgame_delta : public CoordXYRelative<pixel_t, camgame, camgame_delta>
#include <pixel.h>

Public Functions

phys3_delta to_phys3(const CoordManager &mgr, phys_t up = phys_t::zero()) const

There are infinite solutions to this conversion problem because a 2D coordinate is converted into a 3D coordinate.

The user needs to manually give the ‘up’ value of the phys3 result.

viewport_delta to_viewport() const
struct camhud : public CoordXYAbsolute<pixel_t, camhud, camhud_delta>
#include <pixel.h>

Public Functions

viewport to_viewport(const CoordManager &mgr) const
struct camhud_delta : public CoordXYRelative<pixel_t, camhud, camhud_delta>
#include <pixel.h>

Public Functions

viewport_delta to_viewport() const
struct chunk : public CoordNeSeAbsolute<chunk_t, chunk, chunk_delta>
#include <chunk.h>
struct chunk3 : public CoordNeSeUpAbsolute<chunk_t, chunk3, chunk3_delta>
#include <chunk.h>
struct chunk3_delta : public CoordNeSeUpRelative<chunk_t, chunk3, chunk3_delta>
#include <chunk.h>
struct chunk_delta : public CoordNeSeRelative<chunk_t, chunk, chunk_delta>
#include <chunk.h>
class CoordManager
#include <coordmanager.h>

Holds all coordinate-related state and metadata.

Among other things, this stores the camera positions.

Public Functions

CoordManager()

Public Members

viewport_delta viewport_size = {800, }

What’s the current size of the viewport? (what’s the coordinate of the top right pixel + (1, 1)?)

phys3 camgame_phys = {10, , }

What place (in Phys3) is the origin of the CamGame coordinate system looking at?

viewport camgame_viewport = {400, }

Where in the viewport is the origin of the CamGame coordinate system? (this is usually the center of the viewport).

viewport camhud_viewport = {0, }

Where in the viewport is the origin of the CamHUD coordinate system? (this is usually the bottom left corner of the viewport)

camgame_delta tile_size = {96, }

The size of a terrain tile, in pixels.

Rile diamonds are 96 pixels wide and 48 pixels high. The area of each tile is 96 * 48 * 0.5 square pixels.

struct input : public CoordXYAbsolute<pixel_t, input, input_delta>
#include <pixel.h>

Public Functions

viewport to_viewport(const CoordManager &mgr) const
camgame to_camgame(const CoordManager &mgr) const
phys3 to_phys3(const CoordManager &mgr, phys_t up = phys_t::zero()) const
struct input_delta : public CoordXYRelative<pixel_t, input, input_delta>
#include <pixel.h>

Public Functions

viewport_delta to_viewport(const CoordManager &mgr) const
camgame_delta to_camgame(const CoordManager &mgr) const
phys3_delta to_phys3(const CoordManager &mgr, phys_t up = phys_t::zero()) const
struct phys2 : public CoordNeSeAbsolute<phys_t, phys2, phys2_delta>
#include <phys.h>

Public Functions

tile to_tile() const
phys3 to_phys3(const Terrain &terrain, phys_t altitude = 0) const
double distance(phys2 other) const
struct phys2_delta : public CoordNeSeRelative<phys_t, phys2, phys2_delta>
#include <phys.h>

Public Functions

double length() const
phys2_delta normalize(double length = 1) const
phys3_delta to_phys3() const
struct phys3 : public CoordNeSeUpAbsolute<phys_t, phys3, phys3_delta>
#include <phys.h>

Public Functions

tile3 to_tile3() const
tile to_tile() const
phys2 to_phys2() const
camgame to_camgame(const CoordManager &mgr) const
viewport to_viewport(const CoordManager &mgr) const
camhud to_camhud(const CoordManager &mgr) const
struct phys3_delta : public CoordNeSeUpRelative<phys_t, phys3, phys3_delta>
#include <phys.h>

Public Functions

double length() const
phys3_delta normalize(double length = 1) const
camgame_delta to_camgame(const CoordManager &mgr) const
phys2_delta to_phys2() const
struct term : public CoordXYAbsolute<term_t, term, term_delta>
#include <term.h>
struct term_delta : public CoordXYRelative<term_t, term, term_delta>
#include <term.h>
struct tile : public CoordNeSeAbsolute<tile_t, tile, tile_delta>
#include <tile.h>

Public Functions

tile3 to_tile3(const Terrain &terrain, tile_t altitude = 0) const

adds an UP component to the coordinate.

the resulting UP component will be ‘altitude’ tiles above ground elevation.

phys2 to_phys2() const
phys3 to_phys3(const Terrain &terrain, tile_t altitude = 0) const
camgame to_camgame(const CoordManager &mgr, const Terrain &terrain, tile_t altitude = 0) const
viewport to_viewport(const CoordManager &mgr, const Terrain &terrain, tile_t altitude = 0) const
chunk to_chunk() const
tile_delta get_pos_on_chunk() const
struct tile3 : public CoordNeSeUpAbsolute<tile_t, tile3, tile3_delta>
#include <tile.h>

Public Functions

constexpr tile to_tile() const
phys2 to_phys2() const
phys3 to_phys3() const
struct tile3_delta : public CoordNeSeUpRelative<tile_t, tile3, tile3_delta>
#include <tile.h>

Public Functions

constexpr tile_delta to_tile() const
struct tile_delta : public CoordNeSeRelative<tile_t, tile, tile_delta>
#include <tile.h>
struct viewport : public CoordXYAbsolute<pixel_t, viewport, viewport_delta>
#include <pixel.h>

Public Functions

camgame to_camgame(const CoordManager &mgr) const
phys3 to_phys3(const CoordManager &mgr, phys_t up = phys_t::zero()) const
tile to_tile(const CoordManager &mgr, phys_t up = phys_t::zero()) const
camhud to_camhud(const CoordManager &mgr) const
struct viewport_delta : public CoordXYRelative<pixel_t, viewport, viewport_delta>
#include <pixel.h>

Public Functions

constexpr camgame_delta to_camgame() const
phys3_delta to_phys3(const CoordManager &mgr, phys_t up) const
camhud_delta to_camhud() const
struct coord_chunk_hash
#include <terrain.h>

hashing for chunk coordinates.

this allows storage of chunk coords as keys in an unordered map.

Public Functions

size_t operator()(const coord::chunk &input) const
class CreateMode : public openage::OutputMode
#include <game_control.h>

This is mainly the game editor.

Shows menus to choose units to build.

Public Functions

CreateMode(qtsdl::GuiItemLink *gui_link)
bool available() const

Is this mode able to be used?

void on_enter()

Called when switching to this mode.

void on_exit()

Called when the mode is left.

void render()

Display this mode.

std::string name() const

Used for displaying the current mode.

void on_game_control_set()

Called after GameControl has been set by QML from set_game_control.

template<typename T>
class Continuous : public openage::curve::ValueContainer<T>
#include <continuous.h>

Continuous Datatype.

Stores a value container with continuous access. The bound template type T has to implement operator+(T) and operator*(time_t).

Public Functions

T get(const time_t &time) const

will interpolate between the keyframes linearly based on the time.

template<typename val_t, typename container_t, typename iterator_t = typename container_t::const_iterator>
class CurveIterator
#include <iterator.h>

Default interface for curve containers.

Public Functions

virtual const val_t &value() const = 0

access the value of the iterator

virtual bool valid() const = 0

Check if the iterator is still valid (this breaks from the stl - in the best way)

CurveIterator(const container_t *c)

The iterator needs a reference to the container.

CurveIterator(const CurveIterator&)

Default copy c’tor.

virtual ~CurveIterator()
CurveIterator<val_t, container_t, iterator_t> &operator=(const CurveIterator<val_t, container_t, iterator_t>&)

Default assignment operator.

virtual const val_t &operator*() const

Dereference will call the virtual function.

virtual const val_t *operator->() const

Dereference will call the virutal function.

virtual bool operator==(const CurveIterator<val_t, container_t> &rhs) const

For equalness only the base iterator will be testet - not the timespans this is defined in.

virtual bool operator!=(const CurveIterator<val_t, container_t> &rhs) const

For unequalness only the base iterator will be testet - not the timespans this is defined in.

virtual CurveIterator<val_t, container_t> &operator++()

Advance to the next valid element.

const iterator_t &get_base() const

Access the underlying.

const time_t &get_from() const

Access the lower end value of the defined time frame.

const time_t &get_to() const

Access the higher end value of the defined time frame.

Protected Functions

CurveIterator(const iterator_t &base, const container_t *container, const time_t &from, const time_t &to)

Can only be constructed from the referenced container.

Protected Attributes

iterator_t base

The iterator this is currently referring to.

const container_t *container

The base container.

time_t from

The time, from where this iterator started to iterate.

time_t to

The time, to where this iterator will iterate.

template<typename T>
class Discrete : public openage::curve::ValueContainer<T>
#include <discrete.h>

Does not interpolate between values.

The template type does only need to implement operator= and copy ctor.

Public Functions

T get(const time_t &t) const

Does not interpolate anything, just returns gives the raw value of the last keyframe with time <= t.

std::pair<time_t, T> get_time(const time_t &t) const

Return the last time and keyframe with time <= t.

std::optional<std::pair<time_t, T>> get_previous(const time_t &t) const

Return, if existing, the time and value of keyframe with time < t.

template<typename T>
class KeyframeContainer
#include <keyframe_container.h>

A timely ordered list with several management functions.

This class manages different time-based management functions for list approach that lies underneath. It contains list to be accessed via a non-accurate timing functionality, this means, that for getting a value, not the exact timestamp has to be known, it will always return the one closest, less or equal to the requested one.

Public Types

template<>
using curvecontainer = std::list<Keyframe>

The underlaying container type.

The most important property of this container is the iterator validity on insert and remove.

template<>
using KeyframeIterator = typename curvecontainer::const_iterator

The iterator type to access elements in the container.

Public Functions

KeyframeContainer(const std::shared_ptr<event::Loop> &loop)

need the datamanger for change management

~KeyframeContainer()
KeyframeContainer<T>::KeyframeIterator last(const time_t &time, const KeyframeIterator &hint) const

Get the last element with e->time <= time, given a hint where to start the search.

Select the element that directly preceedes the given timestamp.

Without a hint, start to iterate at the beginning of the buffer, and return the element last element before e->time > time. This method returns nullptr, if begin->time > time.

KeyframeIterator last(const time_t &time) const

Get the last element with e->time <= time, without a hint where to start searching.

The usage of this method is discouraged - except if there is absolutely no chance for you to have a hint (or the container is known to be nearly empty)

KeyframeIterator insert(const Keyframe &value)

Insert a new element without a hint.

This function is not recommended for use, whenever possible, keep a hint to insert the data.

KeyframeIterator insert(const Keyframe &value, const KeyframeIterator &hint)

Insert a new element.

The hint shall give an approximate location, where the inserter will start to look for a insertion point. If a good hint is given, the runtime of this function will not be affected by the current history size.

KeyframeIterator insert(const time_t &time, const T &value)

Create and insert a new element without submitting a hint.

The use of this function is discouraged, use it only, if your really do not have the possibility to get a hint

KeyframeIterator insert(const time_t &time, const T &value, const KeyframeIterator &hint)

Create and insert a new element.

The hint gives an approximate location.

KeyframeContainer<T>::KeyframeIterator erase_after(KeyframeIterator last_valid)

Erase all elements that come after this last valid element.

Go from the end to the last_valid element, and call erase on all of them.

KeyframeContainer<T>::KeyframeIterator erase(KeyframeIterator it)

Erase a single element from the curve.

Delete the element from the list and call delete on it.

KeyframeIterator begin() const

Obtain an iterator to the first value with the smallest timestamp.

KeyframeIterator end() const

Obtain an iterator to the position after the last value.

void dump()

Debugging method to be used from gdb to understand bugs better.

Private Members

const std::shared_ptr<event::Loop> loop

The data store.

curvecontainer container
class Keyframe
#include <keyframe_container.h>

A element of the curvecontainer.

This is especially used to keep track of the value-timing.

Public Functions

template<>
Keyframe()

New default object at numericlimits<time>::min.

template<>
Keyframe(const time_t &time)

New, default-constructed element at the given time.

template<>
Keyframe(const time_t &time, const T &value)

New element fron time and value.

Public Members

template<>
const time_t time = std::numeric_limits<time_t>::min()
template<>
T value = T()
template<typename key_t, typename val_t, typename container_t>
class MapFilterIterator : public openage::curve::CurveIterator<val_t, container_t>
#include <map_filter_iterator.h>

A filtering operator to iterate over all elements of a map whose elements exist for a certain livespan.

The range where to iterate is given at construction.

It depends on key_t and val_t as map-parameters, container_t is the container to operate on and the function valid_f, that checks if an element is alive.

Public Types

template<>
using iterator_t = typename container_t::const_iterator

Public Functions

MapFilterIterator(const iterator_t &base, const container_t *container, const time_t &from, const time_t &to)

Construct the iterator from its boundary conditions: time and container.

MapFilterIterator(const MapFilterIterator&)
virtual bool valid() const

Check if the iterator is still valid (this breaks from the stl - in the best way)

val_t const &value() const

Get the value behind the iterator.

Nicer way of accessing it beside operator *.

const key_t &key() const

Get the key pointed to by this iterator.

template<class T>
class Queue
#include <queue.h>

A container that manages events on a timeline.

Every event has exactly one time it will happen. This container can be used to store interactions

Public Types

template<>
using container_t = typename std::deque<queue_wrapper>
template<>
using const_iterator = typename container_t::const_iterator
template<>
using iterator = typename container_t::const_iterator

Public Functions

const T &front(const time_t&) const
QueueFilterIterator<T, Queue<T>> begin(const time_t &t = -std::numeric_limits<time_t>::max()) const
QueueFilterIterator<T, Queue<T>> end(const time_t &t = std::numeric_limits<time_t>::max()) const
QueueFilterIterator<T, Queue<T>> between(const time_t &begin = std::numeric_limits<time_t>::max(), const time_t &end = std::numeric_limits<time_t>::max()) const
void erase(const CurveIterator<T, Queue<T>> &t)
QueueFilterIterator<T, Queue<T>> insert(const time_t &time, const T &e)
void clear()
void clean(const time_t &time)
void dump()

Private Members

container_t container
struct queue_wrapper

Public Functions

template<>
queue_wrapper(const time_t &time, const T &value)
template<>
time_t time() const

Public Members

template<>
time_t _time
template<>
T value
template<typename val_t, typename container_t>
class QueueFilterIterator : public openage::curve::CurveIterator<val_t, container_t, container_t::const_iterator>
#include <queue_filter_iterator.h>

A filtering operator to iterate over all elements of a queue whose elements exist at exactly one point of time, the range where to iterate is given at construction.

It depends on val_t as its value type, container_t is the container to operate on and the function valid_f, that checks if an element is alive.

Public Types

template<>
using const_iterator = typename container_t::const_iterator

Public Functions

QueueFilterIterator(const const_iterator &base, const container_t *base_container, const time_t &from, const time_t &to)

Construct the iterator from its boundary conditions: time and container.

virtual bool valid() const

Check if the iterator is still valid (this breaks from the stl - in the best way)

const val_t &value() const

access the value of the iterator

struct map_test_element

Public Functions

map_test_element(int v)
bool operator!=(int rhs)

Public Members

int value
template<typename key_t, typename val_t>
class UnorderedMap
#include <map.h>

Map that keeps track of the lifetime of the contained elements.

Make sure that no key is reused.

Public Types

template<>
using const_iterator = typename std::unordered_map::const_iterator

Public Functions

std::optional<MapFilterIterator<key_t, val_t, UnorderedMap<key_t, val_t>>> operator()(const time_t &time, const key_t &key) const
std::optional<MapFilterIterator<key_t, val_t, UnorderedMap<key_t, val_t>>> at(const time_t &time, const key_t &key) const
MapFilterIterator<key_t, val_t, UnorderedMap<key_t, val_t>> begin(const time_t &e = std::numeric_limits<time_t>::max()) const
MapFilterIterator<key_t, val_t, UnorderedMap<key_t, val_t>> end(const time_t &e = std::numeric_limits<time_t>::max()) const
MapFilterIterator<key_t, val_t, UnorderedMap<key_t, val_t>> insert(const time_t &birth, const key_t &key, const val_t &value)
MapFilterIterator<key_t, val_t, UnorderedMap<key_t, val_t>> insert(const time_t &birth, const time_t &death, const key_t &key, const val_t &value)
MapFilterIterator<key_t, val_t, UnorderedMap<key_t, val_t>> between(const time_t &start, const time_t &to) const
void birth(const time_t &time, const key_t &key)
void birth(const time_t &time, const MapFilterIterator<val_t, val_t, UnorderedMap> &it)
void kill(const time_t &time, const key_t &key)
void kill(const time_t &time, const MapFilterIterator<val_t, val_t, UnorderedMap> &it)
void clean(const time_t&)
void dump()

gdb helper method.

Private Members

std::unordered_map<key_t, map_element> container

Data holder.

Maps keys to map elements. Map elements themselves store when they are valid.

struct map_element

Internal container to access all data and metadata.

Public Functions

template<>
map_element(const val_t &v, const time_t &a, const time_t &d)

Public Members

template<>
val_t value
template<>
time_t alive
template<>
time_t dead
template<typename T>
class ValueContainer : public openage::event::EventTarget
#include <value_container.h>

Subclassed by openage::curve::Continuous< T >, openage::curve::Discrete< T >

Public Functions

ValueContainer(const std::shared_ptr<event::Loop> &mgr, size_t id, const EventTarget::single_change_notifier &notifier = nullptr)
virtual ~ValueContainer()
virtual T get(const time_t &t) const = 0
virtual T operator()(const time_t &now)
std::pair<time_t, const T&> frame(const time_t &time) const
std::pair<time_t, const T&> next_frame(const time_t &time) const
void set_last(const time_t &at, const T &value)
void set_insert(const time_t &at, const T &value)
virtual size_t id() const

Give a unique event system identifier for the entity.

Protected Attributes

KeyframeContainer<T> container

Stores all the keyframes.

const size_t _id

Identifier for the container.

KeyframeContainer<T>::KeyframeIterator last_element

Cache the iterator for quickly finding the end.

class CVarManager
#include <cvar.h>

Configuration manager.

Stores key-value pairs of config data. Actually it doesn’t store data, instead functions that perform/fetch the configuration at the appropriate place.

pxd:

cppclass CVarManager: string get(string name) except + void set(string name, string value) except + void load_config(Path path) except +

Public Functions

CVarManager(const util::Path &path)
bool create(const std::string &name, const std::pair<get_func, set_func> &accessors)

Creates a configuration entry.

Return

if the entry name was successful. It won’t be if the name was used before.

std::string get(const std::string &name) const

Gets the value of a config entry.

Internally calls the stored get function.

void set(const std::string &name, const std::string &value) const

Sets the config entry value.

void load_config(const util::Path &path)

Performs the loading of a configuration file via the Python implementation.

void load_all()

Perform the load of the default config files.

Private Members

std::unordered_map<std::string, std::pair<get_func, set_func>> store

Store the key-value pair of config options.

The clue is to store the “what does the config do”, not the actual value. That way the system is universal.

util::Path path

Magic path that stores config files.

Auto-redirects to the default and write paths in the home folder. It is set up in openage/cvar/location.py and openage/game/main.py

template<typename T>
class ConcurrentQueue
#include <concurrent_queue.h>

A threadsafe queue.

Wraps the std::queue with a mutex.

Supports waiting for data from another thread.

Public Functions

void clear()

Removes all elements from the queue.

bool empty()

Returns whether the queue is empty.

T &front()

Returns the front item of the queue without removing it.

T &pop()

Removes the front item of the queue and returns it.

void push(const T &item)

Appends the given item to the queue.

std::unique_lock<mutex_t> lock()

Return a lock to the queue so multiple of the above operations can be done sequentially.

Private Types

template<>
using mutex_t = std::recursive_mutex

Type of mutex used for the queue.

Private Members

std::queue<T> queue

The internally used queue.

mutex_t mutex

The mutex to synchronize the queue.

std::condition_variable_any elements_available

Condition variable to signal, whether elements are avaiable from the queue.

template<typename K, typename V, size_t count>
class ConstMap
#include <constexpr_map.h>

Compiletime generic lookup map.

Stores the map entries in an array and uses constexpr methods to search and retrieve them at compile-time.

If you experience compiler errors, make sure you request existing keys. We intentionally trigger compiler failures when a key doesn’t exist.

Messages include: “error: ‘*0u’ is not a constant expression” -> nonexistant key

Public Functions

template<class ...Entries>
constexpr ConstMap(Entries&&... entries)
constexpr int size() const

Return the number of entries in this map.

constexpr bool contains(const K &key) const

Tests if the given key is in this map.

constexpr const V &get(const K &key) const

Return the stored value for the given key.

constexpr const V &operator[](const K &key) const

Access entries by map[key].

Private Functions

constexpr void verify_no_duplicates() const

Abort when the map uses the same key more than once.

constexpr auto find(const K &key) const

Returns the iterator matching key from the array.

  • values.end() if the key is not found.

Private Members

std::array<std::pair<K, V>, count> values

The entries associated with this map.

template<typename K, typename V>
class ConstMap<K, V, 0>
#include <constexpr_map.h>

Specialization for size 0.

Needed until https://bugs.llvm.org/show_bug.cgi?id=40124 is resolved.

Public Functions

constexpr int size() const

Empty map has 0 size.

constexpr bool contains(const K&) const

Empty map contains no key/value pairs.

template<typename T, typename compare = std::less<T>, typename heapnode_t = PairingHeapNode<T, compare>>
class PairingHeap
#include <pairing_heap.h>

(Quite) efficient heap implementation.

Public Types

template<>
using node_t = heapnode_t
template<>
using element_t = std::shared_ptr<node_t>
template<>
using this_type = PairingHeap<T, compare, node_t>
template<>
using cmp_t = compare

Public Functions

PairingHeap()

create a empty heap.

~PairingHeap()
element_t push(const T &item)

adds the given item to the heap.

O(1)

element_t push(T &&item)

moves the given item to the heap.

O(1)

T pop()

returns and removes the smallest item on the heap.

element_t pop_node()

returns the smallest item on the heap and deletes it.

also known as delete_min.

Ω(log log n), O(2^(2*√log log n’))

Unlink a node from the heap.

If the item is the current root, just pop(). else, cut the node from its parent, pop() that subtree and merge these trees.

O(pop_node)

const T &top() const

Returns the smallest item on the heap.

O(1)

const element_t &top_node() const

Returns the smallest node on the heap.

O(1)

void decrease(const element_t &node)

You must call this after the node data decreased.

This cuts the subtree and links the subtree again. If the node value increased and you call this, the heap is corrupted. Also known as the decrease_key operation.

O(1)

void update(const element_t &node)

After a change, call this to reorganize the given node.

Support increase and decrease of values.

Use decrease instead when you know the value decreased.

O(1) (but slower than decrease), and O(pop) when node is the root.

void clear()

erase all elements on the heap.

size_t size() const

Return

the number of nodes stored on the heap.

bool empty() const

Return

whether there are no nodes stored on the heap.

void iter_all(const std::function<void(const element_t&)> &func) const

Protected Functions

void walk_tree(const element_t &root, const std::function<void(const element_t&)> &func) const
void push_node(const element_t &node)

adds the given node to the heap.

use this if the node was not in the heap before. O(1)

void root_insert(const element_t &node)

insert a node into the heap.

Protected Attributes

compare cmp
size_t node_count
element_t root_node
template<typename T, typename compare = std::less<T>>
class PairingHeapNode : public std::enable_shared_from_this<PairingHeapNode<T, compare>>
#include <pairing_heap.h>

Public Types

template<>
using this_type = PairingHeapNode<T, compare>

Public Functions

PairingHeapNode(const T &data)
PairingHeapNode(T &&data)
~PairingHeapNode()
const T &get_data() const

Get contained node data.

void become_child_of(const std::shared_ptr<this_type> &node)

Let this node become a child of the given one.

void add_child(const std::shared_ptr<this_type> &new_child)

Add the given node as a child to this one.

This method decides which node becomes the new root node by comparing this with node.

The new root is returned, it has the other node as child.

Link all siblings backwards from right to left.

Recursive call, one stage for each all childs of the root node. This results in the computation of the new subtree root.

void loosen()

Cut this node from all parent and sibling connections, but keeps the child pointer.

This effectively cuts out the subtree.

Public Members

friend openage::datastructure::PairingHeapNode::PairingHeap< T, compare, this_type >
T data
compare cmp

Private Members

std::shared_ptr<this_type> first_child
std::shared_ptr<this_type> prev_sibling
std::shared_ptr<this_type> next_sibling
std::shared_ptr<this_type> parent
struct heap_elem
#include <tests.h>

simplest priority queue element that supports reordering.

Public Functions

bool operator<(const heap_elem &other) const
bool operator==(const heap_elem &other) const

Public Members

int data
class DeadAction : public openage::UnitAction
#include <action.h>

plays a fixed number of frames for the units dying animation

Public Functions

DeadAction(Unit *e, std::function<void()> on_complete = []() {})
virtual ~DeadAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

Private Members

float end_frame
std::function<void()> on_complete_func
class DecayAction : public openage::UnitAction
#include <action.h>

plays a fixed number of frames for the units dying animation

Public Functions

DecayAction(Unit *e)
virtual ~DecayAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

Private Members

float end_frame
class DrawHandler
#include <handlers.h>

superclass for all possible drawing operations in the game.

Subclassed by openage::GameRenderer

Public Functions

virtual ~DrawHandler()
virtual bool on_draw() = 0

execute the drawing action.

class EditorMode : public openage::OutputMode
#include <game_control.h>

UI mode to provide an interface for map editing.

Public Functions

EditorMode(qtsdl::GuiItemLink *gui_link)
bool available() const

Is this mode able to be used?

void on_enter()

Called when switching to this mode.

void on_exit()

Called when the mode is left.

void render()

Display this mode.

std::string name() const

Used for displaying the current mode.

void on_game_control_set()

Called after GameControl has been set by QML from set_game_control.

void set_current_type_id(int current_type_id)
void set_current_terrain_id(openage::terrain_t current_terrain_id)
void set_paint_terrain(bool paint_terrain)
bool on_single_click(int button, coord::viewport point)
void announce_categories()
void announce_category_content(const std::string &category_name)

Public Members

EditorModeSignals gui_signals

Private Functions

void announce()

Emit the “announced” signal with (name, InputContext::active_binds).

void set_game_control(GameControl *game_control)

Called when the GameControl is set in QML.

void paint_terrain_at(const coord::viewport &point)
void paint_entity_at(const coord::viewport &point, const bool del)

Private Members

terrain_t editor_current_terrain

currently selected terrain id

int current_type_id
std::string category
bool paint_terrain

mouse click mode: true = terrain painting, false = unit placement

class EditorModeSignals : public QObject
#include <game_control.h>

Public Functions

EditorModeSignals(EditorMode *editor_mode)

Public Slots

void on_current_player_name_changed()

Signals

void toggle()
void categories_changed(const std::vector<std::string> &categories)
void categories_content_changed()
void category_content_changed(const std::string &category_name, std::vector<std::tuple<index_t, uint16_t>> &type_and_texture)

Private Members

EditorMode *editor_mode
class Engine : public openage::ResizeHandler, public openage::options::OptionNode
#include <engine.h>

main engine container.

central foundation for everything the openage engine is capable of.

pxd:

cppclass Engine:

InputManager &get_input_manager() except +
CVarManager &get_cvar_manager() except +
CoordManager coord

Public Functions

Engine(const util::Path &root_dir, int32_t fps_limit, bool gl_debug, const char *windowtitle)

engine initialization method.

opens a window and initializes the OpenGL context.

Engine(const Engine &copy)

engine copy constructor.

Engine &operator=(const Engine &copy)

engine assignment operator.

Engine(Engine &&other)

engine move constructor.

Engine &operator=(Engine &&other)

engine move operator.

~Engine()

engine destructor, cleans up memory etc.

deletes opengl context, the SDL window, and engine variables.

void run()

starts the engine loop.

void stop()

enqueues the stop of the main loop.

bool on_resize(coord::viewport_delta new_size)

window resize handler function.

recalculates opengl settings like viewport and projection matrices.

void start_game(const Generator &generator)

Start a game with the given game generator.

void start_game(std::unique_ptr<GameMain> &&game)

Start a game with the given initialized game.

void end_game()

Stop the running game.

void save_screenshot(const char *filename)

draw the current frames per second number on screen.

save the current framebuffer to a given png file.

Parameters
  • filename: the file where the picture will be saved to.

bool draw_debug_overlay()

Draw the game version and the current FPS on screen.

void register_input_action(InputHandler *handler)

register a new input event handler, run for each input event.

void register_tick_action(TickHandler *handler)

register a tick action, executed upon engine tick.

void register_drawhud_action(HudHandler *handler, int order = 1)

register a hud drawing handler, drawn in hud coordinates.

order: 1 above, -1 below

void register_draw_action(DrawHandler *handler)

register a draw handler, run in game coordinates.

void register_resize_action(ResizeHandler *handler)

register a resize handler, run when the window size changes.

const util::Path &get_root_dir()

return the data directory where the engine was started from.

GameMain *get_game()

return currently running game or null if a game is not currently running

job::JobManager *get_job_manager()

return this engine’s job manager.

audio::AudioManager &get_audio_manager()

return this engine’s audio manager.

ScreenshotManager &get_screenshot_manager()

return this engine’s screenshot manager.

input::ActionManager &get_action_manager()

return this engine’s action manager.

cvar::CVarManager &get_cvar_manager()

return this engine’s cvar manager.

input::InputManager &get_input_manager()

return this engine’s keybind manager.

UnitSelection *get_unit_selection()

return this engine’s unit selection.

void announce_global_binds()

send keybindings help string to gui.

renderer::TextRenderer *get_text_renderer()

return this engine’s text renderer.

time_nsec_t lastframe_duration_nsec() const

return the number of nanoseconds that have passed for rendering the last frame.

use that for fps-independent input actions.

void render_text(coord::viewport position, size_t size, const renderer::Color &color, const char *format, ...)

render text with the at a position with specified font size

void move_phys_camera(float x, float y, float amount = 1.0)

move the phys3 camera incorporated in the engine

Public Members

bool running

current engine state variable.

to be set to false to stop the engine loop.

options::Var<bool> drawing_debug_overlay

FPS and game version are drawn when this is true.

options::Var<bool> drawing_huds

this allows to disable drawing of every registered hud.

util::ExternalProfiler external_profiler

profiler used by the engine

coord::CoordManager coord

this engine’s coordinate manager.

EngineSignals gui_signals

Signal emitting capability for the engine.

gui::GuiItemLink *gui_link

Link to the Qt GUI.

Private Functions

void loop()

main engine loop function.

this will be looped once per frame when the game is running.

the loop invokes fps counting, SDL event handling, view translation, and calling the main draw_method.

Private Members

util::Path root_dir

The engine root directory.

Uses the openage fslike path abstraction that can mount paths into one.

This means that this path does simulataneously lead to global assets, home-folder-assets, settings, and basically the whole filesystem access.

time_nsec_t ns_per_frame

how many nanoseconds are in a frame (1e9 / fps_limit).

0 if there is no fps limit.

std::vector<InputHandler *> on_input_event

input event processor objects.

called for each captured sdl input event.

std::vector<TickHandler *> on_engine_tick

run on every engine tick, after input handling, before rendering

std::vector<DrawHandler *> on_drawgame

run every time the game is being drawn, with the renderer set to the camgame system

std::vector<HudHandler *> on_drawhud

run every time the hud is being drawn, with the renderer set to the camhud system

std::vector<ResizeHandler *> on_resize_handler

list of handlers that are executed upon a resize event.

std::unique_ptr<GameMain> game

the currently running game

job::JobManager job_manager

the engine’s job manager, for asynchronous background task queuing.

gui::EngineQMLInfo qml_info

This stores information to be accessible from the QML engine.

Information in there (such as a pointer to the this engine) is then usable from within qml files, after some additional magic.

util::FrameCounter fps_counter

the frame counter measuring fps.

ScreenshotManager screenshot_manager

the engine’s screenshot manager.

cvar::CVarManager cvar_manager

the engine’s cvar manager.

input::ActionManager action_manager

the engine’s action manager.

audio::AudioManager audio_manager

the engine’s audio manager.

input::InputManager input_manager

the engine’s keybind manager.

std::unique_ptr<UnitSelection> unit_selection

the engine’s unit selection.

std::unordered_map<int, renderer::Font *> fonts

the text fonts to be used for (can you believe it?) texts.

maps fontsize -> font

SDL_Window *window

SDL window where everything is displayed within.

SDL_GLContext glcontext

SDL OpenGL context, we’ll only have one, but it would allow having multiple ones.

This is actually a void * but sdl2 thought it was a good idea to name it like a differently.

std::unique_ptr<gui::GUI> gui

the gui binding

util::Profiler profiler

the engines profiler

std::unique_ptr<renderer::FontManager> font_manager

ttf font loading manager

std::unique_ptr<renderer::TextRenderer> text_renderer

2d text renderer

std::unique_ptr<log::FileSink> logsink_file

Logsink to store messages to the filesystem.

Friends

friend openage::Engine::GameMain
class EngineSignals : public QObject
#include <engine.h>

Qt signals for the engine.

Signals

void global_binds_changed(const std::vector<std::string> &global_binds)
class Backtrace
#include <backtrace.h>

Abstract class for objects that provide backtrave information through get_symbols().

For a non-abstract implementation, see stackanalyzer.h.

pxd:

cppclass Backtrace: void get_symbols(Func1[void, backtrace_symbol *] callback, cppbool reversed) except +

Subclassed by openage::error::StackAnalyzer, openage::pyinterface::PyExceptionBacktrace

Public Functions

virtual void get_symbols(std::function<void(const backtrace_symbol *)> cb, bool reversed = true, ) const = 0

Returns (via the callback) symbolic names for all stack frames, to its best knowledge.

The most recent call is returned last (alike Python).

Parameters
  • cb: is called for every symbol in the backtrace, starting with the top-most frame.

  • reversed: if true, the most recent call is given last.

virtual void trim_to_current_stack_frame()

Removes all the lower frames that are also present in the current stack.

Designed to be used in catch clauses, to simulate stack trace collection from throw to catch, instead of from throw to the process entry point.

Defaults to no-op.

virtual ~Backtrace()
struct backtrace_symbol
#include <backtrace.h>

A single symbol, as determined from a program counter, and returned by Backtrace::get_symbols().

pxd:

cppclass backtrace_symbol: string filename int lineno string functionname void *pc

ctypedef const backtrace_symbol *backtrace_symbol_constptr

Public Members

std::string filename
unsigned int lineno
std::string functionname
void *pc
class Error : public runtime_error
#include <error.h>

Openage base exception type; the constructor usage is analogous to log::log().

pxd:

cppclass Error: message msg

string type_name() except + const char *what() except + void rethrow_cause() except + void trim_backtrace() except + void debug_break_on_create(bool state) except +

Backtrace *backtrace

Subclassed by openage::audio::Error, openage::pyinterface::PyException, openage::testing::TestError

Public Functions

Error(const log::message &msg, bool generate_backtrace = true, bool store_cause = true)

Parameters
  • msg: As with log::log()

  • generate_backtrace: If true, some platform-specific code is run to collect traceback information (e.g.: backtrace (3)) (default true). The performance impacts should be not too bad, as only program counter pointers are collected.

  • store_cause: If true, a pointer to the causing exception is collected and stored (default true).

void store_cause()

Stores a pointer to the currently-handled exception in this->cause.

void trim_backtrace()

Calls this->backtrace->trim_to_current_stack_frame(), if this->backtrace is not nullptr.

Designed to be used in catch clauses, to strip away all those unneeded symbols from program init upwards.

Automatically called for cause exceptions, and when storing cause exceptions, and by the to_py converter.

void rethrow_cause() const

Re-throws the exception cause, if the exception has one.

Otherwise, does nothing.

Use this when handling the exception, to handle the cause.

std::string type_name() const

The type name of the exception (for pretty-printing in case the exception hierarchy is used).

Uses typeid internally.

const char *what() const

Returns the message’s content.

Public Members

log::message msg

The error message.

std::shared_ptr<Backtrace> backtrace

The (optional) backtrace.

Public Static Functions

void debug_break_on_create(bool state)

Turn on debug breaks in the constructor.

Private Functions

Error()

Constructs an empty error.

For use by our friend, pyinterface::PyException.

Private Members

std::exception_ptr cause

Re-throw this with rethrow_cause().

class StackAnalyzer : public openage::error::Backtrace
#include <stackanalyzer.h>

Implementation of the Backtrace interface that analyzes the current C++ stack.

The Usage is:

StackAnalyzer sa; sa.analyze();

Integrating analyze() into the constructor would be a bad idea because then, all sorts of allocators and other gory constructor internals might be visible in the Backtrace.

The implementation of analyze() and get_symbols() may use all sorts of analyzers, depending on what’s available on the platform. The quality of the resolved symbol names may vary accordingly.

Public Functions

StackAnalyzer()

Creates an empty StackAnalyzer object.

void analyze()
void get_symbols(std::function<void(const backtrace_symbol *)> cb, bool reversed, ) const

Returns (via the callback) symbolic names for all stack frames, to its best knowledge.

The most recent call is returned last (alike Python).

Parameters
  • cb: is called for every symbol in the backtrace, starting with the top-most frame.

  • reversed: if true, the most recent call is given last.

void trim_to_current_stack_frame()

Removes all the lower frames that are also present in the current stack.

Designed to be used in catch clauses, to simulate stack trace collection from throw to catch, instead of from throw to the process entry point.

Defaults to no-op.

Public Members

std::vector<void *> stack_addrs

All program counters of this backtrace.

class AIInput
#include <aicontroller.h>

Public Functions

const std::vector<PongEvent> &get_inputs(const std::shared_ptr<PongPlayer> &player, const std::shared_ptr<PongBall> &ball, const curve::time_t &now)

Private Members

std::vector<PongEvent> commands
class BallReflectPanel : public openage::event::DependencyEventClass

Public Functions

BallReflectPanel()
void setup_event(const std::shared_ptr<Event> &event, const std::shared_ptr<State> &state)

Called for each event that is created for this EventClass.

The job of the setup function is to add all dependencies with other event targets found in state.

void invoke(Loop &loop, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &time, const EventClass::param_map &params)

This method implements the effects of the event.

It will be called at the time that was determined by predict_invoke_time.

Called from the Loop.

curve::time_t predict_invoke_time(const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &at)

Is called to calculate the execution time for an event of this eventclass.

This is called whenever one of the set up dependencies was changed, or when a REPEAT event was executed.

If the event is obsolete, return <time_t>

min().
Parameters
  • target: the target the event was created for

  • state: the state this shall work on

  • at: the time when the change happened, from there on it shall be calculated onwards

If the time is lower than the previous time, then dependencies may not be resolved perfectly anymore (if other events have already been calculated before that).

class BallReflectWall : public openage::event::DependencyEventClass

Public Functions

BallReflectWall()
void setup_event(const std::shared_ptr<Event> &event, const std::shared_ptr<State> &state)

Called for each event that is created for this EventClass.

The job of the setup function is to add all dependencies with other event targets found in state.

void invoke(Loop &loop, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &time, const EventClass::param_map &params)

This method implements the effects of the event.

It will be called at the time that was determined by predict_invoke_time.

Called from the Loop.

curve::time_t predict_invoke_time(const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &at)

Is called to calculate the execution time for an event of this eventclass.

This is called whenever one of the set up dependencies was changed, or when a REPEAT event was executed.

If the event is obsolete, return <time_t>

min().
Parameters
  • target: the target the event was created for

  • state: the state this shall work on

  • at: the time when the change happened, from there on it shall be calculated onwards

If the time is lower than the previous time, then dependencies may not be resolved perfectly anymore (if other events have already been calculated before that).

class Physics
#include <physics.h>

Public Functions

void process_input(const std::shared_ptr<PongState> &state, const std::shared_ptr<PongPlayer> &player, const std::vector<PongEvent> &input, const std::shared_ptr<Loop> &mgr, const curve::time_t &now)

Public Static Functions

void init(const std::shared_ptr<PongState> &gstate, const std::shared_ptr<Loop> &mgr, const curve::time_t &now)
void reset(const std::shared_ptr<State> &gstate, Loop &mgr, const curve::time_t &now)
class PongBall : public openage::event::EventTarget
#include <gamestate.h>

Public Functions

PongBall(const std::shared_ptr<Loop> &mgr, size_t id)
size_t id() const

Give a unique event system identifier for the entity.

Public Members

std::shared_ptr<curve::Discrete<util::Vector2d>> speed
std::shared_ptr<curve::Continuous<util::Vector2d>> position

Private Functions

void child_changes(const curve::time_t &time)

Private Members

size_t _id
class PongEvent
#include <gamestate.h>

Public Types

enum state_e

Values:

UP
DOWN
START
IDLE
LOST

Public Functions

PongEvent(size_t id, state_e s)
PongEvent()

Public Members

size_t player
state_e state
class PongPlayer : public openage::event::EventTarget
#include <gamestate.h>

Public Functions

PongPlayer(const std::shared_ptr<Loop> &mgr, size_t id)
size_t id() const

Give a unique event system identifier for the entity.

Public Members

std::shared_ptr<curve::Discrete<float>> speed
std::shared_ptr<curve::Continuous<float>> position
std::shared_ptr<curve::Discrete<int>> lives
std::shared_ptr<curve::Discrete<PongEvent>> state
std::shared_ptr<curve::Discrete<float>> size
size_t _id
float paddle_x

Private Functions

void child_changes(const curve::time_t &time)
class PongState : public openage::event::State
#include <gamestate.h>

Public Functions

PongState(const std::shared_ptr<Loop> &mgr, bool enable_gui)

Public Members

std::shared_ptr<PongPlayer> p1
std::shared_ptr<PongPlayer> p2
std::shared_ptr<PongBall> ball
util::Vector2d display_boundary
bool enable_gui
class ResetGame : public openage::event::OnceEventClass

Public Functions

ResetGame()
void setup_event(const std::shared_ptr<Event> &event, const std::shared_ptr<State> &state)

Called for each event that is created for this EventClass.

The job of the setup function is to add all dependencies with other event targets found in state.

void invoke(Loop &loop, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &time, const EventClass::param_map &params)

This method implements the effects of the event.

It will be called at the time that was determined by predict_invoke_time.

Called from the Loop.

curve::time_t predict_invoke_time(const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &at)

Is called to calculate the execution time for an event of this eventclass.

This is called whenever one of the set up dependencies was changed, or when a REPEAT event was executed.

If the event is obsolete, return <time_t>

min().
Parameters
  • target: the target the event was created for

  • state: the state this shall work on

  • at: the time when the change happened, from there on it shall be calculated onwards

If the time is lower than the previous time, then dependencies may not be resolved perfectly anymore (if other events have already been calculated before that).

class DependencyEventClass : public openage::event::EventClass
#include <eventclass.h>

Subclassed by openage::event::demo::BallReflectPanel, openage::event::demo::BallReflectWall

Public Functions

DependencyEventClass(const std::string &name)
class DependencyImmediatelyEventClass : public openage::event::EventClass
#include <eventclass.h>

Public Functions

DependencyImmediatelyEventClass(const std::string &name)
class Event : public std::enable_shared_from_this<Event>
#include <event.h>

The actual one event that may be called - it is used to manage the event itself.

It does not need to be stored.

Public Functions

Event(const std::shared_ptr<EventTarget> &trgt, const std::shared_ptr<EventClass> &eventclass, const EventClass::param_map &params)
const std::weak_ptr<EventTarget> &get_target() const
const std::shared_ptr<EventClass> &get_eventclass() const
void reschedule(const curve::time_t reference_time)

Reschedule will call the predict_invoke_time method to initiate a reschedule for the event it uses the reference_time as base for its calculation.

size_t hash() const
const curve::time_t &get_time() const
void set_time(const curve::time_t &t)
const EventClass::param_map &get_params() const
void depend_on(const std::shared_ptr<EventTarget> &dependency)

Let this event depend on another an event target.

When this target is changes, the event is reevaluated.

To be called in the EventClass::setup function.

bool operator<(const Event &other) const

For sorting events by their trigger time.

Public Members

curve::time_t last_triggered = 0

Private Members

EventClass::param_map params

Parameters for the event (determined by its EventClass)

std::weak_ptr<EventTarget> target

The actor that has the event.

std::shared_ptr<EventClass> eventclass

Type of this event.

curve::time_t time

Time this event occurs/occured.

size_t myhash

Precalculated std::hash for the event.

class EventClass
#include <eventclass.h>

A eventclass has to be implemented for every type of event that exists.

It determines what the event means and how it is handled.

Subclassed by openage::event::DependencyEventClass, openage::event::DependencyImmediatelyEventClass, openage::event::OnceEventClass, openage::event::RepeatEventClass, openage::event::tests::EventTypeTestClass, openage::event::tests::TestEventClass, openage::event::tests::TestEventClassTwo, openage::event::TriggerEventClass

Public Types

enum trigger_type

Available types for the event class: These decide when an event of this event class will be executed.

Values:

DEPENDENCY

Such events are emitted when a modification is done on a target.

The execution time is calculated from the modification time and custom code.

DEPENDENCY_IMMEDIATELY

Like DEPENDENCY, but does not use a recalculated time, instead uses the change-time only.

Behaves exactly like DEPENDENCY, if the DEPENDENCY-event is in the same execution frame.

TRIGGER

Will be executed when the target trigger() function is called.

REPEAT

Will be triggered unconditionally at the set time, “at” is the time that was set as return of predict_invoke_time.

This event will be issued again until predict_invoke_time returns min(). To execute Something only once (i.E. triggered somewhere from the logic and not based on time, use ONCE

ONCE

Will be triggered only once, but until it is triggered the time, when this should happen can be recalculated again and again using the predict_invoke_time method.

Public Functions

EventClass(const std::string &name, const trigger_type &type)

Constructor to be constructed with the unique identifier.

virtual ~EventClass()
const std::string &id()

Return a unique identifier.

virtual void setup_event(const std::shared_ptr<Event> &event, const std::shared_ptr<State> &state) = 0

Called for each event that is created for this EventClass.

The job of the setup function is to add all dependencies with other event targets found in state.

virtual void invoke(Loop &loop, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &time, const param_map &params) = 0

This method implements the effects of the event.

It will be called at the time that was determined by predict_invoke_time.

Called from the Loop.

virtual curve::time_t predict_invoke_time(const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &at) = 0

Is called to calculate the execution time for an event of this eventclass.

This is called whenever one of the set up dependencies was changed, or when a REPEAT event was executed.

If the event is obsolete, return <time_t>

min().
Parameters
  • target: the target the event was created for

  • state: the state this shall work on

  • at: the time when the change happened, from there on it shall be calculated onwards

If the time is lower than the previous time, then dependencies may not be resolved perfectly anymore (if other events have already been calculated before that).

Public Members

const trigger_type type

The event type this event class represents.

Private Members

std::string _id

String identifier for this event class.

class param_map
#include <eventclass.h>

Storage for parameters for an event class.

Public Types

using map_t = std::unordered_map<std::string, std::any>

Public Functions

param_map()
param_map(std::initializer_list<map_t::value_type> l)
param_map(const map_t &map)
template<typename T>
T get(const std::string &key, const T &defaultval = T()) const

Returns the value, if it exists and is the right type.

defaultval if not.

bool contains(const std::string &key) const

Check if the map contains the given key.

template<typename Type>
bool check_type(const std::string &key) const

Check if the type of a map entry is correct.

Private Functions

template<typename T>
bool check_type(const map_t::const_iterator &it) const

Private Members

const map_t map

Data storage.

class EventFilter
#include <eventfilter.h>

Store a filter function that can then be applied on an event target.

Public Functions

EventFilter(const std::function<bool(const std::shared_ptr<EventTarget>&)> &filter)
bool apply(const std::shared_ptr<EventTarget> &target) const

Private Members

std::function<bool(const std::shared_ptr<EventTarget>&)> filter
class EventQueue
#include <eventqueue.h>

The core event class for execution and execution dependencies.

Public Types

using change_set = std::unordered_set<OnChangeElement, OnChangeElement::Hasher, OnChangeElement::Equal>

Type for the set to store changes to track.

Public Functions

EventQueue()
std::shared_ptr<Event> create_event(const std::shared_ptr<EventTarget> &eventtarget, const std::shared_ptr<EventClass> &eventclass, const std::shared_ptr<State> &state, const curve::time_t &reference_time, const EventClass::param_map &params)

Add an event for a specified target.

A target is every single unit in the game world - so best add these events in the constructor of the game objects.

The insertion_time is the time used to calculate when the actual event time will happen!

void remove(const std::shared_ptr<Event> &evnt)

Remove the given event from the queue.

void enqueue_change(const std::shared_ptr<Event> &event)

An update to existing events has to be applied.

The execution time of this event may have changed or it is newly created. This updates/inserts the given event in the main queue.

void reenqueue(const std::shared_ptr<Event> &event)

The event was just removed, add it again.

This is used for REPEAT events so that they are repeated.

void add_change(const std::shared_ptr<Event> &event, const curve::time_t &changed_at)

An event target has changed, and the event shall be retriggered.

const EventStore &get_event_queue() const

Get an accessor to the running queue for state output purpose.

std::shared_ptr<Event> take_event(const curve::time_t &max_time)

Obtain the next event from the event_queue that happens before <= max_time.

const EventQueue::change_set &get_changes() const

Get the change_set to process changes.

void clear_changes()

All changes (fetched with get_changes) have been processed, so we can clear the change_set.

void swap_changesets()

Swap the changes and future_changes.

Private Members

change_set *changes
change_set *future_changes
change_set changeset_A
change_set changeset_B
std::unordered_set<std::shared_ptr<Event>> dependency_events

Stores events that sleep until their dependency changes.

std::unordered_set<std::shared_ptr<Event>> dependency_immediately_events

Stores events that sleep until their dependency changes, but they trigger instantly when their dependency changes.

std::unordered_set<std::shared_ptr<Event>> trigger_events

Events that fire only when triggered.

EventStore event_queue

The universe timeline processes through this queue.

Type::ONCE is only inserted into the queue.

class OnChangeElement
#include <eventqueue.h>

Public Functions

OnChangeElement(const std::shared_ptr<Event> &evnt, const curve::time_t &time)

Public Members

curve::time_t time
std::weak_ptr<Event> evnt
const size_t hash
class Equal
#include <eventqueue.h>

Public Functions

size_t operator()(const OnChangeElement &left, const OnChangeElement &right) const
class Hasher
#include <eventqueue.h>

Public Functions

size_t operator()(const OnChangeElement &e) const
class EventStore
#include <eventstore.h>

Sorted storage for events.

Implemented through a heap that automatically provides the newest event.

Public Types

using heap_t = datastructure::PairingHeap<std::shared_ptr<Event>, util::SharedPtrLess<Event>>
using elemmap_t = std::unordered_map<std::shared_ptr<Event>, heap_t::element_t>

Public Functions

void push(const std::shared_ptr<Event> &event)
std::shared_ptr<Event> pop()
const std::shared_ptr<Event> &top()
bool erase(const std::shared_ptr<Event> &event)
void update(const std::shared_ptr<Event> &event)
bool contains(const std::shared_ptr<Event> &event) const
void clear()
size_t size() const
bool empty() const
std::vector<std::shared_ptr<Event>> get_sorted_events() const

Helper function that should not be called ‘in production’.

It returns the events in the store sorted by time. Use the pop() method instead (but with that you can’t iterate).

Public Members

heap_t heap
elemmap_t events
class EventTarget
#include <eventtarget.h>

Every Object in the gameworld that wants to be targeted by events or as dependency for events, has to implement this class.

Subclassed by openage::curve::ValueContainer< T >, openage::event::demo::PongBall, openage::event::demo::PongPlayer, openage::event::tests::TestState::TestObject

Public Types

using single_change_notifier = std::function<void(const curve::time_t&)>

Public Functions

virtual size_t id() const = 0

Give a unique event system identifier for the entity.

virtual ~EventTarget()
void add_dependent(const std::weak_ptr<Event> &event)

Add a dependent class, that should be notified when dependency is called.

void show_dependents() const

For debugging: print the dependent eventclass ids as log messages.

Protected Functions

EventTarget(const std::shared_ptr<Loop> &loop, single_change_notifier parent_notifier = nullptr)

For children to be able to initialize us.

The notifier is used by hierarchical structures to be able to traverse a change up in the tree, this is necessary to make containers with event targets inside and listen to any changes on the full.

void changes(const curve::time_t &change_time)

Call this whenever some data in the target changes.

This triggers the reevaluation of dependent events.

void trigger(const curve::time_t &last_valid_time)

Call this when a keyframe in the underlying container was passed by in time.

Private Members

std::shared_ptr<Loop> loop

Event loop this target is registered to.

std::list<std::weak_ptr<Event>> dependents

List of events that depend on this target.

single_change_notifier parent_notifier
class Loop
#include <loop.h>

The core class to manage event class and targets.

Public Functions

void add_event_class(const std::shared_ptr<EventClass> &cls)

register a new event class

std::weak_ptr<Event> create_event(const std::string &name, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &reference_time, const EventClass::param_map &params = EventClass::param_map ({}))

Add a new Event to the queue.

The event is from the given class (name) and is invoked for a target in a state.

The reference_time is used to calculate the actual event time.

std::weak_ptr<Event> create_event(const std::shared_ptr<EventClass> &eventclass, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &reference_time, const EventClass::param_map &params = EventClass::param_map ({}))

This will generate a new randomly named eventclass for this specific element.

The reference_time is used to determine the actual event trigger time.

void onfilter(const std::shared_ptr<EventClass> &eventclass, const EventFilter&)
template<class evntclass_t>
void onfilter(const EventFilter &filter)
void register_object(const std::shared_ptr<EventTarget>&)
void reach_time(const curve::time_t &max_time, const std::shared_ptr<State> &state)

Execute all events that are registered until a certain point in time.

template<class T>
void create_change(const std::shared_ptr<Event> &event, const curve::time_t &changes_at, const T &new_value)

Register that a given event must be reevaluated at a time, this usually happens because this event depended on an eventtarget that got changed at this time.

This inserts the event into the changes queue so it will be evaluated in the next loop iteration.

const EventQueue &get_queue() const

Private Functions

int execute_events(const curve::time_t &max_time, const std::shared_ptr<State> &state)

Execute the events.

Return

number of events processed

void update_changes(const std::shared_ptr<State> &state)

Call all the time change functions.

This is constant on the state!

Private Members

std::unordered_map<std::string, std::shared_ptr<EventClass>> classstore

Here we do the bookkeeping of registered event classes.

std::list<EventFilter> filters

Here we store all running filters that shall be applied whenever a new obejct is added to our objectstore.

EventQueue queue

All events are enqueued here.

std::shared_ptr<Event> active_event

The currently processed event.

This is useful for event cancelations (so one can’t cancel itself).

std::unordered_map<uint64_t, std::weak_ptr<EventTarget>> curveindex

Friends

int curvepong()
class OnceEventClass : public openage::event::EventClass
#include <eventclass.h>

Subclassed by openage::event::demo::ResetGame

Public Functions

OnceEventClass(const std::string &name)
class RepeatEventClass : public openage::event::EventClass
#include <eventclass.h>

Public Functions

RepeatEventClass(const std::string &name)
class State
#include <state.h>

Subclassed by openage::event::demo::PongState, openage::event::tests::TestState

Public Functions

State(const std::shared_ptr<Loop>&)
virtual ~State()
class EventTypeTestClass : public openage::event::EventClass

Public Functions

EventTypeTestClass(const std::string &name, EventClass::trigger_type type)
void setup_event(const std::shared_ptr<Event> &event, const std::shared_ptr<State> &state)

Called for each event that is created for this EventClass.

The job of the setup function is to add all dependencies with other event targets found in state.

void invoke(Loop &loop, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &time, const EventClass::param_map &params)

This method implements the effects of the event.

It will be called at the time that was determined by predict_invoke_time.

Called from the Loop.

curve::time_t predict_invoke_time(const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &at)

Is called to calculate the execution time for an event of this eventclass.

This is called whenever one of the set up dependencies was changed, or when a REPEAT event was executed.

If the event is obsolete, return <time_t>

min().
Parameters
  • target: the target the event was created for

  • state: the state this shall work on

  • at: the time when the change happened, from there on it shall be calculated onwards

If the time is lower than the previous time, then dependencies may not be resolved perfectly anymore (if other events have already been calculated before that).

class TestEventClass : public openage::event::EventClass

Public Functions

TestEventClass(const std::string &name, int idx)
void setup_event(const std::shared_ptr<Event> &event, const std::shared_ptr<State> &state)

Called for each event that is created for this EventClass.

The job of the setup function is to add all dependencies with other event targets found in state.

void invoke(Loop &loop, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &time, const EventClass::param_map &params)

This method implements the effects of the event.

It will be called at the time that was determined by predict_invoke_time.

Called from the Loop.

curve::time_t predict_invoke_time(const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &at)

Is called to calculate the execution time for an event of this eventclass.

This is called whenever one of the set up dependencies was changed, or when a REPEAT event was executed.

If the event is obsolete, return <time_t>

min().
Parameters
  • target: the target the event was created for

  • state: the state this shall work on

  • at: the time when the change happened, from there on it shall be calculated onwards

If the time is lower than the previous time, then dependencies may not be resolved perfectly anymore (if other events have already been calculated before that).

Private Members

int idx
class TestEventClassTwo : public openage::event::EventClass

Public Functions

TestEventClassTwo(const std::string &name)
void setup_event(const std::shared_ptr<Event> &event, const std::shared_ptr<State> &state)

Called for each event that is created for this EventClass.

The job of the setup function is to add all dependencies with other event targets found in state.

void invoke(Loop &loop, const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &time, const EventClass::param_map &params)

This method implements the effects of the event.

It will be called at the time that was determined by predict_invoke_time.

Called from the Loop.

curve::time_t predict_invoke_time(const std::shared_ptr<EventTarget> &target, const std::shared_ptr<State> &state, const curve::time_t &at)

Is called to calculate the execution time for an event of this eventclass.

This is called whenever one of the set up dependencies was changed, or when a REPEAT event was executed.

If the event is obsolete, return <time_t>

min().
Parameters
  • target: the target the event was created for

  • state: the state this shall work on

  • at: the time when the change happened, from there on it shall be calculated onwards

If the time is lower than the previous time, then dependencies may not be resolved perfectly anymore (if other events have already been calculated before that).

class TestState : public openage::event::State

Public Functions

TestState(const std::shared_ptr<Loop> &loop)
void log_dbg()

Public Members

std::shared_ptr<TestObject> objectA
std::shared_ptr<TestObject> objectB
std::list<traceelement> trace
class TestObject : public openage::event::EventTarget

Public Functions

TestObject(const std::shared_ptr<Loop> &loop, int id)
void set_number(int number, const curve::time_t &time)
size_t id() const

Give a unique event system identifier for the entity.

void test_trigger(const curve::time_t &time)

Public Members

int number

Private Members

const int _id
struct traceelement

Public Functions

traceelement(const std::string &event, curve::time_t time)

Public Members

curve::time_t time
std::string name
class TriggerEventClass : public openage::event::EventClass
#include <eventclass.h>

Public Functions

TriggerEventClass(const std::string &name)
class FoundationAction : public openage::UnitAction
#include <action.h>

places an idle action on the stack once building is complete

Public Functions

FoundationAction(Unit *e, bool add_destuction = false)
virtual ~FoundationAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

Private Members

bool add_destruct_effect
bool cancel
class GameControl : public openage::HudHandler
#include <game_control.h>

connects the gui system with the game engine switches between contexts such as editor mode and action mode

hud rendering and input handling is redirected to the active mode

Public Functions

GameControl(qtsdl::GuiItemLink *gui_link)
void set_engine(Engine *engine)
void set_game(GameMainHandle *game)
void set_modes(const std::vector<OutputMode *> &modes)
void set_mode(int mode, bool signal_if_unchanged = false)
void announce_mode()
void announce_current_player_name()
bool on_drawhud()

execute the drawing action.

Player *get_current_player() const
Engine *get_engine() const

Public Members

GameControlSignals gui_signals
qtsdl::GuiItemLink *gui_link

Private Members

Engine *engine
GameMainHandle *game
std::vector<OutputMode *> modes
OutputMode *active_mode
int active_mode_index
size_t current_player
class GameControlSignals : public QObject
#include <game_control.h>

Public Functions

GameControlSignals(GameControl *game_control)

Public Slots

void on_game_running(bool running)

Signals

void mode_changed(OutputMode *mode, int mode_index)
void modes_changed(OutputMode *mode, int mode_index)
void current_player_name_changed(const std::string &current_player_name)
void current_civ_index_changed(int current_civ_index)
void is_selected_unit_changed(bool is_selected_unit)

Private Members

GameControl *game_control
class GameMain : public openage::options::OptionNode
#include <game_main.h>

Contains information for a single game This information must be synced across network clients.

TODO: include a list of actions to be saved as the game replay file

Public Functions

GameMain(const Generator &generator)
~GameMain()
unsigned int player_count() const

the number of players

Player *get_player(unsigned int player_id)

player by index

unsigned int team_count() const

the number of teams

Team *get_team(unsigned int team_id)

team by id

GameSpec *get_spec()

the spec in this games settings

void update(time_nsec_t lastframe_duration)

updates the game by one frame

Public Members

std::shared_ptr<Terrain> terrain

map information

std::vector<Team> teams

all teams in the game

Market market

The global market (the global market prices).

UnitContainer placed_units

all the objects that have been placed.

Private Functions

Civilisation *add_civ(int civ_id)

creates a random civ, owned and managed by this game

Private Members

std::vector<std::shared_ptr<Player>> players

all players in the game no objects should be added of removed once populated

std::vector<std::shared_ptr<Civilisation>> civs

civs used in this game

std::shared_ptr<GameSpec> spec
class GameMainHandle
#include <game_main.h>

Class linked to the QML object “GameMain” via GameMainLink.

Gets instanciated from QML.

Public Functions

GameMainHandle(qtsdl::GuiItemLink *gui_link)
void set_engine(Engine *engine)
void clear()

End the game and delete the game handle.

void set_game(std::unique_ptr<GameMain> &&game)

Pass the given game to the engine and start it.

GameMain *get_game() const

Return the game.

bool is_game_running() const

Test if there is a game running.

void announce_running()

Emit a qt signal to notify for changes in a running game.

Public Members

GameMainSignals gui_signals
qtsdl::GuiItemLink *gui_link

Private Members

GameMain *game

The game state as currently owned by the engine, just remembered here to access it quickly.

Engine *engine

The engine the main game handle is attached to.

class GameMainSignals : public QObject
#include <game_main.h>

Signals

void game_running(bool running)
class GameRenderer : private openage::DrawHandler
#include <game_renderer.h>

renders the editor and action views

Public Functions

GameRenderer(Engine *e)
~GameRenderer()
bool on_draw()

execute the drawing action.

GameMain *game() const

the game this renderer is using

GameSpec *game_spec() const

GameSpec used by this renderer.

Public Members

Texture *gaben
RenderOptions settings

Private Members

Engine *engine
class GameSpec
#include <game_spec.h>

GameSpec gives a collection of all game elements this currently includes unit types and terrain types This provides a system which can easily allow game modding.

uses the AssetManager to gather graphic data, composite textures and sounds.

all types are sorted and stored by id values, each data object is referenced by a type and id pair

dealing directly with files done by asset manager TODO: should the audio loading should be moved there?

Public Functions

GameSpec(AssetManager *am)
~GameSpec()
bool initialize()

perform the main loading job.

this loads all the data into the storage.

bool load_complete() const

Check if loading has been completed, a load percent would be nice.

terrain_meta *get_terrain_meta()

return data used for constructing terrain objects

index_t get_slp_graphic(index_t slp)

reverse lookup of slp

Texture *get_texture(index_t graphic_id) const

lookup using a texture id, this specifically avoids returning the missing placeholder texture

Texture *get_texture(const std::string &file_name, bool use_metafile = true) const

lookup using a texture file name

std::shared_ptr<UnitTexture> get_unit_texture(index_t graphic_id) const

get unit texture by graphic id this is an directional texture which also includes graphic deltas

const Sound *get_sound(index_t sound_id) const

get sound by sound id

const gamedata::graphic *get_graphic_data(index_t grp_id) const

gamedata for a graphic nyan will have to replace this somehow

std::vector<const gamedata::unit_command *> get_command_data(index_t unit_id) const

get available commands for a unit id nyan will have to replace this somehow

std::string get_civ_name(int civ_id) const

returns the name of a civ by index

void create_unit_types(unit_meta_list &objects, int civ_id) const

makes initial unit types for a particular civ id

AssetManager *get_asset_manager() const

Return the asset manager used for loading resources of this game specification.

Private Functions

bool valid_graphic_id(index_t graphic_id) const

check graphic id is valid

void create_abilities(const gamedata::empiresdat &gamedata)

create unit abilities from game data

void load_building(const gamedata::building_unit &building, unit_meta_list &list) const

loads required assets to construct a buildings.

adds to the type list if the object can be created safely.

void load_living(const gamedata::living_unit &unit, unit_meta_list &list) const

loads assets for living things.

void load_object(const gamedata::unit_object &object, unit_meta_list &list) const

load assets for other game objects (not building and living).

void load_missile(const gamedata::missile_unit &proj, unit_meta_list &list) const

load missile assets.

void load_terrain(const gamedata::empiresdat &gamedata)

fill in the terrain_data attribute of this

void on_gamedata_loaded(const gamedata::empiresdat &gamedata)

Invoked when the gamedata has been loaded.

Private Members

AssetManager *assetmanager

Asset management entity that is responsible for textures, sounds, etc.

std::vector<gamedata::empiresdat> gamedata

The full original gamedata tree.

terrain_meta terrain_data

data used for constructing terrain objects

std::unordered_map<index_t, index_t> slp_to_graphic

slp to graphic id reverse lookup

std::unordered_map<index_t, const gamedata::graphic *> graphics

map graphic id to gamedata graphic.

std::unordered_map<index_t, std::vector<const gamedata::unit_command *>> commands

commands available for each unit id

std::unordered_map<index_t, std::shared_ptr<UnitTexture>> unit_textures

graphic ids -> unit texture for that id

std::unordered_map<index_t, Sound> available_sounds

sound ids mapped to playable sounds for all available sounds.

bool gamedata_loaded

has game data been load yet

class GameSpecHandle
#include <game_spec.h>

Game specification instanciated in QML.

Linked to the “GameSpec” QML type.

Wraps the “GameSpec” C++ class from above.

Public Functions

GameSpecHandle(qtsdl::GuiItemLink *gui_link)
void set_active(bool active)

Control whether this specification can be loaded (=true) or will not be loaded (=false).

void set_asset_manager(AssetManager *asset_manager)

invoked from qml when the asset_manager member is set.

bool is_ready() const

Return if the specification was fully loaded.

void invalidate()

forget everything about the specification and reload it with start_loading_if_needed.

void announce_spec()

signal about a loaded spec if any

std::shared_ptr<GameSpec> get_spec()

Return the contained game specification.

Public Members

std::shared_ptr<GameSpecSignals> gui_signals
qtsdl::GuiItemLink *gui_link

Private Functions

void start_loading_if_needed()

load the game specification if not already present.

void start_load_job()

Actually dispatch the loading job to the job manager.

void on_loaded(job::result_function_t<bool> result)

called from the job manager when the loading job finished.

Private Members

std::shared_ptr<GameSpec> spec

The real game specification.

bool active

enables the loading of the game specification.

AssetManager *asset_manager
class GameSpecSignals : public QObject
#include <game_spec.h>

Signals

void load_job_finished()
void game_spec_loaded(std::shared_ptr<GameSpec> loaded_game_spec)
class GarrisonAbility : public openage::UnitAbility
#include <ability.h>

ability to garrision inside a building

Public Functions

GarrisonAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class GarrisonAction : public openage::TargetAction
#include <action.h>

garrison inside a building

Public Functions

GarrisonAction(Unit *e, UnitReference build)
virtual ~GarrisonAction()
void update_in_range(unsigned int int, Unit *)

Control units action when in range of the target.

void on_completion_in_range(int)
bool completed_in_range(Unit *) const
std::string name() const

debug string to identify action types

Private Members

bool complete
class GatherAbility : public openage::UnitAbility
#include <ability.h>

initiates an gather resource action when given a valid target

Public Functions

GatherAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class GatherAction : public openage::TargetAction
#include <action.h>

gathers resource from another object

Public Functions

GatherAction(Unit *e, UnitReference tar)
~GatherAction()
void update_in_range(unsigned int int, Unit *)

Control units action when in range of the target.

void on_completion_in_range(int target_type)
bool completed_in_range(Unit *) const
std::string name() const

debug string to identify action types

Private Functions

UnitReference nearest_dropsite(game_resource res_type)

Private Members

bool complete
bool target_resource
UnitReference target
gamedata::unit_classes resource_class
class Generator : public qtsdl::GuiPropertyMap
#include <generator.h>

Manages creation and setup of new games.

required values used to construct a game this includes game spec and players

this will be identical for each networked player in a game

Public Functions

Generator(qtsdl::GuiItemLink *gui_link)
std::shared_ptr<GameSpec> get_spec() const

game spec used by this generator

std::vector<std::string> player_names() const

return the list of player names

std::shared_ptr<Terrain> terrain() const

returns the generated terrain

void add_units(GameMain &m) const

places all initial objects

std::unique_ptr<GameMain> create(std::shared_ptr<GameSpec> spec)

Create a game from a specification.

Public Members

qtsdl::GuiItemLink *gui_link

Private Functions

void create_regions()

Private Members

std::shared_ptr<GameSpec> spec

data version used to create a game

std::vector<Region> regions

the generated data

struct gl_texture_buffer
#include <texture.h>

enables transfer of data to opengl

Public Members

GLuint id
GLuint vertbuf
bool transferred
int texture_format_in
int texture_format_out
std::unique_ptr<uint32_t[]> data
class ActionModeLink : public qtsdl::Inherits<OutputModeLink, ActionModeLink>
#include <game_control_link.h>

Public Functions

ActionModeLink(QObject *parent = nullptr)
virtual ~ActionModeLink()
QString get_ability() const
QString get_population() const
bool get_population_warn() const
int get_selection_size() const
Q_INVOKABLE void openage::gui::ActionModeLink::act(const QString & action)

Signals

void ability_changed()
void action_triggered(const std::string &ability)
void buttons_type_changed(const ActionButtonsType buttons_type)
void population_changed()
void selection_changed()

Property

property openage::gui::ActionModeLink::ability
property openage::gui::ActionModeLink::population
property openage::gui::ActionModeLink::population_warn
property openage::gui::ActionModeLink::selection_size
property openage::gui::ActionModeLink::selection_name
property openage::gui::ActionModeLink::selection_icon
property openage::gui::ActionModeLink::selection_type
property openage::gui::ActionModeLink::selection_owner
property openage::gui::ActionModeLink::selection_hp
property openage::gui::ActionModeLink::selection_attrs

Private Functions

virtual void on_core_adopted()
std::string progress(float progress, int size)

Private Members

const UnitSelection *selection

Private Slots

void on_ability_changed(const std::string &ability)
void on_buttons_type_changed(const ActionButtonsType buttons_type)
void on_population_changed(int demand, int capacity, bool warn)
void on_selection_changed(const UnitSelection *unit_selection, const Player *player)
class ActionsListModel : public QAbstractListModel
#include <actions_list_model.h>

Model used for the Action Buttons to render (e.g.

for civilian units, military units, buildings etc.)

Public Types

enum ActionsRoles

Values:

IconRole = Qt::UserRole + 1
IconCheckedRole
GroupIDRole
NameRole
enum GroupIDs

Values:

NoGroup
StanceGroup

Public Functions

ActionsListModel(QObject *parent = nullptr)
~ActionsListModel()
ActionButtonsType get_active_buttons() const
void set_active_buttons(const ActionButtonsType &active_buttons)
ActionModeLink *get_action_mode() const
QUrl get_icons_source() const
void set_icons_source(const QUrl icons_source)
Q_INVOKABLE void openage::gui::ActionsListModel::set_initial_buttons()

Signals

void icons_source_changed(const QUrl icons_source)

Property

property openage::gui::ActionsListModel::active_buttons
property openage::gui::ActionsListModel::action_mode
property openage::gui::ActionsListModel::iconsSource

Private Functions

QHash<int, QByteArray> roleNames() const
int rowCount(const QModelIndex&) const
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
QMap<int, QVariant> itemData(const QModelIndex &index) const
void set_icons_source(const std::string icons_source)

Utility function to create a QUrl from a string and set it as iconsSource.

void clear_buttons()

Clears all buttons.

void add_button(int ico, int ico_chk, int grp_id, const char *name)

Shortcut to creating a QMap for a button.

Private Members

ActionModeLink *action_mode
QUrl icons_source
std::vector<QMap<int, QVariant>> buttons

Private Slots

void on_buttons_type_changed(const ActionButtonsType buttons_type)
class AssetManagerLink : public qtsdl::GuiItemQObject, public qtsdl::GuiItem<AssetManagerLink>
#include <assetmanager_link.h>

Public Functions

AssetManagerLink(QObject *parent = nullptr)
~AssetManagerLink()
const util::Path &get_asset_dir() const
void set_asset_dir(const util::Path &data_dir)
EngineLink *get_engine() const

Property

property openage::gui::AssetManagerLink::assetDir
property openage::gui::AssetManagerLink::engine

Private Members

util::Path asset_dir
EngineLink *engine
class CategoryContentsListModel : public QAbstractListModel
#include <category_contents_list_model.h>

Adaptor for the contents of a category of the Civilisation.

Public Functions

CategoryContentsListModel(QObject *parent = nullptr)
~CategoryContentsListModel()
QString get_name() const
void set_name(const QString &name)
EditorModeLink *get_editor_mode() const

Property

property openage::gui::CategoryContentsListModel::name
property openage::gui::CategoryContentsListModel::editorMode

Private Functions

QHash<int, QByteArray> roleNames() const
int rowCount(const QModelIndex&) const
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const

Private Members

std::vector<std::tuple<index_t, uint16_t>> type_and_texture
EditorModeLink *editor_mode

Private Slots

void on_category_content_changed(const std::string &category_name, std::vector<std::tuple<index_t, uint16_t>> type_and_texture)
void on_categories_content_changed()
class CreateModeLink : public qtsdl::Inherits<OutputModeLink, CreateModeLink>
#include <game_control_link.h>

Public Functions

CreateModeLink(QObject *parent = nullptr)
virtual ~CreateModeLink()
class EditorModeLink : public qtsdl::Inherits<OutputModeLink, EditorModeLink>
#include <game_control_link.h>

Public Functions

EditorModeLink(QObject *parent = nullptr)
virtual ~EditorModeLink()
int get_current_type_id() const
void set_current_type_id(int current_type_id)
int get_current_terrain_id() const
void set_current_terrain_id(int current_terrain_id)
bool get_paint_terrain() const
void set_paint_terrain(bool paint_terrain)
QStringList get_categories() const
void announce_category_content(const std::string &category_name)

Signals

void toggle()
void categories_changed()
void categories_content_changed()
void category_content_changed(const std::string &category_name, std::vector<std::tuple<index_t, uint16_t>> type_and_texture)

Property

property openage::gui::EditorModeLink::currentTypeId
property openage::gui::EditorModeLink::currentTerrainId
property openage::gui::EditorModeLink::paintTerrain
property openage::gui::EditorModeLink::categories

Private Functions

virtual void on_core_adopted()

Private Members

int current_type_id
int current_terrain_id
bool paint_terrain

Private Slots

void on_categories_changed(const std::vector<std::string> &categories)
class EngineLink : public qtsdl::GuiSingletonItem
#include <engine_link.h>

Public Functions

EngineLink(QObject *parent, Engine *engine)
~EngineLink()
template<typename U>
U *get() const
QStringList get_global_binds() const
void stop()

Signals

void global_binds_changed()

Property

property openage::gui::EngineLink::globalBinds

The text list of global key bindings.

displayed so one can see what keys are active.

Public Static Functions

QObject *provider(QQmlEngine *engine, QJSEngine *)

Private Members

Engine *core
QStringList global_binds

Private Slots

void on_global_binds_changed(const std::vector<std::string> &global_binds)
class EngineQMLInfo : public qtsdl::GuiSingletonItemsInfo
#include <engine_info.h>

This container is attached to the QML engine.

It allows that one can access the members in the qml engine context then. That also means the members accessible during creation of any singleton QML item.

This struct is used to link the openage Engine with QML in engine_link.cpp.

Public Functions

EngineQMLInfo(Engine *engine, const util::Path &asset_dir)

Public Members

Engine *engine

The openage engine, so it can be “used” in QML as a “QML Singleton”.

With this pointer, all of QML can find back to the engine.

util::Path asset_dir

Search path for finding assets n stuff.

class GameControlLink : public qtsdl::GuiItemQObject, public QQmlParserStatus, public qtsdl::GuiItem<GameControlLink>
#include <game_control_link.h>

Public Functions

GameControlLink(QObject *parent = nullptr)
virtual ~GameControlLink()
OutputModeLink *get_mode() const
int get_effective_mode_index() const
int get_mode_index() const
void set_mode_index(int mode)
QVariantList get_modes() const
void set_modes(const QVariantList &modes)
EngineLink *get_engine() const
GameMainLink *get_game() const
QString get_current_player_name() const
int get_current_civ_index() const

Signals

void mode_changed()
void modes_changed()
void current_player_name_changed()
void current_civ_index_changed()

Property

property openage::gui::GameControlLink::mode
property openage::gui::GameControlLink::effectiveModeIndex
property openage::gui::GameControlLink::modeIndex
property openage::gui::GameControlLink::modes
property openage::gui::GameControlLink::engine
property openage::gui::GameControlLink::game
property openage::gui::GameControlLink::currentPlayerName
property openage::gui::GameControlLink::currentCivIndex

Private Functions

virtual void classBegin()
virtual void on_core_adopted()
virtual void componentComplete()

Private Members

OutputModeLink *mode
int effective_mode_index
int mode_index
EngineLink *engine
GameMainLink *game
QString current_player_name
int current_civ_index

Private Slots

void on_mode_changed(OutputMode *mode, int mode_index)
void on_modes_changed(OutputMode *mode, int mode_index)
void on_current_player_name_changed(const std::string &current_player_name)
void on_current_civ_index_changed(int current_civ_index)
class GameCreator : public QObject
#include <game_creator.h>

Public Functions

GameCreator(QObject *parent = nullptr)
~GameCreator()
QString get_error_string() const
void activate()
void clearErrors()

Public Slots

void on_processed(const QString &error_string)

Signals

void error_string_changed()
void game_changed()
void game_spec_changed()
void generator_parameters_changed()

Property

property openage::gui::GameCreator::errorString
property openage::gui::GameCreator::game
property openage::gui::GameCreator::gameSpec
property openage::gui::GameCreator::generatorParameters

Private Members

QString error_string
GameMainLink *game
GameSpecLink *game_spec
GeneratorLink *generator_parameters
class GameCreatorSignals : public QObject
#include <game_creator.h>

Signals

void error_message(const QString &error)
class GameMainLink : public qtsdl::GuiItemQObject, public QQmlParserStatus, public qtsdl::GuiItem<GameMainLink>
#include <game_main_link.h>

Public Types

enum State

Values:

Null
Running

Public Functions

GameMainLink(QObject *parent = nullptr)
~GameMainLink()
GameMainLink::State get_state() const
EngineLink *get_engine() const
void clear()

Signals

void state_changed()

Property

property openage::gui::GameMainLink::state
property openage::gui::GameMainLink::engine

Private Functions

void classBegin()
void on_core_adopted()
void componentComplete()

Private Members

bool active
EngineLink *engine

Private Slots

void on_game_running(bool running)
class GameSaver : public QObject
#include <game_saver.h>

Public Functions

GameSaver(QObject *parent = nullptr)
~GameSaver()
QString get_error_string() const
void activate()
void clearErrors()

Public Slots

void on_processed(const QString &error_string)

Signals

void error_string_changed()
void game_changed()
void generator_parameters_changed()

Property

property openage::gui::GameSaver::errorString
property openage::gui::GameSaver::game
property openage::gui::GameSaver::generatorParameters

Private Members

QString error_string
GameMainLink *game
GeneratorLink *generator_parameters
class GameSaverSignals : public QObject
#include <game_saver.h>

Signals

void error_message(const QString &error)
class GameSpecLink : public qtsdl::GuiItemQObject, public QQmlParserStatus, public qtsdl::GuiItem<GameSpecLink>
#include <game_spec_link.h>

Public Types

enum State

Values:

Null
Loading
Ready

Public Functions

GameSpecLink(QObject *parent = nullptr)
~GameSpecLink()
GameSpecLink::State get_state() const
bool get_active() const
void set_active(bool active)
AssetManagerLink *get_asset_manager() const
int get_terrain_id_count() const
void invalidate()
std::shared_ptr<GameSpec> get_loaded_spec()

Signals

void game_spec_loaded(GameSpecLink *game_spec, std::shared_ptr<GameSpec> loaded_game_spec)

Pass loaded assets to the image provider.

Provider will check if it’s still attached to that spec. Also it may be invalidated in the meantime, so share the ownership.

void state_changed()
void terrain_id_count_changed()

Property

property openage::gui::GameSpecLink::state
property openage::gui::GameSpecLink::active
property openage::gui::GameSpecLink::assetManager
property openage::gui::GameSpecLink::terrainIdCount

Private Functions

void classBegin()
void on_core_adopted()
void componentComplete()
void set_state(State state)

Private Members

AssetManagerLink *asset_manager
int terrain_id_count
std::shared_ptr<GameSpec> loaded_game_spec

Private Slots

void on_load_job_finished()
void on_game_spec_loaded(std::shared_ptr<GameSpec> loaded_game_spec)
class GeneratorLink : public qtsdl::GuiListModel, public qtsdl::GuiItemListModel<GeneratorLink>
#include <generator_link.h>

Public Functions

GeneratorLink(QObject *parent = nullptr)
~GeneratorLink()
class GUI : public openage::InputHandler, public openage::ResizeHandler, public openage::HudHandler
#include <gui.h>

Main entry point for the openage Qt-based user interface.

Public Functions

GUI(SDL_Window *window, const std::string &source, const std::string &rootdir, EngineQMLInfo *info = nullptr)
~GUI()
void process_events()

Private Functions

bool on_resize(coord::viewport_delta new_size)

execute the resize handler.

bool on_input(SDL_Event *event)

execute the input handler.

bool on_drawhud()

execute the drawing action.

Private Members

GLint tex_loc
GLuint screen_quad_vbo
GuiApplicationWithLogger application
qtsdl::GuiEventQueue render_updater
qtsdl::GuiRenderer renderer
qtsdl::GuiEventQueue game_logic_updater
GuiGameSpecImageProvider image_provider_by_filename
GuiGameSpecImageProvider image_provider_by_graphic_id
GuiGameSpecImageProvider image_provider_by_terrain_id
qtsdl::GuiEngine engine
qtsdl::GuiSubtree subtree
qtsdl::GuiInput input
std::unique_ptr<shader::Program> textured_screen_quad_shader
class GuiApplicationWithLogger : public qtsdl::GuiApplication
#include <gui_application_with_logger.h>

Houses gui logic event queue and attaches to game logger.

Public Functions

GuiApplicationWithLogger()
~GuiApplicationWithLogger()
class GuiFilledTextureHandles
#include <gui_filled_texture_handles.h>

Stores pointers to game texture handlers given to the Qt.

Public Functions

GuiFilledTextureHandles()
~GuiFilledTextureHandles()
void add_texture_handle(const QString &id, const QSize &requested_size, SizedTextureHandle *filled_handle)

Memorizes pointer to provided handle object in order to be able to update it if the source changes.

void free_texture_handle(SizedTextureHandle *filled_handle)
void fill_all_handles_with_texture(const TextureHandle &texture)
void refresh_all_handles_with_texture(std::function<void(const QString&, const QSize&, SizedTextureHandle *)> refresher)

Private Members

std::vector<std::tuple<QString, QSize, SizedTextureHandle *>> handles

Changing the texture handles underneath the QSGTexture to reflect the reload of the GameSpec.

It’s not a proper Qt usage, so the live reload of the game assets for the gui may break in future Qt releases. When it breaks, this feature should be implemented via the recreation of the qml engine.

std::mutex handles_mutex
class GuiFilledTextureHandleUser
#include <gui_filled_texture_handles.h>

Public Functions

GuiFilledTextureHandleUser(const std::shared_ptr<GuiFilledTextureHandles> &texture_handles, const QString &id, const QSize &requested_size, SizedTextureHandle *filled_handle)
~GuiFilledTextureHandleUser()
GuiFilledTextureHandleUser(GuiFilledTextureHandleUser&&)

Private Functions

GuiFilledTextureHandleUser(const GuiFilledTextureHandleUser&)
GuiFilledTextureHandleUser &operator=(const GuiFilledTextureHandleUser&)

Private Members

std::shared_ptr<GuiFilledTextureHandles> texture_handles
SizedTextureHandle *filled_handle
class GuiGameSpecImageProvider : public qtsdl::GuiImageProvider
#include <gui_game_spec_image_provider.h>

Public Types

enum Type

Values:

ByFilename
ByGraphicId
ByTerrainId

Public Functions

GuiGameSpecImageProvider(qtsdl::GuiEventQueue *render_updater, Type type)
~GuiGameSpecImageProvider()
class GuiGameSpecImageProviderByFilenameImpl : public openage::gui::GuiGameSpecImageProviderImpl
#include <gui_game_spec_image_provider_by_filename_impl.h>

Exposes game textures to the Qt by their file name.

Id has a form of <filename>.<subid> where <subid> is an integer.

Public Functions

GuiGameSpecImageProviderByFilenameImpl(qtsdl::GuiEventQueue *render_updater)
~GuiGameSpecImageProviderByFilenameImpl()

Public Static Functions

const char *id()

Private Functions

const char *get_id() const
TextureHandle get_texture_handle(const QString &id)
class GuiGameSpecImageProviderByGraphicIdImpl : public openage::gui::GuiGameSpecImageProviderByIdImpl
#include <gui_game_spec_image_provider_by_graphic_id_impl.h>

Exposes game textures to the Qt by their id.

Numeric id has a form of <texture-id>.<subid>.

Public Functions

GuiGameSpecImageProviderByGraphicIdImpl(qtsdl::GuiEventQueue *render_updater)
~GuiGameSpecImageProviderByGraphicIdImpl()

Public Static Functions

const char *id()

Private Functions

const char *get_id() const
openage::Texture *get_texture(int texture_id)
class GuiGameSpecImageProviderByIdImpl : public openage::gui::GuiGameSpecImageProviderImpl
#include <gui_game_spec_image_provider_by_id_impl.h>

Base for providers that expose textures to the Qt by their id.

Numeric id has a form of <texture-id>.<subid>.

Subclassed by openage::gui::GuiGameSpecImageProviderByGraphicIdImpl, openage::gui::GuiGameSpecImageProviderByTerrainIdImpl

Public Functions

GuiGameSpecImageProviderByIdImpl(qtsdl::GuiEventQueue *render_updater)
~GuiGameSpecImageProviderByIdImpl()

Private Functions

TextureHandle get_texture_handle(const QString &id)
virtual openage::Texture *get_texture(int texture_id) = 0
class GuiGameSpecImageProviderByTerrainIdImpl : public openage::gui::GuiGameSpecImageProviderByIdImpl
#include <gui_game_spec_image_provider_by_terrain_id_impl.h>

Exposes terrain textures to the Qt by their id.

Numeric id has a form of <texture-id>.<subid> where texture-id is the position in the terrain_meta.

Public Functions

GuiGameSpecImageProviderByTerrainIdImpl(qtsdl::GuiEventQueue *render_updater)
~GuiGameSpecImageProviderByTerrainIdImpl()

Public Static Functions

const char *id()

Private Functions

const char *get_id() const
openage::Texture *get_texture(int texture_id)
class GuiGameSpecImageProviderImpl : public qtsdl::GuiImageProviderImpl
#include <gui_game_spec_image_provider_impl.h>

Exposes game textures to the Qt.

Subclassed by openage::gui::GuiGameSpecImageProviderByFilenameImpl, openage::gui::GuiGameSpecImageProviderByIdImpl

Public Functions

GuiGameSpecImageProviderImpl(qtsdl::GuiEventQueue *render_updater)
~GuiGameSpecImageProviderImpl()
void on_game_spec_loaded(const std::shared_ptr<GameSpec> &loaded_game_spec)

Unblocks the provider.

Refreshes already loaded assets (if this->loaded_game_spec wasn’t null before the call).

Parameters
  • loaded_game_spec: new source (can’t be null)

void on_game_spec_invalidated()

Set to every sprite the ‘missing texture’ from current spec.

Needed as a visible reaction to setting the property to null. We can’t unload the textures without recreating the engine, so we keep the old source.

GuiFilledTextureHandleUser fill_texture_handle(const QString &id, const QSize &requested_size, SizedTextureHandle *filled_handle)

Fills in the provided handle object.

Memorizes pointer to it in order to update it if the source changes.

Return

pointer to all memorized handles, so the client can unsubscribe.

Protected Functions

TextureHandle get_missing_texture()

Protected Attributes

std::shared_ptr<GameSpec> loaded_game_spec
bool invalidated

When true, still uses the old source but shows the ‘missing texture’.

Private Functions

virtual TextureHandle get_texture_handle(const QString &id) = 0
QQuickTextureFactory *requestTexture(const QString &id, QSize *size, const QSize &requestedSize)
void give_up()
void migrate_to_new_game_spec(const std::shared_ptr<GameSpec> &loaded_game_spec)

Change the already produced texture handles to use new source.

void overwrite_texture_handle(const QString &id, const QSize &requested_size, SizedTextureHandle *filled_handle)

Private Members

std::shared_ptr<GuiFilledTextureHandles> filled_handles

Changing the texture handles underneath the QSGTexture to reflect the reload of the GameSpec.

It’s not a proper Qt usage, so the live reload of the game assets for the gui may break in future Qt releases. When it breaks, this feature should be implemented via the recreation of the qml engine.

std::mutex loaded_game_spec_mutex
std::condition_variable loaded_game_spec_cond
bool ended
qtsdl::GuiCallback render_thread_callback
class GuiImageProviderLink : public QObject
#include <gui_image_provider_link.h>

Public Functions

GuiImageProviderLink(QObject *parent, GuiGameSpecImageProviderImpl &image_provider)
~GuiImageProviderLink()
GameSpecLink *get_game_spec() const

Sets the game spec to load textures from.

Setting to null doesn’t detach from the spec, but picks the ‘missing texture’ from that spec and sets it to every sprite.

Property

property openage::gui::GuiImageProviderLink::gameSpec

Public Static Functions

QObject *provider(QQmlEngine *engine, const char *id)
QObject *provider_by_filename(QQmlEngine *engine, QJSEngine *)
QObject *provider_by_graphic_id(QQmlEngine *engine, QJSEngine *)
QObject *provider_by_terrain_id(QQmlEngine *engine, QJSEngine *)

Private Members

GuiGameSpecImageProviderImpl &image_provider
QPointer<GameSpecLink> game_spec

Private Slots

void on_game_spec_loaded(GameSpecLink *game_spec, std::shared_ptr<GameSpec> loaded_game_spec)

Pass loaded assets to the image provider.

Need to check if we still attached to that spec. Also it may be invalidated in the meantime, so share the ownership.

class GuiStandaloneSubtexture : public QSGTexture
#include <gui_standalone_subtexture.h>

Public Functions

GuiStandaloneSubtexture(GLuint id, const QSize &size)
~GuiStandaloneSubtexture()

Private Functions

void bind()
bool hasAlphaChannel() const
bool hasMipmaps() const
bool isAtlasTexture() const
int textureId() const
QSize textureSize() const

Private Members

const GLuint id
const QSize size
class GuiTexture : public QSGTexture
#include <gui_texture.h>

Public Functions

GuiTexture(const SizedTextureHandle &texture_handle)
~GuiTexture()

Private Functions

void bind()
bool hasAlphaChannel() const
bool hasMipmaps() const
bool isAtlasTexture() const
QSGTexture *removedFromAtlas() const
QRectF normalizedTextureSubRect() const
int textureId() const
QSize textureSize() const

Private Members

const SizedTextureHandle texture_handle
std::unique_ptr<QSGTexture> standalone
class GuiTextureFactory : public QQuickTextureFactory
#include <gui_texture_factory.h>

Public Functions

GuiTextureFactory(GuiGameSpecImageProviderImpl *provider, const QString &id, const QSize &requested_size)
~GuiTextureFactory()
QSGTexture *createTexture(QQuickWindow *window) const
int textureByteCount() const
QSize textureSize() const

Private Members

SizedTextureHandle texture_handle
GuiFilledTextureHandleUser texture_handle_user
class MainArgsLink : public QObject
#include <main_args_link.h>

Used to make arguments of the game available in QML.

Public Functions

MainArgsLink(QObject *parent, const util::Path &asset_dir)
virtual ~MainArgsLink()

Property

property openage::gui::MainArgsLink::assetDir

Public Static Functions

QObject *provider(QQmlEngine *engine, QJSEngine *)

Generates the MainArgsLink object which is then used within QML.

Private Members

util::Path asset_dir
class OutputModeLink : public qtsdl::GuiItemQObject, public QQmlParserStatus, public qtsdl::GuiItemInterface<OutputModeLink>
#include <game_control_link.h>

Public Functions

OutputModeLink(QObject *parent = nullptr)
virtual ~OutputModeLink()
QString get_name() const
QStringList get_binds() const

Signals

void name_changed()
void binds_changed()

Property

property openage::gui::OutputModeLink::name
property openage::gui::OutputModeLink::binds

Protected Functions

virtual void classBegin()
virtual void on_core_adopted()
virtual void componentComplete()

Private Slots

void on_announced(const std::string &name)
void on_binds_changed(const std::vector<std::string> &binds)
class ResourcesListModel : public QAbstractListModel
#include <resources_list_model.h>

Resource table for the gui.

Public Functions

ResourcesListModel(QObject *parent = nullptr)
~ResourcesListModel()
ActionModeLink *get_action_mode() const

Property

property openage::gui::ResourcesListModel::actionMode

Private Functions

int rowCount(const QModelIndex&) const
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const

Private Members

std::vector<int> amounts
ActionModeLink *action_mode

Private Slots

void on_resource_changed(game_resource resource, int amount)
class SizedTextureHandle : public openage::gui::TextureHandle
#include <gui_texture_handle.h>

Public Functions

SizedTextureHandle()
SizedTextureHandle(const TextureHandle &handle, const QSize &size)

Public Members

QSize size
class TextureHandle
#include <gui_texture_handle.h>

Subclassed by openage::gui::SizedTextureHandle

Public Members

openage::Texture *texture
int subid
class HealAbility : public openage::UnitAbility
#include <ability.h>

initiates a heal action when given a valid target

Public Functions

HealAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class HealAction : public openage::TargetAction
#include <action.h>

heals another unit

Public Functions

HealAction(Unit *e, UnitReference tar)
~HealAction()
void update_in_range(unsigned int int, Unit *)

Control units action when in range of the target.

void on_completion_in_range(int)
bool completed_in_range(Unit *target_ptr) const
std::string name() const

debug string to identify action types

Private Functions

void heal(Unit &target)

use heal action

Private Members

IntervalTimer timer
class HudHandler
#include <handlers.h>

superclass for all possible drawing operations in the game.

Subclassed by openage::console::Console, openage::GameControl, openage::gui::GUI, openage::UnitSelection

Public Functions

virtual ~HudHandler()
virtual bool on_drawhud() = 0

execute the drawing action.

class IdleAction : public openage::UnitAction
#include <action.h>

keeps an entity in a fixed position

Public Functions

IdleAction(Unit *e)
virtual ~IdleAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

Private Members

std::shared_ptr<TerrainSearch> search
ability_set auto_abilities
struct influence
#include <terrain.h>

storage for influences by neighbor tiles.

Public Members

uint8_t direction

bitmask for influence directions, bit 0 = neighbor 0, etc.

int priority

the blending priority for this influence

terrain_t terrain_id

the terrain id of the influence

struct influence_group
#include <terrain.h>

influences for one tile.

as a tile has 8 adjacent and diagonal neighbors, the maximum number of influences is 8.

Public Members

int count
terrain_t terrain_ids[8]
struct influence data[8]
struct action_arg_t
#include <action.h>

Contains information about a triggered event.

Public Members

const Event e
const coord::input mouse
const coord::input_delta motion
std::vector<action_id_t> hints
class ActionManager
#include <action.h>

The action manager manages all the actions allow creation, access information and equality.

Public Functions

ActionManager(InputManager *input_manager, cvar::CVarManager *cvar_manager)
action_t get(const std::string &type)
std::string get_name(const action_t action)
bool is(const std::string &type, const action_t action)

Private Functions

bool create(const std::string &type)

Private Members

std::unordered_map<std::string, action_t> actions
std::unordered_map<action_t, std::string> reverse_map
InputManager *const input_manager
cvar::CVarManager *const cvar_manager
action_t next_action_id = 0
struct class_code_hash
#include <event.h>

Public Functions

int operator()(const ClassCode &k) const
class ClassCode
#include <event.h>

base event type containing event class and event code

Public Functions

ClassCode(event_class cl, code_t code)
std::vector<event_class> get_classes() const

classes ordered with most specific first

bool has_class(const event_class &c) const

Public Members

const event_class eclass
const code_t code
class Event
#include <event.h>

Input event, as triggered by some input device like mouse, kezb, joystick, tablet, microwave or dildo.

Some modifier keys may also be pressed during the event.

Public Functions

Event(event_class cl, code_t code, modset_t mod)
Event(event_class cl, const std::string &text, modset_t mod)
char as_char() const

Return keyboard text as char returns 0 for non-text events.

std::string as_utf8() const

Returns a utf encoded char or an empty string for non-utf8 events.

std::string info() const

logable debug info

bool operator==(const Event &other) const

Public Members

const ClassCode cc
const modset_t mod
const std::string utf8
struct event_class_hash
#include <event.h>

Public Functions

int operator()(const event_class &s) const
struct event_hash
#include <event.h>

Public Functions

int operator()(const Event &e) const
class InputContext
#include <input_context.h>

An input context contains all keybindings and actions active in e.g.

the HUD only. For the console, there’s a different input context. That way, each context can have the same keys assigned to different actions, the active context decides, which one to trigger.

Subclassed by openage::OutputMode

Public Functions

InputContext()

Create an unbound input context.

InputContext(InputManager *manager)

Create a bound context, assigned to its manager.

virtual ~InputContext()
std::vector<std::string> active_binds() const

a list of all keys of this context which are bound currently in the active context.

TODO: move this method to the input manager. as InputManager::active_binds(const InputContext &) const;

void bind(action_t type, const action_func_t act)

bind a specific action idetifier this is the highest matching priority

void bind(const Event &ev, const action_func_t act)

bind a specific event this is the second matching priority

void bind(event_class ec, const action_check_t act)

bind all events of a specific class this is the lowest matching priority

bool execute_if_bound(const action_arg_t &e)

lookup an action.

If it is bound, execute it.

Return

true when the action is executed, false else.

void register_to(InputManager *manager)

Called by the InputManager where this context shall be registered to.

void unregister()

Remove the registration to an input manager.

Public Members

bool utf8_mode

Affects which keyboard events are received: true to accpet utf8 text events, false to receive regular char events.

Private Members

InputManager *input_manager

Input manager this context is bound to.

std::unordered_map<action_t, action_func_t> by_type

Maps an action id to a event execution function.

std::unordered_map<Event, action_func_t, event_hash> by_event

map specific overriding events

std::unordered_map<event_class, action_check_t, event_class_hash> by_class

event to action map event_class as key, to ensure all events can be mapped

class InputManager : public openage::InputHandler
#include <input_manager.h>

The input manager manages all input layers (hud, game, …) and triggers the registered actions depending on the active layer.

pxd:

cppclass InputManager: bool set_bind(char* bind_char, string action) except + string get_bind(string action) except +

Public Types

enum Edge

Screen edges used for edge scrolling.

Values:

LEFT
RIGHT
UP
DOWN

Public Functions

InputManager(ActionManager *action_manager)
std::string get_bind(const std::string &action)

Return the string representation of the bind assignated to an action.

bool set_bind(const std::string &bind_str, const std::string action)

Set the given action to be triggered by the given bind (key/mouse /wheel).

Remove previous assignation. Do nothing if either they given bind or action is invalid/unknow.

std::string key_bind_to_string(const Event &ev)

Return the string representation of the key event.

std::string mouse_bind_to_string(const Event &ev)

Return the string representation of the mouse event.

std::string wheel_bind_to_string(const Event &ev)

Return the key representation of the event.

InputContext &get_global_context()

returns the global keybind context.

actions bound here will be retained even when override_context is called.

InputContext &get_top_context()

Returns the context on top.

Note there is always a top context since the global context will be considered on top when none are registered

void push_context(InputContext *context)

register a hotkey context by pushing it onto the stack.

this adds the given pointer to the contexts list. that way the context lays on “top”.

if other contexts are registered afterwards, it wanders down the stack, i.e. looses priority.

void remove_context(InputContext *context)

removes any matching registered context from the stack.

the removal is done by finding the given pointer in the contexts lists, then deleting it in there.

bool ignored(const Event &e)

true if the given event type is being ignored

bool trigger(const Event &e)

manages the pressing of an input event (key, mouse, …).

first checks whether an action is bound to it. if it is, look for an handler to execute that handler. returns true if the event was responded to

void set_state(const Event &ev, bool is_down)

sets the state of a specific key

void set_mouse(int x, int y)

updates mouse position state and motion

void set_motion(int x, int y)

updates mouse motion only

void set_relative(bool mode)

enable relative mouse mode

bool is_mouse_at_edge(Edge edge, int window_size)

Query whether cursor is at edgo of screen.

edge variable is enum Edges

Return

true when the mouse is at the queried screen edge, false else.

bool is_down(const ClassCode &cc) const

Query stored pressing stat for a key.

note that the function stores a unknown/new keycode as ‘not pressed’ if requested

Return

true when the key is pressed, false else.

bool is_down(event_class ec, code_t code) const
bool is_down(SDL_Keycode k) const

Most cases should use above is_down(class, code) instead to avoid relying on sdl types.

Query stored pressing stat for a key.

Return

true when the key is pressed, false else.

bool is_mod_down(modifier mod) const

Checks whether a key modifier is held down.

bool on_input(SDL_Event *e)

When a SDL event happens, this is called.

std::vector<std::string> active_binds(const std::unordered_map<action_t, action_func_t> &ctx_actions) const

Return a string representation of active key bindings from the given context.

ActionManager *get_action_manager() const

Get the action manager attached to this input manager.

Private Functions

modset_t get_mod() const

Private Members

ActionManager *action_manager

The action manager to used for keybind action lookups.

InputContext global_context

The global context.

Used as fallback.

binding_map_t keys

Maps actions to events.

std::vector<InputContext *> contexts

Stack of active input contexts.

The most recent entry is pushed on top of the stack.

std::unordered_map<ClassCode, bool, class_code_hash> states

key to is_down map.

stores a mapping between keycodes and its pressing state. a true value means the key is currently pressed, false indicates the key is untouched.

modset_t keymod

Current key modifiers.

Included ALL modifiers including num lock and caps lock.

bool relative_mode

mode where mouse position is ignored used for map scrolling

coord::input mouse_position = {0, }

mouse position in the window

coord::input_delta mouse_motion = {0, }

mouse position relative to the last frame position.

friend openage::input::InputManager::InputContext
struct modifier_hash
#include <event.h>

Public Functions

int operator()(const modifier &s) const
class InputHandler
#include <handlers.h>

superclass for handling any input event.

Subclassed by openage::console::Console, openage::gui::GUI, openage::input::InputManager

Public Functions

virtual ~InputHandler()
virtual bool on_input(SDL_Event *event) = 0

execute the input handler.

class IntervalTimer
#include <action.h>

A interval triggering timer used in actions.

TODO find a better name for triggers

Public Functions

IntervalTimer(unsigned int interval)

Constructs a timer with a given interval.

IntervalTimer(unsigned int interval, int max_triggers)

Constructs a timer with a given interval which will stop after a given number of triggers.

void skip_to_trigger()
bool update(unsigned int time)
unsigned int get_time_left() const

Returns the time until the next trigger.

float get_progress() const
bool has_triggers() const

Returns true if at least one interval has passed.

bool finished() const

Returns true if the interval passed have reached the max.

int get_triggers() const

Returns the number of intervals passed.

unsigned int get_interval() const
void set_interval(unsigned int interval)

Private Members

unsigned int interval
int max_triggers
unsigned int time_left
int triggers
template<class T>
class AbortableJobState : public openage::job::TypedJobStateBase<T>
#include <abortable_job_state.h>

An abortable job state supports job that can be aborted.

This is done by providing two function objects to the job’s function. One is used to check whether the job should be aborted, while the other one aborts the job.

Public Functions

AbortableJobState(abortable_function_t<T> function, callback_function_t<T> callback)

Creates a new abortable job with the given function and callback.

Public Members

abortable_function_t<T> function

The job’s function.

openage::job::AbortableJobState::function{function} { } virtual ~AbortableJobState() = default

Protected Functions

virtual T execute_and_get(should_abort_t should_abort)

Executes the job and returns the result.

If an exception is thrown it must be passed to the calling function.

template<class T>
class Job
#include <job.h>

A job is a wrapper around a shared job state object and is returned by the job manager.

It can be used to retrieve the current state of the job and its result. A job is a lightweight object which only contains a pointer to its internal shared state. Thus it can be copied around without worrying about performance. Further it is not necessary to create or pass pointers to job objects.

Parameters
  • T: the job’s result type

Public Functions

Job()

Creates an empty job object that is not bound to any state.

Should only be used as dummy object.

bool is_finished() const

Returns whether this job has finished.

If this job wrapper has no assigned background job, true will be returned.

T get_result()

Returns this job’s result if the background execution was successful.

If an exception has happened, it will be rethrown. This method must not be called, if the job’s execution has not yet finished.

Private Functions

Job(std::shared_ptr<TypedJobStateBase<T>> state)

Creates a job with the given shared state.

This method may only be called by the job manager.

Private Members

std::shared_ptr<TypedJobStateBase<T>> state

A shared pointer to the job’s shared state.

Friends

friend openage::job::Job::JobGroup
friend openage::job::Job::JobManager
class JobAbortedException : public exception
#include <job_aborted_exception.h>

An exception that is thrown when a job wants to abort itself.

Public Functions

const char *what() const
class JobGroup
#include <job_group.h>

A job group is a proxy object that forwards job’s to a single worker thread.

It can be used the assure that multiple jobs are executed on the same background thread.

Public Functions

JobGroup()

Creates a new empty job group with no parent worker.

Should only be used as dummy object.

template<class T>
Job<T> enqueue(job_function_t<T> function, callback_function_t<T> callback = {})

Enqueues the given function into the job group’s worker thread.

A lightweight job object is returned, that allows to keep track of the job’s state.

Parameters
  • function: the function that is executed as background job

  • callback: the callback function that is executed, when the background job has finished

template<class T>
Job<T> enqueue(abortable_function_t<T> function, callback_function_t<T> callback = {})

Enqueues the given function into the job group’s worker thread.

A lightweight job object is returned, that allows to keep track of the job’s state.The passed function must accept a function object that returns, whether the job should be aborted at any time. Further it must accept a function that can be used to abort the execution of the function.

Parameters
  • function: the function that is executed as background job

  • callback: the callback function that is executed, when the background job has finished

Private Functions

JobGroup(Worker *parent_worker)

Creates a new job group with the given parent worker.

Private Members

Worker *parent_worker

The parent worker that executes all jobs from this job group.

Friends

friend openage::job::JobGroup::JobManager

The job manager must be a friend of the worker in order to call the private constructor.

class JobManager
#include <job_manager.h>

A job manager can be used to execute functions within separate worker threads.

Public Functions

JobManager(int number_of_workers)

Create a new job manager with a specified number of worker threads.

~JobManager()

Destructor that stops the job manager if it is still running.

JobManager(const JobManager&)
JobManager(JobManager&&)
JobManager &operator=(const JobManager&)
JobManager &operator=(JobManager&&)
void start()

Start the job manager’s worker threads.

void stop()

Stop the job manager’s worker threads.

This method blocks until all currently working threads have finished.

template<class T>
Job<T> enqueue(job_function_t<T> function, callback_function_t<T> callback = {})

Enqueues the given function into the job manager’s queue, so that it will be dispatched by one of the worker threads.

A lightweight Job object is returned, that allows to keep track of the job’s state.

Parameters
  • function: the function that is executed as background job

  • callback: the callback function that is executed, when the background job has finished

template<class T>
Job<T> enqueue(abortable_function_t<T> function, callback_function_t<T> callback = {})

Enqueues the given function into the job manager’s queue, so that it will be dispatched by one of the worker threads.

A lightweight job object is returned, that allows to keep track of the job’s state. The passed function must accept a function object that returns, whether the job should be aborted at any time. Further it must accept a function that can be used to abort the execution of the function.

Parameters
  • function: the function that is executed as background job

  • callback: the callback function that is executed, when the background job has finished

JobGroup create_job_group()

Creates a job group, in order to be able to execute multiple jobs on the same worker thread.

void execute_callbacks()

Executes callbacks for all job’s, that were created by the current thread and have finished.

Private Functions

void enqueue_state(std::shared_ptr<JobStateBase> state)

Enqueues the given job into the internal job queue.

std::shared_ptr<JobStateBase> fetch_job()

Returns a job from the internal job queue.

If the queue is empty, a nullptr is returned.

bool has_job()

Returns whether there are jobs to be executed.

void finish_job(std::shared_ptr<JobStateBase> job)

Adds a finished job to the internal finished job map.

Private Members

int number_of_workers

The number of internal worker threads.

int group_index

The index of the worker thread, that is used for the next returned job group.

std::vector<std::unique_ptr<Worker>> workers

A vector of all worker threads.

std::mutex pending_jobs_mutex

A mutex to synchronize accesses to the internal job queue.

std::queue<std::shared_ptr<JobStateBase>> pending_jobs

A queue of jobs that are to be executed.

std::mutex finished_jobs_mutex

A mutex to synchronize the finished job map.

std::unordered_map<size_t, std::vector<std::shared_ptr<JobStateBase>>> finished_jobs

Mapping from thread id’s to a list of jobs, that have been created by the corresponding thread and have finished.

std::atomic_bool is_running

Whether the job manager is currently running.

Friends

friend openage::job::JobManager::Worker

A worker has to be a friend of the job manager in order to call the private finish_job method.

template<class T>
class JobState : public openage::job::TypedJobStateBase<T>
#include <job_state.h>

A job state supports simple job’s with functions that return a single result.

While executing the job, it cannot be aborted safely.

Public Functions

JobState(job_function_t<T> function, callback_function_t<T> callback)

Creates a new JobState with the given function, that is to be executed.

Public Members

job_function_t<T> function

A function object which is executed by the JobManager.

openage::job::JobState::function{function} { } virtual ~JobState() = default

Protected Functions

T execute_and_get(should_abort_t should_abort)

Executes the job and returns the result.

If an exception is thrown it must be passed to the calling function.

class JobStateBase
#include <job_state_base.h>

An abstract base class for a shared state of a job.

A job state keeps track of its execution state and store’s the job’s result. Further it keeps track of exceptions that occurred during the job’s execution. The real shared state implementation is done in templated subclasses. This is necessary to support arbitrary result types.

Subclassed by openage::job::TypedJobStateBase< T >

Public Functions

virtual ~JobStateBase()

Default constructor.

virtual bool execute(should_abort_t should_abort) = 0

This function executes the job.

It returns whether the job has been aborted.

virtual void execute_callback() = 0

Executes the job’s callback, if a callback function has been provided while constructing this job.

This function may only be called if the job has already finished.

virtual size_t get_thread_id() = 0

Returns the id of the thread that has created this job.

template<class T>
class TypedJobStateBase : public openage::job::JobStateBase
#include <typed_job_state_base.h>

A templated job state base class, that implements basic functionality of job states.

Parameters
  • T: the result type of this job state. This type must have a default constructor and support move semantics.

Subclassed by openage::job::AbortableJobState< T >, openage::job::JobState< T >

Public Functions

TypedJobStateBase(callback_function_t<T> callback)

Creates a new typed job with the given callback.

virtual ~TypedJobStateBase()

Default destructor.

bool execute(should_abort_t should_abort)

Executes the internal function object and stores its result.

Occuring exceptions are stored, as well. Returns whether this job has been aborted.

void execute_callback()

Called when the job was finished.

This is the result notification for the place where the job was constructed.

size_t get_thread_id()

Returns the id of the thread that has created this job.

Public Members

size_t thread_id

Id of the thread, that created this job state.

callback_function_t<T> callback

A callback function that is called when the job has finished.

Can be empty.

std::atomic_bool finished

Whether the Job’s execution has already been finished.

An atomic_bool is used, as this field can be used by multiple threads. Thus explicit synchronization is avoided.

T result

The result of the Job’s executed function.

std::exception_ptr exception

If executing the Job throws an exception, it is stored here.

Protected Functions

virtual T execute_and_get(should_abort_t should_abort) = 0

Executes the job and returns the result.

If an exception is thrown it must be passed to the calling function.

class Worker
#include <worker.h>

A worker encapsulates the execution of multiple jobs in a single background thread.

Public Functions

Worker(JobManager *manager)

Constructs a new worker with the parent job manager.

~Worker()

Default destructor.

void start()

Starts this worker.

void stop()

Stops this worker.

void join()

Joins the internal executing thread.

void enqueue(std::shared_ptr<JobStateBase> job)

Adds the given job to the internal pending job queue.

void notify()

Notifies this worker, that new jobs are available.

This method is although called from the parent job manager.

Private Functions

void execute_job(std::shared_ptr<JobStateBase> &job)

Executes the given job and tells the parent job manager, when it has finished.

void process()

Fetches pending jobs from the parent job manager and from the internal pending job queue and executes them.

If no jobs are available the internal execution thread is wait using a condition variable.

Private Members

JobManager *manager

The parent job manager, this worker is fetching jobs from.

bool is_running

Whether this worker thread is still running.

std::unique_ptr<std::thread> executor

The executing thread.

std::mutex pending_jobs_mutex

A mutex to synchronize the internal pending jobs queue.

std::queue<std::shared_ptr<JobStateBase>> pending_jobs

A queue of jobs that are to be executed.

std::condition_variable jobs_available

A condition variable to wait for new jobs.

class LivingProducer : public openage::MovableProducer
#include <producer.h>

temporary class will be replaced with nyan system in future Stores graphics and attributes for a single unit type in aoe living units are derived from objects

Public Functions

LivingProducer(const Player &owner, const GameSpec &spec, const gamedata::living_unit *ud)
~LivingProducer()
void initialise(Unit *, Player&)

Initialize units attributes to this type spec.

This can be called using existing units to modify type Ensure that the unit has been placed before seting the units type

TODO: make const

TerrainObject *place(Unit *, std::shared_ptr<Terrain>, coord::phys3) const

set unit in place return if placement was successful

This should be used when initially creating a unit or when a unit is ungarrsioned from a building or object TODO: make const

Private Members

const gamedata::living_unit unit_data
class CppHandler

CppHandler calls into the CPP logging system if the library has been loaded.

Public Functions

__init__(self self)
setLevel(self self, level level)

sets the log level

emit(self self, record record)

logs a message

class FileSink : public openage::log::LogSink
#include <file_logsink.h>

Public Functions

FileSink(const char *filename, bool append)

Private Functions

void output_log_message(const message &msg, LogSource *source)

Private Members

std::ofstream outfile
struct level : public openage::util::Enum<level_value>
#include <level.h>

Available logging levels.

pxd:

cppclass level(Enum[level_value]): pass

level MIN “::openage::log::level::MIN” level spam “::openage::log::level::spam” level dbg “::openage::log::level::dbg” level info “::openage::log::level::info” level warn “::openage::log::level::warn” level err “::openage::log::level::err” level crit “::openage::log::level::crit” level MAX “::openage::log::level::MAX”

Public Functions

level()

Public Static Attributes

constexpr level_value MIN openage::log::level::NOOPTIMIZE = {{"min loglevel", -1000}, "5"}
constexpr level_value spam openage::log::level::NOOPTIMIZE = {{"SPAM", -100}, ""}
constexpr level_value dbg openage::log::level::NOOPTIMIZE = {{"DBG", -20}, ""}
constexpr level_value info openage::log::level::NOOPTIMIZE = {{"INFO", 0}, ""}
constexpr level_value warn openage::log::level::NOOPTIMIZE = {{"WARN", 100}, "33"}
constexpr level_value err openage::log::level::NOOPTIMIZE = {{"ERR", 200}, "31;1"}
constexpr level_value crit openage::log::level::NOOPTIMIZE = {{"CRIT", 500}, "31;1;47"}
constexpr level_value MAX openage::log::level::NOOPTIMIZE = {{"max loglevel", 1000}, "5"}
struct level_value : public openage::util::EnumValue<level_value>
#include <level.h>

Data associated with a log level.

pxd:

cppclass level_value(EnumValue[level_value, int]): const char *colorcode

Public Members

const char *colorcode
class LogSink
#include <logsink.h>

Abstract base for classes that - in one way or an other - print log messages.

Instances of this class are automatically added to LogSource::global_sink_list vector by their constructors (and removed by their destructors).

Subclassed by openage::log::FileSink, openage::log::StdOutSink, openage::log::tests::TestLogSink

Public Functions

LogSink()
~LogSink()
void set_loglevel(level loglevel)

TODO: Add iptables-like chains that decide whether a message will be logged, depending on msg.info, logger id, thread id, etc.

This member variable is only a make-shift solution with obvious limitations.

Private Functions

virtual void output_log_message(const struct message &msg, class LogSource *source) = 0

Called internally by put_log_message if a message is accepted.

Private Members

level loglevel

Friends

friend openage::log::LogSink::LogSinkList
class LogSinkList
#include <logsink.h>

Holds a list of all registered log sinks; Maintained from the LogSink constructors/destructors.

Public Functions

LogSinkList(LogSinkList const&)
void operator=(LogSinkList const&)
void log(const message &msg, class LogSource *source) const
void add(LogSink *sink)
void remove(LogSink *sink)
bool supports_loglevel(level loglevel) const
void loglevel_changed()

Public Static Functions

LogSinkList &instance()

Private Functions

LogSinkList()
void set_lowest_loglevel()

Private Members

std::list<LogSink *> sinks
std::mutex sinks_mutex
level lowest_loglevel
class LogSource
#include <logsource.h>

Any class that wants to provide .log() shall inherit from this.

Examples: Engine, Unit, …

pxd:

cppclass LogSource: void log(message msg) except + const size_t logger_id string logsource_name() except +

Subclassed by openage::log::NamedLogSource, openage::log::tests::TestLogSource, openage::Unit

Public Functions

LogSource()
virtual ~LogSource()
void log(const message &msg)

Logs a message (get one via MSG(level)).

virtual std::string logsource_name() = 0

Public Members

const size_t logger_id

Initialized during the LogSource constructor, guaranteed to be unique.

Private Static Functions

size_t get_unique_logger_id()

Provides unique logger ids.

struct message
#include <message.h>

A complete log/exception message, containing a text message and metadata.

The preferred way of creating a message object is to use MessageBuilder via the MSG macro. MessageBuilder is auto-converted to message when needed.

pxd:

cppclass message: string text char *filename unsigned lineno const char *functionname level lvl size_t thread_id int64_t timestamp

void init() except + void init_with_metadata_copy(string filename, string functionname) except +

Public Functions

void init()

Sets all members except for filename, lineno, functionname and level.

void init_with_metadata_copy(const std::string &filename, const std::string &functionname)

Sets all members except for lineno and level.

filename and functionname are copied to an internal cache.

Designed to be used when filename and functionname are temporary objects (e.g. from Python).

Public Members

std::string text
const char *filename

The filename where the message has been constructed.

unsigned lineno

The line number where the message has been constructed.

const char *functionname

The (pretty) function name where the message has been constructed.

level lvl

The log level.

size_t thread_id

A unique id for the thread where the message has been constructed.

int64_t timestamp

A (nanosecond-resolution) timestamp of the message construction.

class MessageBuilder : public openage::util::StringFormatter<MessageBuilder>
#include <message.h>

Wrapper around a log message that allows appending to the message with operator <<.

Auto-converts to message; via the MSG macro, this is the preferred way of creating log and exc messages.

Public Functions

MessageBuilder(const char *filename, unsigned lineno, const char *functionname, level lvl = level::info)

Don’t use this constructor directly; instead use the MSG macro.

Parameters
  • filenamelineno: source file name and line number (FILE, LINE).

  • functionname: (fully qualified) function name (OPENAGE_FUNC_NAME).

  • lvl: loglevel of the message. Also required for exception messages.

operator const message&() const
operator message&()
bool should_format() const

Returns if formatting should actually occur.

Private Members

message msg

Friends

friend openage::log::MessageBuilder::LogSource
class NamedLogSource : public openage::log::LogSource
#include <named_logsource.h>

Simple pure log source class with a string name.

pxd:

cppclass NamedLogSource(LogSource): NamedLogSource(string name) except +

Public Functions

NamedLogSource(const std::string &name)
std::string logsource_name()

Private Members

std::string name
class StdOutSink : public openage::log::LogSink
#include <stdout_logsink.h>

Simple logsink that prints messages to stdout (via std::cout).

Public Functions

StdOutSink()

Private Functions

void output_log_message(const message &msg, LogSource *source)
class TestLogSink : public openage::log::LogSink

Public Functions

TestLogSink(std::ostream &os)

Private Functions

void output_log_message(const message &msg, LogSource *)

Private Members

std::ostream &os
class TestLogSource : public openage::log::LogSource

Public Functions

std::string logsource_name()
struct main_arguments
#include <main.h>

Used for passing arguments to run_game.

pxd:

cppclass main_arguments: Path root_path int32_t fps_limit bool gl_debug

Public Members

util::Path root_path
int32_t fps_limit
bool gl_debug
class Market
#include <market.h>

The global market prices.

Price calculation is documented at doc/reverse_engineering/market.md#prices

Public Functions

Market()
bool sell(Player &player, const game_resource res)

The given player sells the given resource for gold.

Returns true when the transaction is successful.

bool buy(Player &player, const game_resource res)

The given player buys the given resource with gold.

Returns true when the transaction is successful.

ResourceBundle get_buy_prices(const Player &player) const

Get the selling prices for a given player.

ResourceBundle get_sell_prices(const Player &player) const

Get the buying prices for a given player.

Protected Functions

ResourceBundle get_prices(const Player &player, const bool is_buy) const

The getBuyPrices and getSellPrices are redirected here.

double get_multiplier(const Player &player, const bool is_buy) const

Get the multiplier for the base prices.

Private Members

ResourceBundle base_prices

Stores the base price values of each resource.

The ResourceBundle is used to represent the prices instead of the amounts for each resource.

class MovableProducer : public openage::ObjectProducer
#include <producer.h>

movable unit types

Subclassed by openage::LivingProducer

Public Functions

MovableProducer(const Player &owner, const GameSpec &spec, const gamedata::projectile_unit *um)
~MovableProducer()
void initialise(Unit *, Player&)

Initialize units attributes to this type spec.

This can be called using existing units to modify type Ensure that the unit has been placed before seting the units type

TODO: make const

TerrainObject *place(Unit *, std::shared_ptr<Terrain>, coord::phys3) const

set unit in place return if placement was successful

This should be used when initially creating a unit or when a unit is ungarrsioned from a building or object TODO: make const

Protected Attributes

const gamedata::projectile_unit unit_data
UnitTexture *moving
UnitTexture *attacking
const Sound *on_move
const Sound *on_attack
int projectile
class MoveAbility : public openage::UnitAbility
#include <ability.h>

initiates a move action when given a valid target

Public Functions

MoveAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class MoveAction : public openage::UnitAction
#include <action.h>

moves an entity to another location

Public Functions

MoveAction(Unit *e, coord::phys3 tar, bool repath = true)

moves unit to a given fixed location

MoveAction(Unit *e, UnitReference tar, coord::phys_t within_range)

moves a unit to within a distance to another unit

~MoveAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

coord::phys3 next_waypoint() const

Private Functions

void initialise()
void set_path()

use a star to find a path to target

void set_distance()

updates the distance_to_target value

Private Members

UnitReference unit_target
coord::phys3 target
coord::phys_t distance_to_target
coord::phys_t radius
path::Path path
bool allow_repath
bool end_action
struct neighbor_tile
#include <terrain.h>

one influence on another tile.

Public Members

terrain_t terrain_id
tile_state state
int priority
class NyanResearchType : public openage::ResearchType
#include <research.h>

Private Functions

NyanResearchType(Player &owner)
class NyanType : public openage::UnitType
#include <unit_type.h>

An example of how nyan can work with the type system.

Public Functions

NyanType(const Player &owner)

TODO: give the parsed nyan attributes to the constructor.

~NyanType()
int id() const

gets the unique id of this unit type

int parent_id() const

gets the parent id of this unit type which is used for village base and gather types

std::string name() const

gets the name of the unit type being produced

void initialise(Unit *, Player&)

Initialize units attributes to this type spec.

This can be called using existing units to modify type Ensure that the unit has been placed before seting the units type

TODO: make const

TerrainObject *place(Unit *, std::shared_ptr<Terrain>, coord::phys3) const

set unit in place return if placement was successful

This should be used when initially creating a unit or when a unit is ungarrsioned from a building or object TODO: make const

class ObjectProducer : public openage::UnitType
#include <producer.h>

base game data unit type

Subclassed by openage::MovableProducer

Public Functions

ObjectProducer(const Player &owner, const GameSpec &spec, const gamedata::unit_object *ud)
~ObjectProducer()
int id() const

gets the unique id of this unit type

int parent_id() const

gets the parent id of this unit type which is used for village base and gather types

std::string name() const

gets the name of the unit type being produced

void initialise(Unit *, Player&)

Initialize units attributes to this type spec.

This can be called using existing units to modify type Ensure that the unit has been placed before seting the units type

TODO: make const

TerrainObject *place(Unit *, std::shared_ptr<Terrain>, coord::phys3) const

set unit in place return if placement was successful

This should be used when initially creating a unit or when a unit is ungarrsioned from a building or object TODO: make const

Protected Attributes

const GameSpec &dataspec
const gamedata::unit_object unit_data
bool decay

decaying objects have a timed lifespan

const Sound *on_create

Sound id played when object is created or destroyed.

const Sound *on_destroy
std::shared_ptr<Texture> terrain_outline
std::shared_ptr<UnitTexture> default_tex
int dead_unit_id
class OptionAction
#include <options.h>

Public Functions

OptionAction(const std::string &name, const opt_func_t f)
OptionValue do_action()

pass mouse position

Public Members

const std::string name

name of this action

Private Members

const opt_func_t function
class OptionHud
#include <options.h>

A thing for drawing OptionNodes.

generates required gui elements for each variable on a panel

Public Functions

OptionHud()
class OptionNode
#include <options.h>

Allows objects to expose customisable features.

This is used to bind inner game classes with console interaction or gui elements

Subclassed by openage::Engine, openage::GameMain, openage::RenderOptions

Public Functions

OptionNode(const std::string &panel_name)
~OptionNode()
std::vector<std::string> list_options(bool recurse = false, std::string indent = "")

lists all available options in a readable format

std::vector<std::string> list_variables() const

shows all available variable names

std::vector<std::string> list_functions() const

shows all the available function names

OptionValue &get_variable_rw(const std::string &name)
const OptionValue &get_variable(const std::string &name) const
template<class T>
const T &getv(const std::string &name)

shortcut for get_variable(name).value<T>()

OptionNode *get_child(const std::string &name) const

return a child by name, or null if not available

void set_parent(OptionNode *parent)

Set a parent panel which implies adding a child to the parent.

OptionValue do_action(const std::string &aname)

performs the named action returning the actions response

Public Members

const std::string name

name of this node

Protected Functions

void add(const std::string &vname, const OptionValue &value)

add types to the interface

void add_action(const OptionAction &action)

Private Functions

void add_panel(OptionNode *child)

add child nodes

void remove_panel(OptionNode *child)

remove child nodes

Private Members

OptionNode *parent

parent of this node

std::unordered_map<std::string, OptionValue> varmap

Variables which can be used TODO: read only variables.

std::unordered_map<std::string, OptionAction> actions
std::unordered_map<std::string, OptionNode *> children

children of this node

Friends

friend openage::options::OptionNode::Var
class OptionValue
#include <options.h>

stores a type and value

Public Functions

OptionValue(bool b)

value ownership managed by this

OptionValue(int i)
OptionValue(double d)
OptionValue(const char *s)
OptionValue(const std::string &s)
OptionValue(const option_list &l)
OptionValue(const OptionValue &v)
OptionValue(util::Variable<bool> *b)

value owned by another object

OptionValue(util::Variable<int> *i)
OptionValue(util::Variable<double> *d)
OptionValue(util::Variable<std::string> *s)
OptionValue(util::Variable<option_list> *l)
~OptionValue()
bool is_reference() const

True if this value references an object not owned by itself.

bool operator==(const OptionValue &other) const

Checks equality.

const OptionValue &operator=(const OptionValue &other)

Assignment, reference values share their values non reference values are copied.

std::string str_value() const

Value converted to a string.

template<class T>
const T &value() const

read inner type - the templated type must match

Public Members

const option_type type

Private Functions

void set(const OptionValue &other)

set the value

template<class T>
void set_value(const OptionValue &other)

Private Members

bool owner

Use of shared_ptr and unique_ptr doesnt work here possibly solved by templating ownership type.

non-owned variables act as references

util::VariableBase *var
template<class T>
class Var : public openage::util::Variable<T>
#include <options.h>

A interaface variable which gets monitored by an option node allowing reflection, while also being directly accessable as a typed member.

Public Functions

Var(OptionNode *owner, const std::string &name, const T &init)
class OutputMode : public openage::input::InputContext
#include <game_control.h>

A target for input handling and gui rendering.

This allows to switch to different display UIs.

Subclassed by openage::ActionMode, openage::CreateMode, openage::EditorMode

Public Functions

OutputMode(qtsdl::GuiItemLink *gui_link)
~OutputMode()
virtual bool available() const = 0

Is this mode able to be used?

virtual void on_enter() = 0

Called when switching to this mode.

virtual void on_exit() = 0

Called when the mode is left.

virtual void render() = 0

Display this mode.

virtual std::string name() const = 0

Used for displaying the current mode.

void announce()

Emit the “announced” signal with (name, InputContext::active_binds).

void set_game_control(GameControl *game_control)

Called when the GameControl is set in QML.

virtual void on_game_control_set() = 0

Called after GameControl has been set by QML from set_game_control.

Public Members

OutputModeSignals gui_signals

Signals to be triggered when the mode canges.

qtsdl::GuiItemLink *gui_link

Protected Attributes

GameControl *game_control
class OutputModeSignals : public QObject
#include <game_control.h>

Signals for a gui mode.

Signals

void announced(const std::string &name)

Signal is triggered to anounce a new output mode.

name: name of the gui mode.

void binds_changed(const std::vector<std::string> &binds)

Signal is triggered when the bindings of the mode change.

binds: list of strings that describe keybindings.

struct compare_node_cost
#include <path.h>

Cost comparison for node_pt.

Extracts the ptr from the shared_ptr. Calls operator < on Node.

Public Functions

bool operator()(const node_pt &lhs, const node_pt &rhs) const
class Node : public std::enable_shared_from_this<Node>
#include <path.h>

One navigation waypoint in a path.

Public Functions

Node(const coord::phys3 &pos, node_pt prev)
Node(const coord::phys3 &pos, node_pt prev, cost_t past, cost_t heuristic)
bool operator<(const Node &other) const

Orders nodes according to their future cost value.

bool operator==(const Node &other) const

Compare the node to another one.

They are the same if their position is.

cost_t cost_to(const Node &other) const

Calculates the actual movement cose to another node.

Path generate_backtrace()

Create a backtrace path beginning at this node.

std::vector<node_pt> get_neighbors(const nodemap_t &nodes, float scale = 1.0f)

Get all neighbors of this graph node.

Public Members

coord::phys3 position

The tile position this node is associated to.

todo make const

coord::tile tile_position
coord::phys3_delta direction
cost_t future_cost

Future cost estimation value for this node.

cost_t past_cost

Evaluated past cost value for the node.

This stores the actual cost from start to this node.

cost_t heuristic_cost

Heuristic cost cache.

Calculated once, is the heuristic distance from this node to the goal.

bool accessible = false

Can this node be passed?

bool visited = false

Has this Node been visited?

bool was_best = false

Does this node already have an alternative path? If the node was once selected as the best next hop, this is set to true.

cost_t factor

Factor to adjust movement cost.

default: 1

node_pt path_predecessor

Node where this one was reached by least cost.

heap_t::element_t heap_node

Priority queue node that contains this path node.

class Path
#include <path.h>

Represents a planned trajectory.

Generated by pathfinding algorithms.

Public Functions

Path()
Path(const std::vector<Node> &nodes)
void draw_path(const coord::CoordManager &mgr)

Public Members

std::vector<Node> waypoints

These are the waypoints to navigate in order.

Includes the start and end node.

class PatrolAbility : public openage::UnitAbility
#include <ability.h>

initiates a patrol action when given a valid target TODO implement

Public Functions

PatrolAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class Player
#include <player.h>

Public Functions

Player(Civilisation *civ, unsigned int number, std::string name)
bool operator==(const Player &other) const

checks if two players are the same

bool is_enemy(const Player &other) const

the specified player is an enemy of this player

bool is_ally(const Player &other) const

the specified player is an ally of this player

bool owns(Unit &unit) const

this player owns the specified unit

void receive(const ResourceBundle &amount)

add to stockpile

void receive(const game_resource resource, double amount)
bool can_receive(const ResourceBundle &amount) const

Check if can add to stockpile.

bool can_receive(const game_resource resource, double amount) const
bool deduct(const ResourceBundle &amount)

remove from stockpile if available

bool deduct(const game_resource resource, double amount)
bool can_deduct(const ResourceBundle &amount) const

Check if the player has enough resources to deduct the given amount.

bool can_deduct(const game_resource resource, double amount) const
double amount(const game_resource resource) const

current stockpile amount

bool can_make(const UnitType &type) const

Check if the player can make a new unit of the given type.

size_t type_count()

total number of unit types available

UnitType *get_type(index_t type_id) const

unit types by aoe gamedata unit ids the unit type which corresponds to an aoe unit id

UnitType *get_type_index(size_t type_index) const

unit types by list index a continuous array of all types probably not a useful function / can be removed

void initialise_unit_types()

initialise with the base tech level

void active_unit_added(Unit *unit, bool from_pending = false)

Called when a unit is created and active.

If the unit was pending when create (constuction site, training) the method must be called again when the unit activates (with the from_penging param set to true)

void active_unit_removed(Unit *unit)

Called when a unit is destroyed.

void killed_unit(const Unit &unit)

Called when a unit is killed by this player.

void advance_age()

Advance to next age;.

int get_units_have(int type_id) const

Get the number of units the player has for each unit type id.

int get_units_had(int type_id) const

Get the number of units the player ever had for each unit type id.

int get_units_pending(int type_id) const

Get the number of units the player has being made for each unit type id.

int get_age() const

Get the current age.

The first age has the value 1.

int get_workforce_count() const

The number of units considered part of the workforce.

Public Members

const unsigned int player_number

values 0 .

. player count - 1

const unsigned int color

values 1 .

. player count would be better to have rgb color value

const Civilisation *civ

civilisation and techs of this player

const std::string name

visible name of this player

Team *team

the team of this player nullptr if member of no team

PopulationTracker population

Keeps track of the population information.

PlayerScore score

The score of the player.

Private Functions

bool is_unit_pending(Unit *unit) const
void on_resources_change()

Called when the resources amounts change.

Private Members

ResourceBundle resources

The resources this player currently has.

ResourceBundle resources_capacity

The resources capacities this player currently has.

unit_type_list available_objects

unit types which can be produced by this player.

TODO revisit, can be simplified?

std::unordered_map<index_t, UnitType *> available_ids

available objects mapped using type id unit ids -> unit type for that id TODO revisit, can be simplified?

std::unordered_map<int, int> units_have

The number of units the player has for each unit type id.

Used for and event triggers.

std::unordered_map<int, int> units_had

The number of units the player ever had for each unit type id.

Used for unit dependencies (eg. Farm).

std::unordered_map<int, int> units_pending
int age

The current age.

class PlayerScore : public openage::Score
#include <score.h>

The score of a player.

Public Functions

PlayerScore(Player *player)
void update_score()

Calculates the total score from the sub-scores.

TODO update gui here

Private Members

Player *player
class PopulationTracker
#include <population_tracker.h>

Keeps track of the population size and capacity.

Public Functions

PopulationTracker(int capacity_static, int capacity_max)
void demand_population(int i)

Add to the population demand.

void free_population(int i)

Remove from the population demand.

void add_capacity_static(int i)

Changes the capacity given by civ bonuses.

void add_capacity(int i)

Add to the capacity given by units.

void remove_capacity(int i)

Remove from the capacity given by units.

void add_capacity_max(int i)

Changes the max capacity given by civ bonuses.

int get_demand() const
int get_capacity() const
int get_space() const

Returns the available population capacity for new units.

int get_capacity_overflow() const

Returns the population capacity over the max limit.

bool is_capacity_maxed() const

Check if the population capacity has reached the max limit.

Private Functions

void update_capacity()

Calculates the capacity values based on the limits.

Must be called when a capacity variable changes.

Private Members

int demand

The population demand.

int capacity_static

The population capacity given by civ bonuses.

int capacity_real

The population capacity given by units.

int capacity_max

The max population capacity.

int capacity_total

All the population capacity without the limitation.

int capacity

All the population capacity with the limitation.

class ProjectileAction : public openage::UnitAction
#include <action.h>

moves object to fly in a parabolic shape

Public Functions

ProjectileAction(Unit *e, coord::phys3 target)
~ProjectileAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

Private Members

double grav
bool has_hit
class ProjectileProducer : public openage::UnitType
#include <producer.h>

creates projectiles todo use MovableProducer as base class

Public Functions

ProjectileProducer(const Player &owner, const GameSpec &spec, const gamedata::missile_unit *pd)
~ProjectileProducer()
int id() const

gets the unique id of this unit type

int parent_id() const

gets the parent id of this unit type which is used for village base and gather types

std::string name() const

gets the name of the unit type being produced

void initialise(Unit *, Player&)

Initialize units attributes to this type spec.

This can be called using existing units to modify type Ensure that the unit has been placed before seting the units type

TODO: make const

TerrainObject *place(Unit *, std::shared_ptr<Terrain>, coord::phys3) const

set unit in place return if placement was successful

This should be used when initially creating a unit or when a unit is ungarrsioned from a building or object TODO: make const

Private Members

const gamedata::missile_unit unit_data
std::shared_ptr<Texture> terrain_outline
std::shared_ptr<UnitTexture> tex
std::shared_ptr<UnitTexture> sh
std::shared_ptr<UnitTexture> destroyed
template<typename ReturnType, typename ...ArgTypes>
class Func
#include <functional.h>

Holds a function pointer, with bound arguments.

Can be filled via its implicit copy constructor, operator = or bind().

operator = is designed for usage from C++, and accepts set() sets it to an existing std::function object one of its bind() members.

It’s auto-converted to std::function, and can be called via call().

Designed to allow Cython to call C++ functions that accept std::function callbacks, and to provide a callback function type for Cython to offer to C++.

As of right now, Cython doesn’t support variadic templates [https://mail.python.org/pipermail/cython-devel/2015-June/004429.html].

Thus, Func has aliases to allow usage like regular templated types, one for each number of arguments:

from libopenage.pyinterface.functional import Func2 void myfunc(float a0, int a1, int a2): pass Func2[void, int, int] fobj Func2.bind1float

There are definitions up to Func5 and bind3; if you encounter a situation where you’d need more, maybe you should re-think some of your life choices.

Note that you shouldn’t use this type purely internally in Cython, since if you bind a Cython function and call it from Cython, every Exception would be needlessly converted from Py to C++ to Py…

For global function pointers that should be initialized at pyinterface initialization time, use PyIfFunc instead of Func; that class has some additional code to verify successful initialization.

Public Functions

Func()
template<typename F>
Func(F &&f)
template<typename F>
Func(std::reference_wrapper<F> f)
Func(const std::function<ReturnType(ArgTypes...)> &f)
Func(std::function<ReturnType(ArgTypes...)> &&f)
template<typename F>
Func<ReturnType, ArgTypes...> &operator=(F &&f)
template<typename F>
Func<ReturnType, ArgTypes...> &operator=(std::reference_wrapper<F> f)
Func<ReturnType, ArgTypes...> &operator=(const std::function<ReturnType(ArgTypes...)> &f)
Func<ReturnType, ArgTypes...> &operator=(std::function<ReturnType(ArgTypes...)> &&f)
void check_fptr() const

raises an Error if this->fptr is still uninitialized.

ReturnType call(ArgTypes... args) const

for direct usage (mostly from Cython)

openage::pyinterface::Func::operator const std::function< ReturnType(ArgTypes ...) const&

for implicit conversion to std::function, for usage in a context where std::function would be expected.

const std::function<ReturnType(ArgTypes...)> &get() const

for explicit conversion to std::function.

template<typename ...BoundArgTypes>
void bind(util::FunctionPtr<ReturnType, BoundArgTypes..., ArgTypes...> f, BoundArgTypes... bound_args)

For manual binding of function pointers and arguments (from Cython; in C++, assign lambdas).

Adds additional code that catches and converts Python exceptions to C++ exceptions.

The ‘util::FunctionPtr’ argument is due to http://stackoverflow.com/questions/31040075. Note that with clang, it’s possible to directly pass function pointers, while with gcc they need to be explicitly converted. Meh.

template<typename ...BoundArgTypes>
void bind_noexcept(util::FunctionPtr<ReturnType, BoundArgTypes..., ArgTypes...> f, BoundArgTypes... bound_args)

Like bind, but does not add an exception checker.

void bind0(ReturnType (*f)(ArgTypes...))
void bind_noexcept0(ReturnType (*f)(ArgTypes...))
template<typename BoundArgType0>
void bind1(ReturnType (*f)(BoundArgType0, ArgTypes...), BoundArgType0 bound_arg0, )
template<typename BoundArgType0>
void bind_noexcept1(ReturnType (*f)(BoundArgType0, ArgTypes...), BoundArgType0 bound_arg0, )
template<typename BoundArgType0, typename BoundArgType1>
void bind2(ReturnType (*f)(BoundArgType0, BoundArgType1, ArgTypes...), BoundArgType0 bound_arg0, BoundArgType1 bound_arg1, )
template<typename BoundArgType0, typename BoundArgType1>
void bind_noexcept2(ReturnType (*f)(BoundArgType0, BoundArgType1, ArgTypes...), BoundArgType0 bound_arg0, BoundArgType1 bound_arg1, )
template<typename BoundArgType0, typename BoundArgType1, typename BoundArgType2>
void bind3(ReturnType (*f)(BoundArgType0, BoundArgType1, BoundArgType2, ArgTypes...), BoundArgType0 bound_arg0, BoundArgType1 bound_arg1, BoundArgType2 bound_arg2, )
template<typename BoundArgType0, typename BoundArgType1, typename BoundArgType2>
void bind_noexcept3(ReturnType (*f)(BoundArgType0, BoundArgType1, BoundArgType2, ArgTypes...), BoundArgType0 bound_arg0, BoundArgType1 bound_arg1, BoundArgType2 bound_arg2, )

Private Functions

template<bool return_type_is_void, typename ...BoundArgTypes>
std::enable_if<return_type_is_void>::type bind_catchexcept_impl(util::FunctionPtr<ReturnType, BoundArgTypes..., ArgTypes...> f, BoundArgTypes... bound_args)

Specialization for bind() with void return types.

template<bool return_type_is_void, typename ...BoundArgTypes>
std::enable_if<not return_type_is_void>::type bind_catchexcept_impl(util::FunctionPtr<ReturnType, BoundArgTypes..., ArgTypes...> f, BoundArgTypes... bound_args)

Specialization for bind() with non-void return types.

Private Members

std::function<ReturnType(ArgTypes...)> fptr
class PyException : public openage::error::Error
#include <pyexception.h>

Thrown by translate_exc_py_to_cpp() from exctranslate.h.

These objects are constructed entirely empty, and designed to be filled from describe_py_exception().

pxd:

cppclass PyException(Error): PyObjectRef py_obj void init_backtrace() except +

Public Functions

std::string type_name() const

Returns the type name of py_obj.

void init_backtrace()

Initializes this->backtrace with a PyExceptionBacktrace object that points at this->py_obj->get_ref().

Public Members

PyObjectRef py_obj

Reference to the Python exception object.

class PyExceptionBacktrace : public openage::error::Backtrace
#include <pyexception.h>

An implementation of the abstract Backtrace class that does not collect Backtrace information itself, but instead determines the data on the fly from a Python Exception object.

Public Functions

PyExceptionBacktrace(PyObject *ref)

ref is a raw reference to the associated PyObject.

void get_symbols(std::function<void(const error::backtrace_symbol *)> cb, bool reversed, ) const

Accesses the associated Python exception object to translate the traceback as needed.

Private Members

PyObject *ref
template<typename ReturnType, typename ...ArgTypes>
class PyIfFunc : public openage::pyinterface::Func<ReturnType, ArgTypes...>
#include <functional.h>

For usage by “Py Interface Functions”, i.e.

empty global function pointers in libopenage that get filled by Cython at initialization time.

Use only for global objects that have associated symbol names (this is enforced).

The interface for PyIfFunc is identical to that of Func, so we’ll simply typedef them to avoid the redundant pxd lines from above.

pxd:

ctypedef Func0 PyIfFunc0 ctypedef Func1 PyIfFunc1 ctypedef Func2 PyIfFunc2 ctypedef Func3 PyIfFunc3 ctypedef Func4 PyIfFunc4 ctypedef Func5 PyIfFunc5

Public Functions

PyIfFunc()
~PyIfFunc()
PyIfFunc(const PyIfFunc<ReturnType, ArgTypes...> &other)
PyIfFunc(PyIfFunc<ReturnType, ArgTypes...> &&other)
PyIfFunc<ReturnType, ArgTypes...> &operator=(const PyIfFunc<ReturnType, ArgTypes...> &other)
PyIfFunc<ReturnType, ArgTypes...> &operator=(PyIfFunc<ReturnType, ArgTypes...> &&other)
operator Func<ReturnType, ArgTypes...>&() const
class PyObjectRef
#include <pyobject.h>

Holds a Python object, as a PyObject * pointer.

Reference counting (Py_INCREF and Py_DECREF) is correctly performed in the various copy/move constructors/operators.

pxd:

cppclass PyObjectRef: PyObjectRef() noexcept PyObjectRef(PyObject *ref) except +

PyObject *get_ref() noexcept void set_ref(PyObject *ref) except + void set_ref_without_incrementing(PyObject *ref) except + void clear_ref_without_decrementing() noexcept

ctypedef PyObjectRef PyObj

ctypedef PyObjectRef *PyObjectRefPtr ctypedef PyObject *PyObjectPtr

Public Functions

PyObjectRef()

Initializes reference with nullptr.

PyObjectRef(PyObject *ref)

Wraps a raw PyObject * pointer (calls Py_INCREF).

PyObjectRef(const PyObjectRef &other)

Clones a PyObjectRef (calls Py_INCREF).

PyObjectRef(PyObjectRef &&other)

Move-constructs from an other PyObjectRef.

PyObjectRef &operator=(const PyObjectRef &other)

Assigns from an other PyObjectRef (calls Py_XDECREF on the old value, and Py_XINCREF on the new one).

PyObjectRef &operator=(PyObjectRef &&other)

Move-assigns from an other PyObject (calls Py_XDECREF on the old value).

~PyObjectRef()

Destroys the object, calls Py_XDECREF.

std::string str() const

str(obj)

std::string repr() const

repr(obj)

std::string bytes() const

bytes(obj)

int len() const

len(obj)

bool callable() const

callable(obj)

template<typename ...Args>
PyObjectRef call(Args... args) const

obj(args…)

PyObjectRef getattr(const std::string &name) const

getattr(obj, name)

bool hasattr(const std::string &name) const

hasattr(obj, name)

void setattr(const std::string &name, const PyObjectRef &attr) const

setattr(obj, name)

bool isinstance(const PyObjectRef &type) const

isinstance(obj, type)

bool to_bool() const

bool(obj)

int64_t to_int() const

int(obj)

void dir(const Func<void, std::string> &callback) const

for elem in dir(obj): callback(elem)

bool is(const PyObjectRef &other) const

obj is other

bool equals(const PyObjectRef &other) const

obj == other

PyObjectRef eval(const std::string &expression) const

eval(expression, obj)

void exec(const std::string &statement) const

exec(statement, obj)

PyObjectRef get(const PyObjectRef &key) const

obj[key]

PyObjectRef get(const std::string &key) const

obj[key]

PyObjectRef get(int key) const

obj[key]

bool in(const PyObjectRef &container) const

obj in container

PyObjectRef type() const

type(obj)

std::string modulename() const

type(obj).__module__

std::string classname() const

type(obj).__name__

PyObject *get_ref() const

Provide the internal PyObject *.

PyObject *operator()() const

Implicit conversion to PyObject *.

Mainly for convenience to avoid all the get_ref() calls.

void set_ref(PyObject *ref)

Like operator =(const PyObjectRef &other).

void set_ref_without_incrementing(PyObject *ref)

Like set_ref, but does NOT call PY_XINCREF.

Only use in special cases, if you know exactly what you’re doing.

void clear_ref_without_decrementing()

Clears the internal reference, but does NOT call PY_XDECREF.

Only use in special cases, if you know exactly what you’re doing.

template<>
PyObjectRef(int number)

Integer conversion.

template<>
PyObjectRef(const char *data)

Bytes conversion.

template<>
PyObjectRef(const std::string &txt)

String conversion.

Private Functions

PyObjectRef call_impl(std::vector<PyObjectRef> &args) const

obj(args)

template<typename T>
PyObjectRef(T arg)

Primary template for PyObjectRef conversions.

Private Members

PyObject *ref

Internal PyObject * for obj.

class RadialObject : public openage::TerrainObject
#include <terrain_object.h>

Represents circular shaped objects (movable game units) can only be constructed by unit->make_location<RadialObject>(…)

Public Functions

~RadialObject()
tile_range get_range(const coord::phys3 &pos, const Terrain &terrain) const

finds the range covered if the object was in a position

coord::phys_t from_edge(const coord::phys3 &point) const

how far is a point from the edge of this object

coord::phys3 on_edge(const coord::phys3 &angle, coord::phys_t extra = 0) const

get a position on the edge of this object

bool contains(const coord::phys3 &other) const

does this space contain a given point

bool intersects(const TerrainObject &other, const coord::phys3 &position) const

would this intersect with another object if it were positioned at the given point

coord::phys_t min_axis() const

the shortest line that can be placed across the objects center

Public Members

const coord::phys_t phys_radius

radius of this cirular space

Private Functions

RadialObject(Unit &u, float rad)
RadialObject(Unit &u, float rad, std::shared_ptr<Texture> out_tex)

Friends

friend openage::RadialObject::TerrainObject
friend openage::RadialObject::Unit
struct reference_data
#include <unit_container.h>

immutable reference data

Public Functions

reference_data(const UnitContainer *c, id_t id, Unit *u)

Public Members

const UnitContainer *const container
const id_t unit_id
Unit *const unit_ptr
class Region
#include <generator.h>

A region is a set of tiles around a starting point, including functions to create child regions.

Public Functions

Region(int size)

a square of tiles ranging from {-size, -size} to {size, size}

Region(coord::tile center, tileset_t tiles)

a specified set of tiles

tileset_t get_tiles() const

all tiles in this region

coord::tile get_center() const

the center point of the region

coord::tile get_tile(rng::RNG &rng) const

picks a random tile from this subset

tileset_t subset(rng::RNG &rng, coord::tile start_tile, unsigned int number, double p) const

find a group of tiles inside this region, number is the number of tiles to be contained in the subset, p is a probability between 0.0 and 1.0 which produces various shapes.

a value of 1.0 produces circular shapes, where as a low value produces more scattered shapes. a value of 0.0 should not be used, and will always return no tiles

Region take_tiles(rng::RNG &rng, coord::tile start_tile, unsigned int number, double p)

removes the given set of tiles from this region, which get split of as a new child region

Region take_random(rng::RNG &rng, unsigned int number, double p)

similiar to take_tiles, but takes a random group of tiles

Public Members

int owner

player id of the owner, 0 for none

int object_id

the object to be placed on each tile of this region 0 for placing no object

int terrain_id

the base terrain for this region

Private Members

coord::tile center

the center tile of this region

tileset_t tiles

tiles in this region

class Color
#include <color.h>

Public Functions

Color()
Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
bool operator==(const Color &other) const
bool operator!=(const Color &other) const

Public Members

uint8_t r
uint8_t g
uint8_t b
uint8_t a
class Colors
#include <color.h>

Public Static Attributes

Color WHITE = {255, , , }
Color BLACK = {0, , , }
class Font
#include <font.h>

Public Functions

Font(const font_description &description)

Create a font instance from the description.

Parameters
  • description: the font description.

Font(FontManager *font_manager, const font_description &description)

This constructor is used by the font manager to create a new font instance from the description.

Parameters
  • font_manager: The font manager.

  • description: the font description.

~Font()
float get_ascender() const

Get the typographic ascender of font.

Return

The ascender of font.

float get_descender() const

Get the typographic descender of font.

Return

The descender of font.

float get_line_height() const

Get the line spacing of font.

Return

The font’s line height.

float get_horizontal_kerning(codepoint_t left_glyph, codepoint_t right_glyph) const

Get the kerning adjustment between two glyphs.

Return

The kerning adjustment.

Parameters
  • left_glyph: The first glyph.

  • right_glyph: The next glyph.

float get_advance_width(const std::string &text) const

Get the advance width of a particular string.

Return

The advance width of the specified string.

Parameters
  • text: The string for which the width is to be determined.

std::vector<codepoint_t> get_glyphs(const std::string &text) const

Get the list of glyphs for a particular string.

Return

The list of the glyphs.

Parameters
  • text: the string for which the glyphs are to be retrieved.

std::unique_ptr<unsigned char[]> load_glyph(codepoint_t codepoint, Glyph &glyph) const

Load a particular glyph’s info and retrieves the glyph’s bitmap data.

Return

The glyph’s bitmap data.

Parameters
  • codepoint: The glyph.

  • glyph: The glyph’s info is loaded in to this object.

Public Members

font_description description

The description of the font.

See

font_description

Private Functions

void initialize(FT_Library ft_library)

Initializes the font’s face and creates a harfbuzz font instance.

Parameters
  • ft_library: The freetype library that should be used to load the font’s face.

Private Members

std::unique_ptr<FreeTypeLibrary> freetype_library
hb_font_t *hb_font
struct font_description
#include <font.h>

Description for a font.

An instance of font_description is capable of uniquely distinguishing a font.

Public Functions

font_description(const std::string &font_file, unsigned int size, font_direction direction = font_direction::left_to_right, const std::string &language = "en", const std::string &script = "Latn")

Constructs a font_description instance.

Parameters
  • font_file: The path to fon’t font.

  • size: The size of the font in points.

  • direction: The direction of font.

  • language: The font’s language.

  • script: The font’s script.

font_description(const char *family, const char *style, unsigned int size)

Constructs a font_description instance.

This constructor uses fontconfig to determine a font file for the specified font family and style.

Parameters
  • family: The font family.

  • style: The font style.

  • size: The size of the font in points.

font_description(const font_description &other)
font_description &operator=(const font_description &other)
bool operator==(const font_description &other) const
bool operator!=(const font_description &other) const

Public Members

std::string font_file

Path to the font’s file.

unsigned int size

Points size of the font.

font_direction direction

The direction of the font.

std::string language

Language of the font.

std::string script

The font’s script.

class FontManager
#include <font_manager.h>

Public Functions

FontManager()
~FontManager()
FT_Library get_ft_library()

Get the freetype library instance.

Font *get_font(const char *family, const char *style, unsigned int size)

Retrieves a font.

Return

The pointer to font instance.

Parameters
  • family: The font family.

  • style: The font style.

  • size: The size of the font in points.

Font *get_font(const char *font_file, unsigned int size)

Retrieves a font.

Return

The pointer to font instance.

Parameters
  • font_file: The path to font’s file.

  • size: The size of the font in points.

Public Static Functions

std::string get_font_filename(const char *family, const char *style)

Gets the filepath of a particular font family and style.

Return

The path to font’s file.

Parameters
  • family: The font family.

  • style: The font style.

Private Members

FreeTypeLibrary library
std::unordered_map<size_t, std::unique_ptr<Font>> fonts
class FreeTypeLibrary
#include <font_manager.h>

Public Functions

FreeTypeLibrary()
~FreeTypeLibrary()
FreeTypeLibrary(const FreeTypeLibrary &copy)
FreeTypeLibrary &operator=(const FreeTypeLibrary &copy)
FreeTypeLibrary(FreeTypeLibrary &&other)
FreeTypeLibrary &operator=(FreeTypeLibrary &&other)

Public Members

FT_Library ft_library
class Geometry
#include <geometry.h>

A class representing geometry to be passed to a draw call.

Subclassed by openage::renderer::opengl::GlGeometry

Public Functions

virtual ~Geometry()
geometry_t get_type() const

Returns the type of this geometry.

void update_verts(std::vector<uint8_t> const &verts)

In a meshed geometry, updates the vertex data.

The size and type of the vertex data has to be the same as before. If the mesh is indexed, indices will stay the same.

Exceptions
  • if: there is a size mismatch between the new and old vertex data

virtual void update_verts_offset(std::vector<uint8_t> const &verts, size_t offset) = 0

In a meshed geometry, updates the vertex data starting from the offset-th vertex.

The type of the vertex data has to be the same as it was on initializing the geometry. The size plus the offset cannot exceed the previous size of the vertex data. If the mesh is indexed, indices will stay the same.

Exceptions
  • if: there is a size mismatch between the new and old vertex data

Protected Functions

Geometry(geometry_t type)

Initialize the geometry to a given type.

Private Members

geometry_t type
class Glyph
#include <font.h>

Holds info about a single glyph.

Public Members

codepoint_t codepoint

Glyph’s codepoint.

int x_offset

Horizontal distance from origin (current pen position) to glyph’s leftmost boundary.

int y_offset

Vertical distance from the baseline to glyph’s topmost boundary.

unsigned int width

Width of the glyph.

unsigned int height

Height of the glyph.

float x_advance

Advance width of the glyph.

float y_advance

Advance height of the glyph.

class GlyphAtlas
#include <glyph_atlas.h>

A glyph atlas is used to pack and manage several font glyphs in to a single OpenGL texture.

A single glyph atlas can be used to stored glyphs from multiple fonts.

Currently, the glyph atlas uses a naive “Shelf First-Fit” algorithm based on the article “A Thousand Ways to Pack the Bin - A Practical Approach to Two-Dimensional Rectangle Bin Packing” by Jukka Jylänki. The article can be found at http://clb.demon.fi/files/RectangleBinPack.pdf

This is a very basic algorithm. If there is a need for a more complex packing requirement, the glyph atlas can be easily modified.

Public Functions

GlyphAtlas(int width = 1024, int height = 1024)

Creates a glyph atlas with the specified width and height.

Also, creates a OpenGL texture of the same width and height. The contents of this glyph atlas is automatically synchronized to the texture (when you bind the texture).

Parameters
  • width: The width of glyph atlas

  • height: The height of glyph atlas

~GlyphAtlas()
void bind(int unit = 0)

Binds the OpenGL texture of this glyph atlas at the specified unit.

Parameters
  • unit: the texture unit.

GlyphAtlas::Entry get(Font *font, codepoint_t codepoint)

Retrieves the atlas entry for a specified font and glyph.

If the particular entry does not exist in the atlas, the glyph atlas requests the font to provide the glyph info. The provided info along with the glyph’s bitmap data is used to create a new cached entry. This entry is then returned.

Return

The atlas entry.

Parameters
  • font: The font

  • codepoint: The glyph whose atlas entry must be retrieved

Private Functions

size_t get_cache_key(Font *font, codepoint_t codepoint) const
GlyphAtlas::Entry set(size_t key, const Glyph &glyph, const unsigned char *image)
void update_dirty_area(int x, int y, int width, int height)

Private Members

int width
int height
bool is_dirty
dirty_rect dirty_area
std::unique_ptr<unsigned char> buffer
unsigned int texture_id
std::unordered_map<size_t, GlyphAtlas::Entry> glyphs
std::vector<GlyphAtlas::Shelf> shelves
struct dirty_rect

Public Members

int x1
int y1
int x2
int y2
class Entry
#include <glyph_atlas.h>

Datastructure for a single atlas entry.

Public Members

Glyph glyph

The Glyph.

float u0

The bottom-left texture coordinate in u-axis.

float v0

The bottom-left texture coordinate in v-axis.

float u1

The top-right texture coordinate in u-axis.

float v1

The top-right texture coordinate in v-axis.

class Shelf

Public Functions

Shelf(int position, int width, int height)
bool check_fits(int required_width, int required_height)
int reserve(int required_width, int required_height)

Private Members

int y_position
int width
int height
int remaining_width

Friends

friend openage::renderer::GlyphAtlas::Shelf::GlyphAtlas
struct gl_context_capabilities
#include <context.h>

Stores information about context capabilities and limitations.

Public Members

size_t max_vertex_attributes

The maximum number of vertex attributes in a shader.

size_t max_texture_slots

The amount of texture units (GL_TEXTUREi) available.

size_t max_texture_size

The maximum size of a single dimension of a texture.

size_t max_uniform_buffer_bindings

The maximum number of binding points for uniform blocks in a single shader.

int major_version
int minor_version
class GlBuffer : public openage::renderer::opengl::GlSimpleObject
#include <buffer.h>

Represents an OpenGL buffer of memory allocated on the GPU.

Public Functions

GlBuffer(size_t size, GLenum usage = GL_STATIC_DRAW)

Creates an empty buffer of the specified size.

Binds the GL_COPY_WRITE_BUFFER target.

GlBuffer(const uint8_t *data, size_t size, GLenum usage = GL_STATIC_DRAW)

Creates a buffer of the specified size and fills it with the given data.

Binds the GL_COPY_WRITE_BUFFER target.

size_t get_size() const

The size in bytes of this buffer.

void upload_data(const uint8_t *data, size_t offset, size_t size)

Uploads size bytes of new data starting at offset.

offset + size has to be less than or equal to get_size(). Binds the GL_COPY_WRITE_BUFFER target.

void bind(GLenum target) const

Bind this buffer to the specified GL target.

Private Members

size_t size

The size in bytes of this buffer.

class GlContext
#include <context.h>

Manages an OpenGL context.

Public Functions

GlContext(SDL_Window *window)

Create a GL context in the given SDL window.

~GlContext()
GlContext(const GlContext&)

It doesn’t make sense to have more than one instance of the same context.

GlContext &operator=(const GlContext&)
GlContext(GlContext &&other)

We have to support moving to avoid a mess somewhere else.

GlContext &operator=(GlContext &&other)
SDL_GLContext get_raw_context() const

Returns the underlying SDL context pointer.

gl_context_capabilities get_capabilities() const

Returns the capabilities of this context.

void set_vsync(bool on)

Turns VSYNC on or off for this context.

Public Static Functions

void check_error()

Checks whether the current GL context on this thread reported any errors and throws an exception if it did.

Note that it’s static.

Private Members

SDL_GLContext gl_context

Pointer to SDL struct representing the GL context.

gl_context_capabilities capabilities = {}

Context capabilities.

class GlFramebuffer : public openage::renderer::opengl::GlSimpleObject
#include <framebuffer.h>

Represents an OpenGL Framebuffer Object.

It is a collection of bitmap targets that can be drawn into and read from.

Public Functions

GlFramebuffer(std::vector<const GlTexture2d *> textures)

Construct a framebuffer pointing at the given textures.

Texture are attached to points specific to their pixel format, e.g. a depth texture will be set as the depth target.

void bind_read() const

Bind this framebuffer to GL_READ_FRAMEBUFFER.

void bind_write() const

Bind this framebuffer to GL_DRAW_FRAMEBUFFER.

class GlGeometry : public openage::renderer::Geometry
#include <geometry.h>

The OpenGL class representing geometry to be passed to a draw call.

Public Functions

GlGeometry()

The default constructor makes a quad.

GlGeometry(resources::MeshData const &mesh)

Initialize a meshed geometry. Relatively costly, has to initialize GL buffers and copy vertex data.

void draw() const

Executes a draw command for the geometry on the currently active context.

Assumes bound and valid shader program and all other necessary state.

void update_verts_offset(std::vector<uint8_t> const &verts, size_t offset)

In a meshed geometry, updates the vertex data starting from the offset-th vertex.

The type of the vertex data has to be the same as it was on initializing the geometry. The size plus the offset cannot exceed the previous size of the vertex data. If the mesh is indexed, indices will stay the same.

Exceptions
  • if: there is a size mismatch between the new and old vertex data

Private Members

std::optional<GlMesh> mesh

Data managing GPU memory and interpretation of mesh data.

Only present if the type is a mesh.

struct GlMesh

All the pieces of OpenGL state that represent a mesh.

Public Members

GlBuffer vertices
GlVertexArray vao
std::optional<GlBuffer> indices
std::optional<GLenum> index_type
size_t vert_count
GLenum primitive
class GlRenderer : public openage::renderer::Renderer
#include <renderer.h>

The OpenGL specialization of the rendering interface.

Public Functions

GlRenderer(GlContext *ctx)
std::unique_ptr<Texture2d> add_texture(resources::Texture2dData const&)

Uploads the given texture data (usually loaded from disk) to graphics hardware and makes it available as a Texture object that can be used for various operations.

std::unique_ptr<Texture2d> add_texture(resources::Texture2dInfo const&)

Creates a new empty texture with the given parameters on the graphics hardware.

std::unique_ptr<ShaderProgram> add_shader(std::vector<resources::ShaderSource> const&)

Compiles the given shader source code into a shader program.

A shader program is the main tool used for graphics rendering.

std::unique_ptr<Geometry> add_mesh_geometry(resources::MeshData const&)

Creates a Geometry object from the given mesh data, uploading it to the GPU by creating appropriate buffer.

The vertex attributes will be passed to the shader as described in the mesh data.

std::unique_ptr<Geometry> add_bufferless_quad()

Adds a Geometry object that passes a simple 4-vertex drawing command with no vertex attributes to the shader.

Useful for generating positions in the vertex shader.

std::unique_ptr<RenderTarget> create_texture_target(std::vector<Texture2d *>)

Constructs a render target from the given textures.

All subsequent drawing operations pointed at this target will write to these textures. Textures are attached to the target in the order in which they appear within the vector. Depth textures are attached as depth components. Textures of every other type are attached as color components.

RenderTarget const *get_display_target()

Returns the built-in display target that represents the window.

Passes pointed at this target will have their output visible on the screen.

resources::Texture2dData display_into_data()

Stores the display framebuffer into a CPU-accessible data object. Essentially, this takes a screenshot.

void render(RenderPass const&)

Executes a render pass.

Private Members

GlContext *gl_context

The GL context.

GlRenderTarget display
class GlRenderTarget : public openage::renderer::RenderTarget
#include <render_target.h>

Represents an OpenGL target that can be drawn into.

It can be either a framebuffer or the display (the window).

Public Functions

GlRenderTarget()

Construct a render target pointed at the default framebuffer - the window.

GlRenderTarget(std::vector<const GlTexture2d *> textures)

Construct a render target pointing at the given textures.

Texture are attached to points specific to their pixel format, e.g. a depth texture will be set as the depth target.

void bind_write() const

Bind this render target to be drawn into.

void bind_read() const

Bind this render target to be read from.

Private Members

gl_render_target_t type
std::optional<GlFramebuffer> framebuffer

For textures target type, the framebuffer.

class GlShader : public openage::renderer::opengl::GlSimpleObject
#include <shader.h>

A single OpenGL shader stage.

Public Functions

GlShader(const resources::ShaderSource &src)

Compiles the shader from the given source.

GLenum get_type() const

Returns the stage of the rendering pipeline this shader defines.

Private Members

GLenum type

Which stage of the rendering pipeline this shader defines.

class GlShaderProgram : public openage::renderer::ShaderProgram, public openage::renderer::opengl::GlSimpleObject
#include <shader_program.h>

A handle to an OpenGL shader program.

Public Functions

GlShaderProgram(const std::vector<resources::ShaderSource> &srcs, const gl_context_capabilities &caps)

Tries to create a shader program from the given sources.

Throws an exception on compile/link errors.

void use()

Bind this program as the currently used one in the OpenGL context.

void execute_with(const GlUniformInput *unif_in, const GlGeometry *geom)

Does what the description of Renderable specifies - updates the uniform values and draws the Geometry if it’s not nullptr.

If geometry is null, only the uniform values are updated.

bool has_uniform(const char *unif)

Returns whether the shader program contains a uniform variable with the given name.

std::map<size_t, resources::vertex_input_t> vertex_attributes() const

Returns a list of active vertex attributes in the shader program.

Active attributes are those which have an effect on the shader output, meaning they are included in the output calculation and are not unused. Inactive attributes may or may not be present in the list - in particular, in the OpenGL implementation they will most likely be missing. The returned value is a map from the attribute location to its type. Locations need not be consecutive.

Protected Functions

std::unique_ptr<UniformInput> new_unif_in()
void set_i32(UniformInput *in, const char *unif, int32_t val)
void set_u32(UniformInput *in, const char *unif, uint32_t val)
void set_f32(UniformInput *in, const char *unif, float val)
void set_f64(UniformInput *in, const char *unif, double val)
void set_v2f32(UniformInput *in, const char *unif, Eigen::Vector2f const &val)
void set_v3f32(UniformInput *in, const char *unif, Eigen::Vector3f const &val)
void set_v4f32(UniformInput *in, const char *unif, Eigen::Vector4f const &val)
void set_m4f32(UniformInput *in, const char *unif, Eigen::Matrix4f const &val)
void set_tex(UniformInput *in, const char *unif, Texture2d const *val)

Private Functions

void set_unif(UniformInput *in, const char *unif, void const *val, GLenum type)

Private Members

std::unordered_map<std::string, GlUniform> uniforms

Maps uniform names to their descriptions.

Contains only uniforms in the default block, i.e. not within named blocks.

std::unordered_map<std::string, GlUniformBlock> uniform_blocks

Maps uniform block names to their descriptions.

std::unordered_map<std::string, GlVertexAttrib> attribs

Maps per-vertex attribute names to their descriptions.

std::unordered_map<std::string, GLuint> texunits_per_unifs

Maps sampler uniform names to their assigned texture units.

std::unordered_map<GLuint, GLuint> textures_per_texunits

Maps texture units to the texture handles that are currently bound to them.

bool validated

Whether this program has been validated.

struct GlInBlockUniform

Represents a uniform in a named block.

Public Members

GLenum type
size_t offset

Offset from the beginning of the block at which this uniform is placed.

size_t size

The size in bytes of the whole uniform.

If the uniform is an array, the size of the whole array.

size_t stride

Only relevant for arrays and matrices.

In arrays, specifies the distance between the start of each element. In row-major matrices, specifies the distance between the start of each row. In column-major matrices, specifies the distance between the start of each column.

size_t count

Only relevant for arrays. The number of elements in the array.

struct GlUniform

Represents a uniform in the default block, i.e. not within a named block.

Public Members

GLenum type
GLuint location

Location of the uniform for use with glUniform and glGetUniform.

NOT the same as the uniform index.

struct GlUniformBlock

Represents a uniform block in the shader program.

Public Members

GLuint index
size_t data_size

Size of the entire block.

How uniforms are packed within depends on the block layout and is described in corresponding GlUniforms.

std::unordered_map<std::string, GlInBlockUniform> uniforms

Maps uniform names within this block to their descriptions.

GLuint binding_point

The binding point assigned to this block.

struct GlVertexAttrib

Represents a per-vertex input to the shader program.

Public Members

GLenum type
GLint location
GLint size
class GlSimpleObject
#include <simple_object.h>

A base class for all classes representing OpenGL Objects to inherit from.

It allows moving the object, but not copying it through the copy constructor. It has unique_ptr-like semantics. It is called ‘simple’, because in the future we might want to add collections of objects and similar more advanced features.

Subclassed by openage::renderer::opengl::GlBuffer, openage::renderer::opengl::GlFramebuffer, openage::renderer::opengl::GlShader, openage::renderer::opengl::GlShaderProgram, openage::renderer::opengl::GlTexture2d, openage::renderer::opengl::GlTexture2dArray, openage::renderer::opengl::GlVertexArray

Public Functions

GlSimpleObject(GlSimpleObject &&other)
GlSimpleObject &operator=(GlSimpleObject &&other)
GlSimpleObject(GlSimpleObject const&)
GlSimpleObject &operator=(GlSimpleObject const&)
~GlSimpleObject()

Uses delete_fun to destroy the underlying object, but only if the handle is present (hasn’t been moved out).

GLuint get_handle() const

Returns the handle to the underlying OpenGL Object.

Protected Functions

GlSimpleObject(std::function<void(GLuint)> delete_fun)

Protected Attributes

std::optional<GLuint> handle

The handle to the OpenGL Object that this class represents.

std::function<void(GLuint)> delete_fun

The function that deletes the underlying OpenGL Object.

class GlTexture2d : public openage::renderer::Texture2d, public openage::renderer::opengl::GlSimpleObject
#include <texture.h>

A handle to an OpenGL texture.

Public Functions

GlTexture2d(const resources::Texture2dData &data)

Constructs a texture and fills it with the given data.

GlTexture2d(resources::Texture2dInfo const &info)

Constructs an empty texture with the given parameters.

resources::Texture2dData into_data()

Copies this texture’s data from graphics hardware into a CPU-accessible Texture2dData buffer.

void upload(resources::Texture2dData const&)

Uploads the provided data into the GPU texture storage.

The format has to match the format this Texture was originally created with.

class GlTexture2dArray : public openage::renderer::Texture2dArray, public openage::renderer::opengl::GlSimpleObject
#include <texture_array.h>

An OpenGL array of 2D textures.

Public Functions

GlTexture2dArray(const std::vector<resources::Texture2dData> &data)

Constructs an array of the same number of layers as the size of the given vector, and fills the layers with the corresponding vector element.

The texture formats in all vector elements must be the same as defined by Textur2dInfo::operator==.

GlTexture2dArray(size_t n_layers, resources::Texture2dInfo const &layer_info)

Constructs an array of ln_layers empty layers, with the per-layer texture format specified in layer_info.

void upload(size_t layer, resources::Texture2dData const&)

Uploads the given texture data into the specified layer.

layer must be strictly less than the size of the array and the data format must match the format this array was originally created with.

Private Members

size_t n_layers

The number of layers (elements) in the array, AKA the depth.

struct GlUniformInput : public openage::renderer::UniformInput
#include <uniform_input.h>

Describes OpenGL-specific uniform valuations.

Public Members

GlShaderProgram *program

The program that this was created for.

std::unordered_map<std::string, size_t> update_offs

We store uniform updates lazily.

They are only actually uploaded to GPU when a draw call is made. Update_offs maps the uniform names to where their value is in update_data in terms of a byte-wise offset. This is only a partial valuation, so not all uniforms have to be present here.

std::vector<uint8_t> update_data

Buffer containing untyped uniform update data.

class GlVertexArray : public openage::renderer::opengl::GlSimpleObject
#include <vertex_array.h>

An OpenGL Vertex Array Object.

It represents a mapping between a buffer that contains vertex data and a way for the context to interpret it.

class GlWindow : public openage::renderer::Window
#include <window.h>

Public Functions

GlWindow(const char *title, size_t width, size_t height)

Create a shiny window with the given title.

~GlWindow()
void set_size(size_t width, size_t height)

Force the window to the given size.

It’s generally not a good idea to use this, as it makes the window jump around wierdly.

void update()

Polls for window events, calls callbacks for these events, swaps front and back framebuffers to present graphics onto screen.

This has to be called at the end of every graphics frame.

std::unique_ptr<Renderer> make_renderer()

Creates a renderer which uses the window’s graphics API and targets the window.

void make_context_current()

Make this window’s context the current rendering context of the current thread.

Only use this and most other GL functions on a dedicated window thread.

opengl::GlContext *get_context()

Return a pointer to this window’s GL context.

Private Members

SDL_Window *window

The SDL struct representing this window.

std::optional<opengl::GlContext> context

The window’s OpenGL context.

It’s optional because it can’t be constructed immediately, but after the constructor runs it’s guaranteed to be available.

struct Renderable
#include <renderer.h>

A renderable is a set of shader uniform inputs and a possible draw call.

When a renderable is parsed, the uniform inputs are first passed to the shader they were created with. Then, if the geometry is not nullptr, the shader is executed with the geometry and the specified settings and the results are written into the render target. If the geometry is nullptr, the uniform values are uploaded to the shader but no draw call is performed. This can be used to, for example, first set the values of uniforms that many objects have in common, and then only upload the uniforms that vary between them in each draw call. This works because uniform values in any given shader are preserved across a render pass.

Public Members

UniformInput const *unif_in

Uniform values to be set in the appropriate shader.

Contains a reference to the correct shader, and this is the shader that will be used for drawing if geometry is present.

Geometry const *geometry

The geometry.

It can be a simple primitive or a complex mesh. Can be nullptr to only set uniforms but do not perform draw call.

bool alpha_blending

Whether to perform alpha-based color blending with whatever was in the render target before.

bool depth_test

Whether to perform depth testing and discard occluded fragments.

class Renderer
#include <renderer.h>

The renderer.

This class is used for performing all graphics operations. It is abstract and has implementations for various low-level graphics APIs like OpenGL.

Subclassed by openage::renderer::opengl::GlRenderer

Public Functions

virtual ~Renderer()
virtual std::unique_ptr<Texture2d> add_texture(resources::Texture2dData const&) = 0

Uploads the given texture data (usually loaded from disk) to graphics hardware and makes it available as a Texture object that can be used for various operations.

virtual std::unique_ptr<Texture2d> add_texture(resources::Texture2dInfo const&) = 0

Creates a new empty texture with the given parameters on the graphics hardware.

virtual std::unique_ptr<ShaderProgram> add_shader(std::vector<resources::ShaderSource> const&) = 0

Compiles the given shader source code into a shader program.

A shader program is the main tool used for graphics rendering.

virtual std::unique_ptr<Geometry> add_mesh_geometry(resources::MeshData const&) = 0

Creates a Geometry object from the given mesh data, uploading it to the GPU by creating appropriate buffer.

The vertex attributes will be passed to the shader as described in the mesh data.

virtual std::unique_ptr<Geometry> add_bufferless_quad() = 0

Adds a Geometry object that passes a simple 4-vertex drawing command with no vertex attributes to the shader.

Useful for generating positions in the vertex shader.

virtual std::unique_ptr<RenderTarget> create_texture_target(std::vector<Texture2d *>) = 0

Constructs a render target from the given textures.

All subsequent drawing operations pointed at this target will write to these textures. Textures are attached to the target in the order in which they appear within the vector. Depth textures are attached as depth components. Textures of every other type are attached as color components.

virtual RenderTarget const *get_display_target() = 0

Returns the built-in display target that represents the window.

Passes pointed at this target will have their output visible on the screen.

virtual resources::Texture2dData display_into_data() = 0

Stores the display framebuffer into a CPU-accessible data object. Essentially, this takes a screenshot.

virtual void render(RenderPass const&) = 0

Executes a render pass.

struct RenderPass
#include <renderer.h>

A render pass is a series of draw calls represented by renderables that output into the given render target.

Public Members

std::vector<Renderable> renderables

The renderables to parse and possibly execute.

RenderTarget const *target

The render target to write into.

class RenderTarget
#include <renderer.h>

The abstract base for a render target.

Subclassed by openage::renderer::opengl::GlRenderTarget, openage::renderer::vulkan::VlkFramebuffer

Public Functions

virtual ~RenderTarget()

Protected Functions

RenderTarget()
class MeshData
#include <mesh_data.h>

Public Functions

MeshData(const util::Path&)

Tries to load the mesh data from the specified file.

MeshData(std::vector<uint8_t> &&verts, VertexInputInfo info)

Initializes the mesh data to a custom unindexed vertex vector described by the given info.

MeshData(std::vector<uint8_t> &&verts, std::vector<uint8_t> &&ids, VertexInputInfo info)

Initializes the mesh data to a custom indexed vertex vector described by the given info.

std::vector<uint8_t> const &get_data() const

Returns the raw vertex data.

std::optional<std::vector<uint8_t>> const &get_ids() const

Returns the indices used for indexed drawing if they exist.

VertexInputInfo get_info() const

Returns information describing the vertices in this mesh.

Public Static Functions

MeshData make_quad()

Initializes the mesh data with a simple quadrilateral spanning the whole window space, with (vec2 pos, vec2 uv) vertex format.

Private Members

std::vector<uint8_t> data

The raw vertex data. The size is an integer multiple of the size of a single vertex.

std::optional<std::vector<uint8_t>> ids

The indices of vertices to be drawn if the mesh is indexed.

For array drawing, empty optional.

std::optional<VertexInputInfo> info

Information about how to interpret the data to make vertices.

This is optional because initialization is deferred until the constructor obtains the mesh data e.g. from disk, but it should always be present after construction.

class ShaderSource
#include <shader_source.h>

Stores source code for a part of a shader program.

Public Functions

ShaderSource(shader_lang_t lang, shader_stage_t stage, const util::Path &path)

Obtain shader source code from a file.

ShaderSource(shader_lang_t lang, shader_stage_t stage, std::string &&code)

Obtain shader source code from a string.

std::string const &get_source() const

Returns a view of the shader source code.

This might be text or binary data.

shader_lang_t get_lang() const

Returns the language of this shader source.

shader_stage_t get_stage() const

Returns the stage which this shader source implements.

Private Members

shader_lang_t lang

The source language.

shader_stage_t stage

The implemented stage.

std::string code

The shader source code.

class Texture2dData
#include <texture_data.h>

Stores 2D texture data in a CPU-accessible byte buffer.

Provides methods for loading from and storing onto disk, as well as sending to and receiving from graphics hardware.

Public Functions

Texture2dData(const util::Path &path, bool use_metafile = false)

Create a texture from an image file.

Uses

SDL Image internally. For supported image file types, see the SDL_Image initialization in the engine.
Parameters
  • [in] use_metafile: determines whether the loading should read an accompanying metadata file to split the texture into subtextures

Texture2dData(Texture2dInfo const &info, std::vector<uint8_t> &&data)

Construct by moving the information and raw texture data from somewhere else.

Texture2dData flip_y()

Flips the texture along the Y-axis and returns the flipped data with the same info.

Sometimes necessary when converting between storage modes.

const Texture2dInfo &get_info() const

Returns the information describing this texture data.

const uint8_t *get_data() const

Returns a pointer to the raw texture data, in row-major order.

template<typename T>
T read_pixel(size_t x, size_t y) const

Reads the pixel at the given position and casts it to the given type.

The texture is not read as if it consisted of pixels of the given type, but rather according to its original pixel format, so the coordinates have to be specified according to that.

void store(const util::Path &file) const

Stores this texture data in the given file in the PNG format.

Private Members

Texture2dInfo info

Information about this texture data.

std::vector<uint8_t> data

The raw texture data.

class Texture2dInfo
#include <texture_info.h>

Contains information about a 2D texture surface, without actual texture data.

The class supports subtextures, so that one big texture (“texture atlas”) can contain several smaller images, which can be extracted for rendering one-by-one.

Public Functions

Texture2dInfo(size_t width, size_t height, pixel_format fmt, size_t row_alignment = 1, std::vector<Texture2dSubInfo> &&subs = std::vector<Texture2dSubInfo>())

Constructs a Texture2dInfo with the given information.

Texture2dInfo()
Texture2dInfo(Texture2dInfo const&)
~Texture2dInfo()
bool operator==(Texture2dInfo const &other)

Compares the texture parameters excluding the subtexture information and returns true if they’re equal, false otherwise.

bool operator!=(Texture2dInfo const &other)

See operator==.

std::pair<int32_t, int32_t> get_size() const

Returns the dimensions of the whole texture bitmap.

Return

tuple(width, height)

pixel_format get_format() const

Return

the format of pixels in this texture

size_t get_row_alignment() const

Returns the alignment of texture rows to byte boundaries.

size_t get_row_size() const

Returns the size in bytes of a single row, including possible padding at its end.

size_t get_data_size() const

Returns the size in bytes of the raw pixel data.

It is equal to get_row_size() * get_size().second.

size_t get_subtexture_count() const

Returns the number of available subtextures.

const Texture2dSubInfo &get_subtexture(size_t subid) const

Returns the coordinates of the subtexture with the given ID.

std::pair<int, int> get_subtexture_size(size_t subid) const

Returns the size of the subtexture with the given ID.

std::tuple<float, float, float, float> get_subtexture_coordinates(size_t subid) const

Returns atlas subtexture coordinates.

Return

left, right, top and bottom bounds as coordinates these pick the requested area out of the big texture. returned as floats in range 0.0 to 1.0, relative to the whole surface size.

Private Members

int32_t w

Width and height of this texture.

int32_t h
pixel_format format

The pixel format of this texture.

size_t row_alignment

The alignment of texture rows to byte boundaries.

Can be 1, 2, 4 or 8. There is padding at the end of each row to match the alignment if the row size is not a multiple of the alignment.

std::vector<Texture2dSubInfo> subtextures

Some textures are merged together into texture atlases, large images which contain more than one individual texture.

These are their positions in the atlas.

struct Texture2dSubInfo
#include <texture_subinfo.h>

Describes a position of a (sub)texture within a larger texture.

Used for texture atlases and animations where all frames are within one texture file.

Public Functions

Texture2dSubInfo(const std::string &line)

Initializes the info from a CSV line containing its members.

Texture2dSubInfo(uint32_t x, uint32_t y, uint32_t w, uint32_t h, uint32_t cx, uint32_t cy)

Initializes the info from data.

Texture2dSubInfo()
int fill(const std::string &line)

Needed for compatibility reasons, don’t use this directly.

Public Members

uint32_t x = {}

The subtexture position within the atlas.

uint32_t y = {}
uint32_t w = {}

The subtexture size.

uint32_t h = {}
uint32_t cx = {}

Position of the subtexture’s center within the atlas.

uint32_t cy = {}
class VertexInputInfo
#include <mesh_data.h>

Information about vertex input data - which components a vertex contains and how vertices are laid out in memory.

Public Functions

VertexInputInfo(std::vector<vertex_input_t> inputs, vertex_layout_t layout, vertex_primitive_t primitive)

Initialize an input info for array rendering.

VertexInputInfo(std::vector<vertex_input_t> inputs, vertex_layout_t layout, vertex_primitive_t primitive, index_t index_type)

Initialize an input info for indexed rendering.

void add_shader_input_map(std::unordered_map<size_t, size_t> &&in_map)

Adds a mesh->shader input mapping to the info.

By default, attributes are mapped one-to-one according to their order in the input vector, e.g. (vec2 pos, vec2 uv) maps into (0: vec2 pos, 1: vec2 uv) in the shader. However, if a shader skips indices in the layout or takes its inputs in a different order, this can be specified using the map. The map entries must have the format (index_in_vector, index_in_shader) and will overwrite the default mapping. If an entry for a given index in the vector is missing, that attribute and its data will be skipped.

const std::vector<vertex_input_t> &get_inputs() const

Returns the list of per-vertex inputs.

std::optional<std::unordered_map<size_t, size_t>> const &get_shader_input_map() const

Returns the shader input map or an empty optional if it’s not present.

vertex_layout_t get_layout() const

Returns the layout of vertices in memory.

size_t vert_size() const

Returns the size of a single vertex.

vertex_primitive_t get_primitive() const

Returns the primitive interpretation mode.

std::optional<index_t> get_index_type() const

Returns the type of indices used for indexed drawing, which may not be present if array drawing is used.

Private Members

std::vector<vertex_input_t> inputs

What kind of data the vertices contain and how it is laid out in memory.

std::optional<std::unordered_map<size_t, size_t>> shader_input_map

An optional attribute specifying how vertex inputs in the mesh map to vertex inputs in a given shader, for example to reorder inputs of the form (pos, uv) into a shader that takes in (uv, pos) inputs.

vertex_layout_t layout

How the vertices are laid out in the data buffer.

vertex_primitive_t primitive

The primitive type.

std::optional<index_t> index_type

The type of indices if they exist.

class SDL

A static SDL singleton manager. Used to lazily initialize SDL.

Public Functions

~SDL()

Public Static Functions

static void make_available()

Private Static Attributes

SDL sdl
bool inited = false
class ShaderProgram
#include <shader_program.h>

Subclassed by openage::renderer::opengl::GlShaderProgram

Public Functions

virtual ~ShaderProgram()
void update_uniform_input(UniformInput *)
void update_uniform_input(UniformInput *input, const char *unif, int32_t val)
void update_uniform_input(UniformInput *input, const char *unif, uint32_t val)
void update_uniform_input(UniformInput *input, const char *unif, float val)
void update_uniform_input(UniformInput *input, const char *unif, double val)
void update_uniform_input(UniformInput *input, const char *unif, Eigen::Vector2f const &val)
void update_uniform_input(UniformInput *input, const char *unif, Eigen::Vector3f const &val)
void update_uniform_input(UniformInput *input, const char *unif, Eigen::Vector4f const &val)
void update_uniform_input(UniformInput *input, const char *unif, Texture2d const *val)
void update_uniform_input(UniformInput *input, const char *unif, Texture2d *val)
void update_uniform_input(UniformInput *input, const char *unif, Eigen::Matrix4f const &val)
template<typename T>
void update_uniform_input(UniformInput *, const char *unif, T)
virtual bool has_uniform(const char *unif) = 0

Returns whether the shader program contains a uniform variable with the given name.

template<typename ...Ts>
std::unique_ptr<UniformInput> new_uniform_input(Ts... vals)

Creates a new uniform input (a binding of uniform names to values) for this shader and optionally sets some uniform values.

To do that, just pass two arguments -

  • a string literal and the value for that uniform for any uniform you want to set. For example new_uniform_input(“color”, { 0.5, 0.5, 0.5, 1.0 }, “num”, 5) will set “color” to { 0.5, 0.5, 0.5, 0.5 } and “num” to 5. Types are important here and a type mismatch between the uniform variable and the input might result in an error.

template<typename T, typename ...Ts>
void update_uniform_input(UniformInput *input, const char *unif, T val, Ts... vals)

Updates the given uniform input with new uniform values similarly to new_uniform_input.

For example, update_uniform_input(in, “awesome”, true) will set the “awesome” uniform in addition to whatever values were in the uniform input before.

virtual std::map<size_t, resources::vertex_input_t> vertex_attributes() const = 0

Returns a list of active vertex attributes in the shader program.

Active attributes are those which have an effect on the shader output, meaning they are included in the output calculation and are not unused. Inactive attributes may or may not be present in the list - in particular, in the OpenGL implementation they will most likely be missing. The returned value is a map from the attribute location to its type. Locations need not be consecutive.

Protected Functions

virtual std::unique_ptr<UniformInput> new_unif_in() = 0
virtual void set_i32(UniformInput *, const char *, int32_t) = 0
virtual void set_u32(UniformInput *, const char *, uint32_t) = 0
virtual void set_f32(UniformInput *, const char *, float) = 0
virtual void set_f64(UniformInput *, const char *, double) = 0
virtual void set_v2f32(UniformInput *, const char *, Eigen::Vector2f const&) = 0
virtual void set_v3f32(UniformInput *, const char *, Eigen::Vector3f const&) = 0
virtual void set_v4f32(UniformInput *, const char *, Eigen::Vector4f const&) = 0
virtual void set_m4f32(UniformInput *, const char *, Eigen::Matrix4f const&) = 0
virtual void set_tex(UniformInput *, const char *, Texture2d const *) = 0
struct text_render_task

Public Members

GLenum mode
Color color
unsigned int num_elements
unsigned int offset
struct text_render_vertex

Public Functions

text_render_vertex()
text_render_vertex(float x, float y, float u, float v)

Public Members

float x
float y
float u
float v
class TextRenderer
#include <text.h>

Public Functions

TextRenderer()

Requires a working OpenGL context to create buffer objects.

~TextRenderer()
void set_font(Font *font)

Set the font to be used for the future text draw calls.

Parameters
  • font: the font to be used.

void set_color(const Color &color)

Set the color to be used for the future text draw calls.

Parameters
  • color: the color to be used.

void draw(coord::viewport position, const char *format, ...)

Draw a formatted string at the specified position.

Parameters
  • position: where the text should be displayed.

  • format: the text format

void draw(coord::viewport position, const std::string &text)

Draw text at the specified position.

Parameters
  • position: where the text should be displayed.

  • text: the text to be displayed.

void draw(int x, int y, const std::string &text)

Draw text at the specified position.

Parameters
  • x: the position in x-direction.

  • y: the position in y-direction.

  • text: the text to be displayed.

void render()

Render all the text draw requests made during the frame.

Private Members

Font *current_font
Color current_color
bool is_dirty
std::vector<text_render_batch> render_batches
GlyphAtlas glyph_atlas
GLuint vbo
GLuint ibo
struct text_render_batch

The set of text draw requests with the same font and color.

Public Functions

text_render_batch(Font *font, const Color &color)

Public Members

Font *font
Color color
std::vector<text_render_batch_pass> passes
struct text_render_batch_pass

A single text draw request containing the text and position.

Public Functions

text_render_batch_pass(int x, int y, const std::string &text)

Public Members

int x
int y
std::string text
class Texture2d
#include <texture.h>

An abstract base for a handle to a texture buffer allocated in graphics hardware.

Can be obtained by passing texture data to the renderer.

Subclassed by openage::renderer::opengl::GlTexture2d

Public Functions

~Texture2d()
const resources::Texture2dInfo &get_info() const

Returns the texture information.

virtual resources::Texture2dData into_data() = 0

Copies this texture’s data from graphics hardware into a CPU-accessible Texture2dData buffer.

virtual void upload(resources::Texture2dData const&) = 0

Uploads the provided data into the GPU texture storage.

The format has to match the format this Texture was originally created with.

Protected Functions

Texture2d(const resources::Texture2dInfo &info)

Constructs the base with the given information.

Protected Attributes

resources::Texture2dInfo info

Information about the size, format, etc. of this texture.

class Texture2dArray
#include <texture_array.h>

A texture array, where individual elements are 2D textures.

The array elements are referred to as “layers”, and every layer must have the same format (size, pixel format, etc).

Subclassed by openage::renderer::opengl::GlTexture2dArray

Public Functions

~Texture2dArray()
resources::Texture2dInfo const &get_info() const

Returns information about the layer format.

virtual void upload(size_t layer, resources::Texture2dData const&) = 0

Uploads the given texture data into the specified layer.

layer must be strictly less than the size of the array and the data format must match the format this array was originally created with.

Protected Functions

Texture2dArray(const resources::Texture2dInfo &info)

Constructs the base class.

Protected Attributes

resources::Texture2dInfo layer_info

Information about the size, format, etc. of every layer in this array.

class UniformInput
#include <renderer.h>

The abstract base for uniform input.

Besides the uniform values, it stores information about which shader program the input was created for.

Subclassed by openage::renderer::opengl::GlUniformInput

Public Functions

virtual ~UniformInput()

Protected Functions

UniformInput()
struct SurfaceSupportDetails
#include <graphics_device.h>

Contains information about the support of a given physical device for a given surface, for example the formats using which it can present onto the surface.

Public Members

VkPhysicalDevice phys_device

The physical device.

VkSurfaceKHR surface

The surface to which it can draw.

std::vector<VkPresentModeKHR> present_modes

Available present modes.

std::vector<VkSurfaceFormatKHR> surface_formats

Available surface formats.

VkSurfaceCapabilitiesKHR surface_caps

Various capabilities of presentation to the surface.

uint32_t graphics_fam

Index of the device queue family with graphics support.

std::optional<uint32_t> maybe_present_fam

Index of the queue family with presentation support.

This might be the same as the graphics family, in which case this optional is empty.

struct vlk_capabilities
#include <windowvk.h>

Public Members

std::set<std::string> layers

Names of available layers.

std::set<std::string> extensions

Names of available extensions.

class VlkDrawableDisplay
#include <render_target.h>

A Vulkan representation of a display target that can be drawn onto directly, that is not by copying data from another object.

Public Functions

VkSurfaceFormatKHR choose_best_surface_format(std::vector<VkSurfaceFormatKHR> const &formats)
VkPresentModeKHR choose_best_present_mode(std::vector<VkPresentModeKHR> const &modes)
VlkDrawableDisplay(VkDevice device, SurfaceSupportDetails details)
~VlkDrawableDisplay()

Public Members

VkDevice device
VkSwapchainKHR swapchain
VkFormat format
VkExtent2D extent
std::vector<VkImage> images
std::vector<VkImageView> image_views
std::vector<VkFramebuffer> framebuffers
class VlkFramebuffer : public openage::renderer::RenderTarget
#include <render_target.h>

Public Functions

VlkFramebuffer(VkRenderPass, std::vector<VkImageView> const&)

Private Members

std::vector<VkImageView> attachments
VkFramebuffer framebuffer
VkViewport viewport
class VlkGraphicsDevice
#include <graphics_device.h>

Owns a device capable of graphics operations and surface presentation using WSI.

Public Functions

VlkGraphicsDevice(VkPhysicalDevice dev, std::vector<uint32_t> const &q_fams)

Given a physical device and a list of queue family indices in that device, instantiates a logical device with a queue per each of the families.

The device has to support the swapchain extension.

VkPhysicalDevice get_physical_device() const
VkDevice get_device() const
VkQueue get_queue(size_t idx) const
~VlkGraphicsDevice()

Public Static Functions

std::optional<SurfaceSupportDetails> find_device_surface_support(VkPhysicalDevice dev, VkSurfaceKHR surf)

Given a physical device and a surface, checks whether the device is capable of presenting to the surface.

If it is, returns information about its presentation capabilities, otherwise returns an empty optional.

Private Members

VkPhysicalDevice phys_device

The underlying physical device.

VkDevice device

Logical device, owned by this object.

std::vector<VkQueue> queues

The queues instantiated for this device.

class VlkLoader
#include <loader.h>

A class for dynamically loading Vulkan extension functions.

Public Functions

VlkLoader()
void init(VkInstance instance)

Initialize this loader for the given Vulkan instance.

VkResult vkCreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugReportCallbackEXT *pCallback)

Part of VK_EXT_debug_report, allows setting a callback for debug events.

void vkDestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks *pAllocator)

Part of VK_EXT_debug_report, destroys the debug callback object.

Private Members

PFN_vkCreateDebugReportCallbackEXT pCreateDebugReportCallbackEXT
PFN_vkDestroyDebugReportCallbackEXT pDestroyDebugReportCallbackEXT
bool inited
class VlkRenderer
#include <renderer.h>

A renderer using the Vulkan API.

Public Functions

VlkRenderer(VkInstance instance, VkSurfaceKHR surface)
void do_the_thing(util::Path &dir)

Testing function that draws a triangle. Not part of the final renderer implementation.

Private Members

VkInstance instance
VkSurfaceKHR surface
class VlkShaderProgram
#include <shader_program.h>

Public Functions

VlkShaderProgram(VkDevice dev, std::vector<resources::ShaderSource> const &srcs)

Public Members

std::vector<VkShaderModule> modules
std::vector<VkPipelineShaderStageCreateInfo> pipeline_stage_infos
class VlkWindow : public openage::renderer::Window
#include <windowvk.h>

Public Functions

VlkWindow(const char *title)
~VlkWindow()
VkInstance get_instance() const
VkSurfaceKHR get_surface() const

Private Members

vlk_capabilities capabilities
VkInstance instance
VkSurfaceKHR surface
VkDebugReportCallbackEXT debug_callback
VlkLoader loader
SDL_Window *window
class Window
#include <window.h>

Subclassed by openage::renderer::opengl::GlWindow, openage::renderer::vulkan::VlkWindow

Public Types

using key_cb_t = std::function<void(SDL_KeyboardEvent const&)>
using mouse_button_cb_t = std::function<void(SDL_MouseButtonEvent const&)>
using mouse_wheel_cb_t = std::function<void(SDL_MouseWheelEvent const&)>
using resize_cb_t = std::function<void(size_t, size_t)>

Public Functions

virtual ~Window()
std::pair<size_t, size_t> get_size() const

Returns the dimensions of this window.

bool should_close() const

Returns true if this window should be closed.

void add_key_callback(const key_cb_t &cb)
void add_mouse_button_callback(const mouse_button_cb_t &cb)
void add_mouse_wheel_callback(const mouse_wheel_cb_t &cb)
void add_resize_callback(const resize_cb_t &cb)
virtual void set_size(size_t width, size_t height) = 0

Force the window to the given size.

It’s generally not a good idea to use this, as it makes the window jump around wierdly.

virtual void update() = 0

Polls for window events, calls callbacks for these events, swaps front and back framebuffers to present graphics onto screen.

This has to be called at the end of every graphics frame.

virtual std::unique_ptr<Renderer> make_renderer() = 0

Creates a renderer which uses the window’s graphics API and targets the window.

Protected Functions

Window(size_t width, size_t height)

Protected Attributes

bool should_be_closed = false
std::pair<size_t, size_t> size

The current size of the framebuffer.

std::vector<key_cb_t> on_key
std::vector<mouse_button_cb_t> on_mouse_button
std::vector<mouse_wheel_cb_t> on_mouse_wheel
std::vector<resize_cb_t> on_resize
class RenderOptions : public openage::options::OptionNode
#include <game_renderer.h>

Options for the renderer.

These will be included in the user interface via reflection, so adding new members will always be visible

TODO include fog drawing etc

Public Functions

RenderOptions()

Public Members

options::Var<bool> draw_debug
options::Var<bool> terrain_blending
class RepairAbility : public openage::UnitAbility
#include <ability.h>

initiates a repair action when given a valid target

Public Functions

RepairAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class RepairAction : public openage::TargetAction
#include <action.h>

repairs a unit

Public Functions

RepairAction(Unit *e, UnitReference tar)
virtual ~RepairAction()
void update_in_range(unsigned int int, Unit *)

Control units action when in range of the target.

void on_completion_in_range(int)
bool completed_in_range(Unit *) const
std::string name() const

debug string to identify action types

Private Members

ResourceBundle cost

stores the cost of the repair for 1hp

IntervalTimer timer
bool complete
class Research
#include <research.h>

At most one Research must exist for each ResearchType.

A research represents how many times the research type has been completed (completed count) and also how many unit are researching it now (active count).

Public Functions

Research(const ResearchType *type)
void started()

Called when a unit started researching this research.

void stopped()

Called when a unit stopped researching this research before completing it.

void completed()

Called when a unit completed researching this research.

bool can_start() const

Returns true if a unit can start researching this research.

bool is_active() const

Returns true if any unit is researching this research.

bool is_researched() const

Returns true if it has nothing more to offer (reached max repeats).

void apply()

Apply the modifications to the owner player.

Public Members

const ResearchType *type

Protected Attributes

int active_count

The number of units that are researching this research.

int completed_count

The number of times this research has been completed.

class ResearchAbility : public openage::UnitAbility
#include <ability.h>

initiates a research

Public Functions

ResearchAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class ResearchAction : public openage::UnitAction
#include <action.h>

trains a new unit

Public Functions

ResearchAction(Unit *e, Research *research)
virtual ~ResearchAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

float get_progress() const
const ResearchType *get_research_type() const

Private Members

Research *research
IntervalTimer timer
bool complete
class ResearchType
#include <research.h>

Describes a research for a single player.

The get_max_repeats (with a default value of 1) can allow for a research to be performed multiple types

Subclassed by openage::NyanResearchType

Public Functions

ResearchType(Player &owner)
virtual int id() const = 0

Gets the unique id of this research type.

virtual std::string name() const = 0

Gets the name of the research.

virtual research_category category() const = 0

Gets the research category of the research.

std::shared_ptr<Research> initialise() const

Creates a single Research object.

Must be called only once.

int get_max_repeats() const

How many times it can be researched.

All classic researches have a value of 1.

virtual unsigned int get_research_time() const = 0
virtual ResourceCost get_research_cost() const = 0
virtual void apply() const = 0

Performs the modifications (eg.

apply patch to the unit types)

Public Members

Player &owner

The player who owns this research type.

class ResizeHandler
#include <handlers.h>

superclass for handling a window resize event.

Subclassed by openage::console::Console, openage::Engine, openage::gui::GUI

Public Functions

virtual ~ResizeHandler()
virtual bool on_resize(coord::viewport_delta new_size) = 0

execute the resize handler.

class Resource
#include <resource.h>

A resource.

Subclassed by openage::ResourceProducer

Public Functions

Resource()
virtual int id() const = 0
virtual std::string name() const = 0
class ResourceBundle
#include <resource.h>

A set of amounts of game resources.

Can be also used to store other information about the resources.

TODO change amounts from doubles to integers

Public Functions

ResourceBundle()
ResourceBundle(const Resources &resources)
~ResourceBundle()
ResourceBundle(const ResourceBundle &other)
ResourceBundle clone() const
bool operator>(const ResourceBundle &other) const
bool operator>=(const ResourceBundle &other) const
ResourceBundle &operator+=(const ResourceBundle &other)
ResourceBundle &operator-=(const ResourceBundle &other)
ResourceBundle &operator*=(const double a)
ResourceBundle &round()

Round each value to the nearest integer.

Returns itself.

bool has(const ResourceBundle &amount) const
bool has(const ResourceBundle &amount1, const ResourceBundle &amount2) const
bool deduct(const ResourceBundle &amount)

If amount can’t be deducted return false, else deduct the given amount and return true.

void set(const ResourceBundle &amount)
void set_all(const double amount)
void limit(const ResourceBundle &limits)
double &operator[](const game_resource res)
double &operator[](const int id)
double get(const game_resource res) const
double get(const int id) const
double sum() const

Returns the sum of all the resources.

int get_count() const

The number of resources.

Private Functions

ResourceBundle(const int count)
void expand(const ResourceBundle &other)
void expand(const int count)
int min_count(const ResourceBundle &other)

Private Members

int count

The number of resources.

double *value
class ResourceCost
#include <cost.h>

A container for a constant or dynamic ResourceBundle representing the cost.

Public Functions

ResourceCost()

Constant zero cost.

ResourceCost(const ResourceBundle &resources)

Constant cost.

ResourceCost(cost_type type, const ResourceBundle &multiplier)

Dynamic cost.

~ResourceCost()
void set(cost_type type, const ResourceBundle &multiplier)
const ResourceBundle get(const Player &player) const

Returns the cost.

Private Members

cost_type type
ResourceBundle resources
class ResourceProducer : public openage::Resource
#include <resource.h>

Public Functions

ResourceProducer(int id, std::string name)
int id() const
std::string name() const

Private Members

int _id
std::string _name
class Resources
#include <resource.h>

All the resources.

The the ids of the resources must be inside [0, count).

The static variables wood, food, gold, stone are the ids of the representing resource. Any extension of Resources must use this ids as they are an engine dependency (at the moment).

Subclassed by openage::ClassicResources

Public Functions

Resources()
virtual unsigned int get_count() const = 0
virtual const Resource &get_resource(int id) const = 0
ResourceBundle create_bundle() const

Public Static Attributes

const int wood = 0
const int food = 1
const int gold = 2
const int stone = 3
class RNG
#include <rng.h>

This class holds an xorshift128+ rng, as well as utility generator functions.

Public Functions

RNG(uint64_t seed)

Creates an rng and seeds it with the 64 bit seed.

Parameters
  • seed: The inital seed for the following number generation.

RNG(const void *data, size_t count)

Initializes the rng using data from the buffer pointed to by data.

Parameters
  • data: The buffer that contains data for seeding the rng

  • count: The number of bytes in the buffer

Exceptions
  • Error: if 0 bytes are passed

RNG(const std::string &instr)

Reads the rng in from the passed string.

If you want to use the data in the string as a seed, then pass the c_str() to rng(const void*, size_t).

Parameters
  • instr: The string from which the rng is serialized

Exceptions
  • Error: if the rng cannot be read from the string

RNG(std::istream &instream)

Reads the rng in from the passed std::istream.

This serializes the rng, and does not use the data as a random seed.

Parameters
  • instream: The input stream for serializing the rng

Exceptions
  • Error: if stream initialization fails

void seed(uint64_t val)

Seeds with the 64 bit seed.

void seed(const void *data, size_t count)

Initializes the rng using bits from the buffer pointed to by data.

Parameters
  • data: The buffer that contains data for seeding the rng

  • count: The number of bytes in the buffer

Exceptions
  • Error: if 0 bytes are passed

uint64_t random()

Retrieves a random value from the generator.

uint64_t operator()()

Retrieves a random value from the generator.

uint64_t random_range(uint64_t lower, uint64_t upper)

Returns a random integer in the range [lower, upper].

bool probability(double prob)

Returns true with the passed probability.

double real()

Retrieves a double in [0, 1)

double real_range(double lower, double upper)

Returns a double in the range [min, max)

void fill(uint64_t *data, size_t len)

Effeciently fills a chunk of 64 bit integers.

Gives identical result to calling random() len times

Parameters
  • data: The buffer to be filled with random numbers

  • len: the length of the data

void fill_real(double *data, size_t len)

Fills an array of doubles with values in [0, 1) Gives identical results as real() but more effeciently.

Parameters
  • data: A pointer t0 the buffer of doubles

  • len: The length of the buffer

void discard(size_t num_discard)

Discards num_discard numbers from the generator.

std::ostream &to_stream(std::ostream &out) const

Outputs the rng state to a stream.

Exceptions
  • Error: if writing data fails

std::istream &from_stream(std::istream &in)

Reads the rng state from a stream.

Exceptions
  • Error: if reading the stream fails

std::string to_string() const

Writes the rng state to a string.

void from_string(const std::string &instr)

Reads the rng in from a string.

Exceptions
  • Error: if reading from the string fails

Public Static Functions

static constexpr uint64_t max()
static constexpr uint64_t min()

Private Members

uint64_t state[2]

The internal state array.

Private Static Attributes

constexpr size_t discard_on_seed = 50

elements to discard on seed to escape from high-zero seeds

class Score
#include <score.h>

Keeps track of a score and all the sub-scores.

Subclassed by openage::PlayerScore, openage::TeamScore

Public Functions

Score()
void add_score(const score_category cat, double value)
void add_score(const score_category cat, int value)
void remove_score(const score_category cat, double value)
void remove_score(const score_category cat, int value)
void update_map_explored(double progress)

Updates map exploration precentance based sub-scores.

void update_resources(const ResourceBundle &resources)

Updates resource based sub-scores.

void update_score()

Calculates the total score from the sub-scores.

TODO update gui here

int get_score(const score_category cat) const
int get_score(const int index) const
int get_score_total() const

Protected Attributes

int score[static_cast<int>(SCORE_CATEGORY_COUNT)]
int score_total

Private Members

int score_exploration

Used by update_map_explored.

int score_resources

Used by update_resources.

class ScreenshotManager
#include <screenshot.h>

Public Functions

ScreenshotManager(job::JobManager *job_mgr)

Initializes the screenshot manager with the given job manager.

~ScreenshotManager()
void save_screenshot(coord::viewport_delta size)

To be called to save a screenshot.

bool encode_png(std::shared_ptr<uint8_t> pxdata, coord::viewport_delta size)

To be called by the job manager.

Returns true on success, false otherwise.

Public Members

coord::viewport_delta window_size

size of the game window, in coord_sdl

Private Functions

std::string gen_next_filename()

to be called to get the next screenshot filename into the array

Private Members

unsigned count

contains the number to be in the next screenshot filename

std::time_t last_time

contains the last time when a screenshot was taken

job::JobManager *job_manager

the job manager this screenshot manager uses

class SetPointAbility : public openage::UnitAbility
#include <ability.h>

sets the gather point on buildings

Public Functions

SetPointAbility()
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

class Program
#include <program.h>

Public Functions

Program()
Program(Shader *s0, Shader *s1)
~Program()
void attach_shader(Shader *s)
void link()
void use()
void stopusing()
GLint get_uniform_id(const char *name)
GLint get_attribute_id(const char *name)
void set_attribute_id(const char *name, GLuint id)
void dump_active_attributes()

Public Members

GLuint id
GLint pos_id
GLint mvpm_id

Private Functions

void check(GLenum what_to_check)

checks a given status for this program.

Parameters
  • what_to_check: GL_LINK_STATUS GL_VALIDATE_STATUS GL_COMPILE_STATUS

GLint get_info(GLenum pname)
char *get_log()

Private Members

bool is_linked
Shader *vert
Shader *frag
Shader *geom
class Shader
#include <shader.h>

Public Functions

Shader(GLenum type, std::initializer_list<const char *> sources)
~Shader()

Public Members

GLuint id
GLenum type
class SharedAttributeContainer : public openage::AttributeContainer
#include <attribute.h>

Wraps a templated shared attribute.

Shared attributes are common across all units of one type

Subclassed by openage::Attribute< attr_type::armor >, openage::Attribute< attr_type::attack >, openage::Attribute< attr_type::dropsite >, openage::Attribute< attr_type::heal >, openage::Attribute< attr_type::hitpoints >, openage::Attribute< attr_type::multitype >, openage::Attribute< attr_type::owner >, openage::Attribute< attr_type::population >, openage::Attribute< attr_type::resource_generator >, openage::Attribute< attr_type::speed >, openage::Attribute< attr_type::storage >, openage::Attribute< attr_type::worker >

Public Functions

SharedAttributeContainer(attr_type t)
bool shared() const

shared attributes are common across all units of one type, such as max hp, and gather rates

non shared attributes include a units current hp, and the amount a villager is carrying

class Sound
#include <game_spec.h>

simple sound object TODO: move to assetmanager

Public Functions

Sound(GameSpec *spec, std::vector<int> &&sound_items)
void play() const

Public Members

std::vector<int> sound_items
GameSpec *game_spec
class SquareObject : public openage::TerrainObject
#include <terrain_object.h>

terrain object class represents one immobile object on the map (building, trees, fish, …).

can only be constructed by unit->make_location<SquareObject>(…)

Public Functions

~SquareObject()
tile_range get_range(const coord::phys3 &pos, const Terrain &terrain) const

calculate object start and end positions.

set the center position to “middle”, start_pos is % and end_pos = &

Parameters
  • pos: the center position of the building

for a building, the # tile will be “the clicked one”: @ @ @ @ @ @ @ %# & @ @ @ % # & @ % # @ & @ @ @ @ @ @ @ @ @

coord::phys_t from_edge(const coord::phys3 &point) const

how far is a point from the edge of this object

coord::phys3 on_edge(const coord::phys3 &angle, coord::phys_t extra = 0) const

get a position on the edge of this object

bool contains(const coord::phys3 &other) const

does this space contain a given point

bool intersects(const TerrainObject &other, const coord::phys3 &position) const

would this intersect with another object if it were positioned at the given point

coord::phys_t min_axis() const

the shortest line that can be placed across the objects center

Public Members

const coord::tile_delta size

tile size of this objects base

Private Functions

SquareObject(Unit &u, coord::tile_delta foundation_size)
SquareObject(Unit &u, coord::tile_delta foundation_size, std::shared_ptr<Texture> out_tex)

Friends

friend openage::SquareObject::TerrainObject
friend openage::SquareObject::Unit
class TargetAction : public openage::UnitAction
#include <action.h>

Base class for actions which target another unit such as gather, attack, heal and convert TODO implement min range.

Subclassed by openage::AttackAction, openage::BuildAction, openage::ConvertAction, openage::GarrisonAction, openage::GatherAction, openage::HealAction, openage::RepairAction

Public Functions

TargetAction(Unit *e, graphic_type gt, UnitReference r, coord::phys_t action_rad)

action_rad is how close a unit must come to another unit to be considered to touch the other, for example in gathering resource and melee attack

TargetAction(Unit *e, graphic_type gt, UnitReference r)

this constructor uses the default action radius formula which will bring the object as near to the target as the pathing grid will allow.

virtual ~TargetAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

virtual std::string name() const = 0

debug string to identify action types

virtual void update_in_range(unsigned int, Unit *) = 0

Control units action when in range of the target.

virtual void on_completion_in_range(int target_type) = 0
virtual bool completed_in_range(Unit *) const = 0
coord::phys_t distance_to_target()
Unit *update_distance()
UnitReference get_target() const
int get_target_type_id() const
void set_target(UnitReference new_target)

changes target, ending action when new target is invalid

Private Members

UnitReference target
int target_type_id
int repath_attempts
bool end_action
coord::phys_t dist_to_target

tracks distance to target from last update

coord::phys_t radius
class Team
#include <team.h>

A team of players.

Public Functions

Team(unsigned int id)
Team(unsigned int id, std::string name)
Team(unsigned int id, std::string name, Player *leader)
bool operator==(const Team &other) const
void add_member(Player &player, const member_type type)
void change_member_type(Player &player, const member_type type)
bool is_member(const Player &player) const
void remove_member(Player &player)
member_type get_member_type(Player &player)
std::vector<const Player *> get_players() const

TODO find a better way to get all the players.

Public Members

const unsigned int id

unique id of the team

const std::string name

visible name of this team

TeamScore score

The score of the team, based on the team’s players score.

Private Members

std::unordered_map<const Player *, member_type> members
class TeamScore : public openage::Score
#include <score.h>

The score of a team.

Public Functions

TeamScore(Team *team)
void update_score()

Calculates the total score from the sub-scores.

TODO update gui here

Private Members

Team *team
class Terrain
#include <terrain.h>

the terrain class is the main top-management interface for dealing with cost-benefit analysis to maximize company profits.

actually this is just the entrypoint and container for the terrain chunks.

Public Functions

Terrain(terrain_meta *meta, bool is_infinite)
~Terrain()
std::vector<coord::chunk> used_chunks() const

returns a list of all referenced chunks

bool fill(const int *data, const coord::tile_delta &size)

fill the terrain with given terrain_id values.

Return

whether the data filled on the terrain was cut because of the terrains size limit.

void attach_chunk(TerrainChunk *new_chunk, const coord::chunk &position, bool manual = true)

Attach a chunk to the terrain, to a given position.

Parameters
  • new_chunk: The chunk to be attached

  • position: The chunk position where the chunk will be placed

  • manually_created: Was this chunk created manually? If true, it will not be free’d automatically

TerrainChunk *get_chunk(const coord::chunk &position)

get a terrain chunk by a given chunk position.

Return

the chunk if exists, nullptr else

TerrainChunk *get_chunk(const coord::tile &position)

get a terrain chunk by a given tile position.

Return

the chunk it exists, nullptr else

TerrainChunk *get_create_chunk(const coord::chunk &position)

get or create a terrain chunk for a given chunk position.

Return

the (maybe newly created) chunk

TerrainChunk *get_create_chunk(const coord::tile &position)

get or create a terrain chunk for a given tile position.

Return

the (maybe newly created) chunk

TileContent *get_data(const coord::tile &position)

return tile data for the given position.

the only reason the chunks exist, is because of this data.

TerrainObject *obj_at_point(const coord::phys3 &point)

an object which contains the given point, null otherwise

struct chunk_neighbors get_chunk_neighbors(const coord::chunk &position)

get the neighbor chunks of a given chunk.

chunk neighbor ids: 0 / <- ne 7 1 6 @ 2 5 3 4 \ <- se

ne se 0: 1 -1 1: 1 0 2: 1 1 3: 0 1 4: -1 1 5: -1 0 6: -1 -1 7: 0 -1

Parameters
  • position: the position of the center chunk.

unsigned get_subtexture_id(const coord::tile &pos, unsigned atlas_size)

return the subtexture offset id for a given tile position.

the maximum offset is determined by the atlas size.

this function returns always the right value, so that neighbor tiles of the same terrain (like grass-grass) are matching (without blendomatic). -> e.g. grass only map.

tile_state check_tile(const coord::tile &position)

checks the creation state and premissions of a given tile position.

bool check_tile_position(const coord::tile &position)

checks whether the given tile position is allowed to exist on this terrain.

bool validate_terrain(terrain_t terrain_id)

validate whether the given terrain id is available.

bool validate_mask(ssize_t mask_id)

validate whether the given mask id is available.

int priority(terrain_t terrain_id)

return the blending priority for a given terrain id.

int blendmode(terrain_t terrain_id)

return the blending mode/blendomatic mask set for a given terrain id.

Texture *texture(terrain_t terrain_id)

get the terrain texture for a given terrain id.

Texture *blending_mask(ssize_t mask_id)

get the blendomatic mask with the given mask id.

int get_blending_mode(terrain_t base_id, terrain_t neighbor_id)

return the blending mode id for two given neighbor ids.

void draw(Engine *engine, RenderOptions *settings)

draw the currently visible terrain area on screen.

Parameters
  • engine: the engine where the terrain should be drawn to.

struct terrain_render_data create_draw_advice(const coord::tile &ab, const coord::tile &cd, const coord::tile &ef, const coord::tile &gh, bool blending_enabled)

create the drawing instruction data.

created draw data according to the given tile boundaries.

Return

a drawing instruction struct that contains all information for rendering

Parameters
  • ab: upper left tile

  • cd: upper right tile

  • ef: lower right tile

  • gh: lower left tile

struct tile_draw_data create_tile_advice(coord::tile position, bool blending_enabled)

create rendering and blending information for a single tile on the terrain.

void get_neighbors(coord::tile basepos, struct neighbor_tile *neigh_tiles, struct influence *influences_by_terrain_id)

gather neighbors of a given base tile.

Parameters
  • basepos: the base position, around which the neighbors will be fetched

  • neigh_tiles: the destination buffer where the neighbors will be stored

  • influences_by_terrain_id: influence buffer that is reset in the same step

struct influence_group calculate_influences(struct tile_data *base_tile, struct neighbor_tile *neigh_tiles, struct influence *influences_by_terrain_id)

look at neighbor tiles around the base_tile, and store the influence bits.

Return

an influence group that describes the maximum 8 possible influences on the base_tile

Parameters
  • base_tile: the base tile for which influences are calculated

  • neigh_tiles: the neigbors of base_tile

  • influences_by_terrain_id: influences will be stored to this buffer, as bitmasks

void calculate_masks(coord::tile position, struct tile_draw_data *tile_data, struct influence_group *influences)

calculate blending masks for a given tile position.

See

calculate_influences

Parameters
  • position: the base tile position, for which the masks are calculated

  • tile_data: the buffer where the created drawing layers will be stored in

  • influences: the buffer where calculated influences were stored to

Public Members

bool infinite

chunks are automagically created as soon as they are referenced

Private Members

terrain_meta *meta

terrain meta data

std::unordered_map<coord::chunk, TerrainChunk *, coord_chunk_hash> chunks

maps chunk coordinates to chunks.

struct terrain_meta
#include <terrain.h>

specification for all available tile types and blending data

Public Members

size_t terrain_id_count
size_t blendmode_count
std::vector<Texture *> textures
std::vector<Texture *> blending_masks
std::unique_ptr<int[]> terrain_id_priority_map
std::unique_ptr<int[]> terrain_id_blendmode_map
std::unique_ptr<influence[]> influences_buf
struct terrain_render_data
#include <terrain.h>

the complete render instruction collection for the terrain.

this is passed to the renderer and will be drawn on screen.

Public Members

std::vector<struct tile_draw_data> tiles
std::set<TerrainObject *, util::less<TerrainObject *>> objects
class TerrainChunk
#include <terrain_chunk.h>

terrain chunk class represents one chunk of the the drawn terrain.

Public Functions

TerrainChunk()
~TerrainChunk()
void draw(coord::chunk chunk_pos)

draws the terrain chunk on screen.

Parameters
  • chunk_pos: the chunk position where it will be drawn

TileContent *get_data(coord::tile abspos)

get tile data by absolute coordinates.

TileContent *get_data(coord::tile_delta pos)

get tile data by coordinates that are releative to this chunk.

TileContent *get_data(size_t pos)

get tile data by memory position.

TileContent *get_data_neigh(coord::tile_delta pos)

get the tile data a given tile position relative to this chunk.

also queries neighbors if the position is not on this chunk.

int neighbor_id_by_pos(coord::tile_delta pos)
size_t tile_position(coord::tile_delta pos)
size_t tile_position_neigh(coord::tile_delta pos)
size_t get_tile_count()
size_t tiles_in_row(unsigned int row)
size_t get_size()
void set_terrain(Terrain *parent)

Public Members

size_t size

stores the length for one chunk side.

size_t tile_count

number of tiles on that chunk (this->size^2)

TileContent *data

stores the chunk data, one tile_content struct for each tile.

Terrain *terrain

the terrain to which this chunk belongs to.

chunk_neighbors neighbors

the 8 neighbors this chunk has.

bool manually_created
class TerrainObject : public std::enable_shared_from_this<TerrainObject>
#include <terrain_object.h>

Base class for map location types which include square tile aligned positions and radial positions This enables two inheriting classes SquareObject and RadialObject to specify different areas of the map.

All TerrainObjects are owned by a Unit, to construct TerrainObjects, use the make_location function on any Unit

This class allows intersection testing between two TerrainObjects to cover all cases of intersection (water, land or flying objects) the units lambda function is used which takes a tile and returns a bool value of whether that tile can be passed by this

The name of this class is likely to change to TerrainBase or TerrainSpace

Subclassed by openage::RadialObject, openage::SquareObject

Public Functions

TerrainObject(Unit &u)
TerrainObject(const TerrainObject&)
TerrainObject(TerrainObject&&)
~TerrainObject()
bool is_floating() const

is the object a floating outline it is only an indicator of where a building will be built, but not yet started building and does not affect any collisions

bool is_placed() const

returns true if this object has been placed.

this indicates that the object has a position and exists on the map, floating buildings are not considered placed as they are only an indicator for where something can begin construction

bool check_collisions() const

should this object be tested for collisions, which decides whether another object is allowed to overlap the location of this object.

arrows and decaying objects will return false

void draw_outline(const coord::CoordManager &coord) const

draws outline of this terrain space in current position

bool place(object_state init_state)

changes the placement state of this object keeping the existing position.

this is useful for upgrading a floating building to a placed state

bool place(const std::shared_ptr<Terrain> &t, coord::phys3 &pos, object_state init_state)

binds the TerrainObject to a certain TerrainChunk.

Return

true when the object was placed, false when it did not fit at pos.

Parameters
  • terrain: the terrain where the object will be placed onto.

  • pos: (tile) position of the (nw,sw) corner

  • init_state: should be floating, placed or placed_no_collision

bool move(coord::phys3 &pos)

moves the object returns false if object cannot be moved here

void remove()

remove this TerrainObject from the terrain chunks.

void set_ground(int id, int additional = 0)

sets all the ground below the object to a terrain id.

Parameters
  • id: the terrain id to which the ground is set

  • additional: amount of additional space arround the building

template<class T, typename ...Arg>
TerrainObject *make_annex(Arg... args)

appends new annex location for this object

this does not replace any existing annex

const TerrainObject *get_parent() const

Returns the parent terrain object, if null the object has no parent which is the case for most objects.

objects with a parent are owned by that object and to be placed on the map the parent must also be placed

std::vector<TerrainObject *> get_children() const

Returns a list of child objects, this is the inverse of the get_parent() function.

TODO: this does not perform optimally and is likely to change

std::shared_ptr<Terrain> get_terrain() const
bool operator<(const TerrainObject &other)

comparison for TerrainObjects.

sorting for vertical placement. by using this order algorithm, the overlapping order is optimal so the objects can be drawn in correct order.

virtual tile_range get_range(const coord::phys3 &pos, const Terrain &terrain) const = 0

returns the range of tiles covered if the object was in the given pos

Parameters
  • pos: the position to find a range for

virtual coord::phys_t from_edge(const coord::phys3 &point) const = 0

how far is a point from the edge of this object

virtual coord::phys3 on_edge(const coord::phys3 &angle, coord::phys_t extra = 0) const = 0

get a position on the edge of this object

virtual bool contains(const coord::phys3 &other) const = 0

does this space contain a given point

virtual bool intersects(const TerrainObject &other, const coord::phys3 &position) const = 0

would this intersect with another object if it were positioned at the given point

virtual coord::phys_t min_axis() const = 0

the shortest line that can be placed across the objects center

Public Members

tile_range pos

the range of tiles which are covered by this object

Unit &unit
std::function<bool(const coord::phys3&)> passable

decide which terrains this object can be on this function should be true if given a valid position for the object

std::function<void(const Engine &e)> draw

specifies content to be drawn

Protected Functions

void place_unchecked(const std::shared_ptr<Terrain> &t, coord::phys3 &position)

placement function which does not check passibility used only when passibilty is already checked otherwise the place function should be used this does not modify the units placement state

Protected Attributes

object_state state
std::weak_ptr<Terrain> terrain
int occupied_chunk_count
TerrainChunk *occupied_chunk[4]
TerrainObject *parent

annexes and grouped units

std::vector<std::unique_ptr<TerrainObject>> children
std::shared_ptr<Texture> outline_texture

texture for drawing outline

class TerrainSearch
#include <terrain_search.h>

searches outward from a point and returns nearby objects The state of the search is kept within the class, which allows a user to look at a limited number of tiles per update cycle

Public Functions

TerrainSearch(std::shared_ptr<Terrain> t, coord::tile s)

next_tile will cover all tiles on the map

TerrainSearch(std::shared_ptr<Terrain> t, coord::tile s, float radius)

next_tile will iterate over a range of tiles within a radius

~TerrainSearch()
coord::tile start_tile() const

the tile the search began on

void reset()

restarts the search from the start tile

coord::tile next_tile()

returns all objects on the next tile

Private Members

const std::shared_ptr<Terrain> terrain
const coord::tile start
std::queue<coord::tile> tiles
std::unordered_set<coord::tile> visited
float previous_radius
float max_radius
class TestError : public openage::error::Error
#include <testing.h>

To be used by all tests to indicate an error condition.

An optional error message may be passed as part of the message, but the file name and line number are of primary concern.

class TestError
class Texture
#include <texture.h>

A texture for rendering graphically.

You may believe it or not, but this class represents a single texture, which can be drawn on the screen.

The class supports subtextures, so that one big texture can contain several small images. These are the ones actually to be rendered.

Public Functions

Texture(int width, int height, std::unique_ptr<uint32_t[]> data)

Create a texture from a rgba8 array.

It will have w * h * 32bit storage.

Texture(const util::Path &filename, bool use_metafile = false)

Create a texture from a existing image file.

For supported image file types, see the SDL_Image initialization in the engine.

~Texture()
void draw(const coord::CoordManager &mgr, coord::camhud pos, unsigned int mode = 0, bool mirrored = false, int subid = 0, unsigned player = 0) const

Draws the texture at hud coordinates.

void draw(const coord::CoordManager &mgr, coord::camgame pos, unsigned int mode = 0, bool mirrored = false, int subid = 0, unsigned player = 0) const

Draws the texture at game coordinates.

void draw(const coord::CoordManager &mgr, coord::phys3 pos, unsigned int mode = 0, bool mirrored = false, int subid = 0, unsigned player = 0) const

Draws the texture at phys coordinates.

void draw(const coord::CoordManager &mgr, const Terrain &terrain, coord::tile pos, unsigned int mode, int subid, Texture *alpha_texture, int alpha_subid) const

Draws the texture at tile coordinates.

void draw(coord::viewport pos, unsigned int mode, bool mirrored, int subid, unsigned player, Texture *alpha_texture, int alpha_subid) const

Draws the texture at window coordinates.

void reload()

Reload the image file.

Used for inotify refreshing.

const gamedata::subtexture *get_subtexture(uint64_t subid) const

Get the subtexture coordinates by its id.

size_t get_subtexture_count() const

Return

the number of available subtextures

void get_subtexture_size(uint64_t subid, int *w, int *h) const

Fetch the size of the given subtexture.

Parameters
  • subid: index of the requested subtexture

  • w: the subtexture width

  • h: the subtexture height

void get_subtexture_coordinates(uint64_t subid, float *txl, float *txr, float *txt, float *txb) const

get atlas subtexture coordinates.

left, right, top and bottom bounds as coordinates these pick the requested area out of the big texture. returned as floats in range 0.0 to 1.0

void get_subtexture_coordinates(const gamedata::subtexture *subtex, float *txl, float *txr, float *txt, float *txb) const
void fix_hotspots(unsigned x, unsigned y)

fixes the hotspots of all subtextures to (x,y).

this is a temporary workaround; such fixes should actually be done in the convert script.

void activate_alphamask(Texture *mask, uint64_t subid)

activates the influence of a given alpha mask to this texture.

void disable_alphamask()

disable a previously activated alpha mask.

GLuint get_texture_id() const

returns the opengl texture id of this texture.

Public Members

int w
int h

Private Functions

void load()
void load_in_glthread() const

The texture loadin must occur on the thread that manages the gl context.

GLuint make_gl_texture(int iformat, int oformat, int w, int h, void *data) const
void unload()

Private Members

std::unique_ptr<gl_texture_buffer> buffer
std::vector<gamedata::subtexture> subtextures
bool use_metafile
util::Path filename
class TickHandler
#include <handlers.h>

superclass for all calculations being done on engine tick.

Subclassed by openage::console::Console

Public Functions

virtual ~TickHandler()
virtual bool on_tick() = 0

execute the tick action.

struct tile_data
#include <terrain.h>

storage data for a single terrain tile.

Public Members

terrain_t terrain_id
coord::tile pos = {0, }
int subtexture_id
Texture *tex
int priority
int mask_id
int blend_mode
Texture *mask_tex
tile_state state
struct tile_draw_data
#include <terrain.h>

collection of drawing data for a single tile.

because of influences, a maximum of 8+1 draws could be requested.

Public Members

ssize_t count
struct tile_data data[9]
struct tile_range
#include <terrain_object.h>

A rectangle or square of tiles which is the minimim space to fit the units foundation or radius the end tile will have ne and se values greater or equal to the start tile.

Public Members

coord::tile start = {0, }
coord::tile end = {0, }
coord::phys3 draw = {0, , }
class TileContent
#include <terrain.h>

describes the properties of one terrain tile.

this includes the terrain_id (ice, water, grass, …) and the list of objects which have a bounding box overlapping the tile

Public Functions

TileContent()
~TileContent()

Public Members

terrain_t terrain_id
std::vector<TerrainObject *> obj
class TrainAbility : public openage::UnitAbility
#include <ability.h>

buildings train new objects

Public Functions

TrainAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class TrainAction : public openage::UnitAction
#include <action.h>

trains a new unit

Public Functions

TrainAction(Unit *e, UnitType *pp)
virtual ~TrainAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

float get_progress() const

Private Members

UnitType *trained
IntervalTimer timer
bool started
bool complete
class TypePair
#include <type_pair.h>

many effects in aoc use a pair structure such as attack bonuses, armour and selection commands

Public Functions

TypePair()

Private Members

UnitType a
UnitType b
class UngarrisonAbility : public openage::UnitAbility
#include <ability.h>

ability to ungarrision a building

Public Functions

UngarrisonAbility(const Sound *s = nullptr)
ability_type type()
bool can_invoke(Unit &to_modify, const Command &cmd)

true if the paramaters allow an action to be performed

void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false)

applies command to a given unit

Private Members

const Sound *sound
class UngarrisonAction : public openage::UnitAction
#include <action.h>

garrison inside a building

Public Functions

UngarrisonAction(Unit *e, const coord::phys3 &pos)
virtual ~UngarrisonAction()
void update(unsigned int time)

each action has its own update functionality which gets called when this is the active action

void on_completion()

action to perform when popped from a units action stack

bool completed() const

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

bool allow_interrupt() const

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

bool allow_control() const

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

std::string name() const

debug string to identify action types

Private Members

coord::phys3 position
bool complete
class Unit : public openage::log::LogSource
#include <unit.h>

A game object with current state represented by a stack of actions since this class represents both unit and building objects it may be better to name as GameObject.

it is possible that abilities are not required here and they could be moved to selection controller units only need the attributes

Public Functions

Unit(UnitContainer *c, id_t id)
~Unit()

unit cleanup will delete terrain object

template<class T, typename ...Arg>
void make_location(Arg... args)

constructs a new location for this unit replacing any existing locatio

uses same args as the location constructor except the first which will filled automatically

void reset()

removes all actions and abilities current attributes are kept

bool has_action() const

checks the entity has an action, if it has no action it should be removed from the game

Return

true if the entity currently has an action

bool accept_commands() const

true when the unit is alive and able to add new actions

bool is_own_unit(const Player &player)

checks whether the current player is the owner of this unit

UnitAction *top() const

returns the current action on top of the stack

UnitAction *before(const UnitAction *action) const

returns action under the passed action in the stack returns null if stack size is less than 2

bool update(time_nsec_t lastframe_duration)

update this object using the action currently on top of the stack

void draw(const Engine &engine)

draws this action by taking the graphic type of the top action the graphic is found from the current graphic set

this function should be used for most draw purposes

void draw(TerrainObject *loc, const graphic_set &graphics, const Engine &engine)

an generalized draw function which is useful for drawing annexes

void draw(coord::phys3 draw_pos, std::shared_ptr<UnitTexture> graphic, unsigned int frame, const Engine &engine)

draws with a specific graphic and frame

void give_ability(std::shared_ptr<UnitAbility> ability)

adds an available ability to this unit this turns targeted objects into actions which are pushed onto the stack, eg.

targeting a relic may push a collect relic action

UnitAbility *get_ability(ability_type type)

get ability with specified type, null if not available

To invoke commands use the invoke function instead

void push_action(std::unique_ptr<UnitAction> action, bool force = false)

adds a new action on top of the action stack will be performed immediately

void secondary_action(std::unique_ptr<UnitAction> action)

adds a secondary action which is always updated

void add_attribute(std::shared_ptr<AttributeContainer> attr)

give a new attribute this this unit this is used to set things like color, hitpoints and speed

void add_attributes(const Attributes &attr)

Give new attributes to this unit.

This is used to add the default attributes

void add_attributes(const Attributes &attr, bool shared, bool unshared)

Give new attributes to this unit.

If shared is false, shared attributes are ignored. If unshared is false, unshared attributes are ignored.

bool has_attribute(attr_type type) const

returns whether attribute is available

template<attr_type T>
Attribute<T> &get_attribute()

returns attribute based on templated value

std::shared_ptr<UnitAbility> queue_cmd(const Command &cmd)

queues a command to be applied to this unit on the next update

Return

the ability which will apply the command if an action was created otherwise nullptr is returned when no ability can handle the command

void stop_gather()

removes all gather actions without calling their on_complete actions this cancels the gathering action completely

void stop_actions()

removes all actions above and including the first interuptable action this will stop any of the units current moving or attacking actions a direct command from the user will invoke this function

void delete_unit()

begins unit removal by popping some actions

this is the action that occurs when pressing the delete key which plays death sequence and does not remove instantly

UnitReference get_ref()

get a reference which can check against the container to ensure this object still exists

UnitContainer *get_container() const

the container used when constructing this unit

std::string logsource_name()

Returns the unit’s name as the LogSource name.

Public Members

const id_t id

this units unique id value

const UnitType *unit_type

type of this object, this is set by the the UnitType which was most recently applied to this unit

bool selected

should selection features be drawn TODO: should be a pointer to selection to be updated when unit is removed, or null if not selected

std::unique_ptr<TerrainObject> location

space on the map used by this unit null if the object is not yet placed or garrisoned TODO: make private field

Attributes attributes

Unit attributes include color, hitpoints, speed, objects garrisoned etc contains 0 or 1 values for each type.

Private Functions

void apply_all_cmds()

applies new commands as part of the units update process

void apply_cmd(std::shared_ptr<UnitAbility> ability, const Command &cmd)

applies one command using a chosen ability locks the command queue mutex while operating

void update_secondary(int64_t time_elapsed)

update all secondary actions

void erase_after(std::function<bool(std::unique_ptr<UnitAction>&)> func, bool run_completed = true, )

erase from action specified by func to the end of the stack all actions erased will have the on_complete function called

Parameters
  • run_completed: usually each action has an on_complete() function called when it is removed but when run_completed is false this on_complete() function is not called for all popped actions

Private Members

std::unordered_map<ability_type, std::shared_ptr<UnitAbility>> ability_available

ability available actions that this entity can perform when controlled

std::vector<std::unique_ptr<UnitAction>> action_stack

action stack top action determines graphic to be drawn

std::vector<std::unique_ptr<UnitAction>> action_secondary

secondary actions are always updated

std::queue<std::pair<std::shared_ptr<UnitAbility>, const Command>> command_queue

queue commands to be applied on the next update

std::mutex command_queue_lock

mutex controlling updates to the command queue

bool pop_destructables

pop any destructable actions on the next update cycle and prevent additional actions being added

UnitContainer *container

the container that updates this unit

class UnitAbility
#include <ability.h>

Abilities create an action when given a target some abilities target positions such as moving or patrolling others target other game objects, such as attacking or collecting relics.

Abilities are constructed with a default unit texture, but allow the texture to be specified with the invoke function

Subclassed by openage::AttackAbility, openage::BuildAbility, openage::ConvertAbility, openage::GarrisonAbility, openage::GatherAbility, openage::HealAbility, openage::MoveAbility, openage::PatrolAbility, openage::RepairAbility, openage::ResearchAbility, openage::SetPointAbility, openage::TrainAbility, openage::UngarrisonAbility

Public Functions

virtual ~UnitAbility()
virtual ability_type type() = 0
virtual bool can_invoke(Unit &to_modify, const Command &cmd) = 0

true if the paramaters allow an action to be performed

virtual void invoke(Unit &to_modify, const Command &cmd, bool play_sound = false) = 0

applies command to a given unit

bool has_hitpoints(Unit &target)

some common functions

bool is_damaged(Unit &target)
bool has_resource(Unit &target)
bool is_same_player(Unit &to_modify, Unit &target)
bool is_ally(Unit &to_modify, Unit &target)
bool is_enemy(Unit &to_modify, Unit &target)

Public Static Functions

ability_set set_from_list(const std::vector<ability_type> &items)

set bits corresponding to abilities, useful for initialising an ability_set using a brace enclosed list

class UnitAction
#include <action.h>

Actions can be pushed onto any units action stack.

Each update cycle will perform the update function of the action on top of this stack

Subclassed by openage::DeadAction, openage::DecayAction, openage::FoundationAction, openage::IdleAction, openage::MoveAction, openage::ProjectileAction, openage::ResearchAction, openage::TargetAction, openage::TrainAction, openage::UngarrisonAction

Public Functions

UnitAction(Unit *u, graphic_type initial_gt)

Require unit to be updated and an initial graphic type.

virtual ~UnitAction()
graphic_type type() const

type of graphic this action should use

float current_frame() const

frame number to use on the current graphic

virtual void update(unsigned int time) = 0

each action has its own update functionality which gets called when this is the active action

virtual void on_completion() = 0

action to perform when popped from a units action stack

virtual bool completed() const = 0

gets called for all actions on stack each update cycle

Return

true when action is completed so it and everything above it can be popped

virtual bool allow_interrupt() const = 0

checks if the action can be interrupted, allowing it to be popped if the user specifies a new action, if false the action must reach a completed state before removal eg dead action must be completed and cannot be discarded

virtual bool allow_control() const = 0

control whether stack can discard the action automatically and should the stack be modifiable when this action is on top

if true this action must complete and will not allow new actions to be pushed while it is active and also does not update the secondary actions

virtual std::string name() const = 0

debug string to identify action types

const graphic_set &current_graphics() const

determines which graphic should be used for drawing this unit finds the default graphic using the units type, used by most actions

this virtual function is overriden for special cases such as villager task graphics

void draw_debug(const Engine &engine)
void face_towards(const coord::phys3 pos)

common functions for actions

bool damage_unit(Unit &target)

Damage a unit, returns true if the unit was killed in the process.

void move_to(Unit &target, bool use_range = true)

Public Static Functions

coord::phys_t adjacent_range(Unit *u)

a small distance to which units are considered touching when within this distance

coord::phys_t get_attack_range(Unit *u)

looks at an ranged attributes on the unit otherwise returns same as adjacent_range()

coord::phys_t get_heal_range(Unit *u)

looks at heal attribute on the unit otherwise returns same as adjacent_range()

Public Static Attributes

bool show_debug = false

produce debug info such as visualising paths

Protected Attributes

Unit *entity

the entity being updated

graphic_type graphic

common graphic controls

float frame
float frame_rate
std::function<void(const Engine&)> debug_draw_action

additional drawing for debug purposes

class UnitContainer
#include <unit_container.h>

the list of units that are currently in use will also give a view of the current game state for networking in later milestones

Public Functions

UnitContainer()
~UnitContainer()
void reset()
void set_terrain(std::shared_ptr<Terrain> &t)

sets terrain to initialise units on

std::shared_ptr<Terrain> get_terrain() const

returns the terrain which units are placed on

bool valid_id(id_t id) const

checks the id is valid

UnitReference get_unit(id_t id)

returns a reference to a unit

UnitReference new_unit()

creates a new unit without initialising

UnitReference new_unit(UnitType &type, Player &owner, coord::phys3 position)

adds a new unit to the container and initialises using a unit type

UnitReference new_unit(UnitType &type, Player &owner, TerrainObject *other)

adds a new unit to the container and initialises using a unit type places outside an existing object using the player of that object

bool dispatch_command(id_t to_id, const Command &cmd)

give a command to a unit unit creation and deletion should be done as commands

bool update_all(time_nsec_t lastframe_duration)

update dispatched by the game engine on each physics tick.

this will update all game objects.

std::vector<Unit *> all_units()

gets a list of all units in the container

Private Members

id_t next_new_id
std::unordered_map<id_t, std::unique_ptr<Unit>> live_units

mapping unit ids to unit objects

std::weak_ptr<Terrain> terrain

Terrain for initialising new units.

class UnitReference
#include <unit_container.h>

Reference to a single unit, which may have been removed from the game, check is_valid() before calling get()

Public Functions

UnitReference()

create an invalid reference

UnitReference(const UnitContainer *c, id_t id, Unit *u)

create referece by unit id

bool is_valid() const
Unit *get() const

Private Members

std::shared_ptr<reference_data> data

The default copy constructor and assignment will just copy the shared pointer.

class UnitSelection : public openage::HudHandler
#include <selection.h>

a user interface component allowing control of a selected group

Public Functions

UnitSelection(Engine *engine)
bool on_drawhud()

execute the drawing action.

void drag_begin(coord::camgame pos)
void drag_update(coord::camgame pos)
void drag_release(const Player &player, Terrain *terrain, bool append = false)
void clear()
void toggle_unit(const Player &player, Unit *u, bool append = false)
void add_unit(const Player &player, Unit *u, bool append = false)
void remove_unit(Unit *u)
selection_type_t get_selection_type()
void kill_unit(const Player &player)

kill a single unit in the selection

bool contains_builders(const Player &player)

checks whether there are any builders in the selection

bool contains_military(const Player &player)

checks whether there are any military units (i.e.

non-builders) in the selection

void select_point(const Player &player, Terrain *terrain, coord::camgame p, bool append = false)

point unit selection

void select_space(const Player &player, Terrain *terrain, coord::camgame p1, coord::camgame p2, bool append = false)

boxed unit selection

void all_invoke(Command &cmd)

uses command on every selected unit

int get_units_count() const
const UnitReference &get_first_unit() const

Private Functions

selection_type_t get_unit_selection_type(const Player &player, Unit *u)

Check whether the currently selected units may be selected at the same time If not, deselect some units This is the order in which the checks occur: Own units > own building(s) > enemy unit > enemy building > any object.

So you can select a group of units, or a building (or multiple if append is on) Enemy units, enemy buildings and other objects may only be selected one at a time

Private Members

std::unordered_map<id_t, UnitReference> units
selection_type_t selection_type
bool drag_active
coord::camgame start = {0, }
coord::camgame end = {0, }
Engine *engine

Engine where this selection is attached to.

class UnitTexture
#include <unit_texture.h>

Handling animated and directional textures based on the game graphics data.

These objects handle the drawing of regular textures to use a unit’s direction and include delta graphics.

This type can also deal with playing position based game sounds.

Public Functions

UnitTexture(GameSpec &spec, uint16_t graphic_id, bool delta = true)

Delta option specifies whether the delta graphics are included.

Note that the game data contains loops in delta links which mean recursive loading should be avoided

UnitTexture(GameSpec &spec, const gamedata::graphic *graphic, bool delta = true)
bool is_valid() const

invalid unit textures will cause errors if drawn

coord::viewport size() const

pixel size of this texture

void sample(const coord::CoordManager &coord, const coord::camhud &draw_pos, unsigned color = 1) const

a sample drawing for hud

void draw(const coord::CoordManager &coord, const coord::camgame &draw_pos, unsigned int frame, unsigned color) const

draw object with no direction

void draw(const coord::CoordManager &coord, const coord::camgame &draw_pos, coord::phys3_delta &dir, unsigned int frame, unsigned color) const

draw object with direction

void initialise(GameSpec &spec)

initialise graphic data

Public Members

const int16_t id

const attributes of the graphic

const int16_t sound_id
const unsigned int frame_count
const unsigned int angle_count
const int16_t mirroring_mode
const float frame_rate
const bool use_up_angles

draw object with vertical orientation (arrows) adding an addtion degree of orientation

const bool use_deltas

use delta information

Private Functions

unsigned int subtexture(const Texture *t, unsigned int angle, unsigned int frame) const

find which subtexture should be used for drawing this texture

Private Members

const Texture *texture

use a regular texture for drawing

unsigned int safe_frame_count

the above frame count covers the entire graphic (with deltas) the actual number in the base texture may be different

unsigned int angles_included
unsigned int angles_mirrored
unsigned int top_frame
bool draw_this
const Sound *sound
std::vector<gamedata::graphic_delta> delta_id
std::vector<std::pair<std::unique_ptr<UnitTexture>, coord::camgame_delta>> deltas
class UnitType
#include <type_pair.h>

units in aoc have a class and a type

UnitType has to main roles:

initialise(unit, player) should be called on a unit to give it a type and the required attributes, abilities and initial actions of that type

place(unit, terrain, initial position) is called to customise how the unit gets added to the world used to setup the TerrainObject location

UnitType is connected to a player to allow independent tech levels

Subclassed by openage::BuildingProducer, openage::NyanType, openage::ObjectProducer, openage::ProjectileProducer

Public Functions

UnitType()
bool match(class Unit *)

the unit must have either same class or id as this

UnitType(const Player &owner)
virtual ~UnitType()
virtual int id() const = 0

gets the unique id of this unit type

virtual int parent_id() const = 0

gets the parent id of this unit type which is used for village base and gather types

virtual std::string name() const = 0

gets the name of the unit type being produced

virtual void initialise(Unit *, Player&) = 0

Initialize units attributes to this type spec.

This can be called using existing units to modify type Ensure that the unit has been placed before seting the units type

TODO: make const

void reinitialise(Unit *unit, Player &player)

Initialize units shared attributes only to this type spec.

This can be called using existing units to modify type if the type Ensure that the unit has been placed before seting the units type

TODO define if pure vitrual or not / should be in nyan?

virtual TerrainObject *place(Unit *, std::shared_ptr<Terrain>, coord::phys3) const = 0

set unit in place return if placement was successful

This should be used when initially creating a unit or when a unit is ungarrsioned from a building or object TODO: make const

bool operator==(const UnitType &other) const

compare if two types are the same

bool operator!=(const UnitType &other) const
UnitTexture *default_texture()

Get a default texture for HUD drawing.

TerrainObject *place_beside(Unit *u, TerrainObject const *other) const

similar to place but places adjacent to an existing object

void copy_attributes(Unit *unit) const

copy attributes of this unit type to a new unit instance

void upgrade(const std::shared_ptr<AttributeContainer> &attr)

upgrades one attribute of this unit type

UnitType *parent_type() const

returns type matching parent_id()

Public Members

const Player &owner

the player who owns this unit type

std::vector<UnitReference> instances

all instances of units made from this unit type this could allow all units of a type to be upgraded

std::vector<std::shared_ptr<UnitAbility>> type_abilities

abilities given to all instances

Attributes default_attributes

default attributes which get copied to new units

ResourceCost cost

The cost of the unit.

int have_limit

The max number of units of this type that a player can have at an instance.

Use negative values for special cases.

int had_limit

The max number of units of this type that a player can create.

Use negative values for special cases.

graphic_set graphics

The set of graphics used for this type.

int icon

The index of the icon representing this unit.

coord::tile_delta foundation_size

the square dimensions of the placement

gamedata::unit_classes unit_class

raw game data class of this unit instance

Private Members

unsigned int class_id
unsigned int unit_type_id
class UnitTypeMeta
#include <unit_type.h>

an abstract unit type which is not yet owned by any player

Public Types

using type_ptr = std::shared_ptr<UnitType>
using init_func = std::function<type_ptr(const Player &owner)>

Public Functions

UnitTypeMeta(const std::string &name, int id, init_func f)
std::string name() const
int id() const

Public Members

const init_func init

creates the base unit type for a player

Private Members

const std::string type_name
const int type_id
class UnsharedAttributeContainer : public openage::AttributeContainer
#include <attribute.h>

Wraps a templated unshared attribute.

Shared attributes are copied for each unit of one type

Subclassed by openage::Attribute< attr_type::building >, openage::Attribute< attr_type::damaged >, openage::Attribute< attr_type::direction >, openage::Attribute< attr_type::formation >, openage::Attribute< attr_type::garrison >, openage::Attribute< attr_type::projectile >, openage::Attribute< attr_type::resource >

Public Functions

UnsharedAttributeContainer(attr_type t)
bool shared() const

shared attributes are common across all units of one type, such as max hp, and gather rates

non shared attributes include a units current hp, and the amount a villager is carrying

class ByteBuffer

Public Functions

__init__(self self)
__len__(self self)
append(self self, data data)

appends new data to the right of the buffer

discardleft(self self, keep keep)
hasbeendiscarded(self self, position position)
__getitem__(self self, pos pos)

a slice with default stepping is required.

when attempting to access already-discarded data, a ValueError is raised.

get_buffers(self self, start start, end end)

Public Members

bufs
index
discardedbufs
discardedbytes
class DiscardedError
class ByteQueue

Public Functions

__init__(self self)
__len__(self self)

Size of all currently-stored data.

append(self self, data data)

Adds bytes to the buffer.

popleft(self self, size size)

Returns the requested amount of bytes from the buffer.

Public Members

bufs
size
class CachableOSStream
#include <stringformatter.h>

Designed for usage by StringFormatter.

The problem with iostreams, including ExternalOStringStream, is that they use lots of memory, and are quite slow to construct, due to some pesky implementation details.

This class fixes this by keeping a reservoir of such objects, and providing access to them via acquire(), in a thread-safe manner. If the cache is exhausted, new objects are constructed on the heap as needed.

release() makes a cached object available for acquiring again (cache) or destroys it (heap).

Public Functions

CachableOSStream()
CachableOSStream(std::string &output)

Calls stream.use_with(output); for use by heap objects.

Public Members

ExternalOStringStream stream

Public Static Functions

CachableOSStream *acquire(std::string &output)

Returns a brand-new(*) CachableOSStream object.

Origin may vary (static internal cache, heap allocation).

After you’re done, pass the pointer to release().

(*) Disclaimer: Object might not actually be brand-new.

Parameters
  • output: The string object that the stream should output its data to.

void release(CachableOSStream *cs)

Resets the stream to a brand-new state, and clears the flag.

no-op if cs is nullptr.

Private Members

std::atomic_flag flag = ATOMIC_FLAG_INIT

true if all of the following are true:

struct col
#include <color.h>

Public Functions

col(unsigned r, unsigned g, unsigned b, unsigned a)
col(gamedata::palette_color c)
void use()
void use(float alpha)

Public Members

unsigned r
unsigned g
unsigned b
unsigned a
struct color
#include <profiler.h>

Public Members

float r
float g
float b
struct component_time_data
#include <profiler.h>

Public Members

std::string display_name
color drawing_color
std::chrono::high_resolution_clock::time_point start
std::chrono::high_resolution_clock::duration duration
std::array<double, MAX_DURATION_HISTORY> history
template<unsigned int inbuf_size>
class BitStream
#include <bitstream.h>

Bitstream that is stored in 16-bit little-endian numbers.

There are two modes:

Bit stream

This is the default mode. Bits may be retrieved via read_bits().

The input bytes

0babcdefgh 0bijklmnop 0bmnopqrst 0buvwxyzAB

are decoded to the following bitstream:

ijkl mnop abcd efgh uvwx yzAB mnop qrst

Someone should get a medal for this.

Byte stream

In bytestream mode, read_bytes() can be used to read any number of bytes, verbatim, from the data source.

Mode switching

You can switch between modes via

Every modeswitch aligns the stream to a 16-bit boundary by discarding the appropriate amount of nullbits/nullbytes. Calling the modeswitch methods while already in the respective mode does nothing.

Public Functions

BitStream(read_callback_t read_callback)
unsigned read_bits(unsigned int nbits)

for use in bitstream mode.

takes nbits bits from the bit buffer and returns them.

unsigned read_bytes(unsigned char *buf, unsigned count)

for use in bytestream mode.

reads up to count verbatim bytes from the input byte buffer, and writes them to *buf.

reads at least 1 and at most count bytes.

unsigned char read_single_byte()

for use in bytestream mode.

reads a single verbatim byte from the input byte buffer, and returns it.

unsigned int read_4bytes_le()

for use in bytestream mode.

reads a little-endian-encoded 4-byte number and returns it.

void switch_to_bitstream_mode()

Switches to bitstream mode.

If the previous bytestream had an odd size, one byte is discarded first.

void switch_to_bytestream_mode()

Switches to bytestream mode.

Discards 1 to 16 bits to align the bitstream first.

void align_if_in_bitstream_mode()

Aligns the bitstream - that is, if we’re currenlty in bitstream mode.

Otherwise, a no-op.

Public Members

unsigned char eof

true if the read callback has returned EOF.

Private Functions

unsigned int input_bytes_available()

returns the number of bytes that are available in the input byte buffer.

void ensure_input_bytes()

ensures that at least one byte is available in the input byte buffer.

returns the amount of available bytes.

void load_next_16_bits()

for use in bitstream mode.

loads the next 16-bit value into the bitstream.

void ensure_bits(unsigned int nbits)

for use in bitstream mode.

ensures there are at least nbits bits in the bit buffer.

unsigned peek_bits(unsigned int nbits)

for use in bitstream mode.

returns nbits bits from the bit buffer, without removing them.

void remove_bits(unsigned int nbits)

for use in bitstream mode.

removes nbits bits from the bit buffer.

void align_bitstream(unsigned int min_discard = 0)

for use in bitstream mode.

Aligns the bitstream to the next multiple of 2 bytes.

If min_discard is given, at least that amount of bits is discarded.

Private Members

read_callback_t read_callback

read callback function; invoked whenever the input buffer is empty.

template<>
unsigned char inbuf[inbuf_size]

Input byte buffer.

Used by both modes (via ensure_bits and read_bytes).

unsigned char *i_ptr

Pointer to current position in inbuf.

unsigned char *i_end

Pointer to end of valid data in inbuf.

unsigned int bit_buffer

Bit buffer; used in bitstream mode.

Filled by via get_next_byte() via ensure_bits(), read by peak_bits(), cleared by remove_bits().

unsigned int bits_left

The number of valid bits in bit_buffer.

If e.g. the value is 2, only the two most significant bits of bit_buffer are set.

size_t stream_position

counts the number of bits (in bitstream mode) or bytes (in bytestream mode), for determining the correct number of bits/bytes to discard.

bool bitstream_mode

If set, the bitstream is currently in bytestream mode.

Friends

friend openage::util::compress::BitStream::HuffmanTable
template<unsigned int maxsymbols_p, unsigned int tablebits_p, bool allow_empty = false>
class HuffmanTable

Public Functions

HuffmanTable(class LZXDStream *lzx)
int read_sym()

Decodes the next huffman symbol from the input bitstream, and returns it.

Do not use this function on a table unless build_decode_table() succeeded.

void make_decode_table()

calls try_make_decode_table, and, if allow_empty is false, raises an exception on failure.

builds a huffman lookup table from code lengths.

void read_lengths(unsigned int first, unsigned int last)

reads in code lengths for symbols first to last in the given table.

The code lengths are stored in their own special LZX way.

Public Members

template<>
unsigned char len[maxsymbols_p + LZX_LENTABLE_SAFETY]

table of code lengths (in bits) for each symbol

template<>
uint16_t table[(1 << tablebits_p) + (maxsymbols_p * 2)]

table to fill up with decoded values for symbols, and pointers.

symbols shorter than tablebits_p are decoded by direct lookup (that’s the first (1<<tablebits_p) entries). longer symbols are decoded by following pointers to the appropriate leaf in the upper nsyms*2 fields.

bool is_empty

the table could not be constructed and is empty (try_make_decode_table failed).

this will lead to errors, should read_sym() be called.

Public Static Attributes

constexpr unsigned int HUFF_MAXBITS = 16
constexpr unsigned int maxsymbols = maxsymbols_p
constexpr unsigned int tablebits = tablebits_p

Private Functions

bool try_make_decode_table()

This function was originally coded by David Tritscher.

It builds a fast huffman decoding table from a canonical huffman code lengths table.

Private Members

class LZXDStream *lzx
class LZXDecompressor
#include <lzxd.h>

Wraps a LZXDStream object by reference; exposing LZXDStream directly would cause too much header pollution due to its many member objects, and their member objects.

pxd:

cppclass LZXDecompressor: LZXDecompressor( Func2[size_t, unsigned char *, size_t], unsigned int window_bits, unsigned int reset_interval ) except +

unsigned decompress_next_frame(unsigned char *out_buf) except +

Public Functions

LZXDecompressor(read_callback_t read_callback, unsigned int window_bits = 21, unsigned int reset_interval = 0)
~LZXDecompressor()

Frees the internally-allocated LZXDStream object.

unsigned decompress_next_frame(unsigned char *output_buf)

Decompresses a single 32-KiB frame.

Data from the input stream is read as required from read_callback. The decoded frame is written to output_buf. output_buf must be at least LZX_FRAME_SIZE (32768) bytes in size.

Returns 0 in case of EOF, and the size of the frame otherwise.

On error, an exception is thrown. After that, the object shall be destroyed; every other operation on it may invoke undefined behavior.

Private Functions

LZXDecompressor(const LZXDecompressor &other)
LZXDecompressor(LZXDecompressor &&other)
LZXDecompressor &operator=(const LZXDecompressor &other)
LZXDecompressor &operator=(LZXDecompressor &&other)

Private Members

class LZXDStream *stream
class LZXDStream

Public Functions

LZXDStream(read_callback_t callback, unsigned int window_bits, unsigned int reset_interval)

See the doc for LZXDecompressor::LZXDecompressor in lzxd.h.

~LZXDStream()
LZXDStream(const LZXDStream &other)
LZXDStream(LZXDStream &&other)
LZXDStream &operator=(const LZXDStream &other)
LZXDStream &operator=(LZXDStream &&other)
unsigned decompress_next_frame(unsigned char *output_buf)

See the doc for LZXDecompressor::decompress_next_frame in lzxd.h.

void reset_state()

Public Members

ssize_t output_pos
unsigned char *window
unsigned int window_size
unsigned int window_posn
unsigned int frame_posn
unsigned int frame
unsigned int reset_interval
unsigned int R0
unsigned int R1
unsigned int R2
unsigned int block_length
unsigned int block_remaining
signed int e8_magic
bool header_read
unsigned char block_type
unsigned char posn_slots
BitStream<4096> bits
HuffmanTable<LZX_PRETREE_MAXSYMBOLS, LZX_PRETREE_TABLEBITS> htpre
HuffmanTable<LZX_MAINTREE_MAXSYMBOLS, LZX_MAINTREE_TABLEBITS> htmain
HuffmanTable<LZX_LENGTH_MAXSYMBOLS, LZX_LENGTH_TABLEBITS, true> htlength
HuffmanTable<LZX_ALIGNED_MAXSYMBOLS, LZX_ALIGNED_TABLEBITS> htaligned

Private Functions

void init_next_block()

Initializes the next block.

int decode_symbol_from_verbatim_block()

Decodes one symbol from the current verbatim block.

Returns the number of bytes that were decoded. The bytes are written to the window, and window_posn is advanced.

int decode_symbol_from_aligned_block()

Decodes one symbol from the current aligned block.

Returns the number of bytes that were decoded. The bytes are written to the window, and window_posn is advanced.

unsigned int read_data_from_uncompressed_block(unsigned int size)

Reads the given amount of bytes from the current uncompressed block.

Returns its argument (the number of bytes that were read). The bytes are written to the window, and window_posn is advanced.

void postprocess_intel_e8(unsigned char *output_buf, int frame_size)

Postprocesses the a frame’s decoded data with E8 decoding.

Before compressing data, LZX pre-processes it by translating the four bytes following 0xE8-bytes; this optimizes intel x86 machine code.

What the hell, Microsoft?

struct truncated_string_literal
#include <constexpr.h>

Stores a string literal plus a “length specifier”.

Due to the nature of C strings, parts can only be cut off at the start of the string; this struct represents a string literal that has parts cut off at its end.

length represents the remaining length of the string; Functions using an object of this type SHALL NOT access memory locations beyond &literal[length].

Public Members

const char *literal
size_t length
template<typename T>
class ConstInitVector
#include <constinit_vector.h>

A std::vector-like object that has a constexpr constructor, and thus can be initialized during the const- or zero-initialization phase, before any dynamic initialization happens.

Use this class if and only if you need that functionality (that should be pretty uncommon; there generally are better ways of guaranteeing dynamic initialization order, such as static function variables).

Public Functions

constexpr ConstInitVector()
~ConstInitVector()
ConstInitVector(const ConstInitVector<T> &other)

Copying this is not supported.

ConstInitVector(ConstInitVector<T> &&other)
ConstInitVector &operator=(const ConstInitVector<T> &other)
ConstInitVector &operator=(ConstInitVector<T> &&other)
void push_back(const T &val)
const T &operator[](size_t idx) const

The returned reference is invalid if n >= this->size().

It may be invalidated by a call to push_back().

size_t size()

Returns the number of elements that have been pushed back.

Private Members

T *data
size_t capacity
size_t count
class DummyGuard

Provides some utility context guards.

Context guard that does nothing.

Public Static Functions

__enter__()
__exit__(exc_type exc_type, exc_value exc_value, traceback traceback)
template<class lineformat>
struct csv_subdata
#include <csv.h>

Referenced file tree structure.

Used for storing information for subtype members that need to be recursed.

Public Functions

bool read(const CSVCollection &collection, const std::string &basedir)

Read the data of the lineformat from the collection.

Can descend recursively into dependencies.

const lineformat &operator[](size_t idx) const

Convenience operator to access data.

Public Members

std::string filename

File where to read subdata from.

This name is relative to the file that defined the subdata!

std::vector<lineformat> data

Data that was read from the file with this->filename.

class CSVCollection
#include <csv.h>

Collection of multiple csv files.

Read from a packed csv that contains all the data.

Then, data can be read recursively.

Public Types

using csv_file_map_t = std::unordered_map<std::string, std::vector<std::string>>

Type for storing csv data: {filename: [line, …]}.

Public Functions

CSVCollection(const Path &entryfile)

Initialize the collection by reading the given file.

This file must contain the data that this collection is made up of.

virtual ~CSVCollection()
template<class lineformat>
std::vector<lineformat> read(const std::string &filename) const

This function is the entry point to load the whole file tree recursively.

Should be called again from the .recurse() method of the struct.

The internal flow is as follows:

  • read entries of the given files (call to the generated field parsers (the fill function))

  • then, recurse into referenced subdata entries (this implementation is generated)

  • from there, reach this function again to read each subdata entry.

template<typename lineformat>
std::vector<lineformat> get_data(const std::string &filename) const

Parse the data from one file in the map.

Protected Attributes

csv_file_map_t data
template<typename DerivedType>
class Enum
#include <enum.h>

Container for possible enum values.

Inherit from this class with CRTP.

This class should have the various values defined as static constexpr members. Due to the C++ standard, individual enum values must be declared as static constexpr members of a class. If they are declared as static constexpr constants in a namespace instead, the linker will place the constant in the ELF file once per object file instead of deduplicating it.

Objects of this class contain a reference to a static constexpr value.

The static constexpr values can be accessed through operator ->.

See the documentation for the EnumValue class above.

pxd:

cppclass Enum[DerivedType]: const DerivedType &get() except +

bool operator ==(Enum[DerivedType] other) except + bool operator !=(Enum[DerivedType] other) except +

bool operator <(Enum[DerivedType] other) except + bool operator >(Enum[DerivedType] other) except + bool operator <=(Enum[DerivedType] other) except + bool operator >=(Enum[DerivedType] other) except +

Public Functions

constexpr Enum()
constexpr Enum(const DerivedType &value)
constexpr operator const DerivedType&() const
constexpr Enum &operator=(const DerivedType &value)
constexpr const DerivedType *operator->() const
constexpr bool operator==(const this_type &other) const
constexpr bool operator!=(const this_type &other) const
constexpr bool operator<=(const this_type &other) const
constexpr bool operator<(const this_type &other) const
constexpr bool operator>=(const this_type &other) const
constexpr bool operator>(const this_type &other) const
constexpr const DerivedType &get() const

Protected Attributes

const DerivedType *value

Private Types

template<>
using this_type = Enum<DerivedType>

Friends

std::ostream &operator<<(std::ostream &os, const this_type &arg)
template<typename DerivedType, typename NumericType = int>
class EnumValue
#include <enum.h>

Public Functions

EnumValue(const EnumValue &other)
EnumValue &operator=(const EnumValue &other)
constexpr bool operator==(const DerivedType &other) const
constexpr bool operator!=(const DerivedType &other) const
constexpr bool operator<=(const DerivedType &other) const
constexpr bool operator<(const DerivedType &other) const
constexpr bool operator>=(const DerivedType &other) const
constexpr bool operator>(const DerivedType &other) const

Public Members

const char *name
NumericType numeric

Friends

std::ostream &operator<<(std::ostream &os, const DerivedType &arg)
class ExternalOStringStream : public ostream
#include <externalsstream.h>

Similar to std::ostringstream, but data is written to an external string object.

Using this stream before calling use_with will result in undefined behavior.

Public Functions

ExternalOStringStream()

Creates a stream without a valid accumulator.

void use_with(std::string &output)

Resets the stream’s flags, and sets ptr as the internally-used accumulator.

Private Members

ExternalStringBuf buf
class ExternalProfiler
#include <externalprofiler.h>

Public Functions

ExternalProfiler()
void start()
void stop()
void show_results()

Public Members

bool currently_profiling
const bool can_profile

Public Static Attributes

const char *const profiling_filename = "/tmp/openage-gperftools-cpuprofile"
const char *const profiling_pdf_filename = "/tmp/openage-gperftools-cpuprofile.pdf"
class ExternalStringBuf : public streambuf
#include <externalsstream.h>

Used by ExternalOStringStream; data is written to the external accumulator.

If this object’s write functionality is accessed before output has been manually set to a valid std::string object, or if the lifetime of that object has been exceeded, undefined behavior will result.

Public Functions

int overflow(int chr)
std::streamsize xsputn(const char *s, std::streamsize count)

Public Members

std::string *output
class FD
#include <fds.h>

wraps a POSIX file descriptor

Public Functions

FD(int fd)

wraps an existing FD

FD(int fd, bool set_nonblocking)

duplicates an existing FD, and optionally sets it to non-blocking mode

FD(FD *fd, bool set_nonblocking)
~FD()
int write(const char *buf, size_t bytes)

writes ‘bytes’ bytes from buf

int puts(const char *str)

writes the string (excluding the null terminator)

int putbyte(char c)

writes the char

int putcp(int cp)

writes the unicode codepoint, as utf-8

int printf(const char *format, ...)

guess what this does.

because I won’t tell you.

void setinputmodecanon()

sets input to canonical mode.

this includes:

  • disabling ECHO

  • non-buffered input

  • no generation of signals on ^C, ^Z, …

void restoreinputmode()

restores the input mode to the mode that was backed up during the last setinputmodecanon() mode.

Public Members

int fd
bool close_on_destroy = false

if this is set to true, the destructor will close the fd.

will be set to true by the constructor iff the fd was duped.

bool restore_input_mode_on_destroy = false

if this is set to true, the destructor will restore the input mode.

will be set on setinputmodecanon().

struct termios old_tio
class File
#include <file.h>

Generic File implementation, used in our filesystem-like and file-like abtraction system.

Can be created from Python :)

TODO: maybe inherit from std::iostream so we can use it the c++-way

pxd:

cppclass File: File() noexcept File(const string &path, int mode) except + File(PyObj) except +

shared_ptr[FileLike] get_fileobj() except +

Public Types

using seek_t = filelike::FileLike::seek_t
using mode_t = filelike::FileLike::mode_t

Public Functions

File()

Empty constructor, pls don’t use.

It only exists because Cython needs it.

File(const std::string &path, int mode)

Open a filesystem path, int version.

this is just the integer value of the mode_t, because Cython…

File(const std::string &path, mode_t mode = mode_t::R)

Open a filesystem path.

File(std::shared_ptr<filelike::FileLike> filelike)

Create a file from an already created filelike.

File(py::Obj filelike)

Wraps a python filelike object that is already open.

This is called from Cython.

You will probably never call that manually.

virtual ~File()
std::string read(ssize_t max = -1)

Read data from the file and return a string.

If max is negative, return the full remaining file.

size_t read_to(void *buf, ssize_t max = -1)

Read data from the file into a buffer, which has to be large enough to fit max bytes.

If max is negative, read the full remaining file, so buf has to be as big as the remaining file size.

Returns the number of bytes that were read.

bool readable()
void write(const std::string &data)
bool writable()
void seek(ssize_t offset, seek_t how = seek_t::SET)
bool seekable()
size_t tell()
void close()
void flush()
ssize_t size()
std::vector<std::string> get_lines()
std::shared_ptr<filelike::FileLike> get_fileobj() const

Protected Attributes

std::shared_ptr<filelike::FileLike> filelike

Friends

std::ostream &operator<<(std::ostream &stream, const File &file)
class FileLikeObject

Abstract base class for file-like objects.

Note that checking isinstance(obj, FileLikeObject) is a bad idea, because that would exclude actual files, and Python’s built-in file-like objects.

Does not implement/force implementation of line-reading functionality.

Subclassed by openage.util.filelike.fifo.FIFO, openage.util.filelike.readonly.ReadOnlyFileLikeObject, openage.util.fslike.wrapper.GuardedFile

Public Functions

__init__(self self)
read(self self, size size = -1)

Read at most size bytes (less if EOF has been reached).

Shall raise UnsupportedOperation for write-only objects.

readable(self self)

Returns True if read() is allowed.

write(self self, data data)

Writes all of data to the file.

Shall raise UnsupportedOperation for read-only object.

There is no return value.

writable(self self)

Returns True if write() is allowed.

seek(self self, offset offset, whence whence = os.SEEK_SET)

Seeks to a given position.

May raise UnsupportedOperation for any or all arguments, in case of unseekable streams.

For testing seek capabilities, it’s recommended to call seek(0) immediately after object creation.

There is no return value.

seekable(self self)

Returns True if seek() is allowed.

tell(self self)

Returns the current position in the file.

Must work properly for all file-like objects.

close(self self)
flush(self self)
get_size(self self)
__enter__(self self)
__exit__(self self, exc_type exc_type, exc_val exc_val, exc_tb exc_tb)
seek_helper(self self, offset offset, whence whence)

Helper function for use by implementations of seek().

Calculates the new cursor position relative to file start from offset, whence and self.tell().

If size is given, it works for whence=os.SEEK_END; otherwise, UnsupportedOperation is raised.

Public Members

closed
class FIFO

File-like wrapper around ByteQueue.

Data written via write() can later be retrieved via read().

EOF handling is a bit tricky:

EOF in the data source (the writer) can not be auto-detected, and must be manually indicated by calling seteof().

Only then will read() show the desired behavior for EOF.

If EOF has not yet been set, read() will raise ValueError if more data than currently available has been requested.

Subclassed by openage.codegen.codegen.WriteCatcher

Public Functions

__init__(self self)
tell(self self)

Warning

Returns the position for reading.

    Due to the FIFO nature, the position for writing is further-advanced.

tellw(self self)

Returns the position for writing.

seek(self self, offset offset, whence whence = os.SEEK_SET)

Unsupported because this is a FIFO.

seekable(self self)
__len__(self self)

Returns the amount of currently-enqueued data.

seteof(self self)

Declares that no more data will be added using write().

Note that this does not mean that no more data is available through write; the queue may still hold some data.

write(self self, data data)

Works until seteof() has been called; accepts bytes objects.

writable(self self)
read(self self, size size = -1)
readable(self self)
get_size(self self)
flush(self self)
close(self self)

Public Members

eof
queue
pos
closed
class FileLike
#include <filelike.h>

File-like class that has the standard operations like read, seek, write etc.

pxd: ctypedef enum seek_t “openage::util::filelike::FileLike::seek_t”: seek_t_SET “::openage::util::filelike::FileLike::seek_t::SET” = 0 seek_t_CUR “::openage::util::filelike::FileLike::seek_t::CUR” = 1 seek_t_END “::openage::util::filelike::FileLike::seek_t::END” = 2

cppclass FileLike: string read(ssize_t max) except + bool readable() except + void write(const string &data) except + bool writable() except + void seek(ssize_t offset, seek_t how) except + bool seekable() except + size_t tell() except + void close() except + void flush() except + ssize_t get_size() except +

bool is_python_native() noexcept

Subclassed by openage::util::filelike::Native, openage::util::filelike::Python

Public Types

enum seek_t

Seek reference point.

Don’t change the numbers, they’re used from Cython.

Values:

SET = 0

offset from file beginning

CUR = 1

offset from current position

END = 2

offset from file end

enum mode_t

File access mode.

Sync the numbers with the fslike/cpp.pyx because Cython can’t enum class yet. TODO: once cython can handle enum class, add pxd annotation.

Values:

R = 0
W = 1
RW = 2
A = 3
AR = 4

Public Functions

FileLike()
virtual ~FileLike()
virtual std::string read(ssize_t max = -1) = 0
virtual size_t read_to(void *buf, ssize_t max = -1) = 0
virtual bool readable() = 0
virtual void write(const std::string &data) = 0
virtual bool writable() = 0
virtual void seek(ssize_t offset, seek_t how = seek_t::SET) = 0
virtual bool seekable() = 0
virtual size_t tell() = 0
virtual void close() = 0
virtual void flush() = 0
virtual ssize_t get_size() = 0
bool is_python_native() const
virtual std::ostream &repr(std::ostream&) = 0

string representation of the filelike

class Native : public openage::util::filelike::FileLike
#include <native.h>

File-like class that uses native stdlib functions to access data.

Public Functions

Native(const std::string &path, mode_t mode = mode_t::R)
~Native()
std::string read(ssize_t max)
size_t read_to(void *buf, ssize_t max)
bool readable()
void write(const std::string &data)
bool writable()
void seek(ssize_t offset, seek_t how = seek_t::SET)
bool seekable()
size_t tell()
void close()
void flush()
ssize_t get_size()
std::ostream &repr(std::ostream&)

string representation of the filelike

Protected Attributes

std::string path
mode_t mode
std::fstream file
class Python : public openage::util::filelike::FileLike
#include <python.h>

File-like class that wraps a python open() file-like object.

pxd: cppclass Python: PyObj &get_py_fileobj() except +

Public Functions

Python(py::Obj fileobj)
std::string read(ssize_t max)
size_t read_to(void *buf, ssize_t max)
bool readable()
void write(const std::string &data)
bool writable()
void seek(ssize_t offset, seek_t how = seek_t::SET)
bool seekable()
size_t tell()
void close()
void flush()
ssize_t get_size()
bool is_python_native() const
py::Obj &get_py_fileobj() const
std::ostream &repr(std::ostream&)

string representation of the filelike

Protected Attributes

std::shared_ptr<py::Obj> fileobj
class PosSavingReadOnlyFileLikeObject

Stores the current seek position in self.pos.

Avoids code duplication.

Subclassed by openage.cabextract.cab.CABFolderStream, openage.util.filelike.stream.StreamFragment, openage.util.filelike.stream.StreamSeekBuffer

Public Functions

__init__(self self)
seek(self self, offset offset, whence whence = os.SEEK_SET)
seekable(self self)
tell(self self)

Public Members

pos
class ReadOnlyFileLikeObject

Subclassed by openage.cabextract.lzxdstream.LZXDStream, openage.util.filelike.readonly.PosSavingReadOnlyFileLikeObject

Public Functions

flush(self self)
readable(self self)
write(self self, data data)
writable(self self)
class StreamFragment

Public Functions

__init__(self self, stream stream, start start, size size)
read(self self, size size = -1)
get_size(self self)
close(self self)

Public Members

stream
start
size
closed
class StreamSeekBuffer

Public Functions

__init__(self self, wrappee wrappee, keepbuffered keepbuffered = INF, minread minread = 1048576)
resetwrappeed(self self)

resets the wrappeed object, and clears self.buf.

read(self self, size size = -1)
get_size(self self)
close(self self)

Public Members

wrapped
keepbuffered
minread
buf
closed
template<typename int_type, unsigned int fractional_bits>
class FixedPoint
#include <fixed_point.h>

Fixed-point integer class;.

this is designed to be used instead of floats in places where guaranteed precision is required.

For example, FixedPoint<int64_t, 32> can store values from -2**32 to +2**32 with a constant precision of 2**-32.

Public Types

template<>
using raw_type = int_type
template<>
using this_type = FixedPoint<int_type, fractional_bits>
template<>
using unsigned_int_type = typename std::make_unsigned<int_type>::type
template<>
using same_type_but_unsigned = FixedPoint<typename FixedPoint::unsigned_int_type, fractional_bits>

Public Functions

constexpr FixedPoint(const FixedPoint &other)
constexpr FixedPoint(FixedPoint &&other)
constexpr FixedPoint &operator=(const FixedPoint &other)
constexpr FixedPoint &operator=(FixedPoint &&other)
constexpr FixedPoint()

Empty constructor.

Initializes the number to 0.

constexpr FixedPoint(double n)

floating-point constructor.

Initializes the number from a double.

constexpr int_type get_raw_value() const

Converter to retrieve the raw value of the fixed-point number.

Don’t use this.

constexpr int_type to_int() const

Converter to retrieve the int (pre-decimal) part of the number.

constexpr operator int() const
constexpr float to_float() const

Converter to retrieve the number as float.

constexpr operator float() const
constexpr double to_double() const

Converter to retrieve the number as double.

constexpr operator double() const
std::string str() const

Show a string representation.

Useful for debugging in gdb.

constexpr FixedPoint::same_type_but_unsigned get_fractional_part() const

Converter to retrieve the fractional (post-decimal) part of the number.

constexpr bool operator==(const FixedPoint &o) const
constexpr bool operator!=(const FixedPoint &o) const
constexpr bool operator<(const FixedPoint &o) const
constexpr bool operator>(const FixedPoint &o) const
constexpr bool operator<=(const FixedPoint &o) const
constexpr bool operator>=(const FixedPoint &o) const
constexpr FixedPoint operator+() const
template<typename inner_int_type = int_type>
constexpr std::enable_if<std::is_signed<inner_int_type>::value, typename FixedPoint::this_type>::type operator-() const
template<typename I, unsigned F>
constexpr double hypot(const FixedPoint<I, F> rhs)
template<typename I, unsigned F>
constexpr FixedPoint<I, F> hypotfp(const FixedPoint<I, F> rhs)
constexpr FixedPoint &operator+=(const FixedPoint &n)
constexpr FixedPoint &operator-=(const FixedPoint &n)
template<typename N>
std::enable_if<std::is_arithmetic<N>::value, FixedPoint&>::type constexpr operator*=(const N &rhs)

FixedPoint *= N, where N is not a FixedPoint.

template<typename N>
constexpr FixedPoint &operator/=(const N &rhs)

FixedPoint /= N.

void swap(FixedPoint &rhs)
constexpr double sqrt()

Public Static Functions

static constexpr FixedPoint zero()

FixedPoint value that is preinitialized to zero.

static constexpr FixedPoint from_int(int_type n)

Factory function to get a fixed-point number from an integer.

static constexpr FixedPoint from_float(float n)

Factory function to get a fixed-point number from a float.

static constexpr FixedPoint from_double(double n)

Factory function to get a fixed-point number from a double.

template<typename other_int_type, unsigned int other_fractional_bits>
static constexpr FixedPoint from_fixedpoint(const FixedPoint<other_int_type, other_fractional_bits> &other)

Factory function to get a fixed-point number from a fixed-point number of different type.

static constexpr const FixedPoint min_value()

The minimum possible value of this type.

static constexpr const FixedPoint max_value()

The maximum possible value of this type.

static constexpr FixedPoint from_raw_value(int_type raw_value)

Factory function to construct a fixed-point number with a given raw value.

Don’t use this.

Private Members

int_type raw_value

Storage of the fixed point data.

Private Static Functions

static constexpr double power_of_two(unsigned int power)
static constexpr FixedPoint::unsigned_int_type fractional_part_bitmask()
static constexpr int_type raw_value_from_double(double n)

Private Static Attributes

constexpr const double from_double_factor = power_of_two(fractional_bits)
constexpr const double to_double_factor = 1 / from_double_factor
constexpr const float from_float_factor = from_double_factor
constexpr const float to_float_factor = to_double_factor
constexpr const unsigned int approx_decimal_places = static_cast<unsigned int>(static_cast<double>(fractional_bits) * 0.30103 + 1)

Friends

std::ostream &operator<<(std::ostream &os, const FixedPoint &n)
std::istream &operator>>(std::istream &is, FixedPoint &n)
template<unsigned decimals, unsigned w = 0>
struct FloatFixed
#include <strings.h>

Quick-formatter for floats when working with string streams.

Usage: cout << FormatFloat{1.0, 10};

Public Members

float value
class Formatter : public openage::util::StringFormatter<Formatter>
#include <stringformatter.h>

Allows simple direct usage of StringFormatter.

class FrameCounter
#include <fps.h>

Public Functions

FrameCounter()
~FrameCounter()
void frame()

to be called each time a frame has been completed

Public Members

float fps

auto-updated to always contain the current FPS value

float display_fps

auto-updated every 20 frames to always contain the current FPS value

uint64_t count

contains the number of completed frames

time_nsec_t nsec_lastframe

nanoseconds used for the last frame

Private Members

float frame_count_weighted
float frame_length_sum_weighted
Timer frame_timer
class FSLikeObject

Subclassed by openage.util.fslike.abstract.ReadOnlyFSLikeObject, openage.util.fslike.directory.Directory, openage.util.fslike.filecollection.FileCollection, openage.util.fslike.union.Union, openage.util.fslike.wrapper.Wrapper

Public Functions

root(self self)

Returns a path-like object for the root of this file system.

This is the main interface that is used normally.

pretty(self self, parts parts)

pretty-format a path in this filesystem like object.

open_r(self self, parts parts)

Shall return a BufferedReader for the given file (“mode ‘rb’”).

open_w(self self, parts parts)

Shall return a BufferedWriter for the given file (“mode ‘wb’”).

open_rw(self self, parts parts)

Shall return a BufferedWriter for the given file (“mode ‘r+’”).

open_a(self self, parts parts)

Shall return a BufferedWriter for the given file (“mode ‘a’”).

open_ar(self self, parts parts)

Shall return a BufferedWriter for the given file (“mode ‘a+’”).

exists(self self, parts parts)

Test if the parts are a file or a directory.

resolve_r(self self, parts parts)
resolve_w(self self, parts parts)

Returns a new flattened path.

This skips funny mounts in between.

   Returns None if the path does not exist or is not writable.

get_native_path(self self, parts parts)
list(self self, parts parts)

Shall yield the entry names of the given directory.

filesize(self self, parts parts)
mtime(self self, parts parts)
mkdirs(self self, parts parts)

Shall ensure that the directory exists.

rmdir(self self, parts parts)

Shall remove an empty directory.

Shall remove a single file.

touch(self self, parts parts)

Shall create the file or update its timestamp.

rename(self self, srcparts srcparts, tgtparts tgtparts)

Shall rename a file or directory to the target name.

is_file(self self, parts parts)
is_dir(self self, parts parts)
writable(self self, parts parts)
watch(self self, parts parts, callback callback)
poll_watches(self self)
class ReadOnlyFSLikeObject

Subclassed by openage.util.fslike.wrapper.WriteBlocker

Public Functions

read_only_error(self self, parts parts)

Helper method to be called from all other methods.

open_w(self self, parts parts)
mkdirs(self self, parts parts)
rmdir(self self, parts parts)
touch(self self, parts parts)
rename(self self, srcparts srcparts, tgtparts tgtparts)
writable(self self, parts parts)
class Directory : public openage::util::fslike::FSLike
#include <directory.h>

Filesystem-like object which uses native libc calls.

It is used to directly access your real filesystem that the kernel mounted for you.

Public Functions

Directory(const std::string &basepath, bool create_if_missing = false)
bool is_file(const Path::parts_t &parts)
bool is_dir(const Path::parts_t &parts)
bool writable(const Path::parts_t &parts)
std::vector<Path::part_t> list(const Path::parts_t &parts)
bool mkdirs(const Path::parts_t &parts)
File open_r(const Path::parts_t &parts)
File open_w(const Path::parts_t &parts)
File open_rw(const Path::parts_t &parts)
File open_a(const Path::parts_t &parts)
File open_ar(const Path::parts_t &parts)
std::string get_native_path(const Path::parts_t &parts)
bool rename(const Path::parts_t &parts, const Path::parts_t &target_parts)
bool rmdir(const Path::parts_t &parts)
bool touch(const Path::parts_t &parts)
bool unlink(const Path::parts_t &parts)
int get_mtime(const Path::parts_t &parts)
uint64_t get_filesize(const Path::parts_t &parts)
std::ostream &repr(std::ostream &stream)

Protected Functions

std::string resolve(const Path::parts_t &parts) const

resolve the path to an actually usable one.

basically basepath + “/”.join(parts)

std::tuple<struct stat, int> do_stat(const Path::parts_t &parts) const

Protected Attributes

std::string basepath
class CaseIgnoringDirectory

Public Functions

__init__(self self, path path, create_if_missing create_if_missing = False)
__repr__(self self)
actual_name(self self, stem stem, name name)
resolve(self self, parts parts)
list(self self, parts parts)

Public Members

cache
listings
class Directory

Provides an actual file system directory’s contents as-they-are.

Initialized from some real path that is mounted already by your system.

Subclassed by openage.util.fslike.directory.CaseIgnoringDirectory

Public Functions

__init__(self self, path_ path_, create_if_missing create_if_missing = False)
__repr__(self self)
resolve(self self, parts parts)

resolves parts to an actual path name.

open_r(self self, parts parts)
open_w(self self, parts parts)
open_rw(self self, parts parts)
open_a(self self, parts parts)
open_ar(self self, parts parts)
get_native_path(self self, parts parts)
list(self self, parts parts)
filesize(self self, parts parts)
mtime(self self, parts parts)
mkdirs(self self, parts parts)
rmdir(self self, parts parts)
touch(self self, parts parts)
rename(self self, srcparts srcparts, tgtparts tgtparts)
is_file(self self, parts parts)
is_dir(self self, parts parts)
writable(self self, parts parts)
watch(self self, parts parts, callback callback)
poll_watches(self self)

Public Members

path
class FileCollection

FSLikeObject that holds several individual files.

Uses lambdas to access files somewhere else on the fly.

Subclassed by openage.cabextract.cab.CABFile, openage.convert.drs.DRS

Public Functions

__init__(self self)
root(self self)
get_direntries(self self, parts parts = None, create create = False)

Fetches the fileentries, subdirentries tuple for the given dir.

If create == False, raises FileNotFoundError if the directory doesn’t exist.

Helper method for internal use.

add_fileentry(self self, parts parts, fileentry fileentry)

Adds a file entry (and parent directory entries, if needed).

This method should not be called directly; instead, use the add_file method of Path objects that were obtained from this.

fileentry must be open_r, open_w, size, mtime.

get_fileentry(self self, parts parts)

Gets a file entry.

Helper method for internal use.

   Returns open_r, open_w, size, mtime

open_r(self self, parts parts)
open_w(self self, parts parts)
list(self self, parts parts)
filesize(self self, parts parts)
mtime(self self, parts parts)
mkdirs(self self, parts parts)
rmdir(self self, parts parts)
touch(self self, parts parts)
rename(self self, srcparts srcparts, tgtparts tgtparts)
is_file(self self, parts parts)
is_dir(self self, parts parts)
writable(self self, parts parts)
watch(self self, parts parts, callback callback)
poll_watches(self self)

Public Members

rootentries
class FileCollectionPath

Provides an additional method for adding a file at this path.

Public Functions

add_file(self self, open_r open_r = None, open_w open_w = None, filesize filesize = None, mtime mtime = None)

All parent directories are ‘created’, if needed.

Any arguments may be None, and shall be callable otherwise. If open_r/open_w are None, the file will write-/read-only.

add_file_from_path(self self, path path)

Like add_file, but uses a Path object instead of callables.

class FSLike : public std::enable_shared_from_this<FSLike>
#include <fslike.h>

Base class for possible path implementations.

pxd: cppclass FSLike: Path root() except + bool is_file(const parts_t &parts) except + bool is_dir(const parts_t &parts) except + bool writable(const parts_t &parts) except + parts_t list(const parts_t &parts) except + bool mkdirs(const parts_t &parts) except +

File open_r(const parts_t &parts) except + File open_w(const parts_t &parts) except + File open_rw(const parts_t &parts) except + File open_a(const parts_t &parts) except + File open_ar(const parts_t &parts) except + pair[bool, Path] resolve_r(const parts_t &parts) except + pair[bool, Path] resolve_w(const parts_t &parts) except + string get_native_path(const parts_t &parts) except +

bool rename(const parts_t &parts, const parts_t &target_parts) except + bool rmdir(const parts_t &parts) except + bool touch(const parts_t &parts) except + bool unlink(const parts_t &parts) except +

int get_mtime(const parts_t &parts) except + uint64_t get_filesize(const parts_t &parts) except +

bool is_python_native() noexcept shared_ptr[FSLike] shared_from_this() except +

Subclassed by openage::util::fslike::Directory, openage::util::fslike::Python

Public Functions

FSLike()
virtual ~FSLike()
Path root()
virtual bool is_file(const Path::parts_t &parts) = 0
virtual bool is_dir(const Path::parts_t &parts) = 0
virtual bool writable(const Path::parts_t &parts) = 0
virtual Path::parts_t list(const Path::parts_t &parts) = 0
virtual bool mkdirs(const Path::parts_t &parts) = 0
virtual File open_r(const Path::parts_t &parts) = 0
virtual File open_w(const Path::parts_t &parts) = 0
virtual File open_rw(const Path::parts_t &parts) = 0
virtual File open_a(const Path::parts_t &parts) = 0
virtual File open_ar(const Path::parts_t &parts) = 0
std::pair<bool, Path> resolve_r(const Path::parts_t &parts)
std::pair<bool, Path> resolve_w(const Path::parts_t &parts)
virtual std::string get_native_path(const Path::parts_t &parts) = 0
virtual bool rename(const Path::parts_t &parts, const Path::parts_t &target_parts) = 0
virtual bool rmdir(const Path::parts_t &parts) = 0
virtual bool touch(const Path::parts_t &parts) = 0
virtual bool unlink(const Path::parts_t &parts) = 0
virtual int get_mtime(const Path::parts_t &parts) = 0
virtual uint64_t get_filesize(const Path::parts_t &parts) = 0
bool is_python_native() const
virtual std::ostream &repr(std::ostream&) = 0
class Path

Subclassed by openage.util.fslike.filecollection.FileCollectionPath, openage.util.fslike.union.UnionPath

Public Functions

__init__(self self, fsobj fsobj, parts parts = None)
__str__(self self)
__repr__(self self)
exists(self self)

True if path exists.

is_dir(self self)

True if path points to dir (or symlink to one)

is_file(self self)

True if path points to file (or symlink to one)

writable(self self)

True if path is probably writable.

list(self self)

Yields path names for all members of this dir.

iterdir(self self)

Yields path objects for all members of this dir.

mkdirs(self self)

Creates this path (including parents).

No-op if path exists.

open(self self, mode mode = "r")

Opens the file at this path; returns a file-like object.

open_r(self self)

open with mode=’rb’

open_w(self self)

open with mode=’wb’

resolve_native_path(self self, mode mode = "r")
resolve_native_path_r(self self)
resolve_native_path_w(self self)
rename(self self, targetpath targetpath)

renames to targetpath

rmdir(self self)

Removes the empty directory at this path.

touch(self self)

Creates the file at this path, or updates the timestamp.

Removes the file at this path.

removerecursive(self self)

Recursively deletes this file or directory.

mtime(self self)

Returns the time of last modification of the file or directory.

filesize(self self)

Returns the file size.

watch(self self, callback callback)
poll_fs_watches(self self)

Polls the installed watches for the entire file-system.

parent(self self)

Parent path object.

The parent of root is root.

name(self self)

The name of the topmost component (str).

suffix(self self)

The last suffix of the name of the topmost component (str).

suffixes(self self)

The suffixes of the name of the topmost component (str list).

stem(self self)

Name without suffix (such that stem + suffix == name).

joinpath(self self, subpath subpath)

Returns path for the given subpath.

__getitem__(self self, subpath subpath)

Like joinpath.

__truediv__(self self, subpath subpath)

Like joinpath.

__eq__(self self, other other)

comparison by fslike and parts

with_name(self self, name name)

Returns path for differing name (same parent).

with_suffix(self self, suffix suffix)

Returns path for different suffix (same parent and stem).

mount(self self, pathobj pathobj, priority priority = 0)

This is only valid for UnionPath, don’t call here.

Public Members

fsobj
parts

Private Functions

_get_native_path(self self)
_resolve_r(self self)
_resolve_w(self self)
class Python : public openage::util::fslike::FSLike
#include <python.h>

Filesystem-like object that wraps a filesystem-like object from Python.

Calls are relayed via Cython, which performs the data conversion.

pxd: cppclass Python(FSLike): PyObj &get_py_fsobj() except +

Public Functions

Python(py::Obj fsobj)
bool is_file(const Path::parts_t &parts)
bool is_dir(const Path::parts_t &parts)
bool writable(const Path::parts_t &parts)
std::vector<Path::part_t> list(const Path::parts_t &parts)
bool mkdirs(const Path::parts_t &parts)
File open_r(const Path::parts_t &parts)
File open_w(const Path::parts_t &parts)
File open_rw(const Path::parts_t &parts)
File open_a(const Path::parts_t &parts)
File open_ar(const Path::parts_t &parts)
std::pair<bool, Path> resolve_r(const Path::parts_t &parts)
std::pair<bool, Path> resolve_w(const Path::parts_t &parts)
std::string get_native_path(const Path::parts_t &parts)
bool rename(const Path::parts_t &parts, const Path::parts_t &target_parts)
bool rmdir(const Path::parts_t &parts)
bool touch(const Path::parts_t &parts)
bool unlink(const Path::parts_t &parts)
int get_mtime(const Path::parts_t &parts)
uint64_t get_filesize(const Path::parts_t &parts)
bool is_python_native() const
py::Obj &get_py_fsobj() const
std::ostream &repr(std::ostream &stream)

Protected Attributes

std::shared_ptr<py::Obj> fsobj
class Union

FSLikeObject that provides a structure for mounting several path objects.

Unlike in POSIX, mounts may overlap. If multiple mounts match for a directory, those that have a higher priority are preferred. In case of equal priorities, later mounts are preferred.

Public Functions

__init__(self self)
__str__(self self)
root(self self)
add_mount(self self, pathobj pathobj, mountpoint mountpoint, priority priority)
remove_mount(self self, search_mountpoint search_mountpoint, source_pathobj source_pathobj = None)
candidate_paths(self self, parts parts)

Helper method.

Yields path objects from all mounts that match parts, in the order of their priorities.

open_r(self self, parts parts)
open_w(self self, parts parts)
resolve_r(self self, parts parts)
resolve_w(self self, parts parts)
list(self self, parts parts)
filesize(self self, parts parts)
mtime(self self, parts parts)
mkdirs(self self, parts parts)
rmdir(self self, parts parts)
touch(self self, parts parts)
rename(self self, srcparts srcparts, tgtparts tgtparts)
is_file(self self, parts parts)
is_dir(self self, parts parts)
writable(self self, parts parts)
watch(self self, parts parts, callback callback)
poll_watches(self self)

Public Members

mounts
dirstructure
class UnionPath

Provides an additional method for mounting an other path at this path.

Public Functions

mount(self self, pathobj pathobj, priority priority = 0)

Mounts pathobj here.

All parent directories are ‘created’, if needed.

unmount(self self, pathobj pathobj = None)
class DirectoryCreator

Public Functions

open_w(self self, parts parts)
__repr__(self self)
class GuardedFile

Public Functions

__init__(self self, obj obj, guard guard)
read(self self, size size = -1)
readable(self self)
write(self self, data data)
writable(self self)
seek(self self, offset offset, whence whence = os.SEEK_SET)
seekable(self self)
tell(self self)
close(self self)
flush(self self)
get_size(self self)
__repr__(self self)

Public Members

obj
guard
class Synchronizer

Wraps a FSLikeObject, securing all wrapped calls with a mutex.

Public Functions

__init__(self self, obj obj)
__repr__(self self)

Public Members

lock
class Wrapper

Wraps a Path, implementing all methods as pass-through.

Inherit to override individual methods. Pass a context guard to protect calls.

Subclassed by openage.codegen.codegen.CodegenDirWrapper, openage.util.fslike.wrapper.DirectoryCreator, openage.util.fslike.wrapper.Synchronizer, openage.util.fslike.wrapper.WriteBlocker

Public Functions

__init__(self self, obj obj, contextguard contextguard = None)
__repr__(self self)
open_r(self self, parts parts)
open_w(self self, parts parts)
resolve_r(self self, parts parts)
resolve_w(self self, parts parts)
list(self self, parts parts)
filesize(self self, parts parts)
mtime(self self, parts parts)
mkdirs(self self, parts parts)
rmdir(self self, parts parts)
touch(self self, parts parts)
rename(self self, srcparts srcparts, tgtparts tgtparts)
is_file(self self, parts parts)
is_dir(self self, parts parts)
writable(self self, parts parts)
watch(self self, parts parts, callback callback)
poll_watches(self self)

Public Members

obj
contextguard
class WriteBlocker

Wraps a FSLikeObject, transparently passing through all read-only calls.

All writing calls raise IOError, and writable returns False.

Public Functions

__repr__(self self)
class FString : public openage::util::StringFormatter<FString>
#include <stringformatter.h>

A self-formatting string! Get yours today!

Use like this:

std::string stuff() { FString s; s << “test: ” << 5 << std::cout; return s; }

Use as a faster, care-free replacement for stringstream:

std::string stuff() { std::stringstream sstr; sstr << “test: ” << 5 << std::cout; return sstr.str(); }

Public Functions

FString()

Public Members

openage::util::FString::buffer{other} {}FString(std::string &&other) noexcept :StringFormatter<FString>{this->buffer}
template<typename ReturnType, typename ...ArgTypes>
class FunctionPtr
#include <language.h>

Simple wrapper type that contains a function pointer.

Needed as workaround for http://stackoverflow.com/questions/31040075

Public Functions

FunctionPtr(ReturnType (*ptr)(ArgTypes...))

Implicit conversion from raw type.

Public Members

template<>
ReturnType (*ptr)(ArgTypes...)
template<typename T>
struct less
#include <misc.h>

generic callable, that compares any types for creating a total order.

use for stdlib structures like std::set. the template parameter has to be a pointer type.

Public Functions

bool operator()(const T x, const T y) const
template<size_t M, size_t N, typename T>
class Matrix : public std::array<std::array<T, N>, M>
#include <matrix.h>

Matrix class with arithmetic.

M rows, N columns. T = underlying single value type (float, double, …)

Public Types

template<>
using this_type = Matrix<M, N, T>

Public Functions

Matrix()

Initialize the matrix to zeroes.

~Matrix()
template<bool cond = is_column_vector, typename = typename std::enable_if<cond>::type>
Matrix(const Vector<M, T> &vec)

Constructor from Vector.

template<typename ...Ts>
Matrix(Ts... args)

Constructor with N*M values.

bool equals(const this_type &other, float eps = default_eps) const

Test if both matrices contain the same values within epsilon.

template<size_t P>
Matrix<M, P, T> operator*(const Matrix<N, P, T> &other) const

Matrix multiplication.

Matrix<M, 1, T> operator*(const Vector<M, T> &vec) const

Matrix-Vector multiplication.

this_type operator+(const this_type &other) const

Matrix addition.

this_type operator-(const this_type &other) const

Matrix subtraction.

void operator*=(T other)

Scalar multiplication with assignment.

this_type operator*(T other) const

Scalar multiplication.

void operator/=(T other)

Scalar division with assignment.

this_type operator/(T other) const

Scalar division.

Matrix<N, M, T> transpose() const

Transposition.

template<bool cond = is_column_vector, typename = typename std::enable_if<cond>::type>
Vector<M, T> to_vector() const

Conversion to Vector.

template<bool cond = is_square, typename = typename std::enable_if<cond>::type>
T trace() const

Matrix trace: the sum of all diagonal entries.

Public Static Functions

template<bool cond = is_square, typename = typename std::enable_if<cond>::type>
static this_type identity()

Constructs the identity matrix for the current size.

Public Static Attributes

constexpr float default_eps = 1e-5
constexpr size_t rows = M
constexpr size_t cols = N
constexpr bool is_square = (M == N)
constexpr bool is_row_vector = (M == 1)
constexpr bool is_column_vector = (N == 1)

Friends

std::ostream &operator<<(std::ostream &o, const this_type &mat)

Print to output stream using ‘<<’.

class OnDeInit
#include <init.h>

Runs code() on destruction.

Designed mostly for use as a global object, though theoretically it might be useful as a stack-allocated object in some circumstances.

Public Functions

OnDeInit(std::function<void()> code)
~OnDeInit()

Private Functions

OnDeInit(const OnDeInit&)
OnDeInit(OnDeInit&&)
OnDeInit &operator=(const OnDeInit&)
OnDeInit &operator=(OnDeInit&&)

Private Members

std::function<void()> code
class OnInit
#include <init.h>

Runs code() on construction.

Designed for use as a global object. Note that your regular dynamic initialization order concerns apply.

Example:

// anonymous namespace as container for these global objects namespace { util::OnInit stuff_to_be_done_on_initialization([]() { do_stuff(1 * 2 + 3); }); }

Public Functions

OnInit(std::function<void()> code)
~OnInit()

Private Functions

OnInit(const OnInit&)
OnInit(OnInit&&)
OnInit &operator=(const OnInit&)
OnInit &operator=(OnInit&&)
class Path
#include <path.h>

C++ pendant to the python util.fslike.path.Path.

Contains a filesystem-like object and path-parts.

pxd: cppclass Path: ctypedef string part_t ctypedef vector[string] parts_t

Path() noexcept Path(PyObj, const vector[string]&) except +

FSLike *get_fsobj() except + const vector[string] &get_parts() except +

Public Types

using part_t = std::string

Storage type for a part of a path access.

Basically this is the name of a file or directory.

using parts_t = std::vector<part_t>

Storage type for the filesystem access parts this is basically a list/of/elements/in/a/path.

Public Functions

Path()

Nullary constructor, pls don’t use.

It only exists because Cython can’t RAII. It should be just friend of cython.

Path(py::Obj fslike, const parts_t &parts = {})

Construct a path object from a python fslike object.

This is called from Cython.

You will probably never call that manually.

Path(const std::shared_ptr<fslike::FSLike> &fslike, const parts_t &parts = {})

Construct a path from a fslike pointer.

virtual ~Path()
bool exists() const
bool is_file() const
bool is_dir() const
bool writable() const
std::vector<Path::part_t> list()
std::vector<Path> iterdir()
bool mkdirs()
File open(const std::string &mode = "r") const
File open_r() const
File open_w() const
File open_rw() const
File open_a() const
File open_ar() const
std::string resolve_native_path(const std::string &mode = "r") const

Resolve the native path by flattening all underlying filesystem objects (like unions).

Returns the /native/path/on/disk. Throws up if there is no native path.

This basically is the same as resolve_*().get_native_path().

std::string resolve_native_path_r() const
std::string resolve_native_path_w() const
bool rename(const Path &target_path)
bool rmdir()
bool touch()
bool unlink()
void removerecursive()
int get_mtime() const
uint64_t get_filesize() const
Path get_parent() const
const std::string &get_name() const
std::string get_suffix() const
std::vector<std::string> get_suffixes() const
std::string get_stem() const
Path joinpath(const parts_t &subpaths) const
Path joinpath(const part_t &subpath) const
Path operator[](const parts_t &subpaths) const
Path operator[](const part_t &subpath) const
Path operator/(const part_t &subpath) const
Path with_name(const part_t &name) const
Path with_suffix(const part_t &suffix) const
bool operator==(const Path &other) const
bool operator!=(const Path &other) const
fslike::FSLike *get_fsobj() const
const Path::parts_t &get_parts() const

Protected Attributes

std::shared_ptr<fslike::FSLike> fsobj
parts_t parts

Private Functions

std::string get_native_path() const

Return the native path (something like /your/folder/with/file) for this path.

returns emptystring (“”) if there is no native path.

This does not minimize/flatten (= “resolve”) the path!

You probably want to use resolve_native_path instead.

Friends

std::ostream &operator<<(std::ostream &stream, const Path &path)
class Profiler
#include <profiler.h>

Public Functions

Profiler(Engine *engine)
~Profiler()
void register_component(std::string com, color component_color)

registers a component

Parameters
  • com: the identifier to distinguish the components

  • component_color: color of the plotted line

void unregister_component(std::string com)

unregisters an individual component

Parameters
  • com: component name which should be unregistered

void unregister_all()

unregisters all remaining components

std::vector<std::string> registered_components()

returns a vector of registered component names

void start_measure(std::string com, color component_color = {1.0, , })
void end_measure(std::string com)
void show(bool debug_mode)
void show()
bool registered(std::string com) const
unsigned size() const
void start_frame_measure()

sets the start point for the actual frame which is used as a reference value for the registered components

void end_frame_measure()

sets the end point for the reference time used to compute the portions of the components.

Each recorded measurement for the registered components get appended to their history complete the measurement.

Private Functions

void draw_canvas()
void draw_legend()
void draw_component_performance(std::string com)
double duration_to_percentage(std::chrono::high_resolution_clock::duration duration)
void append_to_history(std::string com, double percentage)
bool engine_in_debug_mode()

Private Members

std::chrono::high_resolution_clock::time_point frame_start
std::chrono::high_resolution_clock::duration frame_duration
std::unordered_map<std::string, component_time_data> components
int insert_pos = 0
Engine *engine
class Profiler

A class for quick and easy profiling.

print(p.report())

Usage

p = Profiler() with p: call methods that need to be profiled here

The ‘with’ statement can be replaced with calls to p.enable() and p.disable().

Public Functions

__init__(self self, oStream oStream = None)
__enter__(self self)

Activate data collection.

__exit__(self self, exc_type exc_type, exc_value exc_value, traceback traceback)

Stop profiling.

write_report(self self, sortby sortby = 'calls')

Write the profile stats to profile_stream’s file.

report(self self, sortby sortby = 'calls')

Return the profile_stats to the console.

enable(self self)

Begins profiling calls.

disable(self self)

Stop profiling calls.

Public Static Attributes

openage.util.profiler.Profiler.profile = None
openage.util.profiler.Profiler.profile_stats = None
openage.util.profiler.Profiler.profile_stream = None
template<typename T>
class Quaternion
#include <quaternion.h>

Implements Quaternions to represent 3d rotations.

The 4 components stores 3 components as rotation axis, and one component as the rotation amount.

This is mainly Ken Shoemake stuff from: http://www.cs.ucr.edu/~vbz/resources/quatut.pdf

Also: From Quaternion to Matrix and Back J.M.P. van Waveren, id Software, 2005

Public Types

template<>
using this_type = Quaternion<T>
template<>
using type = T

Public Functions

Quaternion(T w, T x, T y, T z)
Quaternion()

Create a identity quaternion.

template<size_t N = 4>
Quaternion(const Matrix<N, N, T> &mat)

Constructs a quaternion from a rotation matrix.

mat is assumed to be a left-matrix: vec_transformed = mat * vec_orig.

mat can be 3x3 or 4x4.

This tries to avoid float-fuckups in near-zero divides by using larger components first: w, then x, y, or z.

trace(mat) >= 0 => |w| > 1/2 => as small as a largest component can be. else: max diagonal entry <=> max (|x|, |y|, |z|) which is larger than |w| and >= 1/2

Quaternion(const this_type &other)
Quaternion(this_type &&other)
Quaternion &operator=(const this_type &other)
Quaternion &operator=(this_type &&other)
virtual ~Quaternion()
T dot(const this_type &o) const

Perform a dot product with another quaternion.

T norm() const

Calculate the length of the quaternion.

T normalize()

Ensure that the quaternion’s length equals 1.

this_type normalized() const

Return the normalized version of this quaternion.

void inverse()

Inverted the quaternion: Flip the rotation axes and scale by inverse sum of all components squared.

inv(q)= conj(q)/(w*w + x*x + y*y + z*z)

this_type inversed() const

Return the inverted quaternion.

void conjugate()

Conjugate the quaternion by additive inverting the x, y and z components.

this_type conjugated() const

Return the conjugated quaternion.

bool equals(const this_type &other, T eps = default_eps) const

Test if the rotation of both quaternions is the same.

bool equals_number(const this_type &other, T eps = default_eps) const

Test if both quaternion store the same numbers.

bool equals_rad(const this_type &other, T rad_eps = default_eps) const

Test rotation equality with another quaternion with given precision in radians.

bool equals_deg(const this_type &other, T deg_eps = default_eps) const

Test rotation equality with another quaternion with given precision in degree.

Matrix3t<T> to_matrix() const

Generate the corresponding rotation matrix.

Vector3t<T> operator*(const Vector3t<T> &vec) const

Transforms a vector by this quaternion.

const this_type &operator+=(const this_type &other)
this_type operator+(const this_type &other) const
const this_type &operator-=(const this_type &other)
this_type operator-(const this_type &other) const
const this_type &operator*=(const T &fac)
this_type operator*(const T &fac) const
const this_type &operator*=(const this_type &other)
this_type operator*(const this_type &other) const
const this_type &operator/=(const T &fac)
this_type operator/(const T &fac) const
const this_type operator-() const
bool operator==(const this_type &other) const
bool operator!=(const this_type &other) const

Public Static Functions

static this_type from_rad(T rad, Vector3t<T> axis)

Create a quaternion from a rotation in radians around a given axis.

static this_type from_deg(T deg, Vector3t<T> axis)

Create a quaternion from a rotation in degree around a given axis.

Public Static Attributes

constexpr T default_eps = 1e-4

Protected Attributes

T w

Stored quaternion number components.

T x
T y
T z

Friends

std::ostream &operator<<(std::ostream &o, const this_type &q)
template<typename T>
struct SharedPtrLess
#include <misc.h>

Comparator that returns true if the contained value of the left sharedptr is < than the value contained in the right sharedptr.

Public Functions

bool operator()(const std::shared_ptr<T> &left, const std::shared_ptr<T> &right)
class Siphash
#include <hash.h>

Contains a Siphash implementration.

https://131002.net/siphash/

Public Functions

Siphash(std::array<uint8_t, 16> key)

Creates a hash generator.

Parameters
  • key: Key to use with this hasher.

Siphash &set_key(std::array<uint8_t, 16> key)

Set the key for subsequent hashes.

Return

Reference to itself, for method chaining.

Parameters
  • k: Key to use with this hasher.

uint64_t digest(const uint8_t *data, size_t len_data)

Hashes the input data as uint8_t array and returns the result.

Return

Hash.

Parameters
  • data: Start of the input data.

  • len_data: Number of bytes to read.

uint64_t digest(const uint64_t value)

Hashes a single uint64_t number and returns the result.

The 64-bit word is interpreted as big-endian. e.g. 0x0123456789abcdef -> {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}

Return

Hash.

Parameters
  • value: uint64_t to hash.

Private Members

uint64_t key[2]

The key to use for hashing.

As two 64-bit little-endian words.

template<typename ChildType>
class StringFormatter
#include <stringformatter.h>

Wraps an output string stream, and provides all sorts of overloads for operator <<, plus some other formatting methods.

Designed mainly for usage by the Formatter / logging / MSG system.

The operator << methods return references to ChildType.

If possible, input data is written directly to the buffer, but if needed, a CachableOSStream is acquired (and later released). As an optimization, instead of creating a new ExternalOStringStream object, CachableOSStream.acquire() is used internally.

Public Functions

StringFormatter(std::string &output)

Parameters
  • buffer: All input data is appended to this object.

virtual ~StringFormatter()

Releases the CachableOSStream object (if it was acquired).

ChildType &child_type_ref()
StringFormatter(StringFormatter<ChildType> &&other)
StringFormatter<ChildType> &operator=(StringFormatter<ChildType> &&other)
StringFormatter(const StringFormatter&)
StringFormatter &operator=(const StringFormatter&)
template<typename T>
ChildType &operator<<(const T &t)
ChildType &operator<<(std::ios &(*x)(std::ios&))
ChildType &operator<<(std::ostream &(*x)(std::ostream&))
ChildType &operator<<(const char *s)
ChildType &operator<<(const std::string &s)
ChildType &fmt(const char *fmt, ...)
template<typename T>ChildType ChildType& openage::util::StringFormatter::operator<<(const std::unique_ptr< T > & ptr)
template<typename T>
ChildType &operator<<(const std::shared_ptr<T> &ptr)
void reset_flags()

Clears the underlying stream object’s flags, if such a stream object exists.

virtual bool should_format() const

Returns if formatting should actually occur.

Private Functions

void ensure_stream_obj()

Ensures that we have a valid CachableOSStream object in stream_ptr.

Private Members

std::string *output
CachableOSStream *stream_ptr
class Flags

Designed to be inherited from, similar to Enum.

Used to generate flag parsers (for boolean flags that are stored in an integer value).

Specify the bit numbers of all possible flags as attributes, e.g.:

class MyFlags(Flags): thisflag = 0 thatflag = 1

The constructor of the class takes an integer argument, which is parsed; all the boolean values are stored in the attributes. If any unknown bits are set, self.unknown() is called.

Subclassed by openage.cabextract.cab.CFFileAttributes, openage.cabextract.cab.CFHeaderFlags

Public Functions

__init__(self self, val val)
unknown(self self, unknownflags unknownflags)

Default handler for any unknown bits.

Overload if needed.

as_dict(self self)

Returns a key-value dict for all flags.

__repr__(self self)

Private Static Attributes

_flags
class FlagsMeta

Metaclass for Flags.

Compare to NamedStructMeta.

Subclassed by openage.util.struct.Flags

Public Functions

__new__(mcs mcs, name name, bases bases, classdict classdict, kwds kwds)
class NamedStruct

Designed to be inherited from, similar to Enum.

Specify all fields of the struct, as ‘membername = specstr’, where specstr is a string describing the field, as in struct.Struct. NamedStructMeta translates those individual specstr fragments to a complete specstr.

Alternatively to a specstr, a callable object with a specstr member may be passed; the specstr is used as usual, but afterwards the callable is invoked to post-process the extracted data. One example for such a callable is the Flags class.

Alternatively, attributes may be set to None; those are ignored, and may be set manually at some later point.

The first member must be ‘endianess’.

Examples

class MyStruct(NamedStruct):
    endianness = "<"

    mgck = "4s"
    test = "I"
    rofl = "H"
    flag = MyFlagType

The constructor takes a bytes object of the appropriate length, and fills
in all the members with the struct's actual values.

Subclassed by openage.cabextract.cab.CFData, openage.cabextract.cab.CFFile, openage.cabextract.cab.CFFolder, openage.cabextract.cab.CFHeader, openage.cabextract.cab.CFHeaderReservedFields, openage.convert.drs.DRSFileInfo, openage.convert.drs.DRSHeader, openage.convert.drs.DRSTableInfo, openage.convert.pefile.PECOFFHeader, openage.convert.pefile.PEDataDirectory, openage.convert.pefile.PEDOSHeader, openage.convert.pefile.PEOptionalHeader, openage.convert.pefile.PESection, openage.convert.peresource.ResourceDirectory, openage.convert.peresource.ResourceDirectoryEntry, openage.convert.peresource.ResourceLeaf, openage.convert.peresource.StringLiteral

Public Functions

__init__(self self, data data)
unpack(cls cls, data data)

Unpacks data and returns a NamedStruct object that holds the fields.

size(cls cls)

Returns the size of the struct, in bytes.

read(cls cls, fileobj fileobj)

Reads the appropriate amount of data from fileobj, and unpacks it.

from_nullbytes(cls cls)

Decodes nullbytes (sort of a ‘default’ value).

__len__(self self)

Returns the number of fields.

__getitem__(self self, index index)

Returns the n-th field, or raises IndexError.

as_dict(self self)

Returns a key-value dict for all attributes.

__iter__(self self)
__repr__(self self)
__str__(self self)

Private Static Attributes

_postprocessors
_struct
_attributes
class NamedStructMeta

Metaclass for NamedStruct.

Not unlike the meta-class for Enum, processes all the member attributes at class-creation time.

Subclassed by openage.util.struct.NamedStruct

Public Functions

__prepare__(mcs mcs, name name, bases bases, kwds kwds)
__new__(mcs mcs, name name, bases bases, classdict classdict, kwds kwds)
struct testenum : public openage::util::Enum<testenum_value>
#include <enum_test.h>

pxd:

cppclass testenum(Enum[testenum_value]): testenum_value *value

testenum foo “::openage::util::tests::testenum::foo” testenum bar “::openage::util::tests::testenum::bar”

Public Functions

testenum()

Public Static Attributes

constexpr testenum_value openage::util::tests::testenum::foo = {{"foo", 1}, "foooooooooooooooooo"}
constexpr testenum_value openage::util::tests::testenum::bar = {{"bar", 2}, "barrrrrrrrrrrrrrrrr"}
struct testenum_value : public openage::util::EnumValue<testenum_value>
#include <enum_test.h>

pxd:

cppclass testenum_value(EnumValue[testenum_value, int]): int numeric const char *name const char *stuff

Public Functions

const char *get_stuff() const

Public Members

const char *stuff
class ClosableQueue

For use in concurrent_chain.

Behaves like Queue until close() has been called. After that, any call to put() raises RuntimeError.

Public Functions

__init__(self self)
put(self self, item item, block block = True, timeout timeout = None)
close(self self, reason reason = None)
raise_if_closed(self self)

Public Members

closed
close_reason
class GeneratorEvent

Public Static Attributes

int openage.util.threading.GeneratorEvent.VALUE = 0
int openage.util.threading.GeneratorEvent.EXCEPTION = 1
int openage.util.threading.GeneratorEvent.STOP_ITERATION = 2
class Timer
#include <timer.h>

Time measurement class.

Public Functions

Timer(bool stopped = true)

creates the timer, in either stopped or running state.

void reset(bool stopped = true)

resets the timer, in either stopped or running state.

void stop()

stops/pauses the timer.

void start()

starts/unpauses the timer.

time_nsec_t getval() const

reads the current timer value, in nanoseconds.

time_nsec_t getandresetval()

reads the current timer value, in nanoseconds, and resets the timer to zero (preserving started/stopped state).

bool isstopped() const

returns whether the timer is currently running.

Public Members

time_nsec_t stoppedat

while paused, stores the current timer value

time_nsec_t starttime

while running, stores the time the timer is counting from

Private Members

bool stopped
union openage::util::Timer::[anonymous] [anonymous]
class utf8_decoder
#include <unicode.h>

Public Functions

utf8_decoder()
bool feed(char c)

feeds one char to the decoder state machine returns false on decoding error, true else

once a character has been completely decoded, remaining is set to false and out is set to the decoded character. note that even if true is returned, remaining MAY be false (e.g. multi-byte characters), and remaining MAY be true even if false is returned (successful re-synchronization).

thus, after each call to feed(), you’ll first want to evaluate the return value and print an error message or add the U+FFFD replacement character. then, you’ll want to check for remaining == 0 out >= 0

void reset()

resets the decoder to its initial state

Public Members

codepoint_t out

current result character code point; overwritten on feed().

if no valid output character currently exists, this is negative or remaining is not 0.

unsigned remaining

number of remaining characters

template<class T>
class Variable : public openage::util::VariableBase
#include <variable.h>

Subclassed by openage::options::Var< T >

Public Functions

Variable(const T &initial_value)
const T &get() const
void set(const T &v)

Public Members

T value

accessable typed value

class VariableBase
#include <variable.h>

A typed value holder.

Subclassed by openage::util::Variable< T >, openage::util::Variable< bool >

Public Functions

virtual ~VariableBase()
template<class T, class V>
void set(const V &value)

sets the type and value

template<class T>
const T &get() const

returns the stored value throws an exception if the template does not match the set type

template<size_t N, typename T>
class Vector : public std::array<T, N>
#include <vector.h>

Vector class with arithmetic.

N = dimensions T = underlying single value type (double, float, …)

Public Types

template<>
using this_type = Vector<N, T>

Public Functions

Vector()

Default, random-value constructor.

~Vector()
template<typename ...Ts>
Vector(Ts... args)

Constructor for initialisation with N T values.

bool equals(const this_type &other, T eps = default_eps)

Equality test with given precision.

this_type &operator+=(const this_type &other)

Vector addition with assignment.

this_type operator+(const this_type &other) const

Vector addition.

this_type &operator-=(const this_type &other)

Vector subtraction with assignment.

this_type operator-(const this_type &other) const

Vector subtraction.

this_type &operator*=(T a)

Scalar multiplication with assignment.

this_type operator*(T a) const

Scalar multiplication.

this_type &operator/=(T a)

Scalar division with assignment.

this_type operator/(T a) const

Scalar division.

T dot(const this_type &other) const

Dot product of two Vectors.

T norm() const

Euclidian norm aka length.

this_type &normalize()

Scales the Vector so that its norm is 1.

template<typename U = this_type>
std::enable_if<N == 3, U>::type cross_product(const this_type &other) const

Cross-product of two 3-dimensional vectors.

Public Static Attributes

constexpr T default_eps = 1e-4

Default comparison epsilon.

Friends

this_type operator*(T a, const this_type &v)

Scalar multiplication with swapped arguments.

std::ostream &operator<<(std::ostream &o, const this_type &v)

Print to output stream using ‘<<’.

template<typename F, typename ...Args>
struct can_call : public decltypecan_call_test::f<F, Args...>
#include <gui_item_link.h>

Evaluates to true if callable can be called with given argument types.

Template Parameters
  • F: callable

  • A: arguments to test against the callable

struct can_call_test
#include <gui_item_link.h>

Checking that callable can be called with given argument types.

Public Static Functions

template<typename F, typename ... Args>static decltype(std::declval<F>()(std::declval<Args>()...), std::true_type()) qtsdl::can_call_test::f(int)
template<typename F, typename ...Args>
static std::false_type f(...)
class CtxExtractionException : public runtime_error
#include <gui_ctx_setup.h>

Public Functions

CtxExtractionException(const std::string &what_arg)
class CtxExtractionMode
#include <gui_ctx_setup.h>

Abstract base for the method of getting a Qt-usable context.

Subclassed by qtsdl::GuiSeparateRenderingContext, qtsdl::GuiUniqueRenderingContext

Public Functions

virtual ~CtxExtractionMode()
QOpenGLContext *get_ctx()

Return

context that can be used by Qt

virtual void pre_render() = 0

Function that must be called before rendering the GUI.

virtual void post_render() = 0

Function that must be called after rendering the GUI.

Protected Attributes

QOpenGLContext ctx
class DeferredInitialConstantPropertyValues
#include <deferred_initial_constant_property_values.h>

Stores static properties during initialization to be able to assign them after all ‘liveReloadTag’ properties are set.

Subclassed by qtsdl::GuiItemBase

Public Functions

DeferredInitialConstantPropertyValues()
~DeferredInitialConstantPropertyValues()

Is virtual to be able to catch the error when non-persistent item uses liveReloadTag.

void apply_static_properties()

Execute saved static properties assignments (for newly created cores).

void clear_static_properties()

Clear saved static properties assignments (for cores that existed before the GUI reload).

bool is_init_over() const

Protected Attributes

bool init_over
std::vector<std::function<void()>> static_properties_assignments
class EventHandlingQuickWindow : public QQuickWindow
#include <gui_renderer_impl.h>

Public Functions

EventHandlingQuickWindow(QQuickRenderControl *render_control)
~EventHandlingQuickWindow()

Public Slots

void on_input_event(std::atomic<bool> *processed, QEvent *event, bool only_if_grabbed)
void on_resized(const QSize &size)

Private Members

QQuickItem *focused_item
class GameLogicCaller : public QObject
#include <game_logic_caller.h>

Attaches to the GuiCallbackImpl.

Public Functions

GameLogicCaller()
void set_game_logic_callback(GuiCallback *game_logic_callback)

Set up signal to be able to run code in the game logic thread.

Signals

void in_game_logic_thread(const std::function<void()> &f) const
void in_game_logic_thread_blocking(const std::function<void()> &f) const
struct gl_debug_parameters
#include <opengl_debug_logger.h>

Public Members

bool is_debug

True if the GL context is a debug context.

GLvoid *callback

Function that GL context uses to report debug messages.

bool synchronous

True if debug callback calling method is chosen to be synchronous.

class GuiApplication
#include <gui_application.h>

Houses gui logic event queue.

Subclassed by openage::gui::GuiApplicationWithLogger

Public Functions

GuiApplication()
GuiApplication(std::shared_ptr<GuiApplicationImpl> application)
~GuiApplication()
void processEvents()

Private Members

std::shared_ptr<GuiApplicationImpl> application
class GuiApplicationImpl
#include <gui_application_impl.h>

Houses gui logic event queue.

To launch it in a dedicated thread, use qtsdl::GuiDedicatedThread instead.

Public Functions

~GuiApplicationImpl()
void processEvents()

Public Static Functions

std::shared_ptr<GuiApplicationImpl> get()

Private Functions

GuiApplicationImpl()
GuiApplicationImpl(const GuiApplicationImpl&)
GuiApplicationImpl &operator=(const GuiApplicationImpl&)

Private Members

const std::thread::id owner
QGuiApplication app

Private Static Attributes

std::weak_ptr<GuiApplicationImpl> instance
class GuiCallback : public QObject
#include <gui_callback.h>

Public Functions

GuiCallback()
~GuiCallback()

Public Slots

void process(const std::function<void()> &f)

Signals

void process_blocking(const std::function<void()> &f)
class GuiDedicatedThread
#include <gui_dedicated_thread.h>

Runs the gui logic in separate thread.

For sharing the thread with something else, use qtsdl::GuiApplicationImpl instead.

Public Functions

~GuiDedicatedThread()

Public Static Functions

std::shared_ptr<GuiDedicatedThread> get()

Private Functions

GuiDedicatedThread()

Private Members

std::thread worker

Private Static Attributes

std::weak_ptr<GuiDedicatedThread> instance
bool exists = false
std::mutex existence_guard
std::condition_variable destroyed
class GuiEngine
#include <gui_engine.h>

Represents one QML execution environment.

Public Functions

GuiEngine(GuiRenderer *renderer, const std::vector<GuiImageProvider *> &image_providers = std::vector<GuiImageProvider *>(), GuiSingletonItemsInfo *singleton_items_info = nullptr)
~GuiEngine()

Private Members

std::unique_ptr<GuiEngineImpl> impl

Friends

friend qtsdl::GuiEngine::GuiEngineImpl
class GuiEngineImpl : public QObject
#include <gui_engine_impl.h>

Public Functions

GuiEngineImpl(GuiRenderer *renderer, const std::vector<GuiImageProvider *> &image_providers = std::vector<GuiImageProvider *>(), GuiSingletonItemsInfo *singleton_items_info = nullptr)
~GuiEngineImpl()
QQmlEngine *get_qml_engine()
void add_root_dir_path(const QString &root_dir_path)
void remove_root_dir_path(const QString &root_dir_path)

Public Slots

void attach_to(GuiRendererImpl *renderer)
void onReload()

Signals

void reload()
void rootDirsPathsChanged(const QStringList&)

Public Static Functions

GuiEngineImpl *impl(GuiEngine *engine)

Private Members

GuiRendererImpl *renderer
QmlEngineWithSingletonItemsInfo engine
RecursiveDirectoryWatcher watcher
QStringList root_dirs_paths
class GuiEngineImplConnection
#include <gui_subtree_impl.h>

Public Functions

GuiEngineImplConnection()
GuiEngineImplConnection(GuiSubtreeImpl *subtree, GuiEngineImpl *engine, const QString &root_dir)
~GuiEngineImplConnection()
GuiEngineImplConnection(GuiEngineImplConnection &&cnx)
GuiEngineImplConnection &operator=(GuiEngineImplConnection &&cnx)
bool has_subtree() const
QQmlContext *rootContext() const
QQmlEngine *get_qml_engine() const

Private Functions

GuiEngineImplConnection(const GuiEngineImplConnection &cnx)
GuiEngineImplConnection &operator=(const GuiEngineImplConnection &cnx)
void disconnect()

Private Members

GuiSubtreeImpl *subtree
GuiEngineImpl *engine
QString root_dir
class GuiEventQueue
#include <gui_event_queue.h>

Provides synchronization with some game thread.

Public Functions

GuiEventQueue()
~GuiEventQueue()
void process_callbacks()

Private Members

std::unique_ptr<GuiEventQueueImpl> impl

Friends

friend qtsdl::GuiEventQueue::GuiEventQueueImpl
class GuiEventQueueImpl
#include <gui_event_queue_impl.h>

Provides synchronization with some game thread.

Public Functions

GuiEventQueueImpl()
~GuiEventQueueImpl()
void process_callbacks()
QThread *get_thread()

Public Static Functions

GuiEventQueueImpl *impl(GuiEventQueue *event_queue)

Private Members

QThread *const thread
QEventLoop callback_processor
class GuiImageProvider
#include <gui_image_provider.h>

Subclassed by openage::gui::GuiGameSpecImageProvider

Public Functions

GuiImageProvider(std::unique_ptr<GuiImageProviderImpl> impl)
~GuiImageProvider()

Private Members

std::unique_ptr<GuiImageProviderImpl, std::function<void(GuiImageProviderImpl *)>> impl

Friends

friend qtsdl::GuiImageProvider::GuiImageProviderImpl
class GuiImageProviderImpl : public QQuickImageProvider
#include <gui_image_provider_impl.h>

Subclassed by openage::gui::GuiGameSpecImageProviderImpl

Public Functions

GuiImageProviderImpl()
~GuiImageProviderImpl()
virtual const char *get_id() const = 0
virtual void give_up() = 0

Public Static Functions

std::unique_ptr<GuiImageProviderImpl> take_ownership(GuiImageProvider *image_provider)
std::vector<std::unique_ptr<GuiImageProviderImpl>> take_ownership(const std::vector<GuiImageProvider *> &image_providers)
class GuiInput
#include <gui_input.h>

Converts SDL input events into Qt events.

Public Functions

GuiInput(GuiRenderer *renderer, GuiEventQueue *game_logic_updater)
~GuiInput()
bool process(SDL_Event *event)

Returns true if the event was accepted.

Private Members

std::unique_ptr<GuiInputImpl> impl

Friends

friend qtsdl::GuiInput::GuiInputImpl
class GuiInputImpl : public QObject
#include <gui_input_impl.h>

Public Functions

GuiInputImpl(GuiRenderer *renderer, GuiEventQueue *game_logic_updater)
~GuiInputImpl()
bool process(SDL_Event *e)

Returns true if the event was accepted.

Signals

void input_event(std::atomic<bool> *processed, QEvent *ev, bool only_if_grabbed = false)

Private Functions

bool relay_input_event(QEvent *ev, bool only_if_grabbed = false)

Private Members

Qt::MouseButtons mouse_buttons_state
GuiEventQueueImpl *game_logic_updater
template<typename T>
class GuiItem : public qtsdl::GuiItemOrigin<T>, public qtsdl::GuiItemCoreInstantiator<T>
#include <gui_item.h>

Base for shell QObjects that need corresponding cores to be kept alive across GUI reloads.

These shell objects are destroyed by Qt during GUI reload. Their cores are adopted by new shells identified by the ‘LR.tag’ in QML code.

For each descendant the specializations of Wrap and Unwrap must be provided. Corresponding cores must have public ‘gui::GuiItemLink *gui_link` members.

Template Parameters
  • T: type of the concrete shell class (pass the descendant class)

Subclassed by qtsdl::GuiItemListModel< T >

Public Functions

GuiItem(GuiItemBase *item_base)

Creates an empty QObject shell for a core that is wrappable into a type *T.

class GuiItemBase : public qtsdl::DeferredInitialConstantPropertyValues
#include <gui_item.h>

Subclassed by qtsdl::GuiItemQObject, qtsdl::GuiListModel

Public Functions

virtual ~GuiItemBase()

Protected Attributes

GameLogicCaller game_logic_caller
std::function<std::unique_ptr<PersistentCoreHolderBase>)> qtsdl::GuiItemBase::instantiate_core_func
std::function<void(PersistentCoreHolderBase *, const QString&)> do_adopt_core_func
std::function<void()> on_core_adopted_func

Private Functions

std::unique_ptr<PersistentCoreHolderBase> instantiate_core()

Creates and returns a core object inside a holder.

void adopt_core(PersistentCoreHolderBase *holder, const QString &tag)

Attaches to a core object.

void do_adopt_core(PersistentCoreHolderBase *holder, const QString &tag)
virtual void on_core_adopted()
void set_game_logic_callback(GuiCallback *game_logic_callback)

Set up signal to be able to run code in the game logic thread.

Friends

friend qtsdl::GuiItemBase::GuiLiveReloader
friend qtsdl::GuiItemBase::GuiSubtreeImpl
friend qtsdl::GuiItemBase::GuiItemMethods
friend qtsdl::GuiItemBase::GuiItemCoreInstantiator
friend qtsdl::GuiItemBase::GuiItemListModel
template<typename T>
class GuiItemCoreInstantiator : public qtsdl::GuiItemMethods<T>
#include <gui_item.h>

Subclassed by qtsdl::GuiItem< T >

Public Functions

GuiItemCoreInstantiator(GuiItemBase *item_base)

Sets up a factory for the type T.

Public Members

item_base instantiate_core_func = std::bind(&GuiItemCoreInstantiator::instantiate_core, )
item_base do_adopt_core_func = std::bind(&GuiItemCoreInstantiator::do_adopt_core, , , )

Private Functions

std::unique_ptr<PersistentCoreHolderBase> instantiate_core()

Creates and returns a core object of type Unwrap<T>::Type inside a holder.

void do_adopt_core(PersistentCoreHolderBase *holder, const QString &tag)

Attaches to a core object.

GuiItemCoreInstantiator(const GuiItemCoreInstantiator&)
GuiItemCoreInstantiator &operator=(const GuiItemCoreInstantiator&)
template<typename T>
class GuiItemInterface : public qtsdl::GuiItemOrigin<T>, public qtsdl::GuiItemMethods<T>
#include <gui_item.h>

Public Functions

GuiItemInterface()
class GuiItemLink
#include <gui_item_link.h>

Base for QObject wrapper of the domain-specific classes.

Subclassed by qtsdl::GuiItemQObject, qtsdl::GuiListModel, qtsdl::GuiSingletonItem

Public Functions

virtual ~GuiItemLink()
template<typename T>
class GuiItemListModel : public qtsdl::GuiItem<T>
#include <gui_item_list_model.h>

A shell object fir cores inherited from GuiPropertyMap.

Core can use a key-value interface while in QML it looks like a ListModel.

Public Functions

GuiItemListModel(GuiItemBase *item_base)

Private Functions

void on_core_adopted()
void establish_from_gui_propagation()
void establish_to_gui_propagation()
void do_initial_to_gui_propagation()
template<typename T>
class GuiItemMethods
#include <gui_item.h>

Member function of the GuiPersistentItem.

Subclassed by qtsdl::GuiItemCoreInstantiator< T >, qtsdl::GuiItemInterface< T >

Public Functions

virtual ~GuiItemMethods()
template<typename U>
U *get() const

Get core.

template<typename U>
U *get()

Get core.

template<typename F, typename ...Args>
void i(F f, Args&&... args)

Invoke a function in the logic thread (the thread of the core of this object).

Protected Functions

template<typename F, typename P, typename A>
void s(F f, P &p, A &&arg)

Set property.

template<typename F, typename P, typename A>
void sf(F f, P &p, A &&arg)

Set property even if it’s the same.

Private Functions

template<typename F, typename A>
void assign_while_catching_constant_properies_inits(F f, A &&arg)

Static QML properties assignments during the init phase are stored for a batch assignment at the end of the init phase.

template<typename T>
class GuiItemOrigin
#include <gui_item.h>

Subclassed by qtsdl::GuiItem< T >, qtsdl::GuiItemInterface< T >

Private Members

PersistentCoreHolder<typename Unwrap<T>::Type> *holder

Implementation object.

Friends

friend qtsdl::GuiItemOrigin::GuiItemMethods
friend qtsdl::GuiItemOrigin::GuiItemCoreInstantiator
class GuiItemQObject : public QObject, public qtsdl::GuiItemBase, public qtsdl::GuiItemLink
#include <gui_item.h>

Subclassed by openage::gui::AssetManagerLink, openage::gui::GameControlLink, openage::gui::GameMainLink, openage::gui::GameSpecLink, openage::gui::OutputModeLink

Public Functions

GuiItemQObject(QObject *parent = nullptr)
class GuiListModel : public QAbstractListModel, public qtsdl::GuiItemBase, public qtsdl::GuiItemLink
#include <gui_list_model.h>

Adapts core that uses a property map to QAbstractListModel interface.

Subclassed by openage::gui::GeneratorLink

Public Functions

GuiListModel(QObject *parent = nullptr)
~GuiListModel()
void set(const std::vector<std::tuple<QByteArray, QVariant>> &values)

Public Slots

void on_property_changed(const QByteArray &name, const QVariant &value)

Signals

void changed_from_gui(const char *name, const QVariant &value)

Private Functions

int rowCount(const QModelIndex&) const
Qt::ItemFlags flags(const QModelIndex &index) const
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)

Private Members

std::vector<std::tuple<QByteArray, QVariant>> values
class GuiLiveReloader
#include <gui_live_reloader.h>

Stores objects that need to be kept alive across GUI reloads.

Public Functions

void init_persistent_items(const QList<GuiLiveReloaderAttachedProperty *> &items)

Private Types

using TagToPreservableMap = std::unordered_map<QString, std::unique_ptr<PersistentCoreHolderBase>>

Private Members

TagToPreservableMap preservable
class GuiLiveReloaderAttachedProperty : public QObject
#include <gui_live_reloader.h>

The ‘LR.tag’ attached property.

Public Functions

GuiLiveReloaderAttachedProperty(QObject *object)
GuiItemBase *get_attachee() const
QString get_tag() const
void set_tag(const QString &tag)
QString get_tag_for_init() const

Property

property qtsdl::GuiLiveReloaderAttachedProperty::tag

Tag that allows to connect newly created shells to corresponding cores after GUI reload.

class GuiLiveReloaderAttachedPropertyProvider : public QObject
#include <gui_live_reloader.h>

Non-instantiable type that is needed to use a ‘LR.tag’ attached property.

Public Static Functions

GuiLiveReloaderAttachedProperty *qmlAttachedProperties(QObject *attachee)
struct GuiPropertyMap
#include <gui_property_map.h>

Subclassed by openage::Generator

Public Functions

GuiPropertyMap()
~GuiPropertyMap()
template<typename T>
T getv(const char *name) const
template<typename T>
T getv(const std::string &name) const
std::vector<std::string> get_csv(const char *name) const
std::vector<std::string> get_csv(const std::string &name) const
template<typename T>
void setv(const char *name, T v)
template<typename T>
void setv(const std::string &name, T v)
void set_csv(const char *name, const std::vector<std::string> &v)
void set_csv(const std::string &name, const std::vector<std::string> &v)
void setv(const char *name, const std::string &v)
void setv(const std::string &name, const std::string &v)
void setv(const char *name, const std::vector<std::string> &v)
void setv(const std::string &name, const std::vector<std::string> &v)
template<>
bool getv(const char *name) const
template<>
void setv(const char *name, bool v)
template<>
int getv(const char *name) const
template<>
void setv(const char *name, int v)
template<>
double getv(const char *name) const
template<>
void setv(const char *name, double v)
template<>
void setv(const char *name, const char *v)
template<>
QString getv(const char *name) const
template<>
void setv(const char *name, const QString &v)
template<>
QStringList getv(const char *name) const
template<>
void setv(const char *name, const QStringList &v)
template<>
bool getv(const char *name) const
template<>
void setv(const char *name, bool v)
template<>
int getv(const char *name) const
template<>
void setv(const char *name, int v)
template<>
double getv(const char *name) const
template<>
void setv(const char *name, double v)
template<>
std::string getv(const char *name) const
template<>
void setv(const char *name, const std::string &v)
template<>
void setv(const char *name, const char *v)
template<>
std::vector<std::string> getv(const char *name) const

Public Members

std::unique_ptr<GuiPropertyMapImpl> impl
class GuiPropertyMapImpl : public QObject
#include <gui_property_map_impl.h>

Public Functions

GuiPropertyMapImpl()
~GuiPropertyMapImpl()

Signals

void property_changed(const QByteArray &name, const QVariant &value)

Private Functions

bool event(QEvent *e)
class GuiRenderer
#include <gui_renderer.h>

Passes the native graphic context to Qt.

Public Functions

GuiRenderer(SDL_Window *window)
~GuiRenderer()
GLuint render()
void resize(int w, int h)

Private Members

std::unique_ptr<GuiRendererImpl> impl

Friends

friend qtsdl::GuiRenderer::GuiRendererImpl
class GuiRendererImpl : public QObject
#include <gui_renderer_impl.h>

Passes the native graphic context to Qt.

Public Functions

GuiRendererImpl(SDL_Window *window)
~GuiRendererImpl()
GLuint render()

Return

texture ID where GUI was rendered

void resize(const QSize &size)
EventHandlingQuickWindow *get_window()
void make_sure_render_thread_unlocked()

When render thread is locked waiting for the gui thread to finish its current event and go to the high-priority ‘freeze’ event; but the gui thread can’t finish the current event because it’s going to lock the game-logic thread that will lock the render thread somehow.

In this situation the gui thread should call this function to immediately process the ‘freeze’ event handler inside current event and remove the event from the gui queue.

GuiRendererImpl::need_sync’ is only set from the gui thread, so after the calling this function, we are fine for entire duration of the processing of the current event.

If ‘GuiRendererImpl::need_sync’ is set, this function blocks until the render thread comes around to do the ‘QQuickRenderControl::sync()’. If it’s not good enough, it’s possible to implement two separate functions to set ‘GuiRendererImpl::need_sync’ to false and then back to true.

bool make_sure_render_thread_wont_sync()

Assures that the render thread won’t try to stop the gui thread for syncing.

Must be called from the gui thread.

Return

true if need_sync was set to false (you should restore it with the demand_sync())

void demand_sync()

Sets ‘GuiRendererImpl::need_sync’ to true.

Must be called from the gui thread.

Signals

void resized(const QSize &size)

Public Static Functions

GuiRendererImpl *impl(GuiRenderer *renderer)

Private Functions

bool event(QEvent *e)
void process_freeze(std::unique_lock<std::mutex> lck)
void reinit_fbo_if_needed()

If size changes, then create a new FBO for GUI rendering.

Private Members

GuiRenderingSetupRoutines gui_rendering_setup_routines

Contains rendering context Use GuiRenderingCtxActivator to enable it.

std::unique_ptr<EventHandlingQuickWindow> window

Contains scene graph of the GUI.

QQuickRenderControl render_control

Object for sending render command to Qt.

std::unique_ptr<QOpenGLFramebufferObject> fbo

FBO where the GUI is rendered.

std::atomic<int> new_fbo_width
std::atomic<int> new_fbo_height
std::atomic<bool> need_fbo_resize
std::atomic<bool> need_sync
std::atomic<bool> need_render
bool gui_locked
std::mutex gui_guard
std::condition_variable gui_locked_cond
bool renderer_waiting_on_cond

Private Slots

void on_scene_changed()
class GuiRenderingCtxActivator
#include <gui_rendering_setup_routines.h>

Prepares the context for rendering the GUI for one frame.

Activator must be destroyed as soon as the GUI has executed its frame render call.

Public Functions

GuiRenderingCtxActivator(GuiRenderingSetupRoutines &rendering_setup_routines)
~GuiRenderingCtxActivator()
GuiRenderingCtxActivator(GuiRenderingCtxActivator &&o)
GuiRenderingCtxActivator &operator=(GuiRenderingCtxActivator &&o)

Private Functions

GuiRenderingCtxActivator(const GuiRenderingCtxActivator&)
GuiRenderingCtxActivator &operator=(const GuiRenderingCtxActivator&)

Private Members

GuiRenderingSetupRoutines *rendering_setup_routines
class GuiRenderingSetupRoutines
#include <gui_rendering_setup_routines.h>

Returns a GL context usable by Qt classes.

Provides pre- and post-rendering functions to make the context usable for GUI rendering.

Public Functions

GuiRenderingSetupRoutines(SDL_Window *window)
~GuiRenderingSetupRoutines()
QOpenGLContext *get_ctx()

Private Functions

void pre_render()
void post_render()

Private Members

std::unique_ptr<CtxExtractionMode> ctx_extraction_mode

Friends

friend qtsdl::GuiRenderingSetupRoutines::GuiRenderingCtxActivator
class GuiSeparateRenderingContext : public qtsdl::CtxExtractionMode
#include <gui_ctx_setup.h>

Create a separate context to render the GUI, make it shared with the main context.

Public Functions

GuiSeparateRenderingContext(SDL_Window *window)
~GuiSeparateRenderingContext()
void pre_render()

Function that must be called before rendering the GUI.

void post_render()

Function that must be called after rendering the GUI.

Private Members

QOpenGLContext main_ctx

GL context of the game.

std::unique_ptr<QOpenGLDebugLogger> ctx_logger

GL debug logger of the GL context of the GUI.

std::function<void()> make_current_back

Function to make the game context current.

QOffscreenSurface offscreen_surface

Surface that is needed to make the GUI context current.

class GuiSingletonItem : public QObject, public qtsdl::GuiItemLink
#include <gui_singleton_item.h>

Subclassed by openage::gui::EngineLink

Public Functions

GuiSingletonItem(QObject *parent = nullptr)
~GuiSingletonItem()
class GuiSingletonItemsInfo
#include <gui_singleton_items_info.h>

Accessible during creation of any singleton QML item.

Subclassed by openage::gui::EngineQMLInfo

class GuiSubtree
#include <gui_subtree.h>

A root item that loads its code from source url.

rootdir is the qml file root folder which is watched for changes.

Public Functions

GuiSubtree(GuiRenderer *renderer, GuiEventQueue *game_logic_updater, GuiEngine *engine, const std::string &source, const std::string &rootdir)
~GuiSubtree()

Private Members

std::unique_ptr<GuiSubtreeImpl> impl

Friends

friend qtsdl::GuiSubtree::GuiSubtreeImpl
class GuiSubtreeImpl : public QObject
#include <gui_subtree_impl.h>

Public Functions

GuiSubtreeImpl(GuiRenderer *renderer, GuiEventQueue *game_logic_updater, GuiEngine *engine, const QString &source, const QString &rootdir)
~GuiSubtreeImpl()

Public Slots

void onEngineReloaded()
void attach_to(GuiEventQueueImpl *game_logic_updater)
void attach_to(GuiRendererImpl *renderer)
void attach_to(GuiEngineImpl *engine, const QString &source)

Signals

void process_game_logic_callback_blocking(const std::function<void()> &f)

Private Functions

void init_persistent_items()
void reparent_root()
void destroy_root()

Private Members

GuiRendererImpl *renderer
GuiEngineImplConnection engine
GuiLiveReloader reloader
GuiCallback game_logic_callback
std::unique_ptr<QQmlComponent> root_component
QQuickItem *root

Private Slots

void component_status_changed(QQmlComponent::Status status)
void on_resized(const QSize &size)
void on_process_game_logic_callback_blocking(const std::function<void()> &f)
class GuiUniqueRenderingContext : public qtsdl::CtxExtractionMode
#include <gui_ctx_setup.h>

Use the same context to render the GUI.

Public Functions

GuiUniqueRenderingContext(SDL_Window *window)
void pre_render()

Function that must be called before rendering the GUI.

void post_render()

Function that must be called after rendering the GUI.

template<typename T, typename P>
class Inherits : public qtsdl::Shadow<T>, public qtsdl::GuiItemCoreInstantiator<P>
#include <gui_item.h>

Switches the factory to production of the instances of the derived class.

Public Functions

Inherits(QObject *parent = nullptr)
template<typename T>
class PersistentCoreHolder : public qtsdl::PersistentCoreHolderBase
#include <gui_item.h>

Public Functions

PersistentCoreHolder(std::unique_ptr<T> core)
PersistentCoreHolder()

Establish link from the core to the shell.

Core must have a public ‘gui::GuiItemLink *gui_link` member.

Public Members

std::unique_ptr<T> core
class PersistentCoreHolderBase
#include <gui_item.h>

Helper to hide the type of the core.

Subclassed by qtsdl::PersistentCoreHolder< typename qtsdl::Unwrap< AssetManagerLink >::Type >, qtsdl::PersistentCoreHolder< typename qtsdl::Unwrap< GameControlLink >::Type >, qtsdl::PersistentCoreHolder< typename qtsdl::Unwrap< GameMainLink >::Type >, qtsdl::PersistentCoreHolder< typename qtsdl::Unwrap< GameSpecLink >::Type >, qtsdl::PersistentCoreHolder< typename qtsdl::Unwrap< GeneratorLink >::Type >, qtsdl::PersistentCoreHolder< typename qtsdl::Unwrap< OutputModeLink >::Type >, qtsdl::PersistentCoreHolder< typename qtsdl::Unwrap< T >::Type >, qtsdl::PersistentCoreHolder< T >

Public Functions

virtual ~PersistentCoreHolderBase()

Establish link from the core to the shell.

Core must have a public ‘gui::GuiItemLink *gui_link` member.

class QmlEngineWithSingletonItemsInfo : public QQmlEngine
#include <qml_engine_with_singleton_items_info.h>

The Qml Engine used by openage.

It’s extended to contain the “singleton items info” and a list of image providers. The singleton item info is just a struct that allows to carry some variables in the qml-engine, namely the openage-engine.

That way, the openage-engine and the qml-engine have a 1:1 relation and qml can access the main engine directly.

Public Functions

QmlEngineWithSingletonItemsInfo(std::vector<std::unique_ptr<GuiImageProviderImpl>> &&image_providers, GuiSingletonItemsInfo *singleton_items_info = nullptr)
QmlEngineWithSingletonItemsInfo(std::vector<std::unique_ptr<GuiImageProviderImpl>> &image_providers, GuiSingletonItemsInfo *singleton_items_info = nullptr)
~QmlEngineWithSingletonItemsInfo()
GuiSingletonItemsInfo *get_singleton_items_info() const
std::vector<GuiImageProviderImpl *> get_image_providers() const

Private Members

std::vector<GuiImageProviderImpl *> image_providers
GuiSingletonItemsInfo *singleton_items_info
class RecursiveDirectoryWatcher : public QObject
#include <recursive_directory_watcher.h>

Emits a signal when anything changes in the directories.

Public Functions

RecursiveDirectoryWatcher(QObject *parent = nullptr)
~RecursiveDirectoryWatcher()

Signals

void changeDetected()
void rootDirsPathsChanged(const QStringList&)
void quit()

Private Members

std::future<void> worker
class RecursiveDirectoryWatcherWorker : public QObject
#include <recursive_directory_watcher_worker.h>

Emits a signal when anything changes in the directories.

Public Functions

RecursiveDirectoryWatcherWorker()

Public Slots

void onRootDirsPathsChanged(const QStringList &root_dirs_paths)
void restartWatching()

Signals

void changeDetected()

Private Functions

void restart_watching(const QStringList &entries_to_watch)

Private Members

std::unique_ptr<QFileSystemWatcher> watcher

Actual watcher.

Its event processing and destruction has to be in the same separate thread.

QTimer batching_timer

Waits to glue multiple changes into one event.

QStringList root_dirs_paths

Private Slots

void onEntryChanged()
template<typename T>
class Shadow : public T
#include <gui_item.h>

Shadows inherited member functions.

Subclassed by qtsdl::Inherits< T, P >

Public Functions

Shadow(QObject *parent = nullptr)
void get(NullClass)
void i(NullClass)
void s(NullClass)
void sf(NullClass)
class TemporaryDisableGuiRendererSync
#include <gui_renderer_impl.h>

Public Functions

TemporaryDisableGuiRendererSync(GuiRendererImpl &renderer)
~TemporaryDisableGuiRendererSync()

Private Functions

TemporaryDisableGuiRendererSync(const TemporaryDisableGuiRendererSync&)
TemporaryDisableGuiRendererSync &operator=(const TemporaryDisableGuiRendererSync&)

Private Members

GuiRendererImpl &renderer
const bool need_sync
template<typename T>
struct Unwrap
#include <gui_item_link.h>

If the core ‘MyClass’ has a shell ‘MyClassLink’ then ‘Unwrap<MyClassLink>’ must have a ‘using Type = MyClass’.

template<>
struct Unwrap<openage::gui::ActionModeLink>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::ActionMode
template<>
struct Unwrap<openage::gui::AssetManagerLink>
#include <assetmanager_link.h>

Public Types

template<>
using Type = openage::AssetManager
template<>
struct Unwrap<openage::gui::CreateModeLink>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::CreateMode
template<>
struct Unwrap<openage::gui::EditorModeLink>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::EditorMode
template<>
struct Unwrap<openage::gui::EngineLink>
#include <engine_link.h>

Public Types

template<>
using Type = openage::Engine
template<>
struct Unwrap<openage::gui::GameControlLink>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::GameControl
template<>
struct Unwrap<openage::gui::GameMainLink>
#include <game_main_link.h>

Public Types

template<>
using Type = openage::GameMainHandle
template<>
struct Unwrap<openage::gui::GameSpecLink>
#include <game_spec_link.h>

Public Types

template<>
using Type = openage::GameSpecHandle
template<>
struct Unwrap<openage::gui::GeneratorLink>
#include <generator_link.h>

Public Types

template<>
using Type = openage::Generator
template<>
struct Unwrap<openage::gui::OutputModeLink>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::OutputMode
template<typename U>
struct Wrap
#include <gui_item_link.h>

If the core ‘MyClass’ has a shell ‘MyClassLink’ then ‘Wrap<MyClass>’ must have a ‘using Type = MyClassLink’.

template<>
struct Wrap<openage::ActionMode>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::gui::ActionModeLink
template<>
struct Wrap<openage::AssetManager>
#include <assetmanager_link.h>

Public Types

template<>
using Type = openage::gui::AssetManagerLink
template<>
struct Wrap<openage::CreateMode>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::gui::CreateModeLink
template<>
struct Wrap<openage::EditorMode>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::gui::EditorModeLink
template<>
struct Wrap<openage::Engine>
#include <engine_link.h>

Public Types

template<>
using Type = openage::gui::EngineLink
template<>
struct Wrap<openage::GameControl>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::gui::GameControlLink
template<>
struct Wrap<openage::GameMainHandle>
#include <game_main_link.h>

Public Types

template<>
using Type = openage::gui::GameMainLink
template<>
struct Wrap<openage::GameSpecHandle>
#include <game_spec_link.h>

Public Types

template<>
using Type = openage::gui::GameSpecLink
template<>
struct Wrap<openage::Generator>
#include <generator_link.h>

Public Types

template<>
using Type = openage::gui::GeneratorLink
template<>
struct Wrap<openage::OutputMode>
#include <game_control_link.h>

Public Types

template<>
using Type = openage::gui::OutputModeLink
template<>
struct hash<openage::ability_type>
#include <ability.h>

hasher for ability type enum

Public Types

typedef underlying_type<openage::ability_type>::type underlying_type

Public Functions

size_t operator()(const openage::ability_type &arg) const
template<>
struct hash<openage::command_flag>
#include <command.h>

hasher for game command flags

Public Types

typedef underlying_type<openage::command_flag>::type underlying_type

Public Functions

size_t operator()(const openage::command_flag &arg) const
template<>
struct hash<openage::coord::phys3>
#include <phys.h>

Public Functions

size_t operator()(const openage::coord::phys3 &pos) const
template<>
struct hash<openage::coord::tile>
#include <tile.h>

Public Functions

size_t operator()(const openage::coord::tile &pos) const
template<>
struct hash<openage::datastructure::tests::heap_elem>
#include <tests.h>

hash function for the simple heap_elem

Public Functions

size_t operator()(const openage::datastructure::tests::heap_elem &elem) const
template<>
struct hash<openage::game_resource>
#include <resource.h>

hasher for game resource

Public Types

typedef underlying_type<openage::game_resource>::type underlying_type

Public Functions

size_t operator()(const openage::game_resource &arg) const
template<>
struct hash<openage::gamedata::unit_classes>
#include <attribute.h>

hasher for unit classes enum type

Public Types

typedef underlying_type<openage::gamedata::unit_classes>::type underlying_type

Public Functions

size_t operator()(const openage::gamedata::unit_classes &arg) const
template<>
struct hash<openage::path::Node&>
#include <path.h>

Hash function for path nodes.

Just uses their position.

Public Functions

size_t operator()(const openage::path::Node &x) const
template<>
struct hash<openage::renderer::font_description>
#include <font.h>

Public Functions

size_t operator()(const openage::renderer::font_description &fd) const
template<>
struct hash<openage::score_category>
#include <score.h>

hasher for score_category TODO decide if needed, not used at the moment

Public Types

typedef underlying_type<openage::score_category>::type underlying_type

Public Functions

size_t operator()(const openage::score_category &arg) const
template<typename I, unsigned F>
struct hash<openage::util::FixedPoint<I, F>>
#include <fixed_point.h>

Public Functions

constexpr size_t operator()(const openage::util::FixedPoint<I, F> &n) const
template<>
struct hash<QString>
#include <gui_live_reloader.h>

Public Functions

size_t operator()(const QString &val) const
template<>
struct hash<std::tuple<openage::audio::category_t, int>>
#include <hash_functions.h>

Public Functions

size_t operator()(const std::tuple<openage::audio::category_t, int> &t) const
template<>
struct hash<openage::audio::category_t>
#include <hash_functions.h>

Public Functions

size_t operator()(const openage::audio::category_t &c) const
template<typename I, unsigned F>
struct numeric_limits<openage::util::FixedPoint<I, F>>
#include <fixed_point.h>

Public Static Functions

static constexpr openage::util::FixedPoint<I, F> min()
static constexpr openage::util::FixedPoint<I, F> max()
namespace openage

This file contains forward declarations for all the coordinate types, as well as their scalar types.

Main openage namespace to store all things that make the have to do with the game.

It was created to escape circular-include hell.

Game entity management, graphics drawing, gui stuff, input handling etc. So basically everything that makes the game work lies in here…

Typedefs

using index_t = int

the key type mapped to data objects

using unit_type_list = std::vector<std::shared_ptr<UnitType>>

could use unique ptr

using unit_meta_list = std::vector<std::shared_ptr<UnitTypeMeta>>
using tileset_t = std::unordered_set<coord::tile>

the type to store a set of tiles

using terrain_t = int

type that for terrain ids.

it’s signed so that -1 can indicate a missing tile. TODO: get rid of the signedness.

using ability_set = std::bitset<ability_type_size>
using ability_id_t = unsigned int
using graphic_set = std::map<graphic_type, std::shared_ptr<UnitTexture>>

Collection of graphics attached to each unit.

using typeamount_map = std::unordered_map<int, unsigned int>

An unordered_map with a int key used as a type id and a unsigned int value used as the amount.

using id_t = unsigned long int

Type used to identify each single unit in the game.

using time_nsec_t = uint64_t

Type to store time in nanoseconds.

Enums

enum ActionButtonsType

Values:

None
MilitaryUnits
CivilianUnits
BuildMenu
MilBuildMenu
enum cost_type

Types of dynamic cost calculation (and one constant).

Used in ResourceCost TODO use in TimeCost

Values:

constant

Constant resources.

workforce

Dynamic cost based on the workforce.

enum game_resource

Values:

wood = 0
food = 1
gold = 2
stone = 3
RESOURCE_TYPE_COUNT = 4
enum score_category

The categories of sub-scores that sum to a player’s score.

Values:

military

20% of units killed cost

economy

20% of alive units cost and 10% of resources

technology

20% of researched technologies and 10 for each 1% of map explored

society

20% of Castles and Wonders cost

SCORE_CATEGORY_COUNT
enum member_type

Types of membership.

Values:

leader
member
recruit
none
enum tile_state

describes the state of a terrain tile.

Values:

missing

tile is not created yet

existing

tile is already existing

creatable

tile does not exist but can be created

invalid

tile does not exist and can not be created

enum object_state

only placed will enable collision checks

Values:

removed
floating
placed
placed_no_collision
enum ability_type

roughly the same as command_ability in game data

Values:

move
patrol
set_point
garrison
ungarrison
train
build
research
gather
attack
convert
repair
heal
MAX
enum graphic_type

Types of action graphics.

Values:

construct
shadow
decay
dying
standing
walking
carrying
attack
heal
work
enum attr_type

List of unit’s attribute types.

Values:

owner
population
damaged
hitpoints
armor
attack
formation
heal
speed
direction
projectile
building
dropsite
resource
resource_generator
worker
storage
multitype
garrison
enum attack_stance

List of unit’s attack stance.

Can be used for buildings also.

Values:

aggressive
defensive
stand_ground
do_nothing
enum attack_formation

List of unit’s formation.

Effect applys on a group of units.

Values:

line
staggered
box
flank
enum command_flag

additional flags which may affect some abilities

Values:

interrupt
use_range
attack_res
enum research_category

Values:

unit_upgrade

Research which modify unit type data.

age_advance

Research which modify unit type data and also progresses the next age.

Separate category for simplification.

generic

Research which modify unit type data and something else.

(eg. see enemy line of sight)

RESEARCH_CATEGORY_COUNT
enum selection_type_t

A selection of units always has a type You can’t select units from multiple types at once Earlier types have precedence over later types.

So you can select a group of units, or a building (or multiple if append is on) Enemy units, enemy buildings and other objects may only be selected one at a time

Values:

own_units
own_buildings
enemy_unit
enemy_building
nothing

Functions

coord::tile random_tile(rng::RNG &rng, tileset_t tiles)

picks a random tile from a set

OAAPI int openage::run_game(const main_arguments & args)

runs the game.

pxd: int run_game(const main_arguments &args) except +

std::vector<coord::tile> tile_list(const tile_range &rng)

get all tiles in the tile range useful for iterating returns a flat list of tiles between the rectangle enclosed by the tile_range start and end tiles

tile_range building_center(coord::phys3 west, coord::tile_delta size, const Terrain &terrain)

given the west most point of a building foundation and the tile_delta size of the foundation, this will return the tile range covered by the base, which includes start and end tiles, and phys3 center point (used for drawing)

bool complete_building(Unit &u)

sets a building to a fully completed state

std::shared_ptr<Texture> square_outline(coord::tile_delta foundation_size)

Generate a isometric square outline texture.

std::shared_ptr<Texture> radial_outline(float radius)

Generate a isometric circle outline texture.

TerrainObject *find_near(const TerrainObject &start, std::function<bool(const TerrainObject&)> found, unsigned int search_limit, )
TerrainObject *find_in_radius(const TerrainObject &start, std::function<bool(const TerrainObject&)> found, float radius, )
std::unordered_set<terrain_t> allowed_terrains(const gamedata::ground_type &restriction)
ResourceBundle create_resource_cost(game_resource resource, int amount)
std::vector<coord::tile> tiles_in_range(coord::camgame p1, coord::camgame p2, const coord::CoordManager &coord)
bool dispatch_command(id_t, const Command&)
unsigned int dir_group(coord::phys3_delta dir, unsigned int angles = 8)

the set of images to used based on unit direction, usually 8 directions to draw for each unit (3 are mirrored)

Return

image set index

Parameters
  • dir: a world space direction,

  • angles: number of angles, usually 8

  • first_angle: offset added to angle, modulo number of angles

Variables

constexpr coord::tile_delta const openage::neigh_tiles[]= { { 1, 0}, {-1, 0}, { 0, 1}, { 0, -1}}

the four directions available for 2d tiles

constexpr double MARKET_PRICE_D = 3.0
constexpr double MARKET_PRICE_MIN = 20.0
constexpr double MARKET_PRICE_MAX = 9999.0
constexpr double MARKET_TRANSACTION_AMOUNT = 100.0
constexpr coord::tile_delta const openage::neigh_offsets[]= { { 1, -1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, { 0, -1}}

coordinate offsets for getting tile neighbors by their id.

constexpr size_t chunk_size = 16

the number of tiles per direction on a chunk

constexpr coord::tile_delta const openage::neigh_tile[]= { {0, 1}, {0, -1}, {1, 0}, {-1, 0}}
constexpr int PLAYERCOLORED = 1 << 0
constexpr int ALPHAMASKED = 1 << 1
constexpr int ability_type_size = static_cast<int>(ability_type::MAX)

a container where each ability uses 1 bit

const ability_set ability_all = ability_set().set()

all bits set to 1

std::vector<ability_type> ability_priority{ability_type::gather, , , , , , , , , , , , ,}

the order abilities should be used when available

string openage.VERSION = "< unknown version; ./configure incomplete >"
tuple openage.LONGVERSION = VERSION
namespace __main__

Functions

main(argv argv = None)

Top-level argparsing; invokes subparser for all submodules.

namespace alphamask_shader

Variables

shader::Program *program
GLint base_texture
GLint mask_texture
GLint base_coord
GLint mask_coord
GLint show_mask
namespace assets

Functions

get_asset_path(custom_asset_dir custom_asset_dir = None)

Returns a Path object for the game assets.

custom_asset_dir can a custom asset directory, which is mounted at the top of the union filesystem (i.e. has highest priority).

This function is used by the both the conversion process and the game startup. The conversion uses it for its output, the game as its data source(s).

test()

Tests whether a specific asset exists.

namespace audio

Typedefs

using pcm_data_t = std::vector<int16_t>

pcm_data_t is a vector consisting of signed 16 bit integer samples.

It is used to represent one complete audio resource’s buffer.

using pcm_chunk_t = std::vector<int16_t>

pcm_chunk_t is a vector consisting of signed 16 bit integer samples.

It is used to represent a chunk of a audio resource’s buffer with a fixed size.

Enums

enum category_t

Values:

GAME
INTERFACE
MUSIC
TAUNT
enum format_t

Values:

OPUS
WAV
MP3
FLAC
enum loader_policy_t

Values:

IN_MEMORY
DYNAMIC

Functions

const char *category_t_to_str(category_t val)
std::ostream &operator<<(std::ostream &os, const category_t val)
const char *format_t_to_str(format_t val)
std::ostream &operator<<(std::ostream &os, const format_t val)
const char *loader_policy_t_to_str(loader_policy_t val)
std::ostream &operator<<(std::ostream &os, const loader_policy_t val)
opus_file_t open_opus_file(const util::Path &path)

Opens a opus file.

Its location is specified by the path stored in the DynamicLoader.

Variables

auto opus_deleter = [](OggOpusFile *op_file) { if (op_file != nullptr) { op_free(op_file); }}
op_read_func opus_reader = [](void *stream, unsigned char *buf, int count) -> int {util::File *file = reinterpret_cast<util::File *>(stream); return file->read_to(buf, count);}
op_seek_func opus_seeker = [](void *stream, opus_int64 offset, int whence) -> int {util::File *file = reinterpret_cast<util::File *>(stream); if (unlikely(not file->seekable())) { return -1; } file->seek(offset, static_cast<util::File::seek_t>(whence)); return 0;}
op_tell_func opus_teller = [](void *stream) -> opus_int64 {util::File *file = reinterpret_cast<util::File *>(stream); return file->tell();}
OpusFileCallbacks opus_access_funcs{opus_reader, , , }
namespace cabextract
namespace cab
namespace lzxdstream
namespace test

Functions

open_cached_test_archive()

Opens the cached test archive file.

open_test_archive()

Opens the cached test archive file, or downloads it if necessary.

test()

The actual test function; registered in openage.testing.testlist.

Variables

int openage.cabextract.test.TEST_ARCHIVE_SIZE = 1057766
string openage.cabextract.test.TEST_ARCHIVE_URL = "http://pub.sft.mx/openage/openage_testarc.cab"
dictionary openage.cabextract.test.TEST_FILES= { "testfilea": ("68fe7d874c7887bdd3f6aaca46abd306", 524288), "testfileb": ("7f614da9329cd3aebf59b91aadc30bf0", 67108864), "testfilec": ("d41d8cd98f00b204e9800998ecf8427e", 0), "testdir/testfiled": ("6f75302850b485421030f034fe67380b", 10), "testdir/testfilee": ("65116b303f205837d280d3c08b1e0419", 1033720)}
openage.cabextract.test.TEST_ARCHIVE_FILENAME = os.path.join(gettempdir(), "openage_testarc.cab")
namespace codegen
namespace codegen

Functions

codegen(mode mode, input_dir input_dir, output_dir output_dir)
depend_module_blacklist()
get_codegen_depends(outputwrapper outputwrapper)

Yields all codegen dependencies.

outputwrapper is the CodegenDirWrapper that was passed to generate_all; it’s used to determine the files that have been read.

In addition, all imported python modules are yielded.

get_header_lines()

Yields the lines for the automatically-added file header.

postprocess_write(parts parts, data data)

Post-processes a single write operation, as intercepted during codegen.

namespace coord

Functions

generate_coord_basetypes(projectdir projectdir)

Generates the test/demo method symbol lookup file from tests_cpp.

projectdir is a util.fslike.path.Path.

namespace cpp_testlist

Functions

generate_testlist(projectdir projectdir)

Generates the test/demo method symbol lookup file from tests_cpp.

projectdir is a util.fslike.path.Path.

namespace gamespec_structs

Functions

generate_gamespec_structs(projectdir projectdir)

Header and C++ files for the gamespec structs.

namespace listing

Functions

generate_all(projectdir projectdir)

Contains the listing of all code generator invocations.

Generates all source files in targetdir.

namespace main

Functions

init_subparser(cli cli)

Codegen-specific CLI.

main(args args, error error)

Codegen CLI entry point.

namespace console

In-game console subsystem.

Featuring a full terminal emulator.

Typedefs

using chrcol_t = uint8_t

the length of the escape sequence buffer, and thus the maximum length of any escape sequence that will be successfully processed.

longer escape sequences will be ignored.

using chrflags_t = uint16_t
using linetype_t = uint8_t

Functions

void print_cps(FILE *f, std::vector<int> *v)

Variables

constexpr chrflags_t CHR_BOLD = (1 << 0)
constexpr chrflags_t CHR_FAINT = (1 << 1)
constexpr chrflags_t CHR_ITALIC = (1 << 2)
constexpr chrflags_t CHR_BLINKING = (1 << 3)
constexpr chrflags_t CHR_BLINKINGFAST = (1 << 4)
constexpr chrflags_t CHR_UNDERLINED = (1 << 5)
constexpr chrflags_t CHR_STRUCKOUT = (1 << 6)
constexpr chrflags_t CHR_FRAKTUR = (1 << 7)
constexpr chrflags_t CHR_NEGATIVE = (1 << 8)
constexpr chrflags_t CHR_INVISIBLE = (1 << 9)
constexpr chrflags_t CHR_FRAMED = (1 << 10)
constexpr chrflags_t CHR_ENCIRCLED = (1 << 11)
constexpr chrflags_t CHR_OVERLINED = (1 << 12)
constexpr chrflags_t CHR_RIGHTLINED = (1 << 13)
constexpr chrflags_t CHR_LEFTLINED = (1 << 14)
constexpr chrflags_t CHR_STRESS_IDEOGRAM = (1 << 15)
constexpr linetype_t LINE_EMPTY = 0

the line has not been written yet (or cleared in between)

constexpr linetype_t LINE_REGULAR = 1

the line has some contents

constexpr linetype_t LINE_WRAPPED = 2

the line has been written to until it auto-wrapped; its continuation can be found in the next line

this value is required for re-calculating the buffer on resize

constexpr buf_line BUF_LINE_DEFAULT = {LINE_EMPTY}
namespace draw

Functions

void to_opengl(Engine *engine, Console *console)

experimental and totally inefficient opengl draw of a terminal buffer.

void to_terminal(Buf *buf, util::FD *fd, bool clear)

very early and inefficient printing of the console to a pty.

namespace tests

Functions

int max(int a, int b)
void render()
void interactive()
namespace convert
namespace binpack

Functions

factor(n n)

Return two (preferable close) factors of n.

maxside_heuristic(block block)

Heuristic Order blocks by maximum side.

namespace blendomatic
namespace changelog

Functions

changes(asset_version asset_version, spec_version spec_version)

return all changed components since the passed version number.

test()

verify only allowed versions are stored in the changes

Variables

string openage.convert.changelog.ASSET_VERSION_FILENAME = "asset_version"
string openage.convert.changelog.GAMESPEC_VERSION_FILENAME = "gamespec_version"
dictionary openage.convert.changelog.COMPONENTS= { "graphics", "sounds", "metadata", "interface",}
tuple openage.convert.changelog.CHANGES= ( {"graphics", "sounds"}, {"sounds"}, {"graphics"}, {"interface"}, {"interface"}, {"metadata"}, {"metadata"}, {"graphics"},)
int openage.convert.changelog.ASSET_VERSION = len(CHANGES) - 1
namespace colortable
namespace dataformat
namespace content_snippet
namespace data_definition
namespace data_formatter
namespace entry_parser
namespace exportable
namespace generated_file
namespace header_snippet
namespace member_access

Variables

openage.convert.dataformat.member_access.READ = MemberAccess.READ
openage.convert.dataformat.member_access.READ_EXPORT = MemberAccess.READ_EXPORT
openage.convert.dataformat.member_access.NOREAD_EXPORT = MemberAccess.NOREAD_EXPORT
openage.convert.dataformat.member_access.READ_UNKNOWN = MemberAccess.READ_UNKNOWN
namespace members
namespace multisubtype_base
namespace struct_definition

Variables

openage.convert.dataformat.struct_definition.vararray_match = re.compile("([{0}]+) *\[([{0}]+)\] *;?".format("a-zA-Z0-9_"))
openage.convert.dataformat.struct_definition.integer_match = re.compile("\d+")
namespace struct_snippet
namespace util

Functions

encode_value(val val)
gather_data(obj obj, members members)
determine_header(for_type for_type)

returns the includable headers for using the given C type.

determine_headers(for_types for_types)
commentify_lines(commentstr commentstr, text text)

Variables

dictionary openage.convert.dataformat.util.struct_type_lookup= { "char": "b", "unsigned char": "B", "int8_t": "b", "uint8_t": "B", "short": "h", "unsigned short": "H", "int16_t": "h", "uint16_t": "H", "int": "i", "unsigned int": "I", "int32_t": "i", "uint32_t": "I", "long": "l", "unsigned long": "L", "long long": "q", "unsigned long long": "Q", "int64_t": "q", "uint64_t": "Q", "float": "f", "double": "d", "char[]": "s",}
namespace driver

Functions

get_string_resources(args args)

reads the (language) string resources

get_blendomatic_data(srcdir srcdir)

reads blendomatic.dat

get_gamespec(srcdir srcdir, game_versions game_versions, dont_pickle dont_pickle)

reads empires.dat and fixes it

convert(args args)
get_palette(srcdir srcdir, offset offset = 0)

Read and create the color palette.

convert_metadata(args args)

Converts the metadata part.

extract_mediafiles_names_map(srcdir srcdir)
slp_rename(filepath filepath, names_map names_map)

Returns a human-readable name if it’s in the map.

convert_media(args args)

Converts the media part.

get_filter(args args)
change_dir(path_parts path_parts, dirname dirname)
convert_slp(filepath filepath, dirname dirname, names_map names_map, converter_pool converter_pool, args args)
convert_wav(filepath filepath, dirname dirname, args args)

Convert a wav audio file to an opus file.

convert_mediafile(filepath filepath, dirname dirname, names_map names_map, converter_pool converter_pool, args args)
namespace drs

Variables

int openage.convert.drs.FILE_VERSION = 57
int openage.convert.drs.COPYRIGHT_SIZE = 40
namespace fix_data

Functions

fix_data(data data)

modernizes/patches the gamespec.

updates given input with modifications.

input empiresdat object, vanilla, fully read. output empiresdat object, fixed.

namespace game_versions

Functions

get_game_versions(srcdir srcdir)
has_x1_p1(versions versions)

Determine whether any of the versions has patch 1, i.e.

the *_x1_p1.* files

namespace gamedata
namespace civ
namespace empiresdat

Functions

load_gamespec(fileobj fileobj, game_versions game_versions, cachefile_name cachefile_name = None, load_cache load_cache = False)
namespace graphic
namespace maps
namespace playercolor
namespace research
namespace sound
namespace tech

Variables

string openage.convert.gamedata.tech.name_struct = "tech"
string openage.convert.gamedata.tech.name_struct_file = "tech"
string openage.convert.gamedata.tech.struct_description = "a technology definition."
list openage.convert.gamedata.tech.data_format= [ (READ, "name", "char[31]"), # always CHUN4 (change unit 4-arg) (READ, "effect_count", "uint16_t"), (READ, "effects", SubdataMember( ref_type=Effect, length="effect_count", )), ]
namespace terrain
namespace unit

Variables

dictionary openage.convert.gamedata.unit.unit_type_lookup= { 10: "object", 20: "animated", 25: "doppelganger", 30: "moving", 40: "action", 60: "missile", 70: "living", 80: "building", 90: "tree",}
dictionary openage.convert.gamedata.unit.unit_type_class_lookup= { "object": UnitObject, "animated": AnimatedUnit, "doppelganger": DoppelgangerUnit, "moving": MovingUnit, "action": ActionUnit, "missile": MissileUnit, "living": LivingUnit, "building": BuildingUnit, "tree": TreeUnit,}
namespace hardcoded
namespace langcodes

Variables

dictionary openage.convert.hardcoded.langcodes.LANGCODES
namespace langcodes_hd

Variables

dictionary openage.convert.hardcoded.langcodes_hd.LANGCODE_MAP_HD= { 'br': 'pt_BR', 'cn': 'zh_CN', 'de': 'de_DE', 'en': 'en_US', 'es': 'es_ES', 'fr': 'fr_FR', 'it': 'it_IT', 'ja': 'ja_JP', 'ko': 'ko_KR', 'nl': 'nl_NL', 'ru': 'ru_RU'}
namespace termcolors

Variables

list openage.convert.hardcoded.termcolors.URXVTCOLS

The 256 colors for use by the in-game terminal.

Proudly determined from an URXVT screenshot.

namespace terrain_tile_size

Variables

dictionary openage.convert.hardcoded.terrain_tile_size.TILE_HALFSIZE= { "x": 48, "y": 24,}

Tile size for terrain pieces.

namespace texture

Variables

int openage.convert.hardcoded.texture.MAX_TEXTURE_DIMENSION = 8194

Constants for texture generation.

int openage.convert.hardcoded.texture.MARGIN = 1
int openage.convert.hardcoded.texture.TERRAIN_ASPECT_RATIO = 97 / 94
namespace hdlanguagefile

Functions

read_age2_hd_fe_stringresources(stringres stringres, path path)
read_age2_hd_3x_stringresources(stringres stringres, srcdir srcdir)
read_hd_language_file(fileobj fileobj, langcode langcode, enc enc = 'utf-8')

Takes a file object, and the file’s language code.

namespace interface
namespace cutter
namespace hardcoded

Functions

ingame_hud_background_index(idx idx)

Index in the hardcoded list of the known ingame hud backgrounds to match the civ.

is_ingame_hud_background(idx idx)

True if in the hardcoded list of the known ingame hud backgrounds.

Variables

list openage.convert.interface.hardcoded.INGAME_HUD_BACKGROUNDS= [ 51141, 51142, 51143, 51144, 51145, 51146, 51147, 51148, 51149, 51150, 51151, 51152, 51153, 51154, 51157, 51158, 51159, 51160,]

Additional hardcoded information about user interface assets.

openage.convert.interface.hardcoded.INGAME_HUD_BACKGROUNDS_SET = set(INGAME_HUD_BACKGROUNDS)
dictionary openage.convert.interface.hardcoded.ASSETS= { '50721': 'hudactions'}
tuple openage.convert.interface.hardcoded.TOP_STRIP_PATTERN_CORNERS = (400, 0, 464, 32)
tuple openage.convert.interface.hardcoded.TOP_STRIP_PATTERN_SEARCH_AREA_CORNERS = (400, 0, 1024, 32)
tuple openage.convert.interface.hardcoded.MID_STRIP_PATTERN_CORNERS = (339, 806, 403, 818)
tuple openage.convert.interface.hardcoded.MID_STRIP_PATTERN_SEARCH_AREA_CORNERS = (339, 806, 850, 818)
list openage.convert.interface.hardcoded.KNOWN_SUBTEX_CORNER_COORDS= [ (0, 806, 339, 1024), (850, 806, 1280, 1024), (8, 10, 34, 27), (85, 10, 111, 27), (162, 10, 188, 27), (239, 10, 265, 27), (316, 10, 342, 27),]
namespace rename

Functions

hud_rename(filepath filepath)

Renaming interface assets and splitting into directories.

asset_rename(filepath filepath)

Rename a slp asset path by the lookup map above.

namespace main

Functions

mount_drs_archives(srcdir srcdir, game_versions game_versions = None)
mount_input(srcdir srcdir = None, prev_source_dir_path prev_source_dir_path = None)

Mount the input folders for conversion.

convert_assets(assets assets, args args, srcdir srcdir = None, prev_source_dir_path prev_source_dir_path = None)

Perform asset conversion.

Requires original assets and stores them in usable and free formats.

assets must be a filesystem-like object pointing at the game’s asset dir. srcdir must be None, or point at some source directory.

If gen_extra_files is True, some more files, mostly for debugging purposes, are created.

This method prepares srcdir and targetdir to allow a pleasant, unified conversion experience, then passes them to .driver.convert().

expand_relative_path(path path)

Expand relative path to an absolute one, including abbreviations like ~ and environment variables.

wanna_use_wine()
set_custom_wineprefix()

Allow the customization of the WINEPREFIX environment variable.

query_source_dir(proposals proposals)
acquire_conversion_source_dir(prev_source_dir_path prev_source_dir_path = None)

Acquires source dir for the asset conversion.

Returns a file system-like object that holds all the required files.

wine_to_real_path(path path)

Turn a Wine file path (C:\xyz) into a local filesystem path (~/.wine/xyz)

unescape_winereg(value value)

Remove quotes and escapes from a Wine registry value.

source_dir_proposals(call_wine call_wine)

Yield a list of directory names where an installation might be found.

conversion_required(asset_dir asset_dir, args args)

Returns true if an asset conversion is required to run the game.

Sets options in args according to what sorts of conversion are required.

interactive_browser(srcdir srcdir = None)
init_subparser(cli cli)

Initializes the parser for convert-specific args.

main(args args, error error)

CLI entry point.

Variables

openage.convert.main.STANDARD_PATH_IN_32BIT_WINEPREFIX = \
openage.convert.main.STANDARD_PATH_IN_64BIT_WINEPREFIX = \
openage.convert.main.STANDARD_PATH_IN_WINEPREFIX_STEAM = \
openage.convert.main.REGISTRY_KEY = \
string openage.convert.main.REGISTRY_SUFFIX_AOK = "Age of Empires\2.0"
string openage.convert.main.REGISTRY_SUFFIX_TC = "Age of Empires II: The Conquerors Expansion\1.0"
namespace opus
namespace demo

Functions

convert(args args)

Demonstrates the usage of the opusenc module.

namespace pefile
namespace peresource

Variables

dictionary openage.convert.peresource.RESOURCE_TYPES= { 0: 'unknown', 1: 'cursor', 2: 'bitmap', 3: 'icon', 4: 'menu', 5: 'dialog', 6: 'string', 7: 'fontdir', 8: 'font', 9: 'accelerator', 10: 'rcdata', 11: 'messagetable', 12: 'group_cursor', 14: 'group_icon', 16: 'version', 17: 'dlginclude', 19: 'plugplay', 20: 'vxd', 21: 'anicursor', 22: 'aniicon', 23: 'html', 24: 'manifest'}
dictionary openage.convert.peresource.RESOURCE_IDS = {value: key for key, value in RESOURCE_TYPES.items()}
int openage.convert.peresource.STRINGTABLE_SIZE = 16
namespace singlefile

Functions

init_subparser(cli cli)

Initializes the parser for convert-specific args.

main(args args, error error)

CLI entry point for single file conversions.

namespace slp_converter_pool

Functions

converter_process(inqueue inqueue, outqueue outqueue)

This is the function that runs inside each individual process.

namespace stringresource
namespace texture

Functions

subtexture_meta(tx tx, ty ty, hx hx, hy hy, cx cx, cy cy)
merge_frames(frames frames)

merge all given frames of this slp to a single image file.

frames = [TextureImage, …]

returns = TextureImage, (width, height), [drawn_frames_meta]

namespace coord

Typedefs

using phys_t = util::FixedPoint<int64_t, phys_t_radix_pos>
using tile_t = int64_t
using pixel_t = int32_t
using chunk_t = int32_t
using term_t = int

Variables

constexpr unsigned int phys_t_radix_pos = 16
constexpr tile_t tiles_per_chunk = 16
namespace tests

Functions

void coord()

test method for the base CoordXY* classes.

namespace [anonymous]
namespace cppinterface
namespace setup

Functions

setup(args args)

After a call to setup(), the C++ interface is in a usable state.

setup() automatically checks whether there are any remaining un-initialized PyFunc objects, and raises an Exception if so.

Must be invoked before any functions from libopenage are invoked. Runs only once; any subsequent invocations are a no-op, so don’t hesitate to call this method whenever likely.

Do not invoke from a .pyx extension module that itself provides a setup method (circular imports)!

namespace curve

Typedefs

using time_t = util::FixedPoint<int64_t, 16>

Defines the type that is used as time index.

it has to implement all basic mathematically operations.

namespace tests

Functions

std::ostream &operator<<(std::ostream &o, const map_test_element &e)
template<typename key_t, typename val_t>
void dump(const std::unordered_map<key_t, val_t> &map)
void test_map()
void test_list()
void test_queue()
void container()
void curve_types()
namespace cvar

Typedefs

using get_func = std::function<std::string()>

function type used to get a configuration value

using set_func = std::function<void(std::string)>

function type to set the value of a config entry

Variables

OAAPI pyinterface::PyIfFunc< void, CVarManager *, const util::Path & > openage::cvar::pyx_load_config_file

Python function to load a configuration file.

The config manager is passed into it.

pxd: ctypedef CVarManager * CVarManagerPtr PyIfFunc2[void, CVarManagerPtr, const Path&] pyx_load_config_file

namespace config_file

Functions

load_config_file(path path, set_cvar_func set_cvar_func, loaded_files loaded_files = None)

Load a config file, with possible subfile, into the cvar system.

set_cvar is a function that accepts (key, value) to actually add the data.

namespace location

Functions

get_config_path(custom_cfg_dir custom_cfg_dir = None)
namespace datastructure

Functions

template<typename K, typename V, typename ...Entries>
constexpr auto create_const_map(Entries&&... entry)

Creates a compiletime lookup table from K to V, where all entries of K must be unique.

usage: constexpr auto bla = create_const_map<type0, type1>(entry0, entry1, …);

template<typename Entry, typename ...Rest, typename = std::enable_if_t<std::conjunction_v<std::is_same<Entry, Rest>...>>>
ConstMap(Entry, Rest&&...)

Template deduction guide to deduce the Key-Value types for the ConstMap from the paired entries passed.

usage: constexpr ConstMap boss{std::pair{k0, v0}, std::pair{k1, v1}, …};

Note: Use when automatic type deduction is desirable. For manually specifying types, use the other method.

namespace tests

Functions

void pairing_heap_0()
void pairing_heap_1()
void pairing_heap_2()
void pairing_heap_3()
void pairing_heap()
void constexpr_map()
namespace default_dirs

Functions

get_dir(which which)

Variables

dictionary openage.default_dirs.LINUX_DIRS= { "config_home": ("XDG_CONFIG_HOME", ("{HOME}/.config", {"HOME"})), "data_home": ("XDG_DATA_HOME", ("{HOME}/.local/share", {"HOME"})), "data_dirs": ("XDG_DATA_DIRS", ("/usr/local/share/:/usr/share/", {})), "config_dirs": ("XDG_CONFIG_DIRS", ("/etc/xdg", {})), "cache_home": ("XDG_CACHE_HOME", ("{HOME}/.cache", {"HOME"})), "runtime_dir": ("XDG_RUNTIME_DIR", ("/run/user/$UID")),}
dictionary openage.default_dirs.WINDOWS_DIRS= { "config_home": ("APPDATA", (False, None)), "data_home": ("APPDATA", (False, None)), "config_dirs": ("ALLUSERSPROFILE", (False, None)), # TODO: other windows paths}
namespace devmode
namespace error

Functions

std::ostream &operator<<(std::ostream &os, const backtrace_symbol &bt_sym)

Prints a backtrace_symbol object.

std::ostream &operator<<(std::ostream &os, const Backtrace &bt)

Prints an entire Backtrace object.

void demo()
std::ostream &operator<<(std::ostream &os, const Error &e)
std::string no_ensuring_message()
SDL_GLContext create_debug_context(SDL_Window *window)
void terminate_handler()
void sigsegv_handler(int)
void exit_handler()
OAAPI void openage::error::set_exit_ok(bool value)

Call this to set or unset the atexit error handler.

In order to capture any stray calls to exit() from any place in the game (including libraries), set this to true on startup, and back to false right before termination.

pxd: void set_exit_ok(cppbool value) except +

Variables

constexpr const char *runtime_error_message = "polymorphic openage Error object; catch by reference!"
bool enable_break_on_create = false
constexpr uint64_t skip_entry_frames = 1

Skip this many frames at the beginning of the trace.

Can trim away various libc calls.

constexpr uint64_t base_skip_frames = 1

Skip this many stack frames, this drops the stackanalyzer function call itself.

namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace event
namespace demo

Enums

enum timescale

Simulation speeds.

Values:

NOSLEEP
REALTIME
SLOW
FAST

Functions

OAAPI void openage::event::demo::curvepong(bool disable_gui, bool no_human)
int curvepong()
namespace tests

Functions

void eventtrigger()
namespace game
namespace main

Functions

init_subparser(cli cli)

Initializes the parser for game-specific args.

main(args args, error error)
namespace gameio

Functions

void save_unit(std::ofstream &file, Unit *unit)
void load_unit(std::ifstream &file, GameMain *game)
void save_tile_content(std::ofstream &file, openage::TileContent *content)
TileContent load_tile_content(std::ifstream &file)
void save(openage::GameMain *game, std::string fname)

a game save function that sometimes works

void load(openage::GameMain *game, std::string fname)

a game load function that sometimes works

Variables

const std::string save_label = "openage-save-file"
const std::string save_version = "v0.1"
namespace gui

Functions

void gui_log(QtMsgType type, const QMessageLogContext &context, const QString &msg)
std::unique_ptr<QSGTexture> make_standalone_subtexture(GLuint id, const QSize &size)
bool isAtlasTexture(const TextureHandle &texture_handle)
QSize textureSize(const SizedTextureHandle &texture_handle)
QSize native_size(const TextureHandle &texture_handle)
QSize aspect_fit_size(const TextureHandle &texture_handle, const QSize &requested_size)

The sourceSize property of the Image QML element ends up here for checking.

Return

if !requested_size.isValid() or requested_size.isNull() then native size, otherwise fit in the requested_size (zero component in requested_size means unbounded).

Parameters
  • requested_size: sourceSize if used in Image QML element.

Variables

openage::gui::current_type_id = {-1}
openage::gui::current_terrain_id = {-1}
openage::gui::paint_terrain
openage::gui::QQmlParserStatus = {}
openage::gui::GuiItem = {this}
openage::gui::mode = {}
openage::gui::effective_mode_index = {-1}
openage::gui::mode_index = {-1}
openage::gui::engine = {}
openage::gui::game = {}
const int reg_path = qRegisterMetaType<util::Path>("util::Path")
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace input

The openage input layer.

It gets all the events and processes them accordingly.

Typedefs

using action_t = unsigned int

Used to identify actions.

using action_id_t = action_t
using action_func_t = std::function<void(const action_arg_t&)>

Performs the effect of an action.

using action_check_t = std::function<bool(const action_arg_t&)>

For receivers of sets of events a bool is returned to indicate if the event was used.

using code_t = int

types used by events

using modset_t = std::unordered_set<modifier, modifier_hash>
using event_set_t = std::unordered_set<Event, event_hash>
using binding_map_t = std::unordered_map<action_t, Event>

maps actions to events.

Enums

enum event_class

highest level classes of input

Values:

ANY
KEYBOARD
CHAR
ALPHA
DIGIT
PRINT
NONPRINT
OTHER
UTF8
MOUSE
MOUSE_BUTTON
MOUSE_BUTTON_UP
MOUSE_BUTTON_DOWN
MOUSE_WHEEL
MOUSE_MOTION
enum modifier

mods set on an event

Values:

CTRL
ALT
SHIFT

Functions

bool operator==(ClassCode a, ClassCode b)
modset_t sdl_mod(SDL_Keymod mod)
Event sdl_key(SDL_Keycode code, SDL_Keymod mod)
Event utf8(const std::string &text)
Event sdl_mouse(int button, SDL_Keymod mod)
Event sdl_mouse_up_down(int button, bool up, SDL_Keymod mod)
Event sdl_wheel(int direction, SDL_Keymod mod)
Event text_to_event(const std::string &event_str)

Convert a string to an event, throw if the string is not a valid event.

Variables

std::unordered_map<event_class, event_class, event_class_hash> openage::input::event_base{ {event_class::KEYBOARD, event_class::ANY}, {event_class::CHAR, event_class::KEYBOARD}, {event_class::ALPHA, event_class::CHAR}, {event_class::DIGIT, event_class::CHAR}, {event_class::PRINT, event_class::CHAR}, {event_class::NONPRINT, event_class::KEYBOARD}, {event_class::OTHER, event_class::KEYBOARD}, {event_class::UTF8, event_class::KEYBOARD}, {event_class::MOUSE, event_class::ANY}, {event_class::MOUSE_BUTTON, event_class::MOUSE}, {event_class::MOUSE_WHEEL, event_class::MOUSE}, {event_class::MOUSE_MOTION, event_class::MOUSE},}

each event type mapped to parent type

namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace tests

Functions

void parse_event_string()
namespace job

Typedefs

using job_function_t = std::function<T()>

Type of a function that is executed by a job and returns a result.

Parameters
  • T: the job’s result type

using abortable_function_t = std::function<T(std::function<bool()>std::function<void()>)>

Type of a function that is executed by a job and returns a result.

It can be aborted using the two passed function objects.

Parameters
  • T: the job’s result type

using result_function_t = std::function<T()>

Type of a function to retrieve the result of a job.

If the job threw an exception, it is rethrown by this function.

Parameters
  • T: the job’s result type

using callback_function_t = std::function<void(result_function_t<T>)>

Type of a job’s callback function, which is called, when a job has finished.

The passed result function object is used to retrieve the job’s result.

Parameters
  • T: the job’s result type

using should_abort_t = std::function<bool()>

Type of a function that returns whether a job should be aborted.

using abort_t = std::function<void()>

Type of a function that aborts a job.

namespace tests

Functions

void test_simple_job()
void test_simple_job_with_exception()
void test_job_manager()
namespace log

Functions

void log(const message &msg)

Convenience method that makes use of the ‘general’ LogSource.

Invokes general_source()->log(msg).

OAAPI void openage::log::set_level(level lvl)

Sets the log level of the global stdout sink.

pxd: void set_level(level lvl) except +

this msg openage::log::init()
std::ostream &operator<<(std::ostream &os, const message &msg)

prints message to a stream (with color codes and everything!)

NamedLogSource &general_source()

Returns a reference to a general named log source, for use by log::log().

StdOutSink &global_stdoutsink()

Returns a reference to the global stdout logsink object; Initializes the object if needed.

level_colorcode(lvl lvl)

returns the same color codes as in libopenage/log/level.cpp.

_spam(self self, msg msg, args args, kwargs kwargs)

Log ‘msg % args’ with severity ‘SPAM’.

setup_logging()

setup the logging system

set_loglevel(level level)

sets the log level

get_loglevel()

gets the log level

spam(msg msg, args args, kwargs kwargs)

spam message

dbg(msg msg, args args, kwargs kwargs)

debug message

info(msg msg, args args, kwargs kwargs)

info message

warn(msg msg, args args, kwargs kwargs)

warning message

err(msg msg, args args, kwargs kwargs)

error message

crit(msg msg, args args, kwargs kwargs)

critical error message

verbosity_to_level(verbosity verbosity)

Translates an integer verbosity to a log level.

env_verbosity()

Tries to retrieve verbosity from the VERBOSITY environment variable.

Variables

constexpr level_value openage::log::undefined = {{"UNDEFINED", 999}, "5"}
this msg openage::log::lineno = lineno
this msg openage::log::functionname = functionname
this msg openage::log::lvl = lvl
dictionary openage.log.PYTHON_TO_CPP_LOG_LEVEL = {}
openage.log.CPP_HANDLER = CppHandler()
int openage.log.SPAM = 5
openage.log.ENV_VERBOSITY = env_verbosity()
namespace [anonymous]
namespace tests

Functions

void demo()
demo(args args)

Demonstrates the Python logging facility.

namespace math

Functions

template<typename T>
T square(T arg)
template<typename T>
T hypot3(T x, T y, T z)

Variables

constexpr double E = 2.71828182845904523536

e

constexpr double LOG2E = 1.44269504088896340736

log_2 e

constexpr double LOG10E = 0.434294481903251827651

log_10 e

constexpr double LN2 = 0.693147180559945309417

log_e 2

constexpr double LN10 = 2.30258509299404568402

log_e 10

constexpr double PI = 3.14159265358979323846

pi

constexpr double PI_2 = 1.57079632679489661923

pi/2

constexpr double PI_4 = 0.785398163397448309616

pi/4

constexpr double INV_PI = 0.318309886183790671538

1/pi

constexpr double INV2_PI = 0.636619772367581343076

2/pi

constexpr double INV2_SQRT_PI = 1.12837916709551257390

2/sqrt(pi)

constexpr double TAU = 6.28318530717958647693

2*pi

constexpr double DEGSPERRAD = 0.017453292519943295769

tau/360

constexpr double RADSPERDEG = 57.29577951308232087679

360/tau

constexpr double SQRT_2 = 1.41421356237309504880

sqrt(2)

constexpr double INV_SQRT_2 = 0.707106781186547524401

1/sqrt(2)

constexpr unsigned int UINT_INF = std::numeric_limits<unsigned int>::max()
constexpr int INT_INF = std::numeric_limits<int>::max()
constexpr double DOUBLE_INF = std::numeric_limits<double>::max()
namespace options

Typedefs

using option_list = std::vector<OptionValue>

set the container used for lists

using opt_func_t = std::function<OptionValue()>

Enums

enum option_type

list of possible value types

Values:

bool_type
int_type
double_type
string_type
list_type

Functions

OptionValue parse(option_type t, std::string s)
namespace os

similar in its goals to Python’s os module

Functions

std::string read_symlink(const char *path)

reads a symlink

std::string self_exec_filename()

returns openage’s executable name

int execute_file(const char *path, bool background)

tries to xdg-open the file

namespace path

Typedefs

using heuristic_t = cost_t (*)(const coord::phys3 &start, const coord::phys3 &end)

function pointer type for distance estimation functions.

using cost_t = float

The data type for movement cost.

using node_pt = std::shared_ptr<Node>

Type for storing navigation nodes.

using nodemap_t = std::unordered_map<coord::phys3, node_pt>

Type for mapping tiles to nodes.

using heap_t = datastructure::PairingHeap<node_pt, compare_node_cost>

Priority queue node item type.

Functions

Path to_point(coord::phys3 start, coord::phys3 end, std::function<bool(const coord::phys3&)> passable)

path between two static points

Path to_object(openage::TerrainObject *to_move, openage::TerrainObject *end, coord::phys_t rad)

path between 2 objects, with how close to come to end point

Path find_nearest(coord::phys3 start, std::function<bool(const coord::phys3&)> valid_end, std::function<bool(const coord::phys3&)> passable)

path to nearest object with lambda

Path a_star(coord::phys3 start, std::function<bool(const coord::phys3&)> valid_end, std::function<cost_t(const coord::phys3&)> heuristic, std::function<bool(const coord::phys3&)> passable)

finds a path between two endpoints

Return

path between the given tiles

Parameters
  • start: the starting tile coords

  • end: the ending tile coords

  • heuristic: the heuristic for evaluating cost

  • passable: lambda to decide which terrain is passable

cost_t manhattan_cost(const coord::phys3 &start, const coord::phys3 &end)

Manhattan distance cost estimation.

Return

the sum of the x and y difference.

cost_t chebyshev_cost(const coord::phys3 &start, const coord::phys3 &end)

Chebyshev distance cost estimation.

Return

y or x difference, whichever is higher.

cost_t euclidean_cost(const coord::phys3 &start, const coord::phys3 &end)

Euclidean distance cost estimation.

Return

the hypotenuse length of the rectangular triangle formed.

cost_t euclidean_squared_cost(const coord::phys3 &start, const coord::phys3 &end)

Squared euclidean distance cost estimation.

Return

the square of the hypotenuse length of the rectangular triangle formed.

cost_t euclidean_squared_to_euclidean_cost(const cost_t euclidean_squared_value)

Calculate euclidean distance from a already calculated squared euclidean distance.

bool passable_line(node_pt start, node_pt end, std::function<bool(const coord::phys3&)> passable, float samples, )

Variables

constexpr coord::phys_t path_grid_size = {1.f / 8}

Size of phys-coord grid for path nodes.

constexpr coord::phys3_delta const openage::path::neigh_phys[]= { {path_grid_size * 1, path_grid_size * -1, 0}, {path_grid_size * 1, path_grid_size * 0, 0}, {path_grid_size * 1, path_grid_size * 1, 0}, {path_grid_size * 0, path_grid_size * 1, 0}, {path_grid_size * -1, path_grid_size * 1, 0}, {path_grid_size * -1, path_grid_size * 0, 0}, {path_grid_size * -1, path_grid_size * -1, 0}, {path_grid_size * 0, path_grid_size * -1, 0}}

Phys3 delta coordinates to select for path neighbors.

namespace tests

Functions

void node_0()

This function tests setting up basic nodes that point to a previous node.

Tests that direction is set correctly and that factor is set correctly.

void node_cost_to_0()

This function tests Node->cost_to.

The testing is done on 2 unrelated nodes (They have no previous node) to test the basic cost without adding the cost from node->factor.

void node_cost_to_1()

This function tests Node->cost_to.

The testing is done on the neighbor nodes to test how the directional factor effects the cost.

void node_generate_backtrace_0()

This function does a basic test of generating a backtrace from the last node in a path.

void node_get_neighbors_0()

This function tests Node->get_neighbors and how the scale effects the neighbors given.

bool always_passable(const coord::phys3&)

This is a helper passable function that alwalys returns true.

bool not_passable(const coord::phys3&)

This is a helper passable function that always returns false.

bool sometimes_passable(const coord::phys3 &pos)

This is a helper passable function that only returns true when pos.ne == 20.

void node_passable_line_0()

This function tests passable_line.

Tests with always false, always true, and position dependant functions being passed in as args.

void path_node()

Top level node test.

namespace py

Convenience functions and types for the python interface.

Typedefs

using Obj = pyinterface::PyObjectRef

Python object reference.

Functions

Obj builtin(const std::string &name)

getattr(importlib.import_module(“builtins”), name)

Obj import(const std::string &name)

importlib.import_module(name)

Obj str(const std::string &value)

str(value);

Obj bytes(const std::string &value)

bytes(value)

Obj integer(int value)

int(value)

Obj dict()

dict()

Obj list()

list()

namespace pyinterface

Typedefs

using Func0 = Func<RT>
using Func1 = Func<RT, AT0>
using Func2 = Func<RT, AT0, AT1>
using Func3 = Func<RT, AT0, AT1, AT2>
using Func4 = Func<RT, AT0, AT1, AT2, AT3>
using Func5 = Func<RT, AT0, AT1, AT2, AT3, AT4>
using PyObj = PyObjectRef

convenience alias

Functions

OAAPI void openage::pyinterface::set_exc_translation_funcs(void(*raise_cpp_error)( Error *), void(*raise_cpp_pyexception)( PyException *), bool(*check_for_py_exception)(), void(*describe_py_exception)( PyException *))

Installs the basic interface functions that are used for exception translation.

No PyIfFunc wrappers can be used here, because those internally rely on exception translation themselves, which would lead to

  • infinite loops

  • immediate back-conversion of raised Python CPPException objects

Thus, we instead offer this setter function, to be called during openage.cppinterface.exctranslate.setup().

The

PyException still contains a reference to the original Python object that was translated by describe_py_exception - we just use that.
Parameters
  • raise_cpp_error: Raises the given C++ Exception object as a Python exception. called by translate_exc_cpp_to_py.

  • raise_cpp_pyexception: Raises the given C++ PyException object as a Python exception. called by translate_exc_cpp_to_py.

Invoked by openage::pyinterface::cpp_to_py.

Calls PyErr_Fetch and stores all sorts of information in the

PyException. The current Python exception is cleared in the process.
Parameters
  • check_for_py_exception: Used by translate_exc_cpp_to_py to check whether there is a currently-active Python exception.

  • describe_py_exception: Used by translate_exc_cpp_to_py to gather information about the current Python exception.

If the current Python exception had a cause, that cause is set as the new active exception. Call check_exception() afterwards to test whether that has happend.

If there’s no currently-active Python Exception, the behavior is undefined; make sure to call check_exception() before.

Afterwards, the PyException is ready for throwing.

pxd:

void set_exc_translation_funcs( void (*)(Error *) except * with gil, void (*)(PyException *) except * with gil, cppbool (*)() with gil, void (*)(PyException *) except * with gil ) noexcept

OAAPI void openage::pyinterface::translate_exc_cpp_to_py()

Analyzes the current C++ exception, and creates and raises an analogous Python CPPException object.

If there’s no current C++ exception, this terminates the program non-gracefully (std::terminate).

Designed to be called by auto-generated Cython code; Do not use in any other way.

OAAPI void openage::pyinterface::translate_exc_py_to_cpp()

Analyzes the current Python exception, and creates and throws an analogous C++ PyException object.

Works, and is designed to be used in, situations where there is no current Python exception (it’s a no-op then).

OAAPI void openage::pyinterface::init_exc_message(log::message * msg, const std::string & filename, unsigned int lineno, const std::string & functionname)

For use by Python, to initialize a message’s meta data.

Initializes all values.

pxd: void init_exc_message(message *msg, string filename, unsigned int lineno, string functionname) noexcept

std::ostream &operator<<(std::ostream &os, const PyObjectRef &ref)

Stream operator for printing PyObjects.

void add_py_if_component(void *thisptr, std::function<bool()> checker)

Adds a Python interface component.

Usually, you’d call this from a component’s constructor.

thisptr is a pointer to the component object.

checker is a function that must have defined behavior until destroy_py_if_component has been called for thisptr. It shall return true if the object has been properly initialized, and shall not throw any exceptions.

void destroy_py_if_component(void *thisptr)

Signals that an interface component that has been previously registered via add_py_if_component is no longer valid, e.g.

because its destructor has been invoked. Usually, you’d call this from a component’s destructor.

OAAPI void openage::pyinterface::check()

Checks whether all objects that have been registered via add_py_if_component have been properly initialized.

If not, or if components have been destroyed already, raises an exception that contains the component names.

May be called only once.

pxd: void check() except +

Variables

void(* openage::pyinterface::raise_cpp_error) (Error *) = nullptr
void(* openage::pyinterface::raise_cpp_pyexception) (PyException *) = nullptr
void(* openage::pyinterface::describe_py_exception) (PyException *) = nullptr
bool (*check_for_py_exception)() = nullptr
OAAPI PyIfFunc< void, PyObject *, Func< void, const error::backtrace_symbol * > > openage::pyinterface::pyexception_bt_get_symbols
OAAPI PyIfFunc< void, PyObject * > openage::pyinterface::py_xincref
OAAPI PyIfFunc< void, PyObject * > openage::pyinterface::py_xdecref
OAAPI PyIfFunc< std::string, PyObject * > openage::pyinterface::py_str
OAAPI PyIfFunc< std::string, PyObject * > openage::pyinterface::py_repr
OAAPI PyIfFunc< std::string, PyObject * > openage::pyinterface::py_bytes
OAAPI PyIfFunc< int, PyObject * > openage::pyinterface::py_len
OAAPI PyIfFunc< bool, PyObject * > openage::pyinterface::py_callable
OAAPI PyIfFunc< void, PyObjectRef *, PyObject * > openage::pyinterface::py_call0
OAAPI PyIfFunc< void, PyObjectRef *, PyObject *, std::vector< PyObject * > & > openage::pyinterface::py_calln
OAAPI PyIfFunc< bool, PyObject *, std::string > openage::pyinterface::py_hasattr
OAAPI PyIfFunc< void, PyObjectRef *, PyObject *, std::string > openage::pyinterface::py_getattr
OAAPI PyIfFunc< void, PyObject *, std::string, PyObject * > openage::pyinterface::py_setattr
OAAPI PyIfFunc< bool, PyObject *, PyObject * > openage::pyinterface::py_isinstance
OAAPI PyIfFunc< bool, PyObject * > openage::pyinterface::py_to_bool
OAAPI PyIfFunc< int64_t, PyObject * > openage::pyinterface::py_to_int
OAAPI PyIfFunc< void, PyObject *, Func< void, std::string > > openage::pyinterface::py_dir
OAAPI PyIfFunc< bool, PyObject *, PyObject * > openage::pyinterface::py_equals
OAAPI PyIfFunc< void, PyObject *, std::string > openage::pyinterface::py_exec
OAAPI PyIfFunc< void, PyObject *, PyObjectRef *, std::string > openage::pyinterface::py_eval
OAAPI PyIfFunc< void, PyObject *, PyObjectRef *, PyObject * > openage::pyinterface::py_get
OAAPI PyIfFunc< bool, PyObject *, PyObject * > openage::pyinterface::py_in
OAAPI PyIfFunc< void, PyObject *, PyObjectRef * > openage::pyinterface::py_type
OAAPI PyIfFunc< std::string, PyObject * > openage::pyinterface::py_modulename
OAAPI PyIfFunc< std::string, PyObject * > openage::pyinterface::py_classname
OAAPI PyIfFunc< void, PyObjectRef *, const std::string & > openage::pyinterface::py_builtin
OAAPI PyIfFunc< void, PyObjectRef *, const std::string & > openage::pyinterface::py_import
OAAPI PyIfFunc< void, PyObjectRef *, const std::string & > openage::pyinterface::py_createstr
OAAPI PyIfFunc< void, PyObjectRef *, const std::string & > openage::pyinterface::py_createbytes
OAAPI PyIfFunc< void, PyObjectRef *, int > openage::pyinterface::py_createint
OAAPI PyIfFunc< void, PyObjectRef * > openage::pyinterface::py_createdict
OAAPI PyIfFunc< void, PyObjectRef * > openage::pyinterface::py_createlist
OAAPI PyObjectRef openage::pyinterface::None
OAAPI PyObjectRef openage::pyinterface::True
OAAPI PyObjectRef openage::pyinterface::False
namespace [anonymous]
namespace tests

Functions

template<int i = 3>
void throw_foo()
template<>
void throw_foo<0>()
OAAPI void openage::pyinterface::tests::err_cpp_to_py_helper()

Called by cppinterface.demo_cpp_to_py.

Throws some exceptions, for translation to Python.

pxd: void err_cpp_to_py_helper() except +

void err_py_to_cpp()
void err_py_to_cpp_demo()
OAAPI void openage::pyinterface::tests::bounce_call(Func < void > func, int times)

See the doc in exctranslate_tests.pyx.

pxd: void bounce_call(Func0[void], int) except +

void pyobject()
void pyobject_demo()

Variables

OAAPI PyIfFunc< void > openage::pyinterface::tests::err_py_to_cpp_helper

Part of pyinterface::demo_py_to_cpp.

Shall throw some exceptions, which we then translate to C++.

pxd: PyIfFunc0[void] err_py_to_cpp_helper

OAAPI PyIfFunc< void, Func< void >, int > openage::pyinterface::tests::bounce_call_py

Called by bounce_call() to bounce back to Python.

pxd: PyIfFunc2[void, Func0[void], int] bounce_call_py

namespace renderer

Typedefs

using codepoint_t = unsigned int

Enums

enum font_direction

Enumeration of the possible font directions.

Values:

left_to_right
right_to_left
top_to_bottom
bottom_to_top
enum geometry_t

The type of geometry.

Values:

bufferless_quad

This passes 4 vertices with undefined positions to the shader.

The shader has to set the positions itself (e.g. using gl_VertexID in OpenGL).

mesh

This passes valid geometry defined by a mesh to the shader.

Functions

static hb_direction_t get_hb_font_direction(const font_description &description)
static hb_language_t get_hb_font_language(const font_description &description)
static hb_script_t get_hb_font_script(const font_description &description)
* * A shader input mapping is only allowed when there is a single element in buffers In such a * the vertex inputs are paired with VAO attributes according to the mapping instead of in ascending order* openage::renderer::GlVertexArray(std::vector< std::pair< GlBuffer const &, resources::VertexInputInfo const &>> buffers)
GlVertexArray(GlBuffer const&, resources::VertexInputInfo const&)

Executes the buffer list constructor with one element.

GlVertexArray()

The default constructor initializes an empty VAO with no attributes.

This is useful for bufferless drawing.

void bind() const

Make this vertex array object the current one.

void make_sdl_available()

Lazily initializes the global SDL singleton if it isn’t yet available, otherwise does nothing.

Variables

constexpr int FREETYPE_UNIT = 64
* * A shader input mapping is only allowed when there is a single element in buffers In such a openage::renderer::case
namespace opengl

Enums

enum gl_render_target_t

The type of OpenGL render target.

Values:

display

The actual window. This is visible to the user after swapping front and back buffers.

textures

A bunch of textures.

Functions

static gl_context_capabilities find_capabilities()

Finds out the supported graphics functions and OpenGL version of the device.

static void check_program_status(GLuint program, GLenum what_to_check)

Variables

constexpr std::array<std::pair<int, int>, 1> openage::renderer::opengl::gl_versions = {{ { 3, 3 } }}

The first element is the lowest version we need, last is highest version we support.

constexpr auto GL_PIXEL_FORMAT = datastructure::create_const_map<resources::pixel_format, std::tuple<GLint, GLenum, GLenum>>(std::pair(resources::pixel_format::r16ui, ), , , , , , )

Input and output pixel formats from pixel_format.

constexpr auto GL_SHADER_TYPE_SIZE = datastructure::create_const_map<GLenum, size_t>(std::pair(GL_FLOAT, ), , , , , , , , , , , , , , , , , , , , , , , )

Sizes of various uniform/vertex input types in shaders.

constexpr auto GLSL_TYPE_NAME

GL types with corresponding GLSL type strings.

constexpr auto GL_VERT_IN_TYPE = datastructure::create_const_map<GLenum, resources::vertex_input_t>(std::pair(GL_FLOAT, ), , , )

Generic vertex input types from GL types.

constexpr auto GL_VERT_IN_ELEM_TYPE = datastructure::create_const_map<resources::vertex_input_t, GLenum>(std::pair(resources::vertex_input_t::F32, ), , , )

The type of a single element in a per-vertex attribute.

constexpr auto GL_PRIMITIVE = datastructure::create_const_map<resources::vertex_primitive_t, GLenum>(std::pair(resources::vertex_primitive_t::POINTS, ), , , , , )

Mapping from generic primitive types to GL types.

constexpr auto GL_INDEX_TYPE = datastructure::create_const_map<resources::index_t, GLenum>(std::pair(resources::index_t::U8, ), , )

Mapping from generic index types to GL types.

constexpr auto gl_shdr_type = datastructure::create_const_map<resources::shader_stage_t, GLenum>(std::make_pair(resources::shader_stage_t::vertex, ), , , , )
namespace resources

Enums

enum vertex_input_t

The type of a single per-vertex input to the shader program.

Values:

F32
V2F32
V3F32
M3F32
enum vertex_primitive_t

The primitive type that the vertices in a mesh combine into.

Values:

POINTS
LINES
LINE_STRIP
TRIANGLES
TRIANGLE_STRIP
TRIANGLE_FAN
enum index_t

The type of indices used for indexed rendering.

Values:

U8
U16
U32
enum vertex_layout_t

Values:

AOS

Array of structs. XYZUV, XYZUV, XYZUV.

SOA

Struct of arrays. XYZXYZXYZ, UVUVUV.

enum shader_lang_t

The source language of a shader.

Values:

glsl
spirv
enum shader_stage_t

Shader stages present in modern graphics pipelines.

Values:

vertex
geometry
tesselation_control
tesselation_evaluation
fragment
enum pixel_format

How the pixels are represented in a texture.

Values:

r16ui

16 bits per pixel, unsigned integer, single channel

r32ui

32 bits per pixel, unsigned integer, single channel

rgb8

24 bits per pixel, float, RGB order

bgr8

24 bits per pixel, float, BGR order

depth24

24 bits per pixel, depth texture

rgba8

32 bits per pixel, float, alpha channel, RGBA order

rgba8ui

32 bits per pixel, unsigned integer, alpha channel, RGBA order

Functions

size_t vertex_input_size(vertex_input_t in)

Returns the size in bytes of a per-vertex input.

size_t vertex_input_count(vertex_input_t in)

Returns the number of elements of the underlying type in a given per-vertex input type.

For example, V3F32 has 3 float elements, so the value is 3.

static constexpr size_t guess_row_alignment(size_t width, pixel_format fmt, size_t row_size)

Tries to guess the alignment of image rows based on image parameters.

Kinda black magic and might not actually work.

Parameters
  • width: in pixels of the image

  • fmt: of pixels in the image

  • row_size: the actual size in bytes of an image row, including padding

constexpr size_t pixel_size(pixel_format fmt)

Returns the size in bytes of a single pixel of the specified format.

Variables

constexpr auto vin_size = datastructure::create_const_map<vertex_input_t, size_t>(std::make_pair(vertex_input_t::F32, ), , , )
constexpr auto vin_count = datastructure::create_const_map<vertex_input_t, size_t>(std::make_pair(vertex_input_t::F32, ), , , )
constexpr const std::array<float, 16> openage::renderer::resources::QUAD_DATA= { { -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f } }

Vertices of a quadrilateral filling the whole screen.

Format: (pos, tex_coords) = (x, y, u, v)

namespace tests

Functions

void font_manager_test_get_font()
void font_manager()
void font_test_font_description()
void font()
void renderer_demo_0(const util::Path &path)
OAAPI void openage::renderer::tests::renderer_demo(int demo_id, util::Path path)
namespace vulkan

Functions

static VkShaderStageFlagBits vk_shader_stage(resources::shader_stage_t stage)
static VKAPI_ATTR VkBool32 VKAPI_CALL openage::renderer::vulkan::vlk_debug_cb(VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, uint64_t, size_t, int32_t, const char * layerPrefix, const char * msg, void *)
static vlk_capabilities find_capabilities()

Queries the Vulkan implementation for available extensions and layers.

namespace rng

Contains an easy to use and fast random number generator.

This was never designed or intended as a cryptographic-quality, RNG, so don’t use it as one. If you do, I’ll tell my mom.

Functions

uint64_t global_seed()

Returns the value of the global seed.

uint64_t random()

Returns a random number from the global rng.

uint64_t random_range(uint64_t lower, uint64_t upper)

Returns a random number n [lower, upper) from the global rng.

double real()

Returns a double in [0, 1) from the global rng.

double real_range(double lower, double upper)

Returns a double in [lower, upper) from the global rng.

static uint64_t do_rng(uint64_t &s0, uint64_t &s1)
template<class T, class Lambda>
static void act_fill(T *dat, uint64_t *state, size_t len, const Lambda &op)
std::ostream &operator<<(std::ostream &ostream, const RNG &inrng)

Writes the rng state to a stream.

Exceptions
  • Error: if writing data fails

std::istream &operator>>(std::istream &instream, RNG &inrng)

Reads the rng from a stream.

Exceptions
  • Error: if reading from the stream fails

static uint64_t try_random_device()
static uint64_t time_seed(bool randomize)
uint64_t time_seed()

Returns a seed based on time since epoch.

uint64_t random_seed()

Returns a seed based on time since epoch as well as data from std::random_device if available.

Variables

std::mutex rand_mutex
RNG global_rand_gen(global_seed())
const std::array<uint8_t, 16> openage::rng::seed_key{{ 0xba, 0xda, 0x55, 0x00, 0x5e, 0xed, 0x00, 0x00, 0xab, 0xcd, 0xef, 0x12, 0x34, 0x56, 0x78, 0x90}}
namespace tests

Functions

void freq_dist()

Tests the distribution of the bit generator.

We generate many many random numbers, and select a bucket by it. After n random numbers, each bucket should have been selected n/bucket_count times.

void bool_dist()

Tests the distribution of the boolean generation.

For n draws it should result in n/2 trues and n/2 falses.

void real_dist()

Tests the distribution of the floating point numbers.

Perform the test by placing the [0, 1] range into buckets. each bucket should be drawn n/bucket_count times.

Also, the sum of all numbers drawn should be n/2.

void reproduce()

Tests reproducibility.

void serialize()

Tests the serializing functionality.

void fill()

Tests filling integers.

void fill_real()

Tests filling doubles.

void run()

Variables

constexpr size_t num_rand = (1 << 18)

This is the number of generation repetitions.

constexpr float difference_factor = 0.1

Allow the result to be in this range of the expected perfect distribution.

namespace shader

Functions

const char *type_to_string(GLenum type)
namespace simulation

Functions

void test()
namespace subprocess

similar in its goals to Python’s subprocess module

Functions

bool is_executable(const char *filename)

returns true IFF the file is executable

std::string which(const char *name)

finds the path to an executable by evaluating env[PATH]

int call(const std::vector<const char *> &argv, bool wait = false, const char *redirect_stdout_to = nullptr)

starts the process at argv[0] passes argv as argv

on failure, -1 is returned.

Parameters
  • argv: must consist of at least one non-empty string, and end with a nullptr. this is not verified.

  • wait: decides whether we wait for the process to finish. if true, returns the process’s return value if false, returns 0

  • redirect_stdout_to: if not nullptr, the given file is opened and substituted for the process’s stdout. the existing file is overwritten.

namespace teamcolor_shader

Variables

shader::Program *program
GLint texture
GLint tex_coord
GLint player_id_var
GLint alpha_marker_var
GLint player_color_var
namespace test

Functions

void benchmark()
namespace testing

Functions

bool fail(const log::message &msg)

Raises TestError with the message msg.

Mostly designed for usage with the TESTFAIL macro.

OAAPI void openage::testing::run_method(const std::string & name)

Invokes the test or demo with the given name.

pxd: void run_method(string name) except +

namespace benchmark

Functions

benchmark_test_function()

Simple function to call in for benchmarking.

benchmark(func func)
namespace doctest

Functions

test()

Runs doctest on the modules listed in testlist.DOCTEST_MODULES.

namespace list_processor

Functions

list_targets(test_lister test_lister, demo_lister demo_lister, benchmark_lister benchmark_lister)
list_targets_py()

Invokes list_targets() with the py-specific listers.

list_targets_cpp()

Invokes list_targets() with the C++-specific listers.

get_all_targets()

Reads the Python and C++ testspec.

returns an OrderedDict of {(testname, type): conditionfun, lang, description, testfun}.

type is in {‘demo’, ‘test’}, lang is in {‘cpp’, ‘py’}, conditionfun is a callable which determines if the test is to be run in the given environment description is a str, and testfun is callable and takes 0 args for tests / list(str) for demos.

namespace main

Functions

print_test_list(test_list test_list)

Prints a list of all tests and demos in test_list.

init_subparser(cli cli)

Initializes the subparser for the testing command.

process_args(args args, error error)

Processes the given args, detecting errors.

main(args args, error error)

CLI main method.

namespace testing

Functions

assert_value(value value, expected expected = None, validator validator = None)
result(value value)
assert_raises(expectedexception expectedexception)

Context guard that asserts that a certain exception is raised inside.

On successful execution (if the error failed to show up), result() shall be called.

Example usage:

we expect fibonacci to raise ValueError for negative values.

with assert_raises(ValueError): result(fibonacci(-3))

namespace testlist

Functions

doctest_modules()

Lists of all possible tests; enter your tests here.

Yields the names of all Python modules that shall be tested during doctest.

tests_py()
demos_py()

Yields tuples of (name, description) for all Python demo methods.

benchmark_py()
tests_cpp()
demos_cpp()

Yields tuples of (name, description) for all C++ demo methods.

benchmark_cpp()
namespace texture_shader

Variables

shader::Program *program
GLint texture
GLint tex_coord
namespace texturefont_shader

Variables

shader::Program *program
GLint texture
GLint color
GLint tex_coord
namespace timing

Functions

time_nsec_t get_real_time()

returns the number of nanoseconds since the UNIX epoch.

time_nsec_t get_monotonic_time()

returns a monotonically-increasing time that returns the number of nanoseconds since an unspecified event.

not influenced by system time changes.

namespace util

Typedefs

using Matrix2t = Matrix<2, 2, T>
using Matrix3t = Matrix<3, 3, T>
using Matrix4t = Matrix<4, 4, T>
using Matrixf = Matrix<M, N, float>
using Matrixd = Matrix<M, N, double>
using Matrix2f = Matrix<2, 2, float>
using Matrix3f = Matrix<3, 3, float>
using Matrix4f = Matrix<4, 4, float>
using Matrix2d = Matrix<2, 2, double>
using Matrix3d = Matrix<3, 3, double>
using Matrix4d = Matrix<4, 4, double>
using Quaternionf = Quaternion<float>
using Quaterniond = Quaternion<double>
using codepoint_t = int32_t
using Vector2t = Vector<2, T>
using Vector3t = Vector<3, T>
using Vector4t = Vector<4, T>
using Vectorf = Vector<N, float>
using Vectord = Vector<N, double>
using Vector2f = Vector<2, float>
using Vector3f = Vector<3, float>
using Vector4f = Vector<4, float>
using Vector2d = Vector<2, double>
using Vector3d = Vector<3, double>
using Vector4d = Vector<4, double>

Functions

template<class Container, class Function>
Function for_each(Container &&container, Function &&func)

std::for_each except just on containers.

template<class Container, class Function>
void remove_from(Container &container, Function &&func)

Filters items from a container which satisfy a certain predicate.

std::string demangle(const char *symbol)

Demangles a symbol name.

On failure, the mangled symbol name is returned.

std::string addr_to_string(const void *addr)
OAAPI std::string openage::util::symbol_name(const void * addr, bool require_exact_addr = true, bool no_pure_addrs = false)

Returns the (demangled) symbol name for a given address.

If no exact match can be found, if require_exact_addr == true (default): if no_pure_addrs == false (default): a pure hex address string is returned else: an empty string is returned if require_exact_addr == false: name of closest symbol + offset hex string is returned

pxd: string symbol_name(const void *addr) except +

bool is_symbol(const void *addr)

Returns true if the address is the (exact) address of a symbol.

template<typename lineformat>
std::vector<lineformat> read_csv_file(const Path &path)

read a single csv file.

call the destination struct .fill() method for actually storing line data

std::ostream &operator<<(std::ostream &stream, const File &file)
template<unsigned int amount, typename T>static constexpr std::enable_if<(amount + (std::is_signed<T>::value ? 1 : 0) < sizeof(T) * CHAR_BIT), T>::type openage::util::safe_shiftleft(T value)

Helper function that performs a left shift without causing undefined behavior.

regular left-shift is undefined if amount >= bitwidth, or amount >= bitwidth - 1 for signed integers.

template<unsigned int amount, typename T>
static constexpr std::enable_if<(amount >= sizeof(T) * CHAR_BIT), T>::type safe_shiftright(T value)

Helper function that performs a right shift without causing undefined behavior.

right-shift is usually undefined if amount >= bit size.

template<unsigned int amount, typename T>
static constexpr std::enable_if<(amount < sizeof(T) * CHAR_BIT), T>::type safe_shiftright(T value)
template<int amount, typename T>
static constexpr std::enable_if<(amount < 0), T>::type safe_shift(T value)

Helper function that performs either a safe shift-right (amount > 0), or a safe shift-left (amount < 0).

template<int amount, typename T>
static constexpr std::enable_if<(amount >= 0), T>::type safe_shift(T value)
template<typename I, unsigned int F>
constexpr FixedPoint<I, F> operator+(const FixedPoint<I, F> &lhs, const FixedPoint<I, F> &rhs)

FixedPoint + FixedPoint.

template<typename I, unsigned int F>
constexpr FixedPoint<I, F> operator+(const FixedPoint<I, F> &lhs, const double &rhs)

FixedPoint + double.

template<typename I, unsigned int F>
constexpr FixedPoint<I, F> operator-(const FixedPoint<I, F> &lhs, const FixedPoint<I, F> &rhs)

FixedPoint - FixedPoint.

template<typename I, unsigned int F>
constexpr FixedPoint<I, F> operator-(const FixedPoint<I, F> &lhs, const double &rhs)

FixedPoint - double.

template<typename I, unsigned F, typename N>
std::enable_if<std::is_arithmetic<N>::value, FixedPoint<I, F>>::type constexpr operator*(const FixedPoint<I, F> lhs, const N &rhs)

FixedPoint * N.

template<typename I, unsigned F, typename N>
constexpr FixedPoint<I, F> operator/(const FixedPoint<I, F> lhs, const N &rhs)

FixedPoint / N.

size_t hash_combine(size_t hash1, size_t hash2)

A hash combination function Creates a hash value as a combination of two other hashes.

Can be called incrementally to create hash value from several variables. Will always produce the same result for the same combination of hash1 and hash2 during a single run of a program.

uint64_t hash(const uint64_t key[2], const uint8_t *data, size_t len_data)

Siphash implementation.

https://131002.net/siphash/

template<typename T>
size_t type_hash()

Helper function to generate hash of certain type T.

template<typename T>
void ignore_result(T)

Wrapping a function call with ignore_result makes it more clear to readers, compilers and linters that you are, in fact, ignoring the function’s return value on purpose.

template<size_t M, size_t N, typename T>
Matrix<M, N, T> operator*(T a, const Matrix<M, N, T> &mat)

Scalar multiplication with swapped arguments.

template<size_t M, size_t N, typename T>
Matrix<M, N, T> operator*(int64_t a, const Matrix<M, N, T> &mat)

Scalar multiplication with swapped arguments for int.

This was just added because otherwise the above float-multiplication function might not match to the template deduction.

template<typename T>
constexpr T mod(T x, T m)

modulo operation that guarantees to return positive values.

template<typename T, unsigned int modulo>
constexpr T mod(T x)

compiletime defined modulo function.

template<typename T, int amount>
constexpr T rol(T x)

compiletime defined rotate left function

template<typename T>
constexpr T div(T x, T m)

implements the ‘correct’ version of the division operator, which always rounds to -inf

uint64_t array8_to_uint64(const uint8_t *start, size_t count, bool big_endian = false)

Convert a C-style array of uint8_t to a uint64_t.

Uses little-endianness as default. Fills the remaining bytes with zeroes.

e.g (big-endian): {0x01, 0x23, 0x45, 0x67} -> 0x0123456700000000 e.g (little-endian): {0x01, 0x23, 0x45, 0x67} -> 0x0000000067452301

Return

Input data as a 64 bit number.

Parameters
  • start: Pointer to start of the input data.

  • count: Number of bytes to read.

  • big_endian: Endianness of byte array.

std::vector<uint8_t> uint64_to_array8(const uint64_t value, bool big_endian = false)

Convert a uint64_t to an array of uint8_t.

Uses little-endianness as default.

e.g (big-endian): 0x0123456789abcdef -> {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef} e.g (little-endian): 0x0123456789abcdef -> {0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01}

Return

Input data as a 8 bit number array.

Parameters
  • value: 64 bit number to convert.

  • big_endian: Endianness of byte array.

constexpr size_t array64_size(size_t count)

Get the number of uint64-elements that result from converting a count-sized uint8_t array.

Used to determine the size for array8_to_array64()

Return

ceil(count/8)

std::vector<uint64_t> array8_to_array64(const uint8_t *start, size_t count, bool big_endian = false)

Convert a C-style array of uint8_t to a std::vector of uint64_t.

Uses little-endianness as default. Fills the remaining bytes of the last uint64_t with zeroes.

e.g (big-endian): {0x01, 0x23, 0x45, 0x67} -> 0x0123456700000000 e.g (little-endian): {0x01, 0x23, 0x45, 0x67} -> 0x0000000067452301

Return

Input data as a 64 bit number vector.

Parameters
  • start: Start of the input data.

  • count: Number of bytes to convert.

  • big_endian: Endianness of byte array.

std::vector<uint8_t> array64_to_array8(const uint64_t *start, size_t count, bool big_endian = false)

Convert a C-style array of uint64_t to a std::vector of uint8_t.

Uses little-endianness as default.

e.g (big-endian): 0x0123456789abcdef -> {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef} e.g (little-endian): 0x0123456789abcdef -> {0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01}

Return

Input data as a 8 bit number vector.

Parameters
  • Start: of the input data.

  • count: Number of uint64_t to convert.

  • big_endian: Endianness of byte array.

template<typename T>
void vector_extend(std::vector<T> &vec, const std::vector<T> &ext)

Extend a vector with elements, without destroying source one.

template<typename T>
void vector_extend(std::vector<T> &vec, std::vector<T> &&ext)
template<typename T>
void vector_remove_swap_end(std::vector<T> &vec, size_t idx)

Remove the given element index in the vector.

May swap with the end element for efficient removing.

If the element is not in the vector, do nothing.

void gl_check_error()

query the current opengl context for any errors.

raises exceptions on any error.

void path_normalizer(Path::parts_t &output, const Path::parts_t &input)

Strip out ../ etc.

std::ostream &operator<<(std::ostream &stream, const Path &path)
std::string filename(const std::string &fullpath)

get the filename (last part) of a given path

std::string dirname(const std::string &fullpath)

return the head (dirname) part of a path.

std::string repr(const std::string &arg)

method that behaves similar to python’s “repr”.

puts the string in quotes and escapes all sorts of stuff inside.

std::string sformat(const char *fmt, ...)

printf-style to-string formatting.

std::string size_t openage::util::vsformat(const char * fmt, va_list ap, std::string & output)

printf-style valist-to-string formatting; the result is appended to output.

std::unique_ptr<char[]> copy_string(const char *s)

Copies the given string to the returned unique_ptr, including 0 byte.

size_t rstrip(char *s)

Returns the number of whitespace characters on the right of the string.

bool string_matches_pattern(const char *str, const char *pattern)

returns true if str matches the basic globbing pattern in the pattern, ‘*’ matches any number of characters, while all other characters are interpreted as literal.

std::vector<std::string> split(const std::string &txt, char delim)

Split a string at a delimiter into a vector.

Internally, uses the above iterator splitter.

std::vector<std::string> split_escape(const std::string &txt, char delim, size_t size_hint = 0)

Split a string at a delimiter into a vector.

size_hint is to give a predicted size of the vector already.

tokenizes txt by splitting it up to substrings at the deliminiters. “\n” is evaluated to ‘

’; all other ‘’ escape sequences are evaluated to literal X, including the deliminiter.

template<unsigned decimals, unsigned w>
std::ostream &operator<<(std::ostream &os, FloatFixed<decimals, w> f)
template<typename ret_t>
void split(const std::string &txt, char delimiter, ret_t result)

Split a string at a delimiter, push the result back in an iterator.

Why doesn’t the fucking standard library have std::string::split(delimiter)?

size_t get_current_thread_id()

Returns the unique identifier of the current thread.

For compilers with support for thread_local storage, the function also guarantees to return strictly monotonically increasing identifier (no collision).

size_t utf8_decode(const unsigned char *s, size_t len, codepoint_t *outbuf)

decodes a UTF-8 character string of given length

the results are written to outbuf. no leading 0 is written to outbuf (nor is one expected at s). outbuf MUST be large enough to hold all characters. to ensure that outbuf is large enough, it SHOULD have a size of at least len.

the number of actual unicode characters is returned. it might be anywhere in the range [len/4; len].

in case of decoding errors, the special unicode character 0xfffd is written.

code logic gratefully borrowed from rxvt-unicode.

size_t utf8_encode(int cp, char *outbuf)

encodes one Unicode codepoint to a null-terminated UTF-8 character string.

due to the nature of UTF-8, the result string is at most 4 bytes long. on error, the empty string is returned.

cp the codepoint outbuf a output char buffer. outbuf[0] to outbuf[4] MUST be writeable. outbuf[0] will ALWAYS be written to. returns the number of non-NULL bytes that have been written, i.e. strlen(outbuf)

size_t utf8_last_char_size(char *str)

computes the length of the last character in a given UTF-8 string.

str the UTF-8 string returns the length of the last character in bytes

void utf8_pop_back(std::string &str)

pops back (deletes) the last UTF-8 character in a std::string.

Variables

std::string empty_string

global empty string, sometimes needed as return value in some std::string &function() return values.

constexpr size_t uint64_s = 8
constexpr const char *HEX_DIGITS = "0123456789abcdef"
namespace bytequeue
namespace compress

Typedefs

using read_callback_t = std::function<size_t(unsigned char *buf, size_t size)>

Type of the ‘read’ callback function.

See lzxd.h for documentation.

Variables

constexpr unsigned LZX_MIN_MATCH = 2
constexpr unsigned LZX_NUM_CHARS = 256
constexpr unsigned LZX_BLOCKTYPE_INVALID = 0
constexpr unsigned LZX_BLOCKTYPE_VERBATIM = 1
constexpr unsigned LZX_BLOCKTYPE_ALIGNED = 2
constexpr unsigned LZX_BLOCKTYPE_UNCOMPRESSED = 3
constexpr unsigned LZX_PRETREE_NUM_ELEMENTS = 20
constexpr unsigned LZX_ALIGNED_NUM_ELEMENTS = 8
constexpr unsigned LZX_NUM_PRIMARY_LENGTHS = 7
constexpr unsigned LZX_NUM_SECONDARY_LENGTHS = 249
constexpr unsigned LZX_PRETREE_MAXSYMBOLS = LZX_PRETREE_NUM_ELEMENTS
constexpr unsigned LZX_PRETREE_TABLEBITS = 6
constexpr unsigned LZX_MAINTREE_MAXSYMBOLS = LZX_NUM_CHARS + 50 * 8
constexpr unsigned LZX_MAINTREE_TABLEBITS = 12
constexpr unsigned LZX_LENGTH_MAXSYMBOLS = LZX_NUM_SECONDARY_LENGTHS + 1
constexpr unsigned LZX_LENGTH_TABLEBITS = 12
constexpr unsigned LZX_ALIGNED_MAXSYMBOLS = LZX_ALIGNED_NUM_ELEMENTS
constexpr unsigned LZX_ALIGNED_TABLEBITS = 7
constexpr unsigned LZX_LENTABLE_SAFETY = 64
const unsigned position_base[] = {0, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , }
const unsigned char extra_bits[] = {0, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , }
constexpr unsigned LZX_FRAME_SIZE = 32768
namespace constexpr_

This namespace contains constexpr functions, i.e.

C++14 functions that are designed to run at compile-time.

Functions

constexpr bool streq(const char *a, const char *b)

Returns true IFF the string literals have equal content.

constexpr size_t strlen(const char *str)

Returns the length of the string literal, excluding the terminating NULL byte.

constexpr truncated_string_literal get_prefix(const char *str, const char *suffix)

Truncates a suffix from a string literal.

Raises ‘false’ if str doesn’t end in the given suffix.

constexpr truncated_string_literal create_truncated_string_literal(const char *str)

Creates a truncated_string_literal from a regular string literal.

constexpr bool has_prefix(const char *str, const truncated_string_literal prefix)

Tests whether a string literal starts with the given prefix.

constexpr const char *strip_prefix(const char *str, const truncated_string_literal prefix)

Strips a prefix from a given string literal.

If the string literal doesn’t have that prefix, returns the string literal itself.

constexpr const char *strip_prefix(const char *str, const char *prefix)

Strips a prefix, given as const char *, from a given string literal.

If the string literal doesn’t have that prefix, returns the string literal itself.

namespace context
namespace decorators

Functions

run_once(func func)

Some utility function decorators.

Decorator to run func only at its first invocation.

Set func.has_run to False to manually re-run.

namespace filelike

Variables

OAAPI pyinterface::PyIfFunc< std::string, PyObject *, ssize_t > openage::util::filelike::pyx_file_read
OAAPI pyinterface::PyIfFunc< size_t, PyObject *, void *, ssize_t > openage::util::filelike::pyx_file_read_to
OAAPI pyinterface::PyIfFunc< bool, PyObject * > openage::util::filelike::pyx_file_readable
OAAPI pyinterface::PyIfFunc< void, PyObject *, const std::string & > openage::util::filelike::pyx_file_write
OAAPI pyinterface::PyIfFunc< bool, PyObject * > openage::util::filelike::pyx_file_writable
OAAPI pyinterface::PyIfFunc< void, PyObject *, ssize_t, int > openage::util::filelike::pyx_file_seek
OAAPI pyinterface::PyIfFunc< bool, PyObject * > openage::util::filelike::pyx_file_seekable
OAAPI pyinterface::PyIfFunc< size_t, PyObject * > openage::util::filelike::pyx_file_tell
OAAPI pyinterface::PyIfFunc< void, PyObject * > openage::util::filelike::pyx_file_close
OAAPI pyinterface::PyIfFunc< void, PyObject * > openage::util::filelike::pyx_file_flush
OAAPI pyinterface::PyIfFunc< ssize_t, PyObject * > openage::util::filelike::pyx_file_size
namespace abstract
namespace fifo
namespace readonly
namespace stream
namespace files

Functions

read_guaranteed(fileobj fileobj, size size)
read_nullterminated_string(fileobj fileobj, maxlen maxlen = 255)

Reads bytes until a null terminator is reached.

which(filename filename)
namespace fslike

Contains the filesystem-like object abstraction for C++.

With that, filesystem access can be dispatched for transparent archive access, union mounts and more.

Variables

constexpr char PATHSEP = '/'
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_is_file
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_is_dir
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_writable
OAAPI pyinterface::PyIfFunc< std::vector< std::string >, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_list
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_mkdirs
OAAPI pyinterface::PyIfFunc< File, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_open_r
OAAPI pyinterface::PyIfFunc< File, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_open_w
OAAPI pyinterface::PyIfFunc< File, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_open_rw
OAAPI pyinterface::PyIfFunc< File, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_open_a
OAAPI pyinterface::PyIfFunc< File, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_open_ar
OAAPI pyinterface::PyIfFunc< Path, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_resolve_r
OAAPI pyinterface::PyIfFunc< Path, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_resolve_w
OAAPI pyinterface::PyIfFunc< py::Obj, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_get_native_path
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > &, const std::vector< std::string > & > openage::util::fslike::pyx_fs_rename
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_rmdir
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_touch
OAAPI pyinterface::PyIfFunc< bool, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_unlink
OAAPI pyinterface::PyIfFunc< int, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_get_mtime
OAAPI pyinterface::PyIfFunc< uint64_t, PyObject *, const std::vector< std::string > & > openage::util::fslike::pyx_fs_get_filesize
OAAPI pyinterface::PyIfFunc< bool, PyObject * > openage::util::fslike::pyx_fs_is_fslike_directory
namespace abstract
namespace directory
namespace filecollection
namespace path
namespace test

Functions

test_path(root_path root_path, root_dir root_dir)

Test basic functionality of fslike.Path.

test_union(root_path root_path, root_dir root_dir)

Union functionality testing.

Procedure

create and write a file in r create union with w and r mount. r is readonly. read file, should be from r. write file, whould go to w. read file, should be from w. unmount w, file content should be from r again. unmount r, union should be empty now.

is_filesystem_case_sensitive()

Utility function to verify if filesystem is case-sensitive.

test_case_ignoring(root_path root_path, root_dir root_dir)
test_append(root_path root_path)

Test the content append modes.

test()

Perform functionality tests for the filesystem abstraction interface.

namespace union
namespace wrapper
namespace fsprinting

Functions

get_color_rules()

Returns a dict of pattern : colorcode, retrieved from LS_COLORS.

colorize_filename(filename filename)

Colorizes the filename, using the globbing rules from LS_COLORS.

colorize_dirname(dirname dirname)

Colorizes the dirname, using the ‘di’ rule from LS_COLORS.

print_tree(obj obj, path path = "", prefix prefix = "", max_entries max_entries = INF)

Obj is a filesystem-like object; path must be a string.

Recursively descends into subdirectories using prefix.

If max_entries is given, only that number of entries per directory is printed.

Variables

openage.util.fsprinting.RULE_CACHE = OrderedDict()
namespace iterators

Functions

denote_last(iterable iterable)

Provides all sorts of iterator-related stuff.

namespace math

Functions

clamp(val val, minval minval, maxval maxval)

clamps val to be at least minval, and at most maxval.

7 3 5

Variables

openage.util.math.INF = float("+inf")
int openage.util.math.TAU = 2 * math.pi
int openage.util.math.DEGSPERRAD = TAU / 360
namespace profiler
namespace strings

Functions

decode_until_null(data data, encoding encoding = 'utf-8')

decodes a bytes object, aborting at the first \0 character.

‘foo’

try_decode(data data)

does its best to attempt decoding the given string of unknown encoding.

binstr(num num, bits bits = None, group group = 8)
colorize(string string, colorcode colorcode)

Colorizes string with the given EMCA-48 SGR code.

‘\x1b[31;1mfoo\x1b[m’

lstrip_once(string string, substr substr)

Removes substr at the start of string, and raises ValueError on failure.

‘test’ Traceback (most recent call last): ValueError ‘libopenage.test’ doesn’t start with ‘openage.’

rstrip_once(string string, substr substr)

Removes substr at the end of string, and raises ValueError on failure.

‘test’

format_progress(progress progress, total total)

Formats an “x out of y” string with fixed width.

‘ 5/20’

namespace struct
namespace system

Functions

free_memory()
namespace tests

Functions

void constinit_vector()
void enum_()
void fixed_point()
void siphash()
void init()
void matrix()
void array_conversion()
void quaternion()
void vector()

Variables

constexpr testenum_value openage::util::tests::undefined = {{"UNDEFINED", 0}, "undefined test string"}
const std::array<uint8_t, 16> openage::util::tests::test_key{{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}}
namespace [anonymous]
namespace [anonymous]
namespace threading

Functions

concurrent_chain(generators generators, jobs jobs = None)
generator_to_queue(generator generator, queue queue)
test_concurrent_chain()

Tests concurrent_chain.

namespace qtsdl

Functions

QString name_tidier(const char *name)

Cleans a text from unneeded content like “qtsdl”.

template<typename T>
Unwrap<T>::Type *unwrap(T *t)
template<typename T>
const Unwrap<T>::Type *unwrap(const T *t)
template<typename U>
const Wrap<U>::Type *wrap(const U *u)
template<typename U>
Wrap<U>::Type *wrap(U *u, typename std::enable_if<!std::is_base_of<GuiSingletonItem, typename Wrap<U>::Type>::value>::type * = nullptr)
template<typename U>
Wrap<U>::Type *wrap(U *u, typename std::enable_if<std::is_base_of<GuiSingletonItem, typename Wrap<U>::Type>::value>::type * = nullptr)
template<typename P>
constexpr P &&wrap_if_can(typename std::remove_reference<P>::type &&p)
template<typename T>
T wrap_if_can(typename Unwrap<typename std::remove_pointer<T>::type>::Type *u)
template<typename P>
P unwrap_if_can(P &p)
template<typename T, typename Unwrap< T >::Type * = nullptr>Unwrap<T>::Type* qtsdl::unwrap_if_can(T * t)
template<typename F, typename ...Args>
constexpr void static_assert_about_unwrapping()

To print our own error message that warns about possible cause of the argument mismatch.

Unwrapping uses type trait “Unwrap” that is defined in the header with corresponding type. If the header is not included, then compiler considers it as a basic type and tries to pass it wrapped to a function that expects an unwrapped type.

Template Parameters
  • F: callable

  • A: arguments to test against the callable

template<typename T, typename U>
T checked_static_cast(U *u)
gl_debug_parameters get_current_opengl_debug_parameters(const QOpenGLContext &current_source_context)

Get debugging settings of the current GL context.

Return

debugging settings

Parameters
  • current_source_context: current GL context

void apply_opengl_debug_parameters(gl_debug_parameters params, QOpenGLContext &current_dest_context)

Create a GL logger in the current GL context.

Parameters
  • params: debugging settings

  • current_dest_context: current GL context to which parameters will be applied

std::tuple<QVariant, WId> extract_native_context(SDL_Window *window)

Return

current context (or null) and id of the window

std::tuple<QVariant, std::function<void()>> extract_native_context_and_switchback_func(SDL_Window *window)

Return

current context (or null) and function to get it back to the window

template<>
std::string getv<std::string>(const char *name) const
template<>
void setv<const std::string&>(const char *name, const std::string &v)
template<>
std::vector<std::string> getv<std::vector<std::string>>(const char *name) const
template<>
void setv<const std::vector<std::string>&>(const char *name, const std::vector<std::string> &v)
template<>
void setv<const std::vector<std::string>&>(const char *name, const std::vector<std::string> &v)
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace [anonymous]
namespace std

Functions

std::string to_string(const openage::game_resource &res)
std::string to_string(const openage::score_category &cat)
std::string to_string(const openage::ability_type &at)
template<typename I, unsigned F>
constexpr double sqrt(openage::util::FixedPoint<I, F> n)
template<typename I, unsigned F>
constexpr openage::util::FixedPoint<I, F> min(openage::util::FixedPoint<I, F> x, openage::util::FixedPoint<I, F> y)
template<typename I, unsigned F>
constexpr openage::util::FixedPoint<I, F> max(openage::util::FixedPoint<I, F> x, openage::util::FixedPoint<I, F> y)
template<typename I, unsigned F>
constexpr openage::util::FixedPoint<I, F> abs(openage::util::FixedPoint<I, F> n)
template<typename I, unsigned F>
constexpr double hypot(openage::util::FixedPoint<I, F> x, openage::util::FixedPoint<I, F> y)
namespace chrono_literals
namespace placeholders
file assetmanager.cpp
#include “assetmanager.h”#include “util/compiler.h”#include “util/file.h”#include “error/error.h”#include “log/log.h”#include “texture.h”
file assetmanager.h
#include “config.h”#include <unordered_map>#include <string>#include <memory>#include “util/path.h”
file audio_manager.cpp
#include “audio_manager.h”#include <cstring>#include <SDL2/SDL.h>#include <sstream>#include “error.h”#include “hash_functions.h”#include “resource.h”#include “../log/log.h”#include “../util/misc.h”
file audio_manager.h
#include <memory>#include <string>#include <unordered_map>#include <vector>#include <SDL2/SDL.h>#include “category.h”#include “hash_functions.h”#include “sound.h”#include “resource_def.h”
file category.cpp
#include “category.h”#include “../log/log.h”#include “../error/error.h”#include “../util/strings.h”
file category.h
#include <iostream>
file dynamic_loader.cpp
#include “dynamic_loader.h”#include “error.h”#include “opus_dynamic_loader.h”
file dynamic_loader.h
#include <memory>#include <string>#include “format.h”#include “types.h”#include “../util/path.h”
file dynamic_resource.cpp
#include “dynamic_resource.h”#include “audio_manager.h”#include “../engine.h”#include “../job/job_manager.h”#include “../log/log.h”
file dynamic_resource.h
#include <atomic>#include <memory>#include <tuple>#include <unordered_map>#include <vector>#include “category.h”#include “dynamic_loader.h”#include “format.h”#include “resource.h”#include “types.h”#include “../datastructure/concurrent_queue.h”#include “../job/job.h”#include “../job/job_group.h”#include “../util/path.h”
file error.cpp
#include “error.h”
file error.cpp
#include “error.h”#include “../util/compiler.h”#include “stackanalyzer.h”
file error.h
#include “../error/error.h”
file error.h
#include <iostream>#include <memory>#include <stdexcept>#include <string>#include “../util/compiler.h”#include “../log/message.h”

Defines

ENSURE(...)
OPENAGE_PP_GLUE(macro, args)
OPENAGE_ENS_FIRST(...)
OPENAGE_ENS_FIRST_HELPER(first, ...)
OPENAGE_ENS_REST(...)
OPENAGE_ENS_REST_HELPER(qty)
OPENAGE_ENS_REST_HELPER1(qty)
OPENAGE_ENS_REST_HELPER2(qty)
OPENAGE_ENS_REST_HELPER_ONE(first)
OPENAGE_ENS_REST_HELPER_TWOORMORE(first, ...)
OPENAGE_ENS_NUM(...)
OPENAGE_ENS_NUM_IMPL(args)
OPENAGE_ENS_SELECT_2ND(a1, a2, a3, ...)
file format.cpp
#include “format.h”#include “../error/error.h”
file format.h
#include <ostream>
file hash_functions.h
#include <tuple>#include “category.h”
file in_memory_loader.cpp
#include “in_memory_loader.h”#include “error.h”#include “opus_in_memory_loader.h”
file in_memory_loader.h
#include <memory>#include <string>#include <tuple>#include “format.h”#include “types.h”#include “../util/path.h”
file in_memory_resource.cpp
#include “in_memory_resource.h”#include “in_memory_loader.h”
file in_memory_resource.h
#include <string>#include “format.h”#include “resource.h”#include “types.h”#include “../util/path.h”
file loader_policy.cpp
#include “loader_policy.h”#include “../error/error.h”
file loader_policy.h
#include <ostream>
file opus_dynamic_loader.cpp
#include “opus_dynamic_loader.h”#include <opusfile.h>#include “error.h”#include “../log/log.h”
file opus_dynamic_loader.h
#include <string>#include <memory>#include “opus_loading.h”#include “dynamic_loader.h”#include “types.h”#include “../util/path.h”
file opus_in_memory_loader.cpp
#include “opus_in_memory_loader.h”#include <opusfile.h>#include <string>#include “error.h”#include “opus_loading.h”#include “../log/log.h”
file opus_in_memory_loader.h
#include <string>#include “in_memory_loader.h”#include “types.h”#include “../util/path.h”
file opus_loading.cpp
#include “opus_loading.h”#include “error.h”#include “../log/log.h”
file opus_loading.h
#include <functional>#include <memory>#include <opus/opusfile.h>#include <string>#include “../util/path.h”
file resource.cpp
#include “resource.h”#include “../engine.h”#include “../error/error.h”#include “dynamic_resource.h”#include “in_memory_resource.h”
file resource.cpp
#include <string>#include <cmath>#include “resource.h”
file resource.h
#include <memory>#include <string>#include “category.h”#include “resource_def.h”#include “types.h”
file resource.h
#include <functional>#include <string>
file resource_def.cpp
#include “resource_def.h”
file resource_def.h
#include <memory>#include <string>#include “../util/path.h”#include “category.h”#include “format.h”#include “loader_policy.h”
file sound.cpp
#include “sound.h”#include <tuple>#include “audio_manager.h”#include “resource.h”
file sound.h
#include <memory>#include “category.h”
file types.h
#include <functional>#include <memory>#include <vector>
file types.h
#include <functional>
file buf.cpp
#include “buf.h”#include “../util/unicode.h”#include “stdio.h”
file buf.h
#include <stdint.h>#include <stdlib.h>#include <sys/types.h>#include <vector>#include “../coord/term.h”#include “../util/compiler.h”#include “../util/unicode.h”
file console.cpp
#include “console.h”#include “../log/log.h”#include “../error/error.h”#include “../util/strings.h”#include “../util/unicode.h”#include “../engine.h”#include “draw.h”
file console.h
#include <vector>#include <SDL2/SDL.h>#include “buf.h”#include “../handlers.h”#include “../coord/pixel.h”#include “../input/input_manager.h”#include “../util/color.h”#include “../renderer/font/font.h”#include “../gamedata/color.gen.h”
file draw.cpp
#include “draw.h”#include <string.h>#include <stdio.h>#include <stdlib.h>#include <epoxy/gl.h>#include “../util/fds.h”#include “../util/timing.h”#include “buf.h”#include “console.h”#include “../engine.h”#include “../renderer/text.h”
file draw.h
file tests.cpp
#include <vector>#include <string>#include <unistd.h>#include “../util/fds.h”#include “../util/pty.h”#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <errno.h>#include “../log/log.h”#include “../error/error.h”#include “buf.h”#include “console.h”#include “draw.h”
file tests.cpp
#include “tests.h”#include <utility>#include “../testing/testing.h”#include “constexpr_map.h”#include “pairing_heap.h”
file tests.cpp
#include <iostream>#include <cstring>#include “../testing/testing.h”#include “../log/log.h”#include “loop.h”#include “event.h”#include “eventtarget.h”#include “state.h”
file tests.cpp
#include “../log/log.h”#include “../testing/testing.h”#include “job_manager.h”#include <atomic>
file tests.cpp
#include “../log/log.h”#include “../testing/testing.h”#include “heuristics.h”#include “path.h”
file tests.cpp
#include “../../testing/testing.h”#include “font_manager.h”#include “font.h”
file tests.cpp
#include “tests.h”#include <cstdlib>#include <epoxy/gl.h>#include <functional>#include <unordered_map>#include <memory>#include <eigen3/Eigen/Dense>#include “../log/log.h”#include “../error/error.h”#include “resources/shader_source.h”#include “resources/texture_data.h”#include “resources/mesh_data.h”#include “texture.h”#include “shader_program.h”#include “geometry.h”#include “opengl/window.h”

Defines

DBG_GL(txt)
file chunk.cpp
#include “chunk.h”
file chunk.h
#include “declarations.h”#include “coord_nese.gen.h”#include “coord_neseup.gen.h”
file coord_test.cpp
#include “coord_xy.gen.h”#include <cstdint>#include “../testing/testing.h”#include “../util/stringformatter.h”
file coordmanager.cpp
#include “coordmanager.h”
file coordmanager.h
#include “phys.h”#include “pixel.h”#include “tile.h”
file declarations.cpp
#include “declarations.h”
file declarations.h
#include <cstdint>#include “../util/fixed_point.h”
file phys.cpp
#include “phys.h”#include “coordmanager.h”#include “tile.h”#include “pixel.h”#include “../terrain/terrain.h”#include “../util/math.h”
file phys.h
#include “../util/misc.h”#include “../util/hash.h”#include “declarations.h”#include “coord_nese.gen.h”#include “coord_neseup.gen.h”
file pixel.cpp
#include “pixel.h”#include “coordmanager.h”#include “phys.h”
file pixel.h
#include “coord_xy.gen.h”#include “declarations.h”
file term.cpp
#include “term.h”
file term.h
#include “coord_xy.gen.h”#include “declarations.h”
file tile.cpp
#include “tile.h”#include “coordmanager.h”#include “../terrain/terrain.h”
file tile.h
#include “declarations.h”#include “coord_nese.gen.h”#include “coord_neseup.gen.h”#include “../util/misc.h”#include “../util/hash.h”
file continuous.cpp
#include “continuous.h”
file continuous.h
#include <type_traits>#include “value_container.h”#include “../log/log.h”
file curve.cpp
#include “curve.h”
file curve.h
#include <cstdint>#include “../util/fixed_point.h”
file discrete.cpp
#include “discrete.h”
file discrete.h
#include <optional>#include <utility>#include “value_container.h”
file iterator.cpp
#include “iterator.h”
file iterator.h
#include “curve.h”
file keyframe_container.cpp
#include “keyframe_container.h”
file keyframe_container.h
#include <iostream>#include <limits>#include <list>#include “curve.h”#include “../event/loop.h”#include “../error/error.h”
file map.cpp
#include “map.h”
file map.h
#include “curve.h”#include “map_filter_iterator.h”#include <optional>#include <iostream>#include <unordered_map>
file map_filter_iterator.cpp
#include “map_filter_iterator.h”
file map_filter_iterator.h
#include “curve.h”#include “iterator.h”#include <iterator>#include <limits>
file queue.cpp
#include “queue.h”
file queue.h
#include “curve.h”#include “queue_filter_iterator.h”#include <deque>#include <iostream>
file queue_filter_iterator.cpp
#include “queue_filter_iterator.h”
file queue_filter_iterator.h
#include “curve.h”#include “iterator.h”#include <iterator>#include <limits>
file container.cpp
#include “../../testing/testing.h”#include “../curve.h”#include “../continuous.h”#include “../discrete.h”#include “../queue.h”#include “../map.h”#include <unordered_map>#include <unordered_set>
file curve_types.cpp
#include “../../event/loop.h”#include “../../log/log.h”#include “../../testing/testing.h”#include “../continuous.h”#include “../curve.h”#include “../discrete.h”#include “../keyframe_container.h”
file value_container.cpp
#include “value_container.h”
file value_container.h
#include “../event/eventtarget.h”#include “keyframe_container.h”#include <cmath>
file cvar.cpp
#include “cvar.h”#include “../log/log.h”
file cvar.h
#include <functional>#include <stdlib.h>#include <string>#include <unordered_map>#include <utility>#include “../pyinterface/functional.h”#include “../util/path.h”
file concurrent_queue.h
#include <condition_variable>#include <mutex>#include <queue>#include <thread>
file constexpr_map.h
#include <array>#include <type_traits>#include <utility>#include “../error/error.h”
file pairing_heap.h
#include <memory>#include <functional>#include <type_traits>#include <unordered_set>#include “../util/compiler.h”#include “../error/error.h”

This file contains the implementation of a pairing heap.

It is a priority queue with near-optimal runtime.

The main advantage over the STL heap is the presence of the decrease_key operation.

Literature:

Fredman, Michael L., Robert Sedgewick, Daniel D. Sleator, and Robert E. Tarjan. “The pairing heap: A new form of self-adjusting heap.” Algorithmica 1, no. 1-4 (1986): 111-129.

Defines

OPENAGE_PAIRINGHEAP_DEBUG
file tests.h
#include <functional>#include <stddef.h>
file tests.h
#include “../util/compiler.h”#include “../util/path.h”
file engine.cpp
#include “engine.h”#include <cstdint>#include <stdio.h>#include <stdlib.h>#include <time.h>#include <epoxy/gl.h>#include <SDL2/SDL.h>#include <SDL2/SDL_image.h>#include “config.h”#include “error/error.h”#include “error/gl_debug.h”#include “gamestate/game_main.h”#include “gamestate/generator.h”#include “gui/gui.h”#include “log/log.h”#include “renderer/font/font.h”#include “renderer/font/font_manager.h”#include “renderer/text.h”#include “texture.h”#include “util/color.h”#include “util/fps.h”#include “util/opengl.h”#include “util/strings.h”#include “util/timer.h”
file engine.h
#include <cstdint>#include <memory>#include <SDL2/SDL.h>#include <unordered_map>#include <vector>#include <QObject>#include “log/log.h”#include “log/file_logsink.h”#include “audio/audio_manager.h”#include “coord/coordmanager.h”#include “coord/phys.h”#include “coord/pixel.h”#include “cvar/cvar.h”#include “gui/engine_info.h”#include “handlers.h”#include “job/job_manager.h”#include “input/input_manager.h”#include “input/action.h”#include “options.h”#include “util/externalprofiler.h”#include “util/fps.h”#include “util/path.h”#include “util/profiler.h”#include “unit/selection.h”#include “util/strings.h”#include “screenshot.h”
file backtrace.cpp
#include “backtrace.h”#include <iostream>#include “config.h”
file backtrace.h
#include <vector>#include <string>#include <iostream>#include <functional>
file demo.cpp
#include <vector>#include <string>#include “../log/log.h”#include “backtrace.h”#include “error.h”
file gl_debug.cpp
#include “gl_debug.h”#include <epoxy/gl.h>#include “error.h”
file gl_debug.h
#include <SDL2/SDL.h>
file handlers.cpp
#include “handlers.h”#include <exception>#include <iostream>#include <typeinfo>#include <cstring>#include <unistd.h>#include “../util/signal.h”#include “../util/init.h”#include “../util/language.h”#include “error.h”#include “stackanalyzer.h”
file handlers.cpp
#include “handlers.h”
file handlers.h
#include “../util/compiler.h”
file handlers.h
#include <SDL2/SDL.h>#include “coord/pixel.h”
file stackanalyzer.cpp
#include “stackanalyzer.h”#include “config.h”#include “../log/log.h”#include “../util/compiler.h”#include “../util/init.h”#include <execinfo.h>
file stackanalyzer.h
#include “backtrace.h”
file aicontroller.cpp
#include “aicontroller.h”
file aicontroller.h
#include “gamestate.h”#include <vector>
file gamestate.cpp
#include “gamestate.h”
file gamestate.h
#include <functional>#include “config.h”#include “../state.h”#include “../loop.h”#include “../eventtarget.h”#include “../../curve/continuous.h”#include “../../curve/discrete.h”#include “../../util/vector.h”
file gui.cpp
#include “gui.h”
file gui.cpp
#include “../shader/shader.h”#include “../shader/program.h”#include “gui.h”#include “../engine.h”#include “../util/path.h”#include “engine_info.h”

Variables

GLboolean was_on
GLint src
GLint dst
file gui.h
#include “config.h”
file gui.h
#include <memory>#include <string>#include “integration/public/gui_application_with_logger.h”#include “integration/public/gui_game_spec_image_provider.h”#include “guisys/public/gui_engine.h”#include “guisys/public/gui_event_queue.h”#include “guisys/public/gui_input.h”#include “guisys/public/gui_renderer.h”#include “guisys/public/gui_subtree.h”#include “../handlers.h”
file main.cpp
#include “main.h”#include <chrono>#include <ratio>#include <SDL.h>#include “config.h”#include “../event.h”#include “aicontroller.h”#include “gamestate.h”#include “gui.h”#include “physics.h”

Typedefs

using Clock = std::chrono::high_resolution_clock
file main.cpp
#include “main.h”#include “console/console.h”#include “engine.h”#include “game_control.h”#include “game_renderer.h”#include “gamedata/color.gen.h”#include “gamestate/generator.h”#include “log/log.h”#include “shader/program.h”#include “shader/shader.h”#include “util/file.h”
file main.h
#include “../../util/compiler.h”
file main.h
#include <string>#include <cstdint>#include “util/path.h”
file physics.cpp
#include “physics.h”#include <cassert>#include <cmath>#include “config.h”#include “../../error/error.h”#include “../../rng/global_rng.h”#include “../../util/stringformatter.h”
file physics.h
#include “gamestate.h”#include “../../curve/curve.h”#include <vector>
file event.cpp
#include “event.h”#include “eventtarget.h”#include “eventclass.h”#include “../log/log.h”#include “../util/hash.h”
file event.cpp
#include “event.h”#include <functional>
file event.h
#include <memory>#include “eventclass.h”#include “../curve/curve.h”
file event.h
#include <unordered_map>#include <unordered_set>#include <vector>#include <string>#include <SDL2/SDL.h>
file eventclass.cpp
#include “eventclass.h”#include “event.h”#include “eventtarget.h”#include “../log/log.h”
file eventclass.h
#include “../curve/curve.h”#include <any>#include <memory>#include <string>#include <unordered_map>
file eventfilter.cpp
#include “eventfilter.h”
file eventfilter.h
#include <memory>#include <functional>#include “eventtarget.h”
file eventqueue.cpp
#include “eventqueue.h”#include <algorithm>#include “event.h”#include “eventclass.h”#include “eventtarget.h”#include “../log/log.h”#include “../util/compiler.h”
file eventqueue.h
#include <memory>#include <unordered_set>#include “eventclass.h”#include “eventstore.h”#include “../curve/curve.h”
file eventstore.cpp
#include “eventstore.h”#include <algorithm>#include “event.h”#include “../util/compiler.h”#include “../error/error.h”
file eventstore.h
#include “../datastructure/pairing_heap.h”#include “../util/misc.h”#include <memory>#include <unordered_map>
file eventtarget.cpp
#include “eventtarget.h”#include “event.h”#include “eventclass.h”#include “loop.h”#include “../log/log.h”
file eventtarget.h
#include “../curve/curve.h”#include <functional>#include <list>#include <memory>
file loop.cpp
#include “loop.h”#include “event.h”#include “eventclass.h”#include “eventqueue.h”#include “eventtarget.h”#include “../log/log.h”
file loop.h
#include <functional>#include <list>#include <memory>#include <unordered_map>#include “../curve/curve.h”#include “eventqueue.h”#include “eventfilter.h”#include “event.h”#include “../log/log.h”
file loop.h

Defines

LOOP_1(MACRO, X)
LOOP_2(MACRO, X, Y)
LOOP_3(MACRO, X, Y, Z)
LOOP_N(_1, _2, _3, NAME, ...)
LOOP(MACRO, ...)
file state.cpp
#include “state.h”
file state.h
#include <memory>
file game_control.cpp
#include “game_control.h”#include “engine.h”#include “error/error.h”#include “gamestate/game_spec.h”#include “log/log.h”#include “renderer/color.h”#include “terrain/terrain_chunk.h”#include “util/strings.h”
file game_control.h
#include <tuple>#include <QObject>#include “coord/pixel.h”#include “input/input_context.h”#include “rng/rng.h”#include “gamestate/game_main.h”#include “unit/command.h”#include “unit/selection.h”#include “unit/unit_type.h”#include “handlers.h”
file game_renderer.cpp
#include <epoxy/gl.h>#include <SDL2/SDL.h>#include <sys/stat.h>#include <sys/types.h>#include <sstream>#include “console/console.h”#include “engine.h”#include “gamedata/color.gen.h”#include “gamestate/game_main.h”#include “gamestate/game_spec.h”#include “input/input_manager.h”#include “log/log.h”#include “terrain/terrain.h”#include “unit/action.h”#include “unit/command.h”#include “unit/producer.h”#include “unit/unit.h”#include “unit/unit_texture.h”#include “util/timer.h”#include “util/externalprofiler.h”#include “renderer/text.h”#include “game_renderer.h”
file game_renderer.h
#include <SDL2/SDL.h>#include <unordered_map>#include <unordered_set>#include <vector>#include “coord/tile.h”#include “handlers.h”#include “options.h”
file civilisation.cpp
#include “civilisation.h”#include “../log/log.h”#include “../unit/unit_type.h”
file civilisation.h
#include <memory>#include <string>#include <vector>#include “game_spec.h”
file cost.cpp
#include “cost.h”#include “player.h”
file cost.h
#include “resource.h”
file game_main.cpp
#include “game_main.h”#include “../engine.h”#include “../log/log.h”#include “../terrain/terrain.h”#include “../unit/unit_type.h”#include “game_spec.h”#include “generator.h”
file game_main.h
#include <memory>#include <vector>#include <SDL2/SDL.h>#include <QObject>#include “market.h”#include “player.h”#include “team.h”#include “../options.h”#include “../terrain/terrain.h”#include “../unit/unit_container.h”#include “../util/timing.h”
file game_save.cpp
#include “game_save.h”#include <fstream>#include <vector>#include “../log/log.h”#include “../terrain/terrain_chunk.h”#include “../unit/producer.h”#include “../unit/unit.h”#include “../unit/unit_type.h”#include “game_main.h”#include “game_spec.h”
file game_save.h
#include <string>
file game_spec.cpp
#include “game_spec.h”#include <tuple>#include “../assetmanager.h”#include “../audio/error.h”#include “../audio/resource_def.h”#include “../engine.h”#include “../gamedata/blending_mode.gen.h”#include “../gamedata/string_resource.gen.h”#include “../gamedata/terrain.gen.h”#include “../log/log.h”#include “../rng/global_rng.h”#include “../unit/producer.h”#include “../util/compiler.h”#include “../util/strings.h”#include “../util/timer.h”#include “civilisation.h”
file game_spec.h
#include “../job/job.h”#include “../gamedata/gamedata.gen.h”#include “../gamedata/graphic.gen.h”#include “../terrain/terrain.h”#include “../unit/unit_texture.h”#include “../util/csv.h”#include <unordered_map>#include <memory>#include <QObject>
file generator.cpp
#include “generator.h”#include “../log/log.h”#include “../rng/rng.h”#include “../terrain/terrain_chunk.h”#include “../unit/unit.h”#include “../util/math_constants.h”#include “game_main.h”#include “game_save.h”#include “game_spec.h”
file generator.h
#include <unordered_set>#include “../coord/tile.h”#include “../gui/guisys/public/gui_property_map.h”
file market.cpp
#include “player.h”#include “market.h”
file market.h
#include “resource.h”
file player.cpp
#include “player.h”#include “../log/log.h”#include “../unit/unit.h”#include “../unit/unit_type.h”#include “../util/math_constants.h”#include “team.h”
file player.h
#include <string>#include <unordered_map>#include “civilisation.h”#include “population_tracker.h”#include “resource.h”#include “score.h”
file population_tracker.cpp
#include “population_tracker.h”
file population_tracker.h
file score.cpp
#include <cmath>#include “player.h”#include “score.h”#include “team.h”#include “../log/log.h”
file score.h
#include <functional>#include “resource.h”
file team.cpp
#include “team.h”#include “player.h”#include “score.h”
file team.h
#include <string>#include <unordered_map>#include <vector>#include “score.h”
file actions_list_model.cpp
#include “actions_list_model.h”#include “../log/log.h”#include “game_control_link.h”#include <QtQml>
file actions_list_model.h
#include <vector>#include “game_control_link.h”#include <QAbstractListModel>#include <QMap>#include <QUrl>
file assetmanager_link.cpp
#include “assetmanager_link.h”#include <QtQml>#include “engine_link.h”
file assetmanager_link.h
#include “../assetmanager.h”#include “../util/path.h”#include “guisys/link/gui_item.h”
file category_contents_list_model.cpp
#include “category_contents_list_model.h”#include <QtQml>#include “game_control_link.h”
file category_contents_list_model.h
#include <vector>#include <string>#include <tuple>#include <memory>#include “../gamestate/game_spec.h”#include <QAbstractListModel>
file engine_info.cpp
#include “engine_info.h”
file engine_info.h
#include “../util/path.h”#include “guisys/public/gui_singleton_items_info.h”
file engine_link.cpp
#include “engine_link.h”#include <QtQml>#include “../error/error.h”#include “../engine.h”#include “guisys/link/qml_engine_with_singleton_items_info.h”#include “guisys/link/qtsdl_checked_static_cast.h”
file engine_link.h
#include <QStringList>#include “../util/path.h”#include “guisys/link/gui_singleton_item.h”
file game_control_link.cpp
#include “game_control_link.h”#include <algorithm>#include <QtQml>#include “../engine.h”#include “engine_link.h”#include “game_main_link.h”#include “../unit/action.h”#include “../unit/unit.h”
file game_control_link.h
#include <QQmlParserStatus>#include “../game_control.h”#include “guisys/link/gui_item.h”
file game_creator.cpp
#include “game_creator.h”#include <QtQml>#include “../gamestate/game_main.h”#include “../gamestate/game_spec.h”#include “../gamestate/generator.h”#include “game_main_link.h”#include “game_spec_link.h”#include “generator_link.h”
file game_creator.h
#include <QObject>
file game_main_link.cpp
#include “game_main_link.h”#include <QtQml>#include “../engine.h”#include “engine_link.h”
file game_main_link.h
#include <QQmlParserStatus>#include “guisys/link/gui_item.h”#include “../gamestate/game_main.h”
file game_saver.cpp
#include “game_saver.h”#include <QtQml>#include “../gamestate/game_save.h”#include “../gamestate/game_main.h”#include “../gamestate/generator.h”#include “game_main_link.h”#include “generator_link.h”
file game_saver.h
#include <QObject>
file game_spec_link.cpp
#include “game_spec_link.h”#include <QtQml>#include “assetmanager_link.h”
file game_spec_link.h
#include <memory>#include <QMetaType>#include <QQmlParserStatus>#include “guisys/link/gui_item.h”#include “../gamestate/game_spec.h”
file generator_link.cpp
#include “generator_link.h”#include <QtQml>#include “guisys/link/gui_property_map_impl.h”
file generator_link.h
#include “../gamestate/generator.h”#include “guisys/link/gui_list_model.h”#include “guisys/link/gui_item_list_model.h”
file gui_item.cpp
#include “gui_item.h”
file gui_item.h
#include <memory>#include <cassert>#include <functional>#include <type_traits>#include <typeinfo>#include <utility>#include <QObject>#include <QMetaType>#include <QRegularExpression>#include <QDebug>#include “../private/game_logic_caller.h”#include “../private/livereload/deferred_initial_constant_property_values.h”#include “qtsdl_checked_static_cast.h”#include “gui_item_link.h”
file gui_item_link.h
#include <type_traits>#include “qtsdl_checked_static_cast.h”
file gui_item_list_model.h
#include <vector>#include “gui_item.h”#include “gui_property_map_impl.h”#include “gui_list_model.h”
file gui_list_model.cpp
#include “gui_list_model.h”#include <algorithm>
file gui_list_model.h
#include <vector>#include <tuple>#include <QAbstractListModel>#include “gui_item.h”
file gui_property_map_impl.cpp
#include “gui_property_map_impl.h”#include <QDynamicPropertyChangeEvent>#include <QVariant>#include “qtsdl_checked_static_cast.h”
file gui_property_map_impl.h
#include <QObject>
file gui_singleton_item.cpp
#include “gui_singleton_item.h”
file gui_singleton_item.h
#include <QObject>#include “gui_item_link.h”
file qml_engine_with_singleton_items_info.cpp
#include “qml_engine_with_singleton_items_info.h”#include <algorithm>
file qml_engine_with_singleton_items_info.h
#include <memory>#include <QQmlEngine>#include “../private/gui_image_provider_impl.h”
file qtsdl_checked_static_cast.h
#include <cassert>
file game_logic_caller.cpp
#include “game_logic_caller.h”#include “gui_callback.h”
file game_logic_caller.h
#include <functional>#include <QObject>
file gui_application_impl.cpp
#include “gui_application_impl.h”#include <locale>#include <cassert>#include <QtGlobal>#include <QtDebug>
file gui_application_impl.h
#include <thread>#include <memory>#include <QGuiApplication>
file gui_callback.cpp
#include “gui_callback.h”#include <cassert>
file gui_callback.h
#include <functional>#include <QObject>#include <QMetaType>
file gui_ctx_setup.cpp
#include “gui_ctx_setup.h”#include <cassert>#include <QOpenGLDebugLogger>#include “platforms/context_extraction.h”#include “opengl_debug_logger.h”
file gui_ctx_setup.h
#include <stdexcept>#include <memory>#include <functional>#include <QOpenGLContext>#include <QOffscreenSurface>
file gui_dedicated_thread.cpp
#include “gui_dedicated_thread.h”#include <mutex>#include <condition_variable>#include <QCoreApplication>#include “gui_application_impl.h”
file gui_dedicated_thread.h
#include <thread>#include <mutex>#include <memory>#include <condition_variable>
file gui_engine_impl.cpp
#include “gui_engine_impl.h”#include <cassert>#include <QCoreApplication>#include <QQuickWindow>#include <QDebug>#include “../public/gui_engine.h”#include “gui_image_provider_impl.h”#include “gui_renderer_impl.h”
file gui_engine_impl.h
#include <memory>#include <vector>#include “../link/qml_engine_with_singleton_items_info.h”#include “livereload/recursive_directory_watcher.h”
file gui_event_queue_impl.cpp
#include “gui_event_queue_impl.h”#include <cassert>#include <QThread>#include “../public/gui_event_queue.h”
file gui_event_queue_impl.h
#include <QtGlobal>#include <QEventLoop>
file gui_image_provider_impl.cpp
#include “gui_image_provider_impl.h”#include <algorithm>#include “../public/gui_image_provider.h”
file gui_image_provider_impl.h
#include <memory>#include <vector>#include <QQuickImageProvider>
file gui_input_impl.cpp
#include “gui_input_impl.h”#include <QMouseEvent>#include <QThread>#include <QCoreApplication>#include <SDL2/SDL_mouse.h>#include “../public/gui_event_queue.h”#include “../public/gui_renderer.h”#include “gui_event_queue_impl.h”#include “gui_renderer_impl.h”
file gui_input_impl.h
#include <atomic>#include <QObject>#include <SDL2/SDL_events.h>
file gui_renderer_impl.cpp
#include “gui_renderer_impl.h”#include <cassert>#include <QOpenGLContext>#include <QOpenGLFramebufferObject>#include <QQuickRenderControl>#include <QQuickItem>#include <QCoreApplication>#include <QThread>#include “../public/gui_renderer.h”
file gui_renderer_impl.h
#include <memory>#include <atomic>#include <mutex>#include <condition_variable>#include <QtGlobal>#include <QObject>#include <QQuickWindow>#include <QQuickRenderControl>#include <QOffscreenSurface>#include “gui_rendering_setup_routines.h”
file gui_rendering_setup_routines.cpp
#include “gui_rendering_setup_routines.h”#include <cassert>#include <QDebug>#include “gui_ctx_setup.h”
file gui_rendering_setup_routines.h
#include <memory>#include <QtGlobal>
file gui_subtree_impl.cpp
#include “gui_subtree_impl.h”#include “gui_renderer_impl.h”#include <cassert>#include <ciso646>#include <QCoreApplication>#include <QQmlEngine>#include <QQuickWindow>#include <QQuickItem>#include <QFileInfo>#include <QDir>#include <QDebug>#include “gui_engine_impl.h”#include “../link/gui_item.h”#include “../public/gui_subtree.h”#include “gui_event_queue_impl.h”
file gui_subtree_impl.h
#include <memory>#include <vector>#include <string>#include <QObject>#include <QQmlComponent>#include “gui_callback.h”#include “livereload/gui_live_reloader.h”
file deferred_initial_constant_property_values.cpp
#include “deferred_initial_constant_property_values.h”
file deferred_initial_constant_property_values.h
#include <vector>#include <functional>
file gui_live_reloader.cpp
#include “gui_live_reloader.h”#include <algorithm>#include <unordered_set>#include “../../link/gui_item.h”#include “deferred_initial_constant_property_values.h”
file gui_live_reloader.h
#include <unordered_map>#include <tuple>#include <memory>#include <QStringList>#include <QHash>#include <QList>#include <QtQml>
file recursive_directory_watcher.cpp
#include “recursive_directory_watcher.h”#include <QSemaphore>#include <QEventLoop>#include “recursive_directory_watcher_worker.h”
file recursive_directory_watcher.h
#include <future>#include <QObject>#include <QStringList>
file recursive_directory_watcher_worker.cpp
#include “recursive_directory_watcher_worker.h”#include <algorithm>#include <QDirIterator>#include <QDebug>
file recursive_directory_watcher_worker.h
#include <memory>#include <QFileSystemWatcher>#include <QStringList>#include <QTimer>
file opengl_debug_logger.cpp
#include “opengl_debug_logger.h”#include <QOpenGLContext>#include <QOpenGLFunctions_4_4_Core>
file opengl_debug_logger.h
#include <QOpenGLFunctions>
file context_extraction.h
#include <tuple>#include <functional>#include <QWindow>#include <QVariant>
file context_extraction_cocoa.mm
#include <cassert>#include “context_extraction.h”#include <QtPlatformHeaders/QCocoaNativeContext>#include “SDL_syswm.h”#include <AppKit/AppKit.h>
file context_extraction_win32.cpp
#include <cassert>#include <windows.h>#include “context_extraction.h”#include <QtPlatformHeaders/QWGLNativeContext>#include <SDL2/SDL_syswm.h>#include <GL/gl.h>
file context_extraction_x11.cpp
#include <cassert>#include “context_extraction.h”#include <QtPlatformHeaders/QGLXNativeContext>#include <SDL2/SDL_syswm.h>#include <GL/glx.h>
file gui_application.cpp
#include “../public/gui_application.h”#include “../private/gui_application_impl.h”
file gui_application.h
#include <memory>
file gui_engine.cpp
#include “../public/gui_engine.h”#include “../private/gui_engine_impl.h”
file gui_engine.h
#include <memory>#include <vector>
file gui_event_queue.cpp
#include “../public/gui_event_queue.h”#include “../private/gui_event_queue_impl.h”
file gui_event_queue.h
#include <memory>
file gui_image_provider.cpp
#include “../public/gui_image_provider.h”#include “../private/gui_image_provider_impl.h”
file gui_image_provider.h
#include <memory>#include <functional>
file gui_input.cpp
#include “../public/gui_input.h”#include “../private/gui_input_impl.h”
file gui_input.h
#include <memory>#include <SDL2/SDL_events.h>
file gui_property_map.cpp
#include “gui_property_map.h”#include <algorithm>#include <typeinfo>#include <cassert>#include <QVariant>#include <QRegExp>#include <QCoreApplication>#include “../link/gui_property_map_impl.h”
file gui_property_map.h
#include <memory>#include <string>#include <vector>
file gui_renderer.cpp
#include “../public/gui_renderer.h”#include <QSize>#include “../private/gui_renderer_impl.h”
file gui_renderer.h
#include <memory>#include <GL/gl.h>
file gui_singleton_items_info.h
file gui_subtree.cpp
#include “gui_subtree.h”#include “../private/gui_subtree_impl.h”
file gui_subtree.h
#include <memory>#include <string>
file gui_filled_texture_handles.cpp
#include “gui_filled_texture_handles.h”#include “gui_texture_handle.h”
file gui_filled_texture_handles.h
#include <vector>#include <mutex>#include <memory>#include <functional>#include <QString>#include <QSize>
file gui_game_spec_image_provider_by_filename_impl.cpp
#include “gui_game_spec_image_provider_by_filename_impl.h”#include “../../../error/error.h”#include “../../../gamestate/game_spec.h”
file gui_game_spec_image_provider_by_filename_impl.h
#include “gui_game_spec_image_provider_impl.h”
file gui_game_spec_image_provider_by_graphic_id_impl.cpp
#include “gui_game_spec_image_provider_by_graphic_id_impl.h”#include “../../../error/error.h”#include “../../../gamestate/game_spec.h”
file gui_game_spec_image_provider_by_graphic_id_impl.h
#include “gui_game_spec_image_provider_by_id_impl.h”
file gui_game_spec_image_provider_by_id_impl.cpp
#include “gui_game_spec_image_provider_by_id_impl.h”#include “../../../error/error.h”#include “../../../gamestate/game_spec.h”#include “gui_texture_factory.h”
file gui_game_spec_image_provider_by_id_impl.h
#include “gui_game_spec_image_provider_impl.h”
file gui_game_spec_image_provider_by_terrain_id_impl.cpp
#include “gui_game_spec_image_provider_by_terrain_id_impl.h”#include “../../../error/error.h”#include “../../../gamestate/game_spec.h”
file gui_game_spec_image_provider_by_terrain_id_impl.h
#include “gui_game_spec_image_provider_by_id_impl.h”
file gui_game_spec_image_provider_impl.cpp
#include “gui_game_spec_image_provider_impl.h”#include <algorithm>#include <QThread>#include “../../../error/error.h”#include “../../../gamestate/game_spec.h”#include “../../guisys/private/gui_event_queue_impl.h”#include “gui_texture_factory.h”#include “gui_filled_texture_handles.h”
file gui_game_spec_image_provider_impl.h
#include <memory>#include <mutex>#include <vector>#include <tuple>#include <condition_variable>#include “../../guisys/private/gui_image_provider_impl.h”#include “../../guisys/private/gui_callback.h”#include “gui_texture_handle.h”#include “gui_filled_texture_handles.h”
file gui_image_provider_link.cpp
#include “gui_image_provider_link.h”#include <algorithm>#include <QtQml>#include “../../../error/error.h”#include “../../guisys/link/qml_engine_with_singleton_items_info.h”#include “../../guisys/link/qtsdl_checked_static_cast.h”#include “../../game_spec_link.h”#include “gui_game_spec_image_provider_impl.h”#include “gui_game_spec_image_provider_by_filename_impl.h”#include “gui_game_spec_image_provider_by_graphic_id_impl.h”#include “gui_game_spec_image_provider_by_terrain_id_impl.h”
file gui_image_provider_link.h
#include <memory>#include <QObject>#include <QPointer>
file gui_log.cpp
#include “../../integration/private/gui_log.h”#include <QString>#include “../../../log/log.h”
file gui_log.h
#include <QtGlobal>
file gui_make_standalone_subtexture.cpp
#include “gui_make_standalone_subtexture.h”#include “gui_standalone_subtexture.h”
file gui_make_standalone_subtexture.h
#include <memory>#include <QSGTexture>#include <epoxy/gl.h>
file gui_standalone_subtexture.cpp
#include “gui_standalone_subtexture.h”
file gui_standalone_subtexture.h
#include <QtGui>#include <QSGTexture>
file gui_texture.cpp
#include “gui_texture.h”#include <array>#include <QTransform>#include “../../../texture.h”#include “gui_make_standalone_subtexture.h”
file gui_texture.h
#include <memory>#include <QSGTexture>#include “gui_texture_handle.h”
file gui_texture_factory.cpp
#include “gui_texture_factory.h”#include “gui_game_spec_image_provider_impl.h”#include “../../../texture.h”#include “gui_texture.h”#include “gui_filled_texture_handles.h”
file gui_texture_factory.h
#include <memory>#include <QQuickTextureFactory>#include “gui_texture_handle.h”#include “gui_filled_texture_handles.h”
file gui_texture_handle.cpp
#include “gui_texture_handle.h”#include <numeric>#include “../../../texture.h”
file gui_texture_handle.h
#include <QSize>
file gui_application_with_logger.cpp
#include “gui_application_with_logger.h”#include “../../guisys/private/gui_application_impl.h”#include “../private/gui_log.h”
file gui_application_with_logger.h
#include “../../guisys/public/gui_application.h”
file gui_game_spec_image_provider.cpp
#include “gui_game_spec_image_provider.h”#include “../../../error/error.h”#include “../private/gui_game_spec_image_provider_by_filename_impl.h”#include “../private/gui_game_spec_image_provider_by_graphic_id_impl.h”#include “../private/gui_game_spec_image_provider_by_terrain_id_impl.h”
file gui_game_spec_image_provider.h
#include “../../guisys/public/gui_image_provider.h”
file main_args_link.cpp
#include “main_args_link.h”#include <QtQml>#include “../error/error.h”#include “engine_info.h”#include “guisys/link/qml_engine_with_singleton_items_info.h”#include “guisys/link/qtsdl_checked_static_cast.h”
file main_args_link.h
#include <QObject>#include “../util/path.h”
file registrations.cpp
#include “registrations.h”#include <QMetaType>
file registrations.h
#include <QMetaType>#include “../util/path.h”
file resources_list_model.cpp
#include “resources_list_model.h”#include <iterator>#include <type_traits>#include <QtQml>#include “../error/error.h”#include “../game_control.h”#include “game_control_link.h”
file resources_list_model.h
#include <vector>#include <tuple>#include <QAbstractListModel>#include “../gamestate/resource.h”
file action.cpp
#include <functional>#include “../cvar/cvar.h”#include “action.h”#include “input_manager.h”#include “../log/log.h”#include “../log/message.h”#include “../util/repr.h”
file action.cpp
#include <algorithm>#include <cmath>#include “../engine.h”#include “../pathfinding/a_star.h”#include “../pathfinding/heuristics.h”#include “../terrain/terrain.h”#include “../terrain/terrain_search.h”#include “action.h”#include “command.h”#include “producer.h”#include “research.h”#include “unit_texture.h”
file action.h
#include <functional>#include <unordered_map>#include <vector>#include “../coord/pixel.h”#include “event.h”
file action.h
#include <memory>#include <vector>#include “../pathfinding/path.h”#include “../gamestate/resource.h”#include “attribute.h”#include “research.h”#include “unit.h”#include “unit_container.h”
file input_context.cpp
#include “input_context.h”#include “input_manager.h”
file input_context.h
#include <functional>#include <stack>#include <unordered_map>#include <vector>#include “action.h”#include “event.h”
file input_manager.cpp
#include <algorithm>#include <array>#include “../log/log.h”#include “action.h”#include “input_manager.h”#include “text_to_event.h”
file input_manager.h
#include <functional>#include <string>#include <SDL2/SDL.h>#include “../handlers.h”#include “action.h”#include “event.h”#include “input_context.h”
file text_to_event.cpp
#include “text_to_event.h”#include <regex>#include <stdexcept>#include <SDL2/SDL.h>#include “../error/error.h”#include “../log/log.h”#include “../testing/testing.h”
file text_to_event.h
#include <string>#include “event.h”
file abortable_job_state.h
#include <functional>#include “job_aborted_exception.h”#include “typed_job_state_base.h”#include “types.h”
file job.h
#include <exception>#include <memory>#include “typed_job_state_base.h”
file job_aborted_exception.h
#include <stdexcept>
file job_group.cpp
#include “job_group.h”
file job_group.h
#include <memory>#include “../error/error.h”#include “abortable_job_state.h”#include “job.h”#include “job_state.h”#include “types.h”#include “worker.h”
file job_manager.cpp
#include “job_manager.h”#include “../log/log.h”#include “../util/thread_id.h”#include “worker.h”
file job_manager.h
#include <atomic>#include <condition_variable>#include <memory>#include <mutex>#include <queue>#include <thread>#include <unordered_map>#include “abortable_job_state.h”#include “job.h”#include “job_group.h”#include “job_state.h”#include “job_state_base.h”#include “types.h”
file job_state.h
#include <functional>#include “typed_job_state_base.h”#include “types.h”
file job_state_base.h
#include <functional>#include “types.h”
file typed_job_state_base.h
#include <atomic>#include <exception>#include <functional>#include “../util/thread_id.h”#include “../error/error.h”#include “job_aborted_exception.h”#include “job_state_base.h”#include “types.h”
file worker.cpp
#include “job_aborted_exception.h”#include “job_manager.h”#include “worker.h”
file worker.h
#include <atomic>#include <condition_variable>#include <memory>#include <queue>#include <thread>#include “job_state_base.h”
file file_logsink.cpp
#include “file_logsink.h”#include <iostream>#include <iomanip>#include “message.h”#include “logsource.h”
file file_logsink.h
#include <iostream>#include <fstream>#include “logsink.h”
file level.cpp
#include “level.h”
file level.h
#include “../util/enum.h”

Defines

NOOPTIMIZE
file log.cpp
#include “log.h”#include “message.h”#include “named_logsource.h”#include “stdout_logsink.h”
file log.h
#include “level.h”#include “message.h”
file logsink.cpp
#include “logsink.h”#include <algorithm>#include “message.h”
file logsink.h
#include <list>#include <mutex>#include “level.h”
file logsource.cpp
#include “logsource.h”#include “../util/compiler.h”#include “logsink.h”#include “stdout_logsink.h”
file logsource.h
#include <string>#include “message.h”
file message.cpp
#include “message.h”#include <mutex>#include <unordered_set>#include “../util/timing.h”#include “../util/compiler.h”#include “../util/thread_id.h”#include “../util/strings.h”
file message.h
#include <cstdint>#include <string>#include “config.h”#include “../util/constexpr.h”#include “../util/stringformatter.h”#include “logsink.h”#include “level.h”

Defines

OPENAGE_FUNC_NAME
MSG_LVLOBJ(LVLOBJ)
MSG(LVL)
SPAM
DBG
INFO
WARN
ERR
CRIT
file named_logsource.cpp
#include “named_logsource.h”
file named_logsource.h
#include <string>#include “logsource.h”
file stdout_logsink.cpp
#include “stdout_logsink.h”#include <iostream>#include <iomanip>#include “named_logsource.h”
file stdout_logsink.h
#include “logsink.h”
file test.cpp
#include <iostream>#include <iomanip>#include <thread>#include <vector>#include “log.h”#include “logsource.h”#include “logsink.h”#include “../util/strings.h”
file options.cpp
#include “options.h”
file options.h
#include <functional>#include <memory>#include <string>#include <unordered_map>#include <vector>#include “util/variable.h”
file a_star.cpp
#include “a_star.h”#include <cmath>#include “../datastructure/pairing_heap.h”#include “../log/log.h”#include “../terrain/terrain.h”#include “../terrain/terrain_object.h”#include “../util/strings.h”#include “path.h”#include “heuristics.h”

This file implements the A* search algorithm for openage.

Literature: Hart, Peter E., Nils J. Nilsson, and Bertram Raphael. “A formal basis for

the heuristic determination of minimum cost paths.” Systems Science and Cybernetics, IEEE Transactions on 4, no. 2 (1968): 100-107.

file a_star.h
#include <memory>#include “heuristics.h”#include “path.h”
file heuristics.cpp
#include “heuristics.h”#include <algorithm>#include <cmath>
file heuristics.h
#include “path.h”
file path.cpp
#include <cmath>#include “path.h”#include “../terrain/terrain.h”
file path.cpp
#include “path.h”#include “compiler.h”#include “fslike/directory.h”#include “fslike/native.h”#include “fslike/python.h”#include “misc.h”#include “strings.h”#include “../error/error.h”
file path.h
#include <functional>#include <memory>#include <unordered_map>#include <vector>#include “../coord/phys.h”#include “../coord/tile.h”#include “../datastructure/pairing_heap.h”#include “../util/misc.h”#include “../util/hash.h”
file path.h
#include <string>#include <vector>#include “../pyinterface/pyobject.h”#include “file.h”#include “fslike/native.h”
file path_utils.h
file defs.cpp
#include “defs.h”
file defs.h

Typedefs

typedef struct _object PyObject
file exctranslate.cpp
#include “exctranslate.h”#include <new>#include <typeinfo>#include <stdexcept>#include <string>#include <ios>#include “../util/timing.h”#include “../error/error.h”#include “../util/compiler.h”#include “../util/thread_id.h”#include “../log/level.h”#include “pyexception.h”
file exctranslate.h
#include “../error/error.h”

Defines

__Pyx_CppExn2PyErr
file exctranslate_tests.cpp
#include “exctranslate_tests.h”#include <vector>#include “../log/log.h”#include “../testing/testing.h”#include “pyexception.h”
file exctranslate_tests.h
#include “functional.h”
file functional.cpp
#include “functional.h”
file functional.h
#include <functional>#include <mutex>#include “../util/compiler.h”#include “../util/language.h”#include “exctranslate.h”#include “setup.h”
file hacks.cpp
#include “hacks.h”
file hacks.h
#include “exctranslate.h”
file pyexception.cpp
#include “pyexception.h”#include “../log/log.h”
file pyexception.h
#include <memory>#include <string>#include <vector>#include “../error/error.h”#include “../error/backtrace.h”#include “functional.h”#include “pyobject.h”
file pyobject.cpp
#include “pyobject.h”#include <algorithm>#include <functional>
file pyobject.h
#include <cstdint>#include <string>#include <vector>#include “defs.h”#include “functional.h”
file pyobject_tests.cpp
#include “pyobject_tests.h”#include <unordered_set>#include “pyobject.h”#include “pyexception.h”#include “../testing/testing.h”
file pyobject_tests.h
file setup.cpp
#include “setup.h”#include <mutex>#include <set>#include <map>#include “../error/error.h”#include “../util/compiler.h”

Variables

std::mutex lock
std::map<void *, std::function<bool()>> map
std::set<void *> destroyed_components
bool check_performed
file setup.h
#include <functional>#include “../util/compiler.h”
file color.cpp
#include “color.h”
file color.cpp
#include “color.h”#include <epoxy/gl.h>
file color.h
#include <cstdint>
file color.h
#include “../gamedata/color.gen.h”
file font.cpp
#include “font.h”#include <ft2build.h>#include <harfbuzz/hb.h>#include <harfbuzz/hb-ft.h>#include “../../error/error.h”#include “../../util/compiler.h”
file font.h
#include <memory>#include <string>#include <typeindex>#include <vector>#include “../../util/hash.h”#include “font_manager.h”
file font_manager.cpp
#include “font_manager.h”#include <fontconfig/fontconfig.h>#include “../../log/log.h”#include “font.h”
file font_manager.h
#include <ft2build.h>#include <memory>#include <string>#include <unordered_map>#include “../../error/error.h”
file glyph_atlas.cpp
#include “glyph_atlas.h”#include <algorithm>#include <functional>#include <typeindex>#include <cstring>#include <epoxy/gl.h>#include “../../error/error.h”#include “../../util/hash.h”
file glyph_atlas.h
#include <memory>#include <unordered_map>#include <vector>#include “font.h”
file geometry.cpp
#include “geometry.h”
file geometry.cpp
#include “geometry.h”#include <epoxy/gl.h>#include “../../error/error.h”#include “../../datastructure/constexpr_map.h”#include “lookup.h”
file geometry.h
#include <vector>#include <cstdint>#include <cstddef>
file geometry.h
#include <optional>#include “../geometry.h”#include “../resources/mesh_data.h”#include “buffer.h”#include “vertex_array.h”
file buffer.cpp
#include “buffer.h”#include “../../error/error.h”
file buffer.h
#include “simple_object.h”
file context.cpp
#include “context.h”#include <array>#include <epoxy/gl.h>#include “../../log/log.h”#include “../../error/error.h”
file context.h
#include <SDL2/SDL.h>
file framebuffer.cpp
#include “framebuffer.h”
file framebuffer.h
#include <vector>#include “texture.h”#include “simple_object.h”
file lookup.h
#include <epoxy/gl.h>#include “../resources/texture_info.h”#include “../resources/mesh_data.h”
file render_target.cpp
#include “render_target.h”
file render_target.h
#include <optional>#include “../renderer.h”#include “texture.h”#include “framebuffer.h”
file render_target.h
#include <algorithm>#include “../renderer.h”#include “graphics_device.h”
file renderer.cpp
#include “renderer.h”#include “../../log/log.h”#include “../../error/error.h”#include “texture.h”#include “shader_program.h”#include “uniform_input.h”#include “geometry.h”
file renderer.cpp
#include “renderer.h”#include “../../error/error.h”#include “../../util/fslike/directory.h”#include “../resources/shader_source.h”#include “util.h”#include “graphics_device.h”#include “render_target.h”#include “shader_program.h”
file renderer.h
#include <memory>#include <SDL2/SDL.h>#include “context.h”#include “../renderer.h”#include “shader_program.h”#include “render_target.h”
file renderer.h
#include <vector>#include <memory>
file renderer.h
#include <vulkan/vulkan.h>#include “../renderer.h”#include “../../util/path.h”#include “graphics_device.h”
file shader.cpp
#include “shader.h”#include “../../datastructure/constexpr_map.h”
file shader.cpp
#include “shader.h”#include <stdlib.h>#include <stdio.h>#include “../error/error.h”#include “../log/log.h”#include “../util/file.h”#include “../util/strings.h”
file shader.h
#include “../resources/shader_source.h”#include “simple_object.h”
file shader.h
#include <initializer_list>#include <epoxy/gl.h>
file shader_program.cpp
#include “shader_program.h”#include <algorithm>#include <unordered_set>#include “../../error/error.h”#include “../../log/log.h”#include “../../datastructure/constexpr_map.h”#include “texture.h”#include “shader.h”#include “geometry.h”#include “lookup.h”
file shader_program.h
#include <unordered_map>#include <vector>#include “../shader_program.h”#include “../resources/shader_source.h”#include “../renderer.h”#include “uniform_input.h”#include “context.h”#include “geometry.h”#include “simple_object.h”
file shader_program.h
#include <cstdint>#include <vector>#include <map>#include <eigen3/Eigen/Dense>#include “resources/mesh_data.h”#include “../error/error.h”
file shader_program.h
#include “../../error/error.h”#include “../../log/log.h”#include “../resources/shader_source.h”#include “../shader_program.h”
file simple_object.cpp
#include “simple_object.h”#include <utility>
file simple_object.h
#include <optional>#include <functional>#include <epoxy/gl.h>
file texture.cpp
#include “texture.h”#include <epoxy/gl.h>#include <tuple>#include “../../error/error.h”#include “../../datastructure/constexpr_map.h”#include “../../log/log.h”#include “../resources/texture_data.h”#include “render_target.h”#include “lookup.h”
file texture.cpp
#include <cstring>#include “texture.h”#include “../error/error.h”
file texture.cpp
#include “texture.h”#include <SDL2/SDL.h>#include <SDL2/SDL_image.h>#include <cmath>#include <cstdio>#include “log/log.h”#include “error/error.h”#include “util/csv.h”#include “coord/phys.h”
file texture.h
#include “../resources/texture_data.h”#include “../texture.h”#include “simple_object.h”
file texture.h
#include “resources/texture_data.h”
file texture.h
#include <epoxy/gl.h>#include <vector>#include <memory>#include “gamedata/texture.gen.h”#include “coord/pixel.h”#include “coord/tile.h”#include “shader/program.h”#include “shader/shader.h”#include “util/path.h”
file texture_array.cpp
#include “texture_array.h”#include <epoxy/gl.h>#include <tuple>#include “../../error/error.h”#include “../../datastructure/constexpr_map.h”#include “../../log/log.h”#include “../resources/texture_data.h”#include “render_target.h”#include “lookup.h”
file texture_array.cpp
#include “texture_array.h”
file texture_array.h
#include <vector>#include “../texture_array.h”#include “simple_object.h”#include “../resources/texture_data.h”
file texture_array.h
#include “resources/texture_data.h”
file uniform_input.h
#include <unordered_map>#include <vector>#include “../renderer.h”
file vertex_array.cpp
#include “vertex_array.h”#include <map>#include “../../error/error.h”#include “../../datastructure/constexpr_map.h”#include “lookup.h”
file vertex_array.h
#include “../resources/mesh_data.h”#include “buffer.h”#include “simple_object.h”
file window.cpp
#include “window.h”#include “../../log/log.h”#include “../../error/error.h”#include “../sdl_global.h”#include “renderer.h”
file window.cpp
#include “window.h”
file window.h
#include “../window.h”#include <optional>#include “context.h”
file window.h
#include <functional>#include <memory>#include <vector>#include <SDL2/SDL.h>#include “renderer.h”
file mesh_data.cpp
#include “mesh_data.h”#include <array>#include <cstring>#include <utility>#include “../../error/error.h”#include “../../datastructure/constexpr_map.h”
file mesh_data.h
#include <vector>#include <unordered_map>#include <cstdint>#include <cstdlib>#include <optional>#include “../../util/path.h”
file shader_source.cpp
#include “shader_source.h”#include “../../util/file.h”
file shader_source.h
#include <string>#include “../../util/path.h”
file texture_data.cpp
#include “texture_data.h”#include <SDL2/SDL.h>#include <SDL2/SDL_image.h>#include “../../log/log.h”#include “../../error/error.h”#include “../../util/csv.h”
file texture_data.h
#include <vector>#include <cstdint>#include <string>#include “texture_info.h”#include “../../util/path.h”
file texture_info.cpp
#include “texture_info.h”
file texture_info.h
#include <cstdint>#include <vector>#include “../../datastructure/constexpr_map.h”#include “texture_subinfo.h”
file texture_subinfo.cpp
#include “texture_subinfo.h”
file texture_subinfo.h
#include <cstdint>#include “../../util/csv.h”
file sdl_global.cpp
#include <SDL2/SDL.h>#include <SDL2/SDL_image.h>#include “../log/log.h”#include “../error/error.h”
file sdl_global.h
file text.cpp
#include “text.h”#include <algorithm>#include <harfbuzz/hb.h>#include “../util/strings.h”#include “font/font.h”
file text.h
#include <vector>#include <string>#include <epoxy/gl.h>#include “../coord/pixel.h”#include “../shader/program.h”#include “color.h”#include “font/glyph_atlas.h”
file graphics_device.cpp
#include “graphics_device.h”#include <cstring>#include “../../error/error.h”#include “../../log/log.h”#include “util.h”
file graphics_device.h
#include <optional>#include <vector>#include <vulkan/vulkan.h>
file loader.cpp
#include “loader.h”#include “../../error/error.h”
file loader.h
#include <vulkan/vulkan.h>
file README.md
file README.md
file util.h
#include <vulkan/vulkan.h>#include “../../error/error.h”

Defines

VK_CALL_CHECKED(fun, ...)

Functions

template<typename R, typename R2>
std::vector<R> vk_do_ritual(R2 (*func)(uint32_t *, R *))
template<typename T, typename T2, typename R, typename R2>
std::vector<R> vk_do_ritual(R2 (*func)(T, uint32_t *, R *), T2 &&a, )
template<typename T, typename T2, typename U, typename U2, typename R, typename R2>
std::vector<R> vk_do_ritual(R2 (*func)(T, U, uint32_t *, R *), T2 &&a, U2 &&b, )
template<typename T, typename T2, typename U, typename U2, typename V, typename V2, typename R, typename R2>
std::vector<R> vk_do_ritual(R2 (*func)(T, U, V, uint32_t *, R *), T2 &&a, U2 &&b, V2 &&c, )
file windowvk.cpp
#include “windowvk.h”#include <set>#include <SDL2/SDL_vulkan.h>#include “../../error/error.h”#include “../../log/log.h”#include “../sdl_global.h”#include “graphics_device.h”#include “util.h”
file windowvk.h
#include <set>#include <cstring>#include <optional>#include <vulkan/vulkan.h>#include “../window.h”#include “loader.h”
file global_rng.cpp
#include “rng.h”#include “global_rng.h”#include <mutex>
file global_rng.h

This file contains functions for the global random number generator.

Please avoid using it, instead, create rng objects for your current class as members.

file rng.cpp
#include “rng.h”#include <random>#include <sstream>#include <array>#include “../util/timing.h”#include “../util/hash.h”#include “../error/error.h”
file rng.h
#include <iostream>#include <string>
file rng_tests.cpp
#include “rng.h”#include “../log/log.h”#include “../error/error.h”#include “../testing/testing.h”#include <limits>#include <vector>#include <cmath>
file screenshot.cpp
#include “screenshot.h”#include <cstdio>#include <cstring>#include <ctime>#include <epoxy/gl.h>#include <math.h>#include <memory>#include <png.h>#include <stdlib.h>#include “coord/pixel.h”#include “job/job_manager.h”#include “log/log.h”#include “util/strings.h”
file screenshot.h
#include <string>#include <ctime>#include <memory>#include “coord/pixel.h”
file program.cpp
#include “program.h”#include <stdlib.h>#include <stdio.h>#include <iostream>#include “../error/error.h”#include “../log/log.h”#include “../util/compiler.h”#include “../util/file.h”#include “../util/strings.h”#include “shader.h”
file program.h
#include <epoxy/gl.h>
file entity.cpp
#include “entity.h”#include <nyan/nyan.h>
file entity.h
file terrain.cpp
#include “terrain.h”#include <cmath>#include <memory>#include <set>#include <unordered_map>#include “../log/log.h”#include “../error/error.h”#include “../engine.h”#include “../game_renderer.h”#include “../coord/pixel.h”#include “../coord/chunk.h”#include “../coord/tile.h”#include “../util/misc.h”#include “../util/strings.h”#include “terrain_chunk.h”#include “terrain_object.h”
file terrain.h
#include <functional>#include <memory>#include <stddef.h>#include <set>#include <unordered_map>#include <vector>#include “../assetmanager.h”#include “../coord/chunk.h”#include “../coord/phys.h”#include “../coord/pixel.h”#include “../coord/tile.h”#include “../texture.h”#include “../util/misc.h”
file terrain_chunk.cpp
#include “terrain_chunk.h”#include <cmath>#include “../error/error.h”#include “../log/log.h”#include “../engine.h”#include “../texture.h”#include “../coord/tile.h”#include “../coord/phys.h”#include “../coord/pixel.h”#include “../util/misc.h”#include “terrain.h”#include “terrain_object.h”
file terrain_chunk.h
#include <stddef.h>#include <vector>#include “../coord/pixel.h”#include “../coord/tile.h”#include “../texture.h”#include “../util/file.h”
file terrain_object.cpp
#include “terrain_object.h”#include <algorithm>#include <cmath>#include “../engine.h”#include “../error/error.h”#include “../texture.h”#include “../coord/tile.h”#include “../coord/phys.h”#include “../coord/pixel.h”#include “../unit/unit.h”#include “terrain.h”#include “terrain_chunk.h”#include “terrain_outline.h”
file terrain_object.h
#include <memory>#include <stddef.h>#include “../coord/tile.h”#include “../coord/phys.h”
file terrain_outline.cpp
#include <cmath>#include <math.h>#include <memory>#include “../texture.h”#include “terrain_outline.h”
file terrain_outline.h
#include <memory>#include “../coord/tile.h”
file terrain_search.cpp
#include <cmath>#include “terrain.h”#include “terrain_object.h”#include “terrain_search.h”
file terrain_search.h
#include <functional>#include <memory>#include <queue>#include <unordered_set>#include <vector>#include “../coord/tile.h”
file benchmark_test.cpp
#include <chrono>#include <thread>
file testing.cpp
#include “testing.h”
file testing.h
#include “../error/error.h”

Defines

TESTFAIL

Convenience macro, for usage in test functions:

test_stuff() or TESTFAIL;

TESTFAILMSG(...)

As above, but allows printing a message:

test_stuff() or TESTFAIL(“lolnope”);

TESTEQUALS(left, right)

Asserts that the left expression equals the right expression, and that no exception is thrown.

TESTEQUALS_FLOAT(left, right, epsilon)

Asserts that the left expression equals the right expression, within a margin of error epsilon, and that no exception is thrown.

TESTTHROWS(expression)

Asserts that the expression throws an exception.

TESTNOEXCEPT(expression)

Assets that the expression throws no exception (mostly for void expressions).

file testlist.h
#include <string>#include “testing.h”
file ability.cpp
#include <memory>#include “../terrain/terrain_object.h”#include “../gamestate/cost.h”#include “../gamestate/player.h”#include “ability.h”#include “action.h”#include “command.h”#include “research.h”#include “unit.h”
file ability.h
#include <bitset>#include <memory>#include <type_traits>#include <unordered_map>#include <vector>#include “../coord/phys.h”#include “../gamestate/resource.h”
file attribute.cpp
#include “attribute.h”#include “unit.h”#include “unit_type.h”
file attribute.h
#include <functional>#include <map>#include <algorithm>#include “../coord/tile.h”#include “../gamedata/unit.gen.h”#include “../terrain/terrain_object.h”#include “../gamestate/resource.h”#include “unit_container.h”
file attributes.cpp
#include “attributes.h”
file attributes.h
#include <map>#include “attribute.h”
file command.cpp
#include “command.h”
file command.h
#include <unordered_set>#include “../coord/phys.h”#include “ability.h”
file producer.cpp
#include <initializer_list>#include “../engine.h”#include “../log/log.h”#include “../gamedata/unit.gen.h”#include “../terrain/terrain.h”#include “../terrain/terrain_object.h”#include “../terrain/terrain_outline.h”#include “../util/strings.h”#include “ability.h”#include “action.h”#include “producer.h”#include “unit.h”#include “unit_texture.h”

Many values in this file are hardcoded, due to limited understanding of how the original game files work as more becomes known these will be removed.

It is likely the conversion from gamedata to openage units will be done by the nyan system in future

file producer.h
#include <memory>#include <unordered_map>#include <vector>#include “../coord/tile.h”#include “../gamedata/gamedata.gen.h”#include “../gamedata/graphic.gen.h”#include “../gamestate/player.h”#include “unit.h”#include “unit_type.h”
file research.cpp
#include “../gamestate/player.h”#include “research.h”
file research.h
#include <string>#include <memory>
file selection.cpp
#include “selection.h”#include <algorithm>#include <cmath>#include “../coord/tile.h”#include “../engine.h”#include “../log/log.h”#include “../renderer/text.h”#include “../terrain/terrain.h”#include “action.h”#include “command.h”#include “producer.h”#include “unit.h”
file selection.h
#include <vector>#include “../coord/pixel.h”#include “../handlers.h”#include “ability.h”#include “unit_container.h”
file type_pair.cpp
#include “type_pair.h”
file type_pair.h
file unit.cpp
#include <algorithm>#include <cmath>#include <limits>#include “../terrain/terrain.h”#include “../engine.h”#include “ability.h”#include “action.h”#include “command.h”#include “producer.h”#include “unit.h”#include “unit_texture.h”
file unit.h
#include <memory>#include <mutex>#include <unordered_map>#include <vector>#include <queue>#include “../coord/phys.h”#include “../handlers.h”#include “../log/logsource.h”#include “../terrain/terrain_object.h”#include “../util/timing.h”#include “ability.h”#include “attribute.h”#include “attributes.h”#include “command.h”#include “unit_container.h”
file unit_container.cpp
#include “unit_container.h”#include <memory>#include “../log/log.h”#include “../terrain/terrain_object.h”#include “producer.h”#include “unit.h”
file unit_container.h
#include <memory>#include <unordered_map>#include <vector>#include “../coord/tile.h”#include “../handlers.h”#include “../util/timing.h”
file unit_texture.cpp
#include “unit_texture.h”#include <cmath>#include <iostream>#include “../coord/phys.h”#include “../coord/pixel.h”#include “../gamestate/game_spec.h”#include “../log/log.h”#include “../texture.h”#include “../util/math.h”#include “../util/math_constants.h”
file unit_texture.h
#include <cstdint>#include <vector>#include “../coord/phys.h”#include “../gamedata/graphic.gen.h”
file unit_type.cpp
#include “../gamestate/player.h”#include “../terrain/terrain_object.h”#include “../util/math_constants.h”#include “action.h”#include “unit.h”#include “unit_container.h”#include “unit_type.h”
file unit_type.h
#include <functional>#include <memory>#include <unordered_map>#include <vector>#include “../coord/phys.h”#include “../gamestate/cost.h”#include “attributes.h”
file algorithm.h
#include <algorithm>
file compiler.cpp
#include “compiler.h”#include <cxxabi.h>#include <dlfcn.h>#include “strings.h”#include <array>#include <iostream>#include <optional>#include <mutex>
file compiler.h
#include <ciso646>#include <string>#include <signal.h>

Defines

OAAPI

DLL entry-point decorations.

likely(x)
unlikely(x)
BREAKPOINT

Software breakpoint if you’re too lazy to add it in gdb but instead wanna add it into the code directly.

TYPEINFO(var)

As C++ is such a shit language, we found this awesome way to display a type of some variable as a warning.

Other hacks like wrong assignments work as well, but crash the compilation by error.

file bitstream.h
#include <cstring>#include <functional>#include “../../error/error.h”#include “../compiler.h”
file lzxd.cpp
#include “lzxd.h”#include <algorithm>#include <cinttypes>#include <cerrno>#include <cstdarg>#include <cstdint>#include <cstdio>#include <cstdlib>#include <cstring>#include <climits>#include “../../error/error.h”#include “../compiler.h”#include “bitstream.h”
file lzxd.h
#include <cstdlib>#include “bitstream.h”
file constexpr.h
#include <cstdlib>
file constinit_vector.cpp
#include “constinit_vector.h”#include “../testing/testing.h”

Variables

int val
int *ref
file constinit_vector.h
#include <algorithm>#include <memory>#include “compiler.h”
file csv.cpp
#include “csv.h”#include <cstring>#include “file.h”#include “../error/error.h”#include “../log/log.h”
file csv.h
#include <cstdlib>#include <cstring>#include <fstream>#include <string>#include <unordered_map>#include <vector>#include “../error/error.h”#include “compiler.h”#include “fslike/native.h”#include “path.h”
file enum.cpp
#include “enum.h”
file enum.h
#include <iostream>#include <typeinfo>#include “compiler.h”
file enum_test.cpp
#include “enum_test.h”#include “../testing/testing.h”
file enum_test.h
#include “enum.h”
file externalprofiler.cpp
#include “externalprofiler.h”#include <string>#include “config.h”#include “subprocess.h”#include “os.h”#include “../log/log.h”
file externalprofiler.h
file externalsstream.cpp
#include “externalsstream.h”
file externalsstream.h
#include <iostream>#include <string>
file fds.cpp
#include “fds.h”#include <stdarg.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include “pty.h”#include <unistd.h>#include “unicode.h”
file fds.h
#include <stdlib.h>#include <termios.h>
file file.cpp
#include “file.h”#include <cstdio>#include <fstream>#include <string>#include <sys/types.h>#include <sys/stat.h>#include “path.h”#include “filelike/native.h”#include “filelike/python.h”#include “../error/error.h”#include “../log/log.h”
file file.h
#include <memory>#include <string>#include <vector>#include “filelike/filelike.h”#include “../pyinterface/pyobject.h”
file filelike.cpp
#include “filelike.h”
file filelike.h
#include <iostream>#include <string>#include “../compiler.h”
file native.cpp
#include “native.h”#include <sstream>#include “../../error/error.h”
file native.cpp
#include “native.h”
file native.h
#include <fstream>#include <iostream>#include <memory>#include <string>#include “filelike.h”
file native.h
file python.cpp
#include “python.h”#include <type_traits>
file python.cpp
#include “python.h”#include “../../log/log.h”
file python.h
#include <iostream>#include <memory>#include <string>#include “filelike.h”#include “../../pyinterface/functional.h”#include “../../pyinterface/pyobject.h”
file python.h
#include <cstdint>#include <memory>#include <string>#include <vector>#include “../../pyinterface/functional.h”#include “../../pyinterface/pyobject.h”#include “fslike.h”#include “../path.h”#include “../file.h”
file fixed_point.cpp
#include “fixed_point.h”
file fixed_point.h
#include <algorithm>#include <climits>#include <cmath>#include <iomanip>#include <limits>#include <ostream>#include <type_traits>#include “misc.h”
file fixed_point_test.cpp
#include “fixed_point.h”#include <cstdint>#include “../testing/testing.h”#include “stringformatter.h”
file fps.cpp
#include “fps.h”#include <math.h>#include “timing.h”
file fps.h
#include “timer.h”
file directory.cpp
#include “directory.h”#include <cstdio>#include <dirent.h>#include <fcntl.h>#include <iostream>#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>#include “./native.h”#include “../file.h”#include “../filelike/native.h”#include “../misc.h”#include “../path.h”
file directory.h
#include <string>#include <sys/stat.h>#include <tuple>#include <vector>#include “fslike.h”
file fslike.cpp
#include “fslike.h”#include “../path.h”
file fslike.h
#include <cstdint>#include <iostream>#include <memory>#include <string>#include <utility>#include “../path.h”#include “../file.h”
file hash.cpp
#include <array>#include <limits.h>#include “hash.h”#include “misc.h”
file hash.h
#include <cstdlib>#include <array>#include <typeindex>
file hash_test.cpp
#include “hash.h”#include <array>#include “../testing/testing.h”#include “misc.h”
file init.cpp
#include “init.h”#include “../testing/testing.h”
file init.h
#include <functional>
file language.cpp
#include “language.h”
file language.h
file concat.h

Defines

CONCAT_1(OP, X)
CONCAT_2(OP, X, Y)
CONCAT_3(OP, X, Y, Z)
CONCAT_N(_1, _2, _3, NAME, ...)
CONCAT(OP, ...)
file math.h
#include <cmath>
file math_constants.h
#include <limits>
file matrix.cpp
#include “matrix.h”
file matrix.h
#include <array>#include <cmath>#include <cstring>#include <iostream>#include <type_traits>#include “vector.h”
file matrix_test.cpp
#include “matrix.h”#include “vector.h”#include “../testing/testing.h”
file misc.cpp
#include “misc.h”
file misc.h
#include <algorithm>#include <limits.h>#include <cmath>#include <cstring>#include <string>#include <vector>#include <memory>#include “../error/error.h”#include “compiler.h”
file misc_test.cpp
#include “misc.h”#include “../testing/testing.h”
file opengl.cpp
#include “opengl.h”#include <epoxy/gl.h>#include “../error/error.h”
file opengl.h
file os.cpp
#include “os.h”#include <memory>#include <unistd.h>#include “../log/log.h”#include “subprocess.h”
file os.h
#include <string>
file profiler.cpp
#include “profiler.h”#include “../engine.h”#include “../renderer/color.h”#include “misc.h”#include <chrono>#include <epoxy/gl.h>#include <iostream>
file profiler.h
#include <array>#include <chrono>#include <unordered_map>#include <vector>#include <string>

Variables

constexpr int MAX_DURATION_HISTORY = 100
constexpr int PROFILER_CANVAS_WIDTH = 250
constexpr int PROFILER_CANVAS_HEIGHT = 120
constexpr int PROFILER_CANVAS_POSITION_X = 0
constexpr int PROFILER_CANVAS_POSITION_Y = 300
constexpr float PROFILER_CANVAS_ALPHA = 0.6f
constexpr int PROFILER_COM_BOX_WIDTH = 30
constexpr int PROFILER_COM_BOX_HEIGHT = 15
file pty.h
#include <pty.h>
file quaternion.cpp
#include “quaternion.h”
file quaternion.h
#include <cmath>#include “matrix.h”#include “math_constants.h”#include “vector.h”#include “../error/error.h”#include “../log/log.h”
file quaternion_test.cpp
#include “quaternion.h”#include <cmath>#include “../error/error.h”#include “../log/log.h”#include “../testing/testing.h”
file repr.cpp
#include “repr.h”
file repr.h
#include <string>
file signal.h
#include <signal.h>
file stringformatter.cpp
#include “stringformatter.h”#include <array>
file stringformatter.h
#include <atomic>#include <memory>#include <type_traits>#include “../util/compiler.h”#include “externalsstream.h”#include “strings.h”
file strings.cpp
#include “strings.h”#include <cstdlib>#include <cstdio>#include <cstring>#include <memory>#include <string>#include <vector>#include “config.h”#include “../error/error.h”#include “compiler.h”
file strings.h
#include <cstdarg>#include <functional>#include <iomanip>#include <memory>#include <sstream>#include <string>#include <vector>

Defines

ATTRIBUTE_FORMAT(i, j)
file subprocess.cpp
#include “subprocess.h”#include <cstdlib>#include <cstring>#include <cerrno>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <fcntl.h>#include <sys/wait.h>#include “../log/log.h”#include “strings.h”
file subprocess.h
#include <string>#include <vector>
file thread_id.cpp
#include “thread_id.h”#include “config.h”#include <thread>
file thread_id.h
#include <stddef.h>
file timer.cpp
#include “timer.h”#include <ciso646>
file timer.h
#include <cstdint>#include “timing.h”
file timing.cpp
#include “timing.h”#include <chrono>#include <cstring>#include “../error/error.h”
file timing.h
#include <cstdint>
file unicode.cpp
#include “unicode.h”#include <string.h>
file unicode.h
#include <stdint.h>#include <stdlib.h>#include <string>
file variable.h
file vector.cpp
#include “vector.h”
file vector.h
#include <array>#include <cmath>#include <cstring>#include <iostream>#include <type_traits>#include “../error/error.h”#include “../log/log.h”
file vector_test.cpp
#include “vector.h”#include “../testing/testing.h”
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __init__.py
file __main__.py
file assets.py
file cab.py
file lzxdstream.py
file test.py
file test.py
file codegen.py
file coord.py
file cpp_testlist.py
file gamespec_structs.py
file listing.py
file main.py
file main.py
file main.py
file main.py
file binpack.py
file blendomatic.py
file changelog.py
file colortable.py
file content_snippet.py
file data_definition.py
file data_formatter.py
file entry_parser.py
file exportable.py
file generated_file.py
file header_snippet.py
file member_access.py
file members.py
file multisubtype_base.py
file struct_definition.py
file struct_snippet.py
file util.py
file driver.py
file drs.py
file fix_data.py
file game_versions.py
file civ.py
file empiresdat.py
file graphic.py
file maps.py
file playercolor.py
file research.py
file sound.py
file tech.py
file terrain.py
file unit.py
file langcodes.py
file langcodes_hd.py
file termcolors.py
file terrain_tile_size.py
file texture.py
file texture.py
file hdlanguagefile.py
file cutter.py
file hardcoded.py
file rename.py
file demo.py
file pefile.py
file peresource.py
file singlefile.py
file slp_converter_pool.py
file stringresource.py
file setup.py
file config_file.py
file location.py
file default_dirs.py
file devmode.py
file tests.py
file benchmark.py
file doctest.py
file list_processor.py
file testing.py
file testlist.py
file bytequeue.py
file context.py
file decorators.py
file abstract.py
file abstract.py
file fifo.py
file readonly.py
file stream.py
file files.py
file directory.py
file filecollection.py
file path.py
file union.py
file wrapper.py
file fsprinting.py
file iterators.py
file math.py
file profiler.py
file strings.py
file struct.py
file system.py
file threading.py
page md__mnt_c_Users_Jameson_Desktop_git_openage-new-doc-system_libopenage_renderer_vulkan_README

An experimental, mostly unimplemented Vulkan renderer. Can draw one triangle at best.

dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/audio
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/cabextract
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/codegen
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/util/compress
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/console
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/convert
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/coord
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/cppinterface
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/curve
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/cvar
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/cvar
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/convert/dataformat
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/datastructure
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/event/demo
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/error
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/event
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/event
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/util/filelike
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/util/filelike
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/renderer/font
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/util/fslike
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/util/fslike
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/game
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/convert/gamedata
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gamestate
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/guisys
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/convert/hardcoded
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/input
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/integration
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/convert/interface
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/job
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/guisys/link
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/guisys/private/livereload
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/log
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/log
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/util/macro
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/renderer/opengl
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/convert/opus
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/pathfinding
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/guisys/private/platforms
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/guisys/private
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/integration/private
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/integration/public
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/gui/guisys/public
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/pyinterface
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/renderer
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/renderer
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/renderer/resources
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/rng
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/shader
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/simulation
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/terrain
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/testing
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/testing
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/curve/tests
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/unit
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/util
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/openage/util
dir /mnt/c/Users/Jameson/Desktop/git/openage-new-doc-system/libopenage/renderer/vulkan
page index

openage: a volunteer project to create a free engine clone of the Genie Engine used by Age of Empires, Age of Empires II (HD) and Star Wars: Galactic Battlegrounds, comparable to projects like OpenMW, OpenRA, OpenSAGE, OpenTTD and OpenRCT2. At the moment we focus our efforts on the integration of Age of Empires II, while being primarily aimed at POSIX platforms such as GNU/Linux.

openage uses the original game assets (such as sounds and graphics), but (for obvious reasons) doesn’t ship them. To play, you require an original AoE II : TC installation or (installation via Wine or Steam-Linux).

Contact

Technical foundation

Goals

  • Fully authentic look and feel

    • This can only be approximated, since the behaviour of the original game is mostly undocumented, and guessing/experimenting can only get you this close

    • We will not implement useless artificial limitations (max 30 selectable units…)

  • Multiplayer (obviously)

  • Matchmaking and ranking with a haskell masterserver

  • Optionally, improvements over the original game

  • AI scripting in Python, you can use machine learning

  • Re-creating free game assets

  • An easily-moddable content format: yet another notation

  • An integrated Python console and API, comparable to blender

  • Awesome infrastructure such as our own Kevin CI service

But beware, for sanity reasons:

  • No network compatibility with the original game. You really wanna have the same problems again?

  • No binary compatibility with the original game. A one-way script to convert maps/savegames/missions to openage is planned though.

Current State of the Project

  • What features are currently implemented?

    • See /doc/status.md “doc/status.md”.

  • What’s the plan?

    • See /doc/milestones.md “doc/milestones.md”. We also have lists of crazy xor good ideas and a /doc/ideas/fr_technical_overview.md “technical overview for requested features”.

Installation Packages

Supported Platforms: Linux, Windows 10, MacOS X 10.14

  • For Linux check at repology if your distribution has any packages available or here for any future updates on *.deb and AppImage packages.

  • For Windows check our release page for the latest installer or here for nightly builds.

    NOTE: If you have any problems starting conversion or starting openage take a look into the package instructions and our /doc/troubleshooting.md “troubleshooting guide”.

    NOTE: For MacOSX we don’t have packages, but here you can check the the build status

    We also have building instructions in /doc/build_instructions/os_x_10.14_mojave.md “here”.

Dependencies, Building and Running

  • How do I get this to run on my box?

    • See /doc/building.md “doc/building.md”.

  • I compiled everything. Now how do I run it?

    • Execute ./run.

    • /doc/media_convert.md “The convert script” will transform original assets into openage formats, which are a lot saner and more moddable.

    • Use your brain and react to the things you’ll see.

  • Waaaaaah! It

    • segfaults

    • prints error messages I don’t want to read

    • ate my dog

All of those are features, not bugs.

To turn them off, use ./run --dont-segfault --no-errors --dont-eat-dog.

If this still does not help, try our /doc/troubleshooting.md “troubleshooting guide”, the contact section or the bug tracker.

Contributing

  • Being typical computer science students, we hate people.

  • Please don’t contact us.

  • Nobody likes Age of Empires anyway.

  • None of you is interested in making openage more awesome anyway.

  • We don’t want a community.

  • Don’t even think about trying to help.

Guidelines:

  • No bug reports or feature requests, the game is perfect as is.

  • Don’t try to fix any bugs, see above.

  • Don’t implement any features, your code is crap.

  • Don’t even think about sending a pull request.

  • Please ignore the easy tasks that could just be done.

  • Absolutely never ever participate in this boring community.

  • Don’t note the irony, you idiot.

To prevent accidental violation of one of those guidelines, you should never

Cheers, happy hecking.

Development Process

What does openage development look like in practice?

Can I help?

  • /doc/contributing.md “doc/contributing.md”.

All documentation is also in this repo:

  • Code documentation is embedded in the sources for Doxygen (see /doc/README.md “doc readme”).

  • Have a look at the doc directory. This folder tends to outdate when code changes.

License

GNU GPLv3 or later; see copying.md and legal/GPLv3.

I know that probably nobody is ever gonna look at the copying.md file, but if you want to contribute code to openage, please take the time to skim through it and add yourself to the authors list.