Six findings, all of them libakgl's, all closed. The memcheck run is clean. Not one of the four json_load_file calls in src/ was ever matched by a json_decref, so every asset load abandoned its parsed document: 1.5 KB per sprite, 2.1 KB per character, 9 KB per load of the 2x2 fixture map, and on the order of a megabyte for a real one. Each loader now releases it in the CLEANUP block it already had, on the success path as well as the failure one. akgl_registry_load_properties needed its loop moved inside the ATTEMPT block first: props is a borrowed reference into the document and is read after the block ends, so every exit from that loop leaked the whole tree. akgl_get_property copied a fixed AKGL_MAX_STRING_LENGTH bytes out of what SDL handed back, which is SDL's strdup of the value -- four bytes for "0.0". That read up to 4 KiB past the end of somebody else's allocation on every property read, returned whatever was there past the terminator, and would have faulted on a value that landed at the end of a page. It copies the value and its terminator now, and refuses a value too long for an akgl_String rather than truncating it into an unterminated buffer. The header note that described the overread as a quirk describes correct behaviour instead. The four savegame name tables wrote a fixed-width field starting at the registry key, and SDL sizes that allocation to the name. They read past it on every entry and put what they found into the save file: up to half a kilobyte of this process's heap per registered object, in a file a player might send to somebody. They stage through a zeroed buffer now, and a negative-array-size typedef fails the build if a table's width ever outgrows it. akgl_controller_list_keyboards never freed the array SDL_GetKeyboards allocated for it. A font could be opened and published and never handed back -- there was no way to close one, so a game that changed fonts between scenes leaked ten kilobytes each time, and loading over a live name leaked the font it displaced. akgl_text_unloadfont is that missing half, and akgl_text_loadfont calls it when it replaces a name, after the new font has opened so a failed reload leaves the caller with the font they had. A new public symbol takes the version to 0.4.0 and the soname with it: an 0.3 consumer cannot be handed this library and told it is the same ABI. tests/registry.c fills a destination with a sentinel and asserts the bytes past the terminator survive a read, which fails against the old copy. tests/text.c covers unload, double unload, unloading a name that was never registered, and replacement closing the displaced font. The JSON releases have no test of their own and cannot sensibly have one -- nothing in the public API can observe a jansson refcount -- so the memcheck run is their test, which is an argument for gating it rather than against. The two remaining findings are in deps/semver's own unit test, which is vendored. They are suppressed by function name, so a rewrite of those cases comes back as a finding. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
705 lines
25 KiB
C
705 lines
25 KiB
C
/**
|
|
* @file game.c
|
|
* @brief Implements the game subsystem.
|
|
*/
|
|
|
|
#include <SDL3/SDL.h>
|
|
#include <SDL3_image/SDL_image.h>
|
|
#include <SDL3_mixer/SDL_mixer.h>
|
|
#include <SDL3_ttf/SDL_ttf.h>
|
|
#include <stdio.h>
|
|
#include <akerror.h>
|
|
#include <semver.h>
|
|
|
|
#include <akstdlib.h>
|
|
#include <akgl/game.h>
|
|
#include <akgl/controller.h>
|
|
#include <akgl/tilemap.h>
|
|
#include <akgl/sprite.h>
|
|
#include <akgl/heap.h>
|
|
#include <akgl/registry.h>
|
|
#include <akgl/staticstring.h>
|
|
#include <akgl/iterator.h>
|
|
#include <akgl/physics.h>
|
|
#include <akgl/error.h>
|
|
#include <akgl/SDL_GameControllerDB.h>
|
|
|
|
SDL_Window *window = NULL;
|
|
|
|
// Currently active objects
|
|
akgl_RenderBackend *renderer;
|
|
akgl_PhysicsBackend *physics;
|
|
SDL_FRect *camera;
|
|
akgl_Tilemap *gamemap;
|
|
|
|
// Default objects
|
|
akgl_RenderBackend _akgl_renderer;
|
|
akgl_PhysicsBackend _akgl_physics;
|
|
SDL_FRect _akgl_camera;
|
|
akgl_Tilemap _akgl_gamemap;
|
|
|
|
MIX_Audio *bgm = NULL;
|
|
MIX_Mixer *akgl_mixer = NULL;
|
|
MIX_Track *akgl_tracks[AKGL_GAME_AUDIO_MAX_TRACKS];
|
|
akgl_Game game;
|
|
|
|
static akerr_ErrorContext *write_exact(const void *ptr, size_t size, size_t nmemb, FILE *fp)
|
|
{
|
|
size_t transferred;
|
|
|
|
return aksl_fwrite(ptr, size, nmemb, fp, &transferred);
|
|
}
|
|
|
|
/**
|
|
* @brief Widest name field any of the save tables writes.
|
|
*
|
|
* The spritesheet table is the widest at #AKGL_SPRITE_SHEET_MAX_FILENAME_LENGTH;
|
|
* the other three are name lengths half that or less.
|
|
*/
|
|
#define AKGL_GAME_SAVE_MAX_NAME_FIELD AKGL_SPRITE_SHEET_MAX_FILENAME_LENGTH
|
|
|
|
/**
|
|
* @brief Fail the build if a table ever declares a field wider than the staging buffer.
|
|
*
|
|
* A negative array size is a compile error, so widening one of these constants
|
|
* without widening #AKGL_GAME_SAVE_MAX_NAME_FIELD cannot get past the compiler
|
|
* and turn back into the overread this buffer exists to prevent.
|
|
*/
|
|
typedef char akgl_game_save_name_field_fits[
|
|
((AKGL_ACTOR_MAX_NAME_LENGTH <= AKGL_GAME_SAVE_MAX_NAME_FIELD) &&
|
|
(AKGL_SPRITE_MAX_NAME_LENGTH <= AKGL_GAME_SAVE_MAX_NAME_FIELD) &&
|
|
(AKGL_SPRITE_SHEET_MAX_FILENAME_LENGTH <= AKGL_GAME_SAVE_MAX_NAME_FIELD) &&
|
|
(AKGL_SPRITE_MAX_CHARACTER_NAME_LENGTH <= AKGL_GAME_SAVE_MAX_NAME_FIELD)) ? 1 : -1];
|
|
|
|
/**
|
|
* @brief Write a registry key as a fixed-width, zero-padded field.
|
|
*
|
|
* The name tables are read back without a length prefix, so every entry has to
|
|
* occupy exactly @p width bytes. Writing @p width bytes *from the key itself*
|
|
* is what the four iterators used to do, and the key is an SDL allocation sized
|
|
* to the name -- 40 bytes for `benchactor0`. That read past the end of it on
|
|
* every entry, and put whatever was next to it in the heap into the save file:
|
|
* up to half a kilobyte of this process's memory per registered object, in a
|
|
* file a player might send to somebody else.
|
|
*
|
|
* Staging through a zeroed buffer costs one `memset` per entry and makes the
|
|
* padding deterministic, which the reader wanted anyway.
|
|
*
|
|
* @param name The registry key. Required, and NUL-terminated -- it comes from
|
|
* SDL's property table, which stores C strings.
|
|
* @param width Field width in bytes, including the padding. Required to be at
|
|
* most #AKGL_GAME_SAVE_MAX_NAME_FIELD; the compile-time check
|
|
* above is what keeps that true for the four call sites.
|
|
* @param fp Open output stream. Required.
|
|
* @return `NULL` on success, otherwise an error context owned by the caller.
|
|
* @throws AKERR_NULLPOINTER If @p name or @p fp is `NULL`.
|
|
* @throws AKERR_OUTOFBOUNDS If @p width exceeds the staging buffer.
|
|
*/
|
|
static akerr_ErrorContext *write_name_field(const char *name, size_t width, FILE *fp)
|
|
{
|
|
char field[AKGL_GAME_SAVE_MAX_NAME_FIELD];
|
|
|
|
PREPARE_ERROR(e);
|
|
FAIL_ZERO_RETURN(e, name, AKERR_NULLPOINTER, "NULL name");
|
|
FAIL_ZERO_RETURN(e, fp, AKERR_NULLPOINTER, "NULL file pointer");
|
|
FAIL_NONZERO_RETURN(
|
|
e,
|
|
(width > sizeof(field)),
|
|
AKERR_OUTOFBOUNDS,
|
|
"Name field width %zu exceeds the staging buffer (%zu)",
|
|
width,
|
|
sizeof(field));
|
|
|
|
memset(&field, 0x00, sizeof(field));
|
|
strncpy((char *)&field, name, (width - 1));
|
|
PASS(e, write_exact((char *)&field, 1, width, fp));
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
|
|
static akerr_ErrorContext *read_exact(void *ptr, size_t size, size_t nmemb, FILE *fp)
|
|
{
|
|
size_t transferred;
|
|
|
|
return aksl_fread(ptr, size, nmemb, fp, &transferred);
|
|
}
|
|
|
|
void akgl_game_lowfps(void)
|
|
{
|
|
SDL_Log("Low FPS! %d", game.fps);
|
|
return;
|
|
}
|
|
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_init()
|
|
{
|
|
int screenwidth = 0;
|
|
int screenheight = 0;
|
|
|
|
int i = 0;
|
|
PREPARE_ERROR(e);
|
|
// First, before anything that can raise: everything below reports through
|
|
// AKGL_ERR_* codes, and a code raised before its name is registered prints
|
|
// as "Unknown Error" in the stack trace the caller is left holding.
|
|
PASS(e, akgl_error_init());
|
|
strncpy((char *)&game.libversion, AKGL_VERSION, 32);
|
|
game.gameStartTime = SDL_GetTicksNS();
|
|
game.lastIterTime = game.gameStartTime;
|
|
game.lastFPSTime = game.gameStartTime;
|
|
game.lowfpsfunc = &akgl_game_lowfps;
|
|
game.statelock = SDL_CreateMutex();
|
|
FAIL_ZERO_RETURN(e, game.statelock, AKGL_ERR_SDL, "%s", SDL_GetError());
|
|
PASS(e, akgl_game_state_lock());
|
|
FAIL_ZERO_RETURN(e, strlen((char *)&game.name), AKERR_NULLPOINTER, "Must provide game name");
|
|
FAIL_ZERO_RETURN(e, strlen((char *)&game.version), AKERR_NULLPOINTER, "Must provide game version");
|
|
FAIL_ZERO_RETURN(e, strlen((char *)&game.uri), AKERR_NULLPOINTER, "Must provide game uri");
|
|
PASS(e, akgl_heap_init());
|
|
PASS(e, akgl_registry_init_actor());
|
|
PASS(e, akgl_registry_init_sprite());
|
|
PASS(e, akgl_registry_init_spritesheet());
|
|
PASS(e, akgl_registry_init_character());
|
|
PASS(e, akgl_registry_init_font());
|
|
PASS(e, akgl_registry_init_music());
|
|
PASS(e, akgl_registry_init_properties());
|
|
PASS(e, akgl_registry_init_actor_state_strings());
|
|
|
|
SDL_SetAppMetadata(game.name, game.version, game.uri);
|
|
|
|
for ( i = 0 ; i < AKGL_MAX_CONTROL_MAPS; i++ ) {
|
|
memset(&GAME_ControlMaps[i], 0x00, sizeof(akgl_ControlMap));
|
|
}
|
|
|
|
FAIL_ZERO_RETURN(
|
|
e,
|
|
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD | SDL_INIT_AUDIO),
|
|
AKGL_ERR_SDL,
|
|
"Couldn't initialize SDL: %s",
|
|
SDL_GetError());
|
|
|
|
// Load the Game Controller DB
|
|
|
|
for ( i = 0; i < AKGL_SDL_GAMECONTROLLER_DB_LEN ; i++ ) {
|
|
if ( SDL_AddGamepadMapping(SDL_GAMECONTROLLER_DB[i]) == -1 ) {
|
|
FAIL_ZERO_RETURN(e, 0, AKGL_ERR_SDL, "%s", SDL_GetError());
|
|
}
|
|
}
|
|
PASS(e, akgl_controller_open_gamepads());
|
|
|
|
FAIL_ZERO_RETURN(
|
|
e,
|
|
MIX_Init(),
|
|
AKGL_ERR_SDL,
|
|
"Couldn't initialize audio: %s",
|
|
SDL_GetError());
|
|
akgl_mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, 0);
|
|
FAIL_ZERO_RETURN(
|
|
e,
|
|
akgl_mixer,
|
|
AKGL_ERR_SDL,
|
|
"Unable to create mixer device: %s",
|
|
SDL_GetError());
|
|
|
|
FAIL_ZERO_RETURN(
|
|
e,
|
|
TTF_Init(),
|
|
AKGL_ERR_SDL,
|
|
"Couldn't initialize front engine: %s",
|
|
SDL_GetError());
|
|
|
|
camera = &_akgl_camera;
|
|
renderer = &_akgl_renderer;
|
|
physics = &_akgl_physics;
|
|
gamemap = &_akgl_gamemap;
|
|
|
|
PASS(e, akgl_game_state_unlock());
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_state_lock(void)
|
|
{
|
|
PREPARE_ERROR(e);
|
|
SDL_Time totaltime = 0;
|
|
|
|
while ( totaltime < AKGL_TIME_ONESEC_MS ) {
|
|
if ( SDL_TryLockMutex(game.statelock) == true ) {
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
totaltime += 100;
|
|
SDL_Delay(100);
|
|
}
|
|
FAIL_RETURN(e, AKGL_ERR_SDL, "%s", SDL_GetError());
|
|
}
|
|
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_state_unlock(void)
|
|
{
|
|
PREPARE_ERROR(e);
|
|
SDL_UnlockMutex(game.statelock);
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
|
|
void akgl_game_updateFPS()
|
|
{
|
|
SDL_Time curTime;
|
|
curTime = SDL_GetTicksNS();
|
|
if ( (curTime - game.lastFPSTime) > AKGL_TIME_ONESEC_NS ) {
|
|
game.fps = game.framesSinceUpdate;
|
|
game.framesSinceUpdate = 0;
|
|
game.lastFPSTime = curTime;
|
|
}
|
|
if ( game.fps < 30 ) {
|
|
game.lowfpsfunc();
|
|
}
|
|
game.framesSinceUpdate += 1;
|
|
game.lastIterTime = curTime;
|
|
}
|
|
|
|
/*
|
|
* entity name -> pointer map tables
|
|
*/
|
|
|
|
/**
|
|
* @brief Write one actor's name and save-time address to the name table.
|
|
*
|
|
* An `SDL_EnumerateProperties` callback. The name is written at a fixed
|
|
* #AKGL_ACTOR_MAX_NAME_LENGTH bytes so the reader can walk the table without a
|
|
* length prefix, and the pointer is written raw -- it is not a pointer the
|
|
* loader will ever dereference, only a key it maps back to the object that has
|
|
* the same name next run.
|
|
*
|
|
* @param userdata The open output stream, as a `FILE *`. Required.
|
|
* @param props #AKGL_REGISTRY_ACTOR, supplied by SDL.
|
|
* @param name The actor's registry key. Read for
|
|
* #AKGL_ACTOR_MAX_NAME_LENGTH bytes regardless of its actual
|
|
* length, so a shorter key is read past its end.
|
|
*
|
|
* @warning Ends in `FINISH_NORETURN`: an unhandled error here logs a stack trace
|
|
* and then calls libakerror's unhandled-error handler, which by default
|
|
* **exits the process**. A failed write during a save terminates the
|
|
* game rather than returning an error.
|
|
*/
|
|
void akgl_game_save_actorname_iterator(void *userdata, SDL_PropertiesID props, const char *name)
|
|
{
|
|
FILE *fp = (FILE *)userdata;
|
|
akgl_Actor *actor = NULL;
|
|
PREPARE_ERROR(e);
|
|
ATTEMPT {
|
|
FAIL_ZERO_BREAK(e, fp, AKERR_NULLPOINTER, "NULL file pointer");
|
|
CATCH(e, write_name_field(name, AKGL_ACTOR_MAX_NAME_LENGTH, fp));
|
|
actor = SDL_GetPointerProperty(props, name, NULL);
|
|
CATCH(e, write_exact(&actor, 1, sizeof(akgl_Actor *), fp));
|
|
} CLEANUP {
|
|
} PROCESS(e) {
|
|
} FINISH_NORETURN(e);
|
|
}
|
|
|
|
/**
|
|
* @brief Write one sprite's name and save-time address to the name table.
|
|
*
|
|
* As akgl_game_save_actorname_iterator, but the name field is
|
|
* #AKGL_SPRITE_MAX_NAME_LENGTH wide.
|
|
*
|
|
* @param userdata The open output stream, as a `FILE *`. Required.
|
|
* @param props #AKGL_REGISTRY_SPRITE, supplied by SDL.
|
|
* @param name The sprite's registry key, written at fixed width.
|
|
*
|
|
* @warning Terminates the process on an unhandled error. See
|
|
* akgl_game_save_actorname_iterator.
|
|
*/
|
|
void akgl_game_save_spritename_iterator(void *userdata, SDL_PropertiesID props, const char *name)
|
|
{
|
|
FILE *fp = (FILE *)userdata;
|
|
akgl_Sprite *sprite = NULL;
|
|
PREPARE_ERROR(e);
|
|
ATTEMPT {
|
|
FAIL_ZERO_BREAK(e, fp, AKERR_NULLPOINTER, "NULL file pointer");
|
|
sprite = SDL_GetPointerProperty(props, name, NULL);
|
|
CATCH(e, write_name_field(name, AKGL_SPRITE_MAX_NAME_LENGTH, fp));
|
|
CATCH(e, write_exact(&sprite, 1, sizeof(akgl_Sprite *), fp));
|
|
} CLEANUP {
|
|
} PROCESS(e) {
|
|
} FINISH_NORETURN(e);
|
|
}
|
|
|
|
/**
|
|
* @brief Write one spritesheet's name and save-time address to the name table.
|
|
*
|
|
* As akgl_game_save_actorname_iterator, but the name field is
|
|
* #AKGL_SPRITE_SHEET_MAX_FILENAME_LENGTH wide -- the widest of the four, since
|
|
* a spritesheet is keyed by its resolved path.
|
|
*
|
|
* @param userdata The open output stream, as a `FILE *`. Required.
|
|
* @param props #AKGL_REGISTRY_SPRITESHEET, supplied by SDL.
|
|
* @param name The spritesheet's registry key, written at fixed width.
|
|
*
|
|
* @warning Terminates the process on an unhandled error. See
|
|
* akgl_game_save_actorname_iterator.
|
|
* @note This is the table the loader disagrees with: it reads every table at
|
|
* #AKGL_ACTOR_MAX_NAME_LENGTH, so a save containing any spritesheet cannot
|
|
* be read back. TODO.md, "Known and still open" item 7.
|
|
*/
|
|
void akgl_game_save_spritesheetname_iterator(void *userdata, SDL_PropertiesID props, const char *name)
|
|
{
|
|
FILE *fp = (FILE *)userdata;
|
|
akgl_SpriteSheet *spritesheet = NULL;
|
|
PREPARE_ERROR(e);
|
|
ATTEMPT {
|
|
FAIL_ZERO_BREAK(e, fp, AKERR_NULLPOINTER, "NULL file pointer");
|
|
spritesheet = SDL_GetPointerProperty(props, name, NULL);
|
|
CATCH(e, write_name_field(name, AKGL_SPRITE_SHEET_MAX_FILENAME_LENGTH, fp));
|
|
CATCH(e, write_exact(&spritesheet, 1, sizeof(akgl_SpriteSheet *), fp));
|
|
} CLEANUP {
|
|
} PROCESS(e) {
|
|
} FINISH_NORETURN(e);
|
|
}
|
|
|
|
/**
|
|
* @brief Write one character's name and save-time address to the name table.
|
|
*
|
|
* As akgl_game_save_actorname_iterator, but the name field is
|
|
* #AKGL_SPRITE_MAX_CHARACTER_NAME_LENGTH wide.
|
|
*
|
|
* @param userdata The open output stream, as a `FILE *`. Required.
|
|
* @param props #AKGL_REGISTRY_CHARACTER, supplied by SDL.
|
|
* @param name The character's registry key, written at fixed width.
|
|
*
|
|
* @warning Terminates the process on an unhandled error. See
|
|
* akgl_game_save_actorname_iterator.
|
|
*/
|
|
void akgl_game_save_charactername_iterator(void *userdata, SDL_PropertiesID props, const char *name)
|
|
{
|
|
FILE *fp = (FILE *)userdata;
|
|
PREPARE_ERROR(e);
|
|
akgl_Character *character = NULL;
|
|
ATTEMPT {
|
|
FAIL_ZERO_BREAK(e, fp, AKERR_NULLPOINTER, "NULL file pointer");
|
|
character = SDL_GetPointerProperty(props, name, NULL);
|
|
CATCH(e, write_name_field(name, AKGL_SPRITE_MAX_CHARACTER_NAME_LENGTH, fp));
|
|
CATCH(e, write_exact(&character, 1, sizeof(akgl_Character *), fp));
|
|
} CLEANUP {
|
|
} PROCESS(e) {
|
|
} FINISH_NORETURN(e);
|
|
}
|
|
|
|
/**
|
|
* @brief Write all four name-to-address tables, each with its terminator.
|
|
*
|
|
* Actors, sprites, spritesheets, characters, in that order -- which is the order
|
|
* akgl_game_load reads them back in. Each table is the registry enumerated one
|
|
* entry at a time, followed by a zeroed name field and a zeroed pointer that the
|
|
* reader stops on.
|
|
*
|
|
* @param fp The open save-game stream. Required.
|
|
* @return `NULL` on success, otherwise an error context owned by the caller.
|
|
* @throws AKERR_NULLPOINTER If @p fp is `NULL`.
|
|
* @throws AKERR_IO On a stream error or a short write while emitting a
|
|
* terminator.
|
|
*
|
|
* @note Only the terminators are written through the error-reporting path. The
|
|
* entries themselves go through `SDL_EnumerateProperties`, whose callbacks
|
|
* cannot report failure upward and instead terminate the process -- so a
|
|
* write error mid-table never reaches this function's return value.
|
|
*/
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_save_actors(FILE *fp)
|
|
{
|
|
PREPARE_ERROR(e);
|
|
// Each name table ends with a zeroed name field and a zeroed pointer, which
|
|
// is what akgl_game_load_objectnamemap() looks for to stop reading. The
|
|
// terminator has to come from a buffer at least as long as the longest name
|
|
// field: writing N bytes from the address of a single char would emit N-1
|
|
// bytes of whatever happened to follow it on the stack, which both leaks
|
|
// stack contents into the save file and produces a sentinel the loader
|
|
// cannot recognize.
|
|
char nullbuf[AKGL_SPRITE_SHEET_MAX_FILENAME_LENGTH];
|
|
|
|
memset((void *)&nullbuf, 0x00, sizeof(nullbuf));
|
|
|
|
ATTEMPT {
|
|
FAIL_ZERO_BREAK(e, fp, AKERR_NULLPOINTER, "NULL file pointer");
|
|
// write the actor name pointer table
|
|
SDL_EnumerateProperties(
|
|
AKGL_REGISTRY_ACTOR,
|
|
&akgl_game_save_actorname_iterator,
|
|
(void *)fp);
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, AKGL_ACTOR_MAX_NAME_LENGTH, fp));
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, sizeof(akgl_Actor *), fp));
|
|
// write the sprite name pointer table
|
|
SDL_EnumerateProperties(
|
|
AKGL_REGISTRY_SPRITE,
|
|
&akgl_game_save_spritename_iterator,
|
|
(void *)fp);
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, AKGL_SPRITE_MAX_NAME_LENGTH, fp));
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, sizeof(akgl_Sprite *), fp));
|
|
// write the spritesheet name pointer table
|
|
SDL_EnumerateProperties(
|
|
AKGL_REGISTRY_SPRITESHEET,
|
|
&akgl_game_save_spritesheetname_iterator,
|
|
(void *)fp);
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, AKGL_SPRITE_SHEET_MAX_FILENAME_LENGTH, fp));
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, sizeof(akgl_SpriteSheet *), fp));
|
|
// write the character name pointer table
|
|
SDL_EnumerateProperties(
|
|
AKGL_REGISTRY_CHARACTER,
|
|
&akgl_game_save_charactername_iterator,
|
|
(void *)fp);
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, AKGL_SPRITE_MAX_CHARACTER_NAME_LENGTH, fp));
|
|
CATCH(e, write_exact((void *)&nullbuf, 1, sizeof(akgl_Character *), fp));
|
|
} CLEANUP {
|
|
} PROCESS(e) {
|
|
} FINISH(e, true);
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_save(char *fpath)
|
|
{
|
|
FILE *fp = NULL;
|
|
PREPARE_ERROR(e);
|
|
|
|
ATTEMPT {
|
|
FAIL_ZERO_BREAK(e, fpath, AKERR_NULLPOINTER, "NULL file path");
|
|
CATCH(e, aksl_fopen(fpath, "wb", &fp));
|
|
CATCH(e, write_exact(&game, 1, sizeof(akgl_Game), fp));
|
|
CATCH(e, akgl_game_save_actors(fp));
|
|
} CLEANUP {
|
|
// CLEANUP must precede PROCESS: with the two transposed, the fclose
|
|
// lands inside the PROCESS switch and only runs when an error context
|
|
// exists and reports success, so an ordinary save never flushed or
|
|
// closed its stream.
|
|
if ( fp != NULL )
|
|
fclose(fp);
|
|
} PROCESS(e) {
|
|
} FINISH(e, true);
|
|
SUCCEED_RETURN(e); // SUCCEED_NORETURN if in main().
|
|
}
|
|
|
|
/**
|
|
* @brief Read one name table back, building an old-address to current-object map.
|
|
*
|
|
* This is the mechanism that makes a save file portable across runs. Objects are
|
|
* serialized carrying the addresses they had at save time; those addresses mean
|
|
* nothing now, but the table says which *name* lived at each one, and the name
|
|
* still resolves through the registry. So each entry becomes
|
|
* `"0x7f..." -> current object`, and a deserialized pointer can be translated by
|
|
* looking up its printed form.
|
|
*
|
|
* The keys are the old pointers rendered with `%p`, because SDL property sets
|
|
* take string keys only.
|
|
*
|
|
* Reading stops at the terminator -- a zeroed name and a zeroed pointer.
|
|
*
|
|
* @param fp The open save-game stream, positioned at the start of a
|
|
* table. Required.
|
|
* @param map The property set to fill in. Required, and created by the
|
|
* caller.
|
|
* @param namelength Width of the table's name field, which must match what the
|
|
* corresponding save iterator wrote. It also sizes a
|
|
* variable-length array on the stack.
|
|
* @param ptrlength Width of the table's pointer field, i.e. `sizeof` the
|
|
* pointer type that table holds.
|
|
* @param registry The registry to resolve names against -- #AKGL_REGISTRY_ACTOR
|
|
* for the actor table, and so on.
|
|
* @return `NULL` on success, otherwise an error context owned by the caller.
|
|
* @throws AKERR_EOF If the stream ends before a terminator is found, which is
|
|
* what a truncated save file looks like.
|
|
* @throws AKERR_IO On a stream error.
|
|
* @throws AKERR_NULLPOINTER If @p fp is `NULL`, by way of the read wrapper.
|
|
*
|
|
* @note A name in the table that is no longer in @p registry maps to `NULL`
|
|
* rather than being reported: the entry is written with whatever
|
|
* `SDL_GetPointerProperty` returned.
|
|
*/
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_load_objectnamemap(FILE *fp, SDL_PropertiesID map, int namelength, int ptrlength, SDL_PropertiesID registry)
|
|
{
|
|
void *ptr = NULL;
|
|
char ptrstring[32];
|
|
char objname[namelength];
|
|
int retval = 0;
|
|
bool done = false;
|
|
|
|
PREPARE_ERROR(e);
|
|
// The ATTEMPT block sits inside the loop on purpose. CATCH reports a
|
|
// failure by breaking, and a break binds to the innermost enclosing switch
|
|
// or loop, so a CATCH written directly inside `while` would leave the loop
|
|
// and then fall through to SUCCEED_RETURN -- reporting a truncated or
|
|
// corrupt name table as a successful load.
|
|
while ( done == false ) {
|
|
ATTEMPT {
|
|
CATCH(e, read_exact((void *)&objname, 1, namelength, fp));
|
|
CATCH(e, read_exact((void *)&ptr, 1, ptrlength, fp));
|
|
// End of the map
|
|
if ( ptr == 0x00 && objname[0] == 0x00 ) {
|
|
done = true;
|
|
break;
|
|
}
|
|
// The map allows us to say "Object X has a reference to object Y at
|
|
// address Z. The object they had at address Z was named A. Our current
|
|
// instance of object named A is at address B. So we map address Z to
|
|
// address B, so that we can reconnect function pointers on objects loaded
|
|
// from the save game state."
|
|
|
|
// SDL_Properties objects can only use string keys, so we can't use the
|
|
// old pointer as a key without first converting it to a string.
|
|
CATCH(e, aksl_memset((void *)&ptrstring, 0x00, 32));
|
|
snprintf((char *)&ptrstring, 32, "%p", ptr);
|
|
SDL_SetPointerProperty(
|
|
map,
|
|
ptrstring,
|
|
SDL_GetPointerProperty(registry, objname, NULL));
|
|
} CLEANUP {
|
|
} PROCESS(e) {
|
|
} FINISH(e, true);
|
|
};
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
|
|
/**
|
|
* @brief Refuse a save file unless its version matches the running one exactly.
|
|
*
|
|
* Both strings are parsed as semver and compared with `"="` -- exact equality,
|
|
* not compatibility. That is deliberate and strict: a save file is a raw memory
|
|
* image of `akgl_Game` and the object tables, so any change to a struct layout
|
|
* invalidates it, and semver has no way to say "the layout did not move".
|
|
*
|
|
* @param versiontype What is being compared -- `"library"` or `"game"`. Used
|
|
* only to build the message, but required, since a bare
|
|
* "incompatible version" error would not say which.
|
|
* @param newversion The version read out of the save file. Required.
|
|
* @param curversion The version of the running program or library. Required.
|
|
* @return `NULL` when the two match, otherwise an error context owned by the
|
|
* caller.
|
|
* @throws AKERR_NULLPOINTER If any of the three arguments is `NULL`.
|
|
* @throws AKERR_VALUE If either string is not valid semver. The message says
|
|
* which side it came from.
|
|
* @throws AKERR_API If both parse but are not equal. The message quotes both.
|
|
*/
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_load_versioncmp(char *versiontype, char *newversion, char *curversion)
|
|
{
|
|
semver_t current_version = {};
|
|
semver_t compare_version = {};
|
|
PREPARE_ERROR(e);
|
|
FAIL_ZERO_RETURN(e, versiontype, AKERR_NULLPOINTER, "NULL argument");
|
|
FAIL_ZERO_RETURN(e, curversion, AKERR_NULLPOINTER, "NULL argument");
|
|
FAIL_ZERO_RETURN(e, newversion, AKERR_NULLPOINTER, "NULL argument");
|
|
|
|
ATTEMPT {
|
|
// Check save game library version
|
|
FAIL_NONZERO_BREAK(
|
|
e,
|
|
semver_parse((const char *)curversion, ¤t_version),
|
|
AKERR_VALUE,
|
|
"Invalid semantic %s version in current game: %s",
|
|
versiontype,
|
|
(char *)curversion);
|
|
FAIL_NONZERO_BREAK(
|
|
e,
|
|
semver_parse((const char *)newversion, &compare_version),
|
|
AKERR_VALUE,
|
|
"Invalid semantic %s version in save game: %s",
|
|
versiontype,
|
|
(char *)&newversion);
|
|
FAIL_ZERO_BREAK(
|
|
e,
|
|
semver_satisfies(compare_version, current_version, "="),
|
|
AKERR_API,
|
|
"Incompatible save game %s version (%s != %s)",
|
|
versiontype,
|
|
curversion,
|
|
(char *)&newversion);
|
|
} CLEANUP {
|
|
semver_free(¤t_version);
|
|
semver_free(&compare_version);
|
|
} PROCESS(e) {
|
|
} FINISH(e, true);
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_load(char *fpath)
|
|
{
|
|
akgl_Game savegame;
|
|
SDL_PropertiesID actormap;
|
|
SDL_PropertiesID spritemap;
|
|
SDL_PropertiesID spritesheetmap;
|
|
SDL_PropertiesID charactermap;
|
|
FILE *fp = NULL;
|
|
|
|
PREPARE_ERROR(e);
|
|
FAIL_ZERO_RETURN(e, fpath, AKERR_NULLPOINTER, "NULL file path");
|
|
|
|
ATTEMPT {
|
|
CATCH(e, aksl_fopen(fpath, "rb", &fp));
|
|
CATCH(e, read_exact((void *)&savegame, 1, sizeof(akgl_Game), fp));
|
|
CATCH(e, akgl_game_load_versioncmp("library", (char *)&savegame.libversion, (char *)AKGL_VERSION));
|
|
CATCH(e, akgl_game_load_versioncmp("game", (char *)&savegame.version, (char *)&game.version));
|
|
FAIL_NONZERO_RETURN(
|
|
e,
|
|
strncmp((char *)&savegame.name, (char *)&game.name, 256),
|
|
AKERR_API,
|
|
"Savegame is not compatible with this game");
|
|
FAIL_NONZERO_RETURN(
|
|
e,
|
|
strncmp((char *)&savegame.uri, (char *)&game.uri, 256),
|
|
AKERR_API,
|
|
"Savegame is not compatible with this game");
|
|
|
|
memcpy((void *)&game, (void *)&savegame, sizeof(akgl_Game));
|
|
// Load actor name map
|
|
actormap = SDL_CreateProperties();
|
|
CATCH(e, akgl_game_load_objectnamemap(fp, actormap, AKGL_ACTOR_MAX_NAME_LENGTH, sizeof(akgl_Actor *), AKGL_REGISTRY_ACTOR));
|
|
// Load sprite name map
|
|
spritemap = SDL_CreateProperties();
|
|
CATCH(e, akgl_game_load_objectnamemap(fp, spritemap, AKGL_ACTOR_MAX_NAME_LENGTH, sizeof(akgl_Sprite *), AKGL_REGISTRY_SPRITE));
|
|
// Load spritesheet name map
|
|
spritesheetmap = SDL_CreateProperties();
|
|
CATCH(e, akgl_game_load_objectnamemap(fp, spritesheetmap, AKGL_ACTOR_MAX_NAME_LENGTH, sizeof(akgl_SpriteSheet *), AKGL_REGISTRY_SPRITESHEET));
|
|
// Load character name map
|
|
charactermap = SDL_CreateProperties();
|
|
CATCH(e, akgl_game_load_objectnamemap(fp, charactermap, AKGL_ACTOR_MAX_NAME_LENGTH, sizeof(akgl_Character *), AKGL_REGISTRY_CHARACTER));
|
|
// Now that we have all of our pointer maps built, we can load the actual binary objects and reset their pointers
|
|
} CLEANUP {
|
|
if ( fp != NULL ) {
|
|
fclose(fp);
|
|
}
|
|
} PROCESS(e) {
|
|
} FINISH(e, true);
|
|
|
|
SUCCEED_RETURN(e);
|
|
}
|
|
|
|
akerr_ErrorContext AKERR_NOIGNORE *akgl_game_update(akgl_Iterator *opflags)
|
|
{
|
|
PREPARE_ERROR(e);
|
|
akgl_Iterator defflags = {
|
|
.flags = (AKGL_ITERATOR_OP_LAYERMASK | AKGL_ITERATOR_OP_LAYERMASK),
|
|
.layerid = 0
|
|
};
|
|
SDL_Time curTime = SDL_GetTicksNS();
|
|
akgl_Actor *actor = NULL;
|
|
|
|
if ( opflags == NULL ) {
|
|
opflags = &defflags;
|
|
}
|
|
|
|
PASS(e, akgl_game_state_lock());
|
|
|
|
akgl_game_updateFPS();
|
|
|
|
for ( int i = 0; i < AKGL_TILEMAP_MAX_LAYERS; i++ ) {
|
|
if ( opflags == &defflags ) {
|
|
opflags->layerid = i;
|
|
}
|
|
for ( int j = 0; j < AKGL_MAX_HEAP_ACTOR; j++ ) {
|
|
actor = &HEAP_ACTOR[j];
|
|
if ( actor->refcount == 0 ) {
|
|
continue;
|
|
}
|
|
if ( AKGL_BITMASK_HAS(opflags->flags, AKGL_ITERATOR_OP_TILEMAPSCALE) ) {
|
|
PASS(e, akgl_tilemap_scale_actor(gamemap, actor));
|
|
} else {
|
|
actor->scale = 1.0;
|
|
}
|
|
PASS(e, actor->updatefunc(actor));
|
|
}
|
|
}
|
|
PASS(e, physics->simulate(physics, NULL));
|
|
PASS(e, renderer->draw_world(renderer, NULL));
|
|
PASS(e, akgl_game_state_unlock());
|
|
SUCCEED_RETURN(e);
|
|
}
|