16 Commits
Author SHA1 Message Date
YourWishes 49b97ba508 Switch cutscene system to a set of pre deffed buffers 2026-09-13 09:58:57 -05:00
YourWishes 6c11d8165d Revert "Add CUTSCENE_INSERT item to splice another cutscene's items in place"
This reverts commit 6af0e9cf28.
2026-09-13 09:29:23 -05:00
YourWishesandClaude Sonnet 5 93554b39ba Add DUSK_TRACK_MEMORY allocation tracker and memoryCheckUnfreed report
memoryAllocate() becomes a macro capturing __FILE__/__LINE__ into a
fixed-size tracking table when DUSK_TRACK_MEMORY is enabled (Linux only
for now), so a leak surviving to shutdown can be traced back to its call
site. Replaces engineDispose's hard assertTrue with memoryCheckUnfreed(),
which reports unfreed allocations (with call sites when tracking is on,
just a count otherwise) instead of aborting.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-13 09:19:24 -05:00
YourWishesandClaude Sonnet 5 6af0e9cf28 Add CUTSCENE_INSERT item to splice another cutscene's items in place
Unlike CUTSCENE (a one-way jump that replaces the running cutscene),
INSERT splices a referenced cutscene's items into the running one and
resumes right after itself once they run out. Backed by a small return
stack on CUTSCENE_SYSTEM so inserts can nest.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-13 08:56:26 -05:00
YourWishesandClaude Sonnet 5 083deb8357 Move cutscene item type enum and authoring macros to their own headers
cutsceneitemtype_t moves from cutsceneitem.h into cutsceneitembase.h,
alongside a new CUTSCENE_ITEM(TYPE, UNION_NAME, ...) shorthand that
fills in a cutsceneitem_t literal's .type and union member together.

Every CUTSCENE_* authoring macro (CUTSCENE_WAIT, CUTSCENE_TEXT,
CUTSCENE_AUDIO_PLAY, etc.) moves out of the single, ever-growing
cutscene.h into the header of the item type it actually authors,
built on top of CUTSCENE_ITEM. cutscene.h now only holds cutscene_t
itself plus the CUTSCENE/CUTSCENE_REFERENCE/CUTSCENE_CUTSCENE macros,
which aren't tied to any one item type. Every relocated macro also
gained a proper JSDoc-style comment block with @param tags.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 22:30:23 -05:00
YourWishesandClaude Sonnet 5 ffb375faeb Add battle abilities and wire them into START_BATTLE cutscene parsing
Adds a battleability_t enum (starting with FIRE) and a fixed
abilities[8] array on battlefighter_t. Extends the START_BATTLE
cutscene item to parse an optional per-enemy "abilities" JSON array
(via a new cutsceneJsonLookupBattleAbility name lookup) and copies
abilities onto every spawned fighter, from the party roster for
allies and from the parsed config for enemies.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 22:30:12 -05:00
YourWishesandClaude Sonnet 5 b8cbd8ff6a Make party and save-slot init/new-game operate on SAVE.slot directly
party.c's functions no longer take a party_t* - they always operate on
SAVE.slot.party, since gameplay only ever has one active party. That
forced the same change on saveSlotInit/saveSlotNewGame (they called
partyInit/partyAddMember internally), so those are now parameterless
too, always resetting/seeding SAVE.slot. Callers building a save at a
specific index (new-game creation, slot deletion) now set
SAVE.slotCurrent first instead of building an independent local struct -
safe since the select-save screen is only ever reached before any
gameplay starts.

saveSlotWriteJSON/saveSlotReadJSON deliberately keep their explicit
saveslot_t* parameter - they're genuine serialization primitives used
by the save-device layer and tests against arbitrary structs, unrelated
to the single-current-party assumption. saveSlotReadJSON's internal
reset is now a plain memset instead of delegating to the now-global-only
saveSlotInit().

Updates test_save/test_savedevice/test_savedevicelinux/test_saveslot for
the new signatures. Note: test_savedevice/test_savedevicelinux/test_save
have pre-existing failures in this sandbox unrelated to this change -
savetestfixture.c swaps $HOME, but saveDeviceLinuxGetDirectory actually
derives the save path from ASSET.baseDirectory (the executable's own
location), so the fixture's sandboxing never actually applies. test_
saveslot.c (which doesn't depend on that fixture) passes 15/15.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 21:30:08 -05:00
YourWishesandClaude Sonnet 5 c2bd761383 Remove testbattle - superseded by the JSON-driven battle cutscene
testBattleStart() was never actually called anywhere (its only trace
was a stray unused include in uimainmenu.c) - battletest.jsonc's
START_BATTLE/REGULAR_BATTLE flow replaces it.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 21:14:50 -05:00
YourWishesandClaude Sonnet 5 878e3438c8 Complete REGULAR_BATTLE immediately, fix stale saveslot tests
REGULAR_BATTLE previously never completed on its own, hanging any
cutscene that reached it - START_BATTLE already waits out the whole
encounter and returns to the overworld before this item ever runs, so
it's now a completes-immediately hook point for future regular-battle-
specific follow-up.

Also updates test_saveslot.c for the mapName/partyMembers schema
additions: the round-trip test now writes a valid map name for its
in-use slot, "missingFieldsUseDefaults" is replaced with a test for the
blank-slot short-circuit it was actually hitting, and a new regression
test locks in that an in-use slot with no map name is treated as corrupt.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 19:59:16 -05:00
YourWishesandClaude Sonnet 5 3da65370e0 Add requireStrMin save-JSON shorthand
Replaces the hand-rolled mapName missing/null/empty check in
saveSlotVer1ReadJSON with a reusable macro.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-12 19:55:17 -05:00
YourWishesandClaude Sonnet 5 83e646cba9 Load the save's map on select, seed a real new-game slot, fix readString off-by-one
New games now go through saveSlotNewGame (starting party + default map
name) instead of the empty saveSlotInit, and selecting a save loads its
stored map instead of the hardcoded boot-time overworld. Save loading now
requires an in-use slot to have a non-empty map name, treating a blank one
as corruption instead of silently faking a default.

Also fixes a real off-by-one in the readString save-JSON macro: it passed
its maxLength (documented as excluding the null terminator) straight
through as stringCopy's destSize, which needs +1 for the terminator - so a
string exactly at the length limit (e.g. "overworld", 9 chars) always
asserted "src is too long".

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-10 23:14:44 -05:00
YourWishesandClaude Sonnet 5 0566166af4 Persist party across saves and flag/warn on corrupt save slots
Party moves off a global singleton onto each save slot, letting
START_BATTLE pick specific active-order members to bring into a fight,
and round-trips through save/load via saveslotver1. A corrupt slot load
now flags the cache and shows a red "Corrupted Save" warning in the
select-save UI instead of silently resetting.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-10 14:19:03 -05:00
YourWishesandClaude Sonnet 5 ed0b8c3911 Exit delete mode on save select after delete or back button
Previously deleting a save left the panel in delete mode, and pressing
back while in delete mode closed the whole save-select screen instead
of just returning to the normal load view.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-09 21:38:28 -05:00
YourWishesandClaude Sonnet 5 03d753a83f Move cutscene JSON parsing entirely into the async loader phase
File read, yyjson parse, and all item dispatch now happen in
assetCutsceneLoaderAsync - none of it touches the main thread now that
CUTSCENE items defer their nested asset resolution to start time. The
sync phase is now just a state flip, kept only so assetUpdate()'s
onLoaded dispatch (which only fires for entries finishing via the sync
path) still runs.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-09 21:34:47 -05:00
YourWishes cf51ed1988 Fixed cutscene item cutscene trying to recursively load 2026-09-09 21:21:50 -05:00
YourWishesandClaude Sonnet 5 70f46e89d3 Merge branch 'raw-json-maps' into main
Load map chunks from raw JSON at runtime instead of a baked DCF/DMF
step, add a reusable perf timing module, fix a real PSP logDebug/logError
Memory Stick I/O cost bug, and switch chunk tile storage to a dense
minified grid.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-09 15:34:08 -05:00
95 changed files with 2161 additions and 985 deletions

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
{
"items": [
{
"type": "START_BATTLE",
"encounterType": "REGULAR",
"fleeAvailable": true,
"enemies": [
{
"stats": { "attack": 8, "defense": 4, "magic": 0, "speed": 5, "luck": 2 },
"healthMax": 30,
"mpMax": 0
},
{
"stats": { "attack": 6, "defense": 3, "magic": 0, "speed": 7, "luck": 2 },
"healthMax": 20,
"mpMax": 0
}
]
},
{
"type": "REGULAR_BATTLE"
}
]
}
+6
View File
@@ -73,6 +73,12 @@ msgstr "Select Save"
msgid "ui.select_save.empty" msgid "ui.select_save.empty"
msgstr "Empty Slot" msgstr "Empty Slot"
msgid "ui.select_save.corrupt"
msgstr "Corrupted Save"
msgid "ui.select_save.corrupt_warning"
msgstr "This save file is corrupted and could not be loaded. Please contact support if this issue persists."
msgid "ui.select_save.slot_format" msgid "ui.select_save.slot_format"
msgstr "%s Lv.%d %s" msgstr "%s Lv.%d %s"
@@ -1 +1 @@
{"tiles":[[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[6,0],[2,0],[2,0],[2,0],[2,0],[2,0],[2,0],[7,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[4,0],[12,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[9,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0]],"meshes":[{"file":"house_5_3.dmf","pos":[1,1,0]}],"entities":[{"type":"global","globalId":3,"pos":[8,8,1]},{"type":"item","itemId":1,"quantity":1,"pos":[12,2,0]}],"areas":[{"min":[11,3,0],"max":[16,9,10],"callbackId":1,"notify":3,"trigger":6}]} {"tiles":[[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],null,null,null,null,null,[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[6,0],[2,0],[2,0],[2,0],[2,0],[2,0],[2,0],[7,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[1,1],[1,1],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[4,0],[12,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[3,0],[1,1],[1,1],[5,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[8,0],[4,0],[4,0],[9,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0],[1,0]],"meshes":[{"file":"house_5_3.dmf","pos":[1,1,0]}],"entities":[{"type":"global","globalId":3,"pos":[8,8,1]},{"type":"global","globalId":4,"pos":[12,2,0]}],"areas":[{"min":[11,3,0],"max":[16,9,10],"callbackId":1,"notify":3,"trigger":6}]}
+1
View File
@@ -27,6 +27,7 @@ target_link_libraries(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
) )
set(DUSK_BACKTRACE ON CACHE BOOL "Enable backtrace support for assert failures.") set(DUSK_BACKTRACE ON CACHE BOOL "Enable backtrace support for assert failures.")
set(DUSK_TRACK_MEMORY ON CACHE BOOL "Track memoryAllocate() call sites to help find memory leaks.")
# Define platform-specific macros. # Define platform-specific macros.
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
+6
View File
@@ -50,6 +50,12 @@ if(DUSK_BACKTRACE)
) )
endif() endif()
if(DUSK_TRACK_MEMORY)
target_compile_definitions(${DUSK_LIBRARY_TARGET_NAME} PUBLIC
DUSK_TRACK_MEMORY
)
endif()
# Includes # Includes
target_include_directories(${DUSK_LIBRARY_TARGET_NAME} target_include_directories(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
@@ -76,20 +76,13 @@ size_t assetCutsceneComputePoolSize(yyjson_val *itemsArr) {
return size; return size;
} }
void assetCutsceneFreeParsed(assetcutsceneoutput_t *out) { // Raw file-read scratch space - fixed-size (ASSET_CUTSCENE_FILE_SIZE_MAX is
if(out->items != NULL) { // already a hard cap below) rather than malloc'd per load. Safe to share:
memoryFree(out->items); // ASSET only ever runs one async load at a time on its single load thread
out->items = NULL; // (see assetUpdateAsync), and yyjson_read copies everything it needs out
} // of this buffer into the doc before this function returns, so it's free
if(out->pool != NULL) { // to be overwritten by the next load.
memoryFree(out->pool); static uint8_t CUTSCENE_FILE_BUFFER[ASSET_CUTSCENE_FILE_SIZE_MAX];
out->pool = NULL;
}
if(out->doc != NULL) {
yyjson_doc_free(out->doc);
out->doc = NULL;
}
}
errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) { errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL"); assertNotNull(loading, "Loading cannot be NULL");
@@ -101,8 +94,6 @@ errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
errorOk(); errorOk();
} }
assertNull(loading->loading.cutscene.buffer, "Buffer already defined?");
assetfile_t *file = &loading->loading.cutscene.file; assetfile_t *file = &loading->loading.cutscene.file;
assetLoaderErrorChain(loading, assetLoaderErrorChain(loading,
assetFileInit(file, loading->entry->name, NULL, NULL) assetFileInit(file, loading->entry->name, NULL, NULL)
@@ -115,9 +106,10 @@ errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
} }
size_t fileSize = (size_t)file->size; size_t fileSize = (size_t)file->size;
uint8_t *buffer = memoryAllocate(fileSize);
assetLoaderErrorChain(loading, assetFileOpen(file)); assetLoaderErrorChain(loading, assetFileOpen(file));
assetLoaderErrorChain(loading, assetFileRead(file, buffer, fileSize)); assetLoaderErrorChain(
loading, assetFileRead(file, CUTSCENE_FILE_BUFFER, fileSize)
);
assertTrue( assertTrue(
file->lastRead == file->size, file->lastRead == file->size,
"Failed to read entire cutscene file." "Failed to read entire cutscene file."
@@ -125,8 +117,85 @@ errorret_t assetCutsceneLoaderAsync(assetloading_t *loading) {
assetLoaderErrorChain(loading, assetFileClose(file)); assetLoaderErrorChain(loading, assetFileClose(file));
assetLoaderErrorChain(loading, assetFileDispose(file)); assetLoaderErrorChain(loading, assetFileDispose(file));
loading->loading.cutscene.buffer = buffer; // Parsing is pure CPU work with no main-thread dependency (every item
loading->loading.cutscene.size = fileSize; // type's load callback just parses fields - see cutsceneCutsceneLoad's
// doc comment for how CUTSCENE items avoid needing one), so it happens
// right here instead of bouncing to the sync phase.
yyjson_doc *doc = yyjson_read(
(char *)CUTSCENE_FILE_BUFFER, fileSize,
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS
);
if(doc == NULL) {
assetLoaderErrorThrow(loading, "Failed to parse cutscene JSON");
}
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *itemsArr = yyjson_obj_get(root, "items");
if(!yyjson_is_arr(itemsArr)) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(loading, "Cutscene JSON is missing an 'items' array");
}
size_t itemCount = yyjson_arr_size(itemsArr);
if(itemCount > CUTSCENE_LOADED_ITEMS_MAX) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(
loading, "Cutscene has more than CUTSCENE_LOADED_ITEMS_MAX items"
);
}
cutscenepause_t pause = CUTSCENE_PAUSE_DEFAULT;
yyjson_val *pauseArr = yyjson_obj_get(root, "pause");
if(yyjson_is_arr(pauseArr)) {
if(!cutsceneJsonParsePauseFlags(pauseArr, &pause)) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(
loading, "Cutscene JSON has an invalid 'pause' flag"
);
}
}
size_t poolSize = assetCutsceneComputePoolSize(itemsArr);
if(poolSize > CUTSCENE_LOADED_POOL_SIZE_MAX) {
yyjson_doc_free(doc);
assetLoaderErrorThrow(
loading, "Cutscene needs more pool space than CUTSCENE_LOADED_POOL_SIZE_MAX"
);
}
// Everything structural has validated by this point, so it's safe to
// start overwriting the shared CUTSCENE_LOADED_ITEMS/POOL buffers - a
// per-item parse failure past this point still leaves them partially
// overwritten, but that's fine: any load failure here already sends the
// game into the fatal-error overlay (see cutsceneSystemLoad/
// cutsceneCutsceneResolve), so nothing keeps running against stale data.
memoryZero(CUTSCENE_LOADED_ITEMS, itemCount * sizeof(cutsceneitem_t));
size_t poolOffset = 0;
yyjson_arr_iter itemIter = yyjson_arr_iter_with(itemsArr);
yyjson_val *itemVal;
uint8_t index = 0;
while((itemVal = yyjson_arr_iter_next(&itemIter)) != NULL) {
errorret_t itemResult = assetCutsceneParseItem(
loading, itemVal, &CUTSCENE_LOADED_ITEMS[index],
CUTSCENE_LOADED_POOL, &poolOffset, index
);
if(errorIsNotOk(itemResult)) {
yyjson_doc_free(doc);
errorChain(itemResult);
}
index++;
}
// Takes ownership of doc - marker/cutscene-reference name fields point
// directly into it (see cutsceneCutsceneRefLoad/cutsceneMarkerLoad), so
// it must outlive this load, replacing whatever the previously loaded
// cutscene left behind.
cutsceneLoadedSetDoc(doc);
CUTSCENE_LOADED_SCENE.itemCount = (uint8_t)itemCount;
CUTSCENE_LOADED_SCENE.pause = pause;
CUTSCENE_LOADED_SCENE.dataSize = 0;
loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE; loading->loading.cutscene.state = ASSET_CUTSCENE_LOADING_STATE_PARSE;
loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC; loading->entry->state = ASSET_ENTRY_STATE_PENDING_SYNC;
errorOk(); errorOk();
@@ -143,73 +212,15 @@ errorret_t assetCutsceneLoaderSync(assetloading_t *loading) {
errorOk(); errorOk();
} }
assetcutsceneoutput_t *out = &loading->entry->data.cutscene; // Everything else already happened in the async phase - see
uint8_t *buffer = loading->loading.cutscene.buffer; // assetCutsceneLoaderAsync. This flip still has to happen from here
assertNotNull(buffer, "Cutscene data should have been loaded by now."); // rather than the async phase setting LOADED directly, since
size_t bufferSize = loading->loading.cutscene.size; // assetUpdate() only fires an entry's onLoaded callback for entries
// that finish via this sync path.
yyjson_doc *doc = yyjson_read( assertTrue(
(char *)buffer, bufferSize, loading->loading.cutscene.state == ASSET_CUTSCENE_LOADING_STATE_PARSE,
YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS "Unexpected cutscene loading state."
); );
memoryFree(buffer);
loading->loading.cutscene.buffer = NULL;
if(doc == NULL) {
assetLoaderErrorThrow(loading, "Failed to parse cutscene JSON");
}
out->doc = doc;
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *itemsArr = yyjson_obj_get(root, "items");
if(!yyjson_is_arr(itemsArr)) {
assetCutsceneFreeParsed(out);
assetLoaderErrorThrow(loading, "Cutscene JSON is missing an 'items' array");
}
size_t itemCount = yyjson_arr_size(itemsArr);
if(itemCount > UINT8_MAX) {
assetCutsceneFreeParsed(out);
assetLoaderErrorThrow(loading, "Cutscene has more than 255 items");
}
cutscenepause_t pause = CUTSCENE_PAUSE_DEFAULT;
yyjson_val *pauseArr = yyjson_obj_get(root, "pause");
if(yyjson_is_arr(pauseArr)) {
if(!cutsceneJsonParsePauseFlags(pauseArr, &pause)) {
assetCutsceneFreeParsed(out);
assetLoaderErrorThrow(
loading, "Cutscene JSON has an invalid 'pause' flag"
);
}
}
out->items = memoryAllocate(itemCount * sizeof(cutsceneitem_t));
memoryZero(out->items, itemCount * sizeof(cutsceneitem_t));
size_t poolSize = assetCutsceneComputePoolSize(itemsArr);
out->pool = poolSize > 0 ? memoryAllocate(poolSize) : NULL;
size_t poolOffset = 0;
yyjson_arr_iter itemIter = yyjson_arr_iter_with(itemsArr);
yyjson_val *itemVal;
uint8_t index = 0;
while((itemVal = yyjson_arr_iter_next(&itemIter)) != NULL) {
errorret_t itemResult = assetCutsceneParseItem(
loading, itemVal, &out->items[index], out->pool, &poolOffset, index
);
if(errorIsNotOk(itemResult)) {
assetCutsceneFreeParsed(out);
errorChain(itemResult);
}
index++;
}
out->cutscene.items = out->items;
out->cutscene.itemCount = (uint8_t)itemCount;
out->cutscene.pause = pause;
out->cutscene.dataSize = 0;
loading->entry->state = ASSET_ENTRY_STATE_LOADED; loading->entry->state = ASSET_ENTRY_STATE_LOADED;
errorOk(); errorOk();
} }
@@ -219,7 +230,10 @@ errorret_t assetCutsceneDispose(assetentry_t *entry) {
assertTrue(entry->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type."); assertTrue(entry->type == ASSET_LOADER_TYPE_CUTSCENE, "Invalid type.");
assertIsMainThread("Must be called from the main thread."); assertIsMainThread("Must be called from the main thread.");
assetCutsceneFreeParsed(&entry->data.cutscene); // Nothing to free here - a loaded cutscene's data lives in the fixed,
// shared CUTSCENE_LOADED_SCENE/ITEMS/POOL globals (see cutscenesystem.h),
// not per-entry storage; this entry only ever drove the read+parse
// pipeline into them.
errorOk(); errorOk();
} }
@@ -8,6 +8,7 @@
#pragma once #pragma once
#include "asset/assetfile.h" #include "asset/assetfile.h"
#include "rpg/cutscene/cutscene.h" #include "rpg/cutscene/cutscene.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/cutscene/item/cutsceneitem.h" #include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/item/json/cutscenejsonpool.h" #include "rpg/cutscene/item/json/cutscenejsonpool.h"
#include "yyjson.h" #include "yyjson.h"
@@ -30,15 +31,16 @@ typedef enum {
typedef struct { typedef struct {
assetfile_t file; assetfile_t file;
assetcutsceneloadingstate_t state; assetcutsceneloadingstate_t state;
uint8_t *buffer;
size_t size;
} assetcutsceneloaderloading_t; } assetcutsceneloaderloading_t;
typedef struct { typedef struct {
cutscene_t cutscene; // Nothing - a loaded cutscene's data lives entirely in the fixed,
cutsceneitem_t *items; // shared CUTSCENE_LOADED_SCENE/ITEMS/POOL globals (see cutscenesystem.h)
uint8_t *pool; // that assetCutsceneLoaderAsync parses directly into, not per-entry
yyjson_doc *doc; // storage. This entry only ever exists to drive the read+parse
// pipeline, and is unlocked (see cutsceneSystemLoad/
// cutsceneCutsceneResolve) the instant that finishes.
uint8_t unused;
} assetcutsceneoutput_t; } assetcutsceneoutput_t;
/** /**
@@ -69,19 +71,15 @@ errorret_t assetCutsceneParseItem(
const uint8_t index const uint8_t index
); );
/**
* Frees whatever of out->items/out->pool/out->doc is currently non-NULL
* and clears them - shared by both the normal disposer and every parse
* failure path's cleanup.
*
* @param out The output to free.
*/
void assetCutsceneFreeParsed(assetcutsceneoutput_t *out);
/** /**
* Asynchronous loader for cutscene assets. Reads the raw JSONC file bytes * Asynchronous loader for cutscene assets. Reads the raw JSONC file bytes
* into the loading buffer so the sync phase can parse without blocking the * and, in the same call, parses them directly into the fixed, shared
* main thread on I/O. * CUTSCENE_LOADED_ITEMS/CUTSCENE_LOADED_POOL buffers (see cutscenesystem.h)
* - no heap allocation at all, since only one cutscene is ever resident.
* None of that work touches the main thread (every item type's load
* callback is pure parsing now; CUTSCENE items defer their nested asset
* resolution to cutsceneCutsceneStart), so doing it all here keeps a large
* cutscene from ever blocking a frame.
* *
* @param loading Loading information for the asset being loaded. * @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure of the load operation. * @return Error code indicating success or failure of the load operation.
@@ -89,8 +87,11 @@ void assetCutsceneFreeParsed(assetcutsceneoutput_t *out);
errorret_t assetCutsceneLoaderAsync(assetloading_t *loading); errorret_t assetCutsceneLoaderAsync(assetloading_t *loading);
/** /**
* Synchronous loader for cutscene assets. Parses the JSONC previously read * Synchronous loader for cutscene assets. All actual work already
* by the async phase into a heap-allocated cutsceneitem_t array + pool. * happened in the async phase - this only flips the entry to LOADED,
* which must happen through this sync callback (rather than the async
* phase setting it directly) so assetUpdate()'s onLoaded dispatch, which
* only fires for entries finishing via the sync path, still runs.
* *
* @param loading Loading information for the asset being loaded. * @param loading Loading information for the asset being loaded.
* @return Error code indicating success or failure of the load operation. * @return Error code indicating success or failure of the load operation.
+2
View File
@@ -108,5 +108,7 @@ errorret_t engineDispose(void) {
errorChain(assetDispose()); errorChain(assetDispose());
perfDispose(); perfDispose();
memoryCheckUnfreed();
errorOk(); errorOk();
} }
-3
View File
@@ -10,6 +10,3 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
battlefighter.c battlefighter.c
party.c party.c
) )
# Subdirs
add_subdirectory(testbattle)
+17
View File
@@ -0,0 +1,17 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
typedef enum {
BATTLE_ABILITY_NULL,
BATTLE_ABILITY_FIRE,
BATTLE_ABILITY_COUNT
} battleability_t;
+4
View File
@@ -7,6 +7,9 @@
#pragma once #pragma once
#include "error/error.h" #include "error/error.h"
#include "battleability.h"
#define BATTLE_FIGHTER_ABILITY_COUNT_MAX 8
// An empty status means the slot in BATTLE.fighters is unused. // An empty status means the slot in BATTLE.fighters is unused.
typedef enum { typedef enum {
@@ -55,6 +58,7 @@ typedef struct {
uint16_t mpMax; uint16_t mpMax;
battlefighterstats_t stats; battlefighterstats_t stats;
battleability_t abilities[BATTLE_FIGHTER_ABILITY_COUNT_MAX];
} battlefighter_t; } battlefighter_t;
/** /**
+18 -12
View File
@@ -8,22 +8,25 @@
#include "party.h" #include "party.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "save/save.h"
party_t PARTY;
void partyInit(void) { void partyInit(void) {
memoryZero(&PARTY, sizeof(party_t)); party_t *party = &SAVE.slot.party;
memoryZero(party, sizeof(party_t));
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) { for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
PARTY.members[i].id = i; party->members[i].id = i;
} }
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) { for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
PARTY.order[i] = PARTY_ORDER_EMPTY; party->order[i] = PARTY_ORDER_EMPTY;
} }
} }
uint8_t partyGetAvailableMember(void) { uint8_t partyGetAvailableMember(void) {
const party_t *party = &SAVE.slot.party;
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) { for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
if(PARTY.members[i].status == BATTLE_FIGHTER_STATUS_NULL) return i; if(party->members[i].status == BATTLE_FIGHTER_STATUS_NULL) return i;
} }
return 0xFF; return 0xFF;
@@ -34,18 +37,20 @@ battlefighter_t *partyAddMember(
const uint16_t healthMax, const uint16_t healthMax,
const uint16_t mpMax const uint16_t mpMax
) { ) {
party_t *party = &SAVE.slot.party;
const uint8_t index = partyGetAvailableMember(); const uint8_t index = partyGetAvailableMember();
if(index == 0xFF) return NULL; if(index == 0xFF) return NULL;
battlefighter_t *member = &PARTY.members[index]; battlefighter_t *member = &party->members[index];
battleFighterInit( battleFighterInit(
member, BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER, member, BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
stats, healthMax, mpMax stats, healthMax, mpMax
); );
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) { for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
if(PARTY.order[i] != PARTY_ORDER_EMPTY) continue; if(party->order[i] != PARTY_ORDER_EMPTY) continue;
PARTY.order[i] = index; party->order[i] = index;
break; break;
} }
@@ -55,9 +60,10 @@ battlefighter_t *partyAddMember(
battlefighter_t *partyGetOrderMember(const uint8_t slot) { battlefighter_t *partyGetOrderMember(const uint8_t slot) {
assertTrue(slot < PARTY_ACTIVE_SIZE_MAX, "Invalid party order slot"); assertTrue(slot < PARTY_ACTIVE_SIZE_MAX, "Invalid party order slot");
const uint8_t index = PARTY.order[slot]; party_t *party = &SAVE.slot.party;
const uint8_t index = party->order[slot];
if(index == PARTY_ORDER_EMPTY) return NULL; if(index == PARTY_ORDER_EMPTY) return NULL;
return &PARTY.members[index]; return &party->members[index];
} }
void partySetOrder(const uint8_t slot, const uint8_t memberIndex) { void partySetOrder(const uint8_t slot, const uint8_t memberIndex) {
@@ -67,5 +73,5 @@ void partySetOrder(const uint8_t slot, const uint8_t memberIndex) {
"Invalid party member index" "Invalid party member index"
); );
PARTY.order[slot] = memberIndex; SAVE.slot.party.order[slot] = memberIndex;
} }
+13 -10
View File
@@ -22,24 +22,25 @@ typedef struct {
uint8_t order[PARTY_ACTIVE_SIZE_MAX]; uint8_t order[PARTY_ACTIVE_SIZE_MAX];
} party_t; } party_t;
extern party_t PARTY;
/** /**
* Initializes the party system with an empty roster and order. * Initializes the current save slot's party (SAVE.slot.party) with an
* empty roster and order.
*/ */
void partyInit(void); void partyInit(void);
/** /**
* Gets an available (unused) party member slot index. * Gets an available (unused) member slot index in the current save slot's
* party.
* *
* @return The index of an available slot, or 0xFF if the party is full. * @return The index of an available slot, or 0xFF if the party is full.
*/ */
uint8_t partyGetAvailableMember(void); uint8_t partyGetAvailableMember(void);
/** /**
* Adds a member to the party roster in the next available slot. Party * Adds a member to the current save slot's party roster in the next
* members are always allies controlled by the player. If there is a * available slot. Party members are always allies controlled by the
* free active order slot, the new member is placed into it. * player. If there is a free active order slot, the new member is placed
* into it.
* *
* @param stats The member's base combat stats. * @param stats The member's base combat stats.
* @param healthMax The member's maximum health. * @param healthMax The member's maximum health.
@@ -54,7 +55,8 @@ battlefighter_t *partyAddMember(
); );
/** /**
* Gets the roster member currently occupying an active order slot. * Gets the roster member currently occupying an active order slot in the
* current save slot's party.
* *
* @param slot The active order slot to query. * @param slot The active order slot to query.
* @return Pointer to the member in that slot, or NULL if the slot is * @return Pointer to the member in that slot, or NULL if the slot is
@@ -63,8 +65,9 @@ battlefighter_t *partyAddMember(
battlefighter_t *partyGetOrderMember(const uint8_t slot); battlefighter_t *partyGetOrderMember(const uint8_t slot);
/** /**
* Assigns a roster member to an active order slot, replacing whatever * Assigns a roster member to an active order slot in the current save
* was there. Use PARTY_ORDER_EMPTY to clear a slot. * slot's party, replacing whatever was there. Use PARTY_ORDER_EMPTY to
* clear a slot.
* *
* @param slot The active order slot to assign. * @param slot The active order slot to assign.
* @param memberIndex The roster member index to place there, or * @param memberIndex The roster member index to place there, or
@@ -1,10 +0,0 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
testbattle.c
)
@@ -1,43 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "testbattle.h"
#include "rpg/battle/battle.h"
#include "scene/scene.h"
void testBattleStart(void) {
battleInit();
const battlefighterstats_t allyOneStats =
{ .attack = 10, .defense = 5, .magic = 0, .speed = 10, .luck = 0 };
const battlefighterstats_t allyTwoStats =
{ .attack = 8, .defense = 4, .magic = 0, .speed = 8, .luck = 0 };
const battlefighterstats_t enemyOneStats =
{ .attack = 6, .defense = 3, .magic = 0, .speed = 6, .luck = 0 };
const battlefighterstats_t enemyTwoStats =
{ .attack = 7, .defense = 3, .magic = 0, .speed = 5, .luck = 0 };
battleAddFighter(
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
allyOneStats, 30, 10
);
battleAddFighter(
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
allyTwoStats, 25, 10
);
battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemyOneStats, 20, 5
);
battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemyTwoStats, 20, 5
);
battleStart(BATTLE_ENCOUNTER_REGULAR, true);
sceneSet(SCENE_TYPE_BATTLE);
}
@@ -1,16 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
/**
* TEMPORARY test hook: sets up a hardcoded mock battle and switches to the
* battle scene, so the battle scene (camera/fighters/HUD) can be seen and
* played without a real encounter trigger yet.
*/
void testBattleStart(void);
+28 -477
View File
@@ -1,6 +1,6 @@
/** /**
* Copyright (c) 2025 Dominic Masters * Copyright (c) 2025 Dominic Masters
* *
* This software is released under the MIT License. * This software is released under the MIT License.
* https://opensource.org/licenses/MIT * https://opensource.org/licenses/MIT
*/ */
@@ -19,6 +19,18 @@ typedef struct cutscene_s {
size_t dataSize; size_t dataSize;
} cutscene_t; } cutscene_t;
/**
* Declares a standalone, named cutscene_t (and its backing item array) -
* the entry point for a C-authored cutscene.
*
* @param NAME Suffix for the generated CUTSCENE_##NAME cutscene/items
* statics.
* @param SIZE Bytes of custom user data this cutscene needs, carved out
* of CUTSCENE_SYSTEM.data while it runs.
* @param PAUSE_TYPE Suffix of the CUTSCENE_PAUSE_* flag(s) to apply
* while this cutscene runs (e.g. NONE, ALL).
* @param ... The cutscene's cutsceneitem_t entries, in order.
*/
#define CUTSCENE(NAME, SIZE, PAUSE_TYPE, ...) \ #define CUTSCENE(NAME, SIZE, PAUSE_TYPE, ...) \
static const cutsceneitem_t CUTSCENE_##NAME##_ITEMS[] = { __VA_ARGS__ }; \ static const cutsceneitem_t CUTSCENE_##NAME##_ITEMS[] = { __VA_ARGS__ }; \
static const cutscene_t CUTSCENE_##NAME = { \ static const cutscene_t CUTSCENE_##NAME = { \
@@ -28,486 +40,25 @@ typedef struct cutscene_s {
.dataSize = SIZE \ .dataSize = SIZE \
}; };
/**
* References a CUTSCENE(NAME, ...)-declared cutscene by name.
*
* @param CUTSCENE The cutscene's NAME, as passed to CUTSCENE(...).
*/
#define CUTSCENE_REFERENCE(CUTSCENE) \ #define CUTSCENE_REFERENCE(CUTSCENE) \
&CUTSCENE_##CUTSCENE &CUTSCENE_##CUTSCENE
#define CUTSCENE_TEXT(TEXT) \ /**
{ .type = CUTSCENE_ITEM_TYPE_TEXT, .text = { .text = TEXT } } * Hands control over to another CUTSCENE(NAME, ...)-declared cutscene.
* Has no dedicated item header of its own - cutscenecutsceneref_t is
#define CUTSCENE_TEXT_MINI(TEXT, X, Y, Z, DURATION) \ * defined inline in cutsceneitem.h, tightly bound to the asset/loader
{ \ * system, so this shorthand stays here too.
.type = CUTSCENE_ITEM_TYPE_TEXT_MINI, \ *
.textMini = { \ * @param CUTSCENE The referenced cutscene's NAME, as passed to
.text = TEXT, \ * CUTSCENE(...).
.position = { X, Y, Z }, \ */
.duration = DURATION \
} \
}
#define CUTSCENE_TEXT_MINI_HIDE(INDEX) \
{ \
.type = CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE, \
.textMiniHide = { .index = INDEX } \
}
#define CUTSCENE_WAIT(WAIT) \
{ .type = CUTSCENE_ITEM_TYPE_WAIT, .wait = WAIT }
// A named, otherwise no-op position in the item list that cutsceneGoTo
// can jump execution straight to. NAME is matched with stringEquals,
// not pointer identity, so it's safe to use separate string literals
// with the same contents at the marker and at each call site.
#define CUTSCENE_MARKER(NAME) \
{ .type = CUTSCENE_ITEM_TYPE_MARKER, .marker = { .name = NAME } }
// Restarts the currently running cutscene from its first item,
// preserving whatever interact/interacted entities triggered it.
#define CUTSCENE_RESTART() \
{ .type = CUTSCENE_ITEM_TYPE_RESTART }
// Blocks the cutscene here indefinitely - it never completes on its own,
// only cutsceneGoTo (called externally, e.g. from a UI callback) can move
// execution past it.
#define CUTSCENE_IDLE() \
{ .type = CUTSCENE_ITEM_TYPE_IDLE }
// Opens a full-screen UI panel (e.g. the main menu) declaratively, then
// immediately continues on to whatever follows this item.
#define CUTSCENE_UI_SHOW(SCREEN) \
{ .type = CUTSCENE_ITEM_TYPE_UI_SHOW, .uiShow = { .screen = SCREEN } }
// Requests a switch to a different SCENE_TYPE via sceneSet, then
// immediately continues on to whatever follows this item - the switch
// itself doesn't happen until the next sceneUpdate() tick, so it does
// not take effect this frame.
#define CUTSCENE_SCENE(TYPE) \
{ .type = CUTSCENE_ITEM_TYPE_SCENE, .sceneChange = { .type = TYPE } }
#define CUTSCENE_CUTSCENE(CUTSCENE) \ #define CUTSCENE_CUTSCENE(CUTSCENE) \
{ \ { \
.type = CUTSCENE_ITEM_TYPE_CUTSCENE, \ .type = CUTSCENE_ITEM_TYPE_CUTSCENE, \
.cutscene = CUTSCENE_REFERENCE(CUTSCENE) \ .cutsceneRef = { .cutscene = CUTSCENE_REFERENCE(CUTSCENE), .name = NULL } \
}
#define CUTSCENE_CALLBACK(CALLBACK) \
{ .type = CUTSCENE_ITEM_TYPE_CALLBACK, .callback = CALLBACK }
#define CUTSCENE_PRINT(TEXT) \
{ .type = CUTSCENE_ITEM_TYPE_PRINT, .print = { .text = TEXT } }
// Shows a message-only modal (no option buttons) and immediately
// continues on to whatever follows this item - it does not wait for
// the dialog to be dismissed. Script the rest of the interaction (e.g.
// CUTSCENE_CALLBACK to kick off work, CUTSCENE_WAIT, then
// CUTSCENE_MODAL_CLOSE) as later items in the same cutscene.
// TITLE and MESSAGE are each displayed as-is unless they match a
// locale message ID, in which case the translated string is shown
// instead - see uiModalLocalize.
#define CUTSCENE_MODAL(TITLE, MESSAGE) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL, \
.modal = { .title = TITLE, .message = MESSAGE } \
}
// Shows a modal with option buttons and immediately continues on, same
// as CUTSCENE_MODAL - it does not block waiting for a selection.
// Back/cancel input is disabled while it's open (see
// uiMenuSetDisableBack), so it must be dismissed by picking one; CALLBACK
// then fires with the selected option index once the dialog closes.
// Option labels are passed as trailing arguments, e.g.
// CUTSCENE_MODAL_OPTIONS(title, message, callback, "Retry", "Cancel") -
// their strings are not copied by this item, so they must stay valid
// until the modal opens (string literals are fine). Like TITLE and
// MESSAGE, each option is translated if it matches a locale message ID.
#define CUTSCENE_MODAL_OPTIONS(TITLE, MESSAGE, CALLBACK, ...) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL, \
.modal = { \
.title = TITLE, .message = MESSAGE, \
.options = (const char_t *[]){ __VA_ARGS__ }, \
.optionCount = (uint8_t)( \
sizeof((const char_t *[]){ __VA_ARGS__ }) / sizeof(const char_t *) \
), \
.callback = CALLBACK \
} \
}
// Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly one option and
// MARKER1 to jump straight to via cutsceneGoTo once it's selected - no
// callback function to write. Does not fall through to whatever follows
// this item, so MARKER1 must be scripted elsewhere in the same cutscene.
#define CUTSCENE_MODAL_OPTIONS_ONE(TITLE, MESSAGE, OPTION1, MARKER1) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, \
.modalOptionsMarkers = { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1 }, \
.markers = { MARKER1 }, \
.optionCount = 1 \
} \
}
// Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly two options,
// jumping straight to OPTION1_MARKER or OPTION2_MARKER via cutsceneGoTo
// once the corresponding option is selected - no callback function to
// write. Does not fall through to whatever follows this item, so both
// markers must be scripted elsewhere in the same cutscene.
#define CUTSCENE_MODAL_OPTIONS_TWO( \
TITLE, MESSAGE, OPTION1, OPTION1_MARKER, OPTION2, OPTION2_MARKER \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, \
.modalOptionsMarkers = { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1, OPTION2 }, \
.markers = { OPTION1_MARKER, OPTION2_MARKER }, \
.optionCount = 2 \
} \
}
// Closes the currently open modal (if any). Useful when a modal was
// opened outside of a blocking CUTSCENE_MODAL item (e.g. directly via
// uiModalOpen) and this cutscene just needs to dismiss it and continue
// on to whatever follows this item in the sequence.
#define CUTSCENE_MODAL_CLOSE() \
{ .type = CUTSCENE_ITEM_TYPE_MODAL_CLOSE }
// Opens the on-screen keyboard and blocks the cutscene until it closes,
// then caches whatever was typed - see cutsceneSystemGetTextCache to
// read it back afterwards. __VA_ARGS__ are uikeyboardopen_t designated
// initializers, e.g. CUTSCENE_KEYBOARD(.cancel = true, .maxLength = 8).
#define CUTSCENE_KEYBOARD(...) \
{ \
.type = CUTSCENE_ITEM_TYPE_KEYBOARD, \
.keyboard = { .open = { __VA_ARGS__ } } \
}
// (Re)requests an available save device and jumps straight to
// SUCCESS_MARKER or FAILURE_MARKER once it resolves, same as a
// CUTSCENE_MODAL_OPTIONS callback - it does not fall through to
// whatever follows this item, so both markers must be scripted
// elsewhere in the same cutscene.
#define CUTSCENE_SAVE_DEVICE_CHECK(SUCCESS_MARKER, FAILURE_MARKER) \
{ \
.type = CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK, \
.saveDeviceCheck = { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
} \
}
// (Re)loads every save slot via saveLoadAllSlots() and jumps straight to
// SUCCESS_MARKER or FAILURE_MARKER once it resolves, same shape as
// CUTSCENE_SAVE_DEVICE_CHECK - it does not fall through to whatever
// follows this item, so both markers must be scripted elsewhere in the
// same cutscene.
#define CUTSCENE_SAVE_LOAD_ALL_SLOTS(SUCCESS_MARKER, FAILURE_MARKER) \
{ \
.type = CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS, \
.saveLoadAllSlots = { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
} \
}
#define CUTSCENE_ENTITY_WALK_TO(ENTITY_INDEX, X, Y, Z) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
.entityWalkTo = { \
.entityIndex = ENTITY_INDEX, \
.positions = (const worldpos_t[]){ { X, Y, Z } }, \
.count = 1, \
.walkAround = true \
} \
}
#define CUTSCENE_ENTITY_WALK_PATH(NAME, ENTITY_INDEX, ...) \
static const worldpos_t CUTSCENE_##NAME##_POSITIONS[] = { __VA_ARGS__ }; \
static const cutsceneitem_t CUTSCENE_##NAME = { \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
.entityWalkTo = { \
.entityIndex = ENTITY_INDEX, \
.positions = CUTSCENE_##NAME##_POSITIONS, \
.count = sizeof(CUTSCENE_##NAME##_POSITIONS) / sizeof(worldpos_t), \
.walkAround = true \
} \
}
#define CUTSCENE_ENTITY_REMOVE(ENTITY_INDEX) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_REMOVE, \
.entityRemove = { .entityIndex = ENTITY_INDEX } \
}
#define CUTSCENE_ENTITY_ADD(TYPE, X, Y, Z) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_ADD, \
.entityAdd = { .entityType = TYPE, .position = { X, Y, Z } } \
}
#define CUTSCENE_ENTITY_TURN(ENTITY_INDEX, DIRECTION) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_TURN, \
.entityTurn = { .entityIndex = ENTITY_INDEX, .direction = DIRECTION } \
}
// Walks ENTITY_INDEX to stand beside TARGET_ENTITY_INDEX, offset by
// (OFFSET_X, OFFSET_Y) on the 2D plane. The destination Z is resolved
// from nearby terrain each frame, so ramps between the two entities are
// accounted for automatically.
#define CUTSCENE_ENTITY_WALK_TO_ENTITY( \
ENTITY_INDEX, TARGET_ENTITY_INDEX, OFFSET_X, OFFSET_Y \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY, \
.entityWalkToEntity = { \
.entityIndex = ENTITY_INDEX, \
.targetEntityIndex = TARGET_ENTITY_INDEX, \
.offsetX = OFFSET_X, \
.offsetY = OFFSET_Y \
} \
}
#define CUTSCENE_ENTITY_TELEPORT(ENTITY_INDEX, X, Y, Z) \
{ \
.type = CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT, \
.entityTeleport = { .entityIndex = ENTITY_INDEX, .target = { X, Y, Z } } \
}
#define CUTSCENE_FADE(FROM, TO, DURATION, EASING) \
{ \
.type = CUTSCENE_ITEM_TYPE_FADE, \
.fade = { .from = FROM, .to = TO, .duration = DURATION, .easing = EASING } \
}
#define CUTSCENE_FADE_TO_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_BLACK, COLOR_BLACK, DURATION, EASING_LINEAR)
#define CUTSCENE_FADE_FROM_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_BLACK, COLOR_TRANSPARENT_BLACK, DURATION, EASING_LINEAR)
#define CUTSCENE_FADE_TO_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_WHITE, COLOR_WHITE, DURATION, EASING_LINEAR)
#define CUTSCENE_FADE_FROM_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_WHITE, COLOR_TRANSPARENT_WHITE, DURATION, EASING_LINEAR)
#define CUTSCENE_EMOJI(ENTITY_INDEX, EMOJI_TYPE, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_EMOJI, \
.emoji = { \
.entityIndex = ENTITY_INDEX, \
.emojiType = EMOJI_TYPE, \
.duration = DURATION \
} \
}
// AMOUNT ranges 0 (no shake) to 4 (three tiles): 1 is half a tile, 2 is
// a full tile, 3 is two tiles, and 4 is three tiles.
#define CUTSCENE_SHAKE(AMOUNT, DURATION) \
{ \
.type = CUTSCENE_ITEM_TYPE_SHAKE, \
.shake = { .amount = AMOUNT, .duration = DURATION } \
}
// Waits until BATTLE.state reaches STATE. Put this BEFORE
// CUTSCENE_SET_PAUSE(CUTSCENE_PAUSE_BATTLE), not after -- pausing first
// freezes BATTLE.state wherever it already is, so it would never reach
// STATE on its own to satisfy the wait. Waiting unpaused, then pausing the
// moment it's satisfied, catches the battle right at STATE before it can
// advance further.
#define CUTSCENE_BATTLE_WAIT_STATE(STATE) \
{ \
.type = CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE, \
.battleWaitState = { .state = STATE } \
}
// Immediately queues an attack for FIGHTER_INDEX against TARGET_INDEX,
// bypassing normal player/AI selection for that fighter this round.
#define CUTSCENE_BATTLE_FORCE_ACTION(FIGHTER_INDEX, TARGET_INDEX) \
{ \
.type = CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION, \
.battleForceAction = { \
.fighterIndex = FIGHTER_INDEX, .targetIndex = TARGET_INDEX \
} \
}
#define CUTSCENE_SET_PAUSE(FLAGS) \
{ .type = CUTSCENE_ITEM_TYPE_SET_PAUSE, .setPause = (FLAGS) }
#define CUTSCENE_ITEM_GIVE(ITEM_ID, QUANTITY) \
{ \
.type = CUTSCENE_ITEM_TYPE_ITEM_GIVE, \
.itemGive = { .item = ITEM_ID, .quantity = QUANTITY } \
}
// Runs all listed items simultaneously and waits until all are done.
// Concurrent items cannot be nested inside another CUTSCENE_CONCURRENT.
#define CUTSCENE_CONCURRENT(...) \
{ \
.type = CUTSCENE_ITEM_TYPE_CONCURRENT, \
.concurrent = { \
.items = (const cutsceneitem_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((cutsceneitem_t[]){ __VA_ARGS__ }) / \
sizeof(cutsceneitem_t) \
) \
} \
}
#define CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, CALLBACK, NOTIFY, TRIGGER \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_MAP_AREA_ADD, \
.mapAreaAdd = { \
.min = { MIN_X, MIN_Y, MIN_Z }, \
.max = { MAX_X, MAX_Y, MAX_Z }, \
.callback = CALLBACK, \
.notify = NOTIFY, \
.trigger = TRIGGER \
} \
}
#define CUTSCENE_MAP_AREA_REMOVE(AREA_ID) \
{ \
.type = CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE, \
.mapAreaRemove = { .areaId = AREA_ID } \
}
// Waits until any one of the given map area IDs has its callback invoked.
// Accepts CUTSCENE_AREA_LAST_CREATED in place of a literal area ID.
#define CUTSCENE_MAP_AREA_WAIT(...) \
{ \
.type = CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT, \
.mapAreaWait = { \
.areaIds = (const uint8_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((const uint8_t[]){ __VA_ARGS__ }) / sizeof(uint8_t) \
) \
} \
}
// Adds a map area, waits for it to be triggered once, then removes it
// before the cutscene continues. Uses a no-op callback since the wait is
// driven by the area's trigger count rather than callback logic.
#define CUTSCENE_MAP_AREA_TRIGGER_ONCE( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, NOTIFY, TRIGGER \
) \
CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, \
mapAreaNoopCallback, NOTIFY, TRIGGER \
), \
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
// Longhand - every audioMixerQueuePlay() parameter. See
// CUTSCENE_AUDIO_PLAY_SIMPLE/CUTSCENE_AUDIO_PLAY_LOOPED below for the
// shorthands.
#define CUTSCENE_AUDIO_PLAY( \
FILE, CHANNEL, VOLUME, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_PLAY, \
.audioPlay = { \
.file = FILE, \
.channel = CHANNEL, \
.volume = VOLUME, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
}
// Shorthand: play FILE on CHANNEL once, full volume, centered (0.0f, same
// as AUDIO_STREAM_CENTER), no loop.
#define CUTSCENE_AUDIO_PLAY_SIMPLE(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, false, 0, -1.0f, 0.0f)
// Shorthand: play FILE on CHANNEL looping the whole clip forever, full
// volume, centered (0.0f, same as AUDIO_STREAM_CENTER).
#define CUTSCENE_AUDIO_PLAY_LOOPED(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, true, 0, -1.0f, 0.0f)
#define CUTSCENE_AUDIO_STOP(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_STOP, .audioStopChannel = CHANNEL }
#define CUTSCENE_AUDIO_PAUSE(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_PAUSE, .audioPauseChannel = CHANNEL }
#define CUTSCENE_AUDIO_RESUME(CHANNEL) \
{ .type = CUTSCENE_ITEM_TYPE_AUDIO_RESUME, .audioResumeChannel = CHANNEL }
// Longhand - starts CHANNEL fading from FROM to TO over DURATION seconds,
// eased by EASING. Doesn't wait for it - pair with
// CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) to block until it finishes. See
// CUTSCENE_AUDIO_FADE_OUT/CUTSCENE_AUDIO_FADE_IN below for the shorthands;
// use this directly for a custom range, e.g.
// CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.3f, 5.0f, EASING_LINEAR) to fade
// down to "playing quietly" rather than silent.
#define CUTSCENE_AUDIO_FADE(CHANNEL, FROM, TO, DURATION, EASING) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE, \
.audioFade = { \
.channel = CHANNEL, \
.from = FROM, \
.to = TO, \
.duration = DURATION, \
.easing = EASING \
} \
}
// Shorthand: fade CHANNEL from full volume to silent over DURATION seconds.
#define CUTSCENE_AUDIO_FADE_OUT(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.0f, DURATION, EASING_LINEAR)
// Shorthand: fade CHANNEL from silent to full volume over DURATION seconds.
#define CUTSCENE_AUDIO_FADE_IN(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 0.0f, 1.0f, DURATION, EASING_LINEAR)
// Waits until CHANNEL's fade (started elsewhere by CUTSCENE_AUDIO_FADE)
// has finished - a no-op wait if CHANNEL isn't fading.
#define CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT, \
.audioFadeWaitChannel = CHANNEL \
}
#define CUTSCENE_AUDIO_SET_PAN(CHANNEL, PAN) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN, \
.audioSetPan = { .channel = CHANNEL, .pan = PAN } \
}
#define CUTSCENE_AUDIO_SET_LOOP( \
CHANNEL, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP, \
.audioSetLoop = { \
.channel = CHANNEL, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
}
// Combined form of CUTSCENE_AUDIO_SET_PAN + CUTSCENE_AUDIO_SET_LOOP, for
// setting both at once rather than as two separate items.
#define CUTSCENE_AUDIO_SET( \
CHANNEL, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
{ \
.type = CUTSCENE_ITEM_TYPE_AUDIO_SET, \
.audioSet = { \
.channel = CHANNEL, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
} \
} }
+23 -1
View File
@@ -15,6 +15,21 @@
cutscenesystem_t CUTSCENE_SYSTEM; cutscenesystem_t CUTSCENE_SYSTEM;
cutsceneitem_t CUTSCENE_LOADED_ITEMS[CUTSCENE_LOADED_ITEMS_MAX];
uint8_t CUTSCENE_LOADED_POOL[CUTSCENE_LOADED_POOL_SIZE_MAX];
cutscene_t CUTSCENE_LOADED_SCENE = {
.items = CUTSCENE_LOADED_ITEMS,
.itemCount = 0,
.pause = CUTSCENE_PAUSE_NONE,
.dataSize = 0
};
static yyjson_doc *CUTSCENE_LOADED_DOC = NULL;
void cutsceneLoadedSetDoc(yyjson_doc *doc) {
if(CUTSCENE_LOADED_DOC != NULL) yyjson_doc_free(CUTSCENE_LOADED_DOC);
CUTSCENE_LOADED_DOC = doc;
}
void cutsceneSystemInit() { void cutsceneSystemInit() {
memoryZero(&CUTSCENE_SYSTEM, sizeof(cutscenesystem_t)); memoryZero(&CUTSCENE_SYSTEM, sizeof(cutscenesystem_t));
} }
@@ -69,13 +84,18 @@ void cutsceneSystemLoad(const char_t *file) {
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL); assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL);
errorret_t result = assetRequireLoaded(entry); errorret_t result = assetRequireLoaded(entry);
// Released the instant loading finishes - the loader already parsed
// everything we need into CUTSCENE_LOADED_SCENE/ITEMS/POOL, so nothing
// further depends on this entry (see cutscenesystem.h's doc comment on
// CUTSCENE_LOADED_ITEMS_MAX for why only one cutscene stays resident).
assetUnlockEntry(entry);
if(errorIsNotOk(result)) { if(errorIsNotOk(result)) {
errorCatch(errorPrint(result)); errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL); uiFatalErrorOpen(NULL);
return; return;
} }
cutsceneSystemStartCutscene(&entry->data.cutscene.cutscene); cutsceneSystemStartCutscene(&CUTSCENE_LOADED_SCENE);
} }
void cutsceneRestart(void) { void cutsceneRestart(void) {
@@ -259,4 +279,6 @@ void cutsceneSystemDispose() {
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED; CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
CUTSCENE_SYSTEM.textCache[0] = '\0'; CUTSCENE_SYSTEM.textCache[0] = '\0';
CUTSCENE_SYSTEM.onComplete = NULL; CUTSCENE_SYSTEM.onComplete = NULL;
cutsceneLoadedSetDoc(NULL);
} }
+33
View File
@@ -26,6 +26,39 @@ typedef struct entity_s entity_t;
// CUTSCENE_ITEM_TYPE_KEYBOARD item is never truncated caching it here. // CUTSCENE_ITEM_TYPE_KEYBOARD item is never truncated caching it here.
#define CUTSCENE_TEXT_CACHE_MAX 64 #define CUTSCENE_TEXT_CACHE_MAX 64
// Only one JSON-authored cutscene is ever loaded/playing at a time - a
// CUTSCENE item hands control off completely (see cutsceneCutsceneStart)
// and cutsceneSystemLoad/cutsceneCutsceneResolve release their asset lock
// the instant loading finishes - so there's no benefit to malloc'ing a
// fresh items/pool buffer per load. Instead the asset loader
// (assetCutsceneLoaderAsync) parses directly into these fixed, static
// buffers. Bump these if a real cutscene ever needs more; C-authored
// cutscenes (the CUTSCENE(...) macro) don't use these at all - they're
// compiled directly into their own static const arrays.
#define CUTSCENE_LOADED_ITEMS_MAX 128
#define CUTSCENE_LOADED_POOL_SIZE_MAX 4096
extern cutsceneitem_t CUTSCENE_LOADED_ITEMS[CUTSCENE_LOADED_ITEMS_MAX];
extern uint8_t CUTSCENE_LOADED_POOL[CUTSCENE_LOADED_POOL_SIZE_MAX];
// The cutscene_t for whatever was last parsed into CUTSCENE_LOADED_ITEMS/
// CUTSCENE_LOADED_POOL - .items always points at CUTSCENE_LOADED_ITEMS;
// itemCount/pause/dataSize are overwritten by the loader on each load.
extern cutscene_t CUTSCENE_LOADED_SCENE;
/**
* Frees whatever yyjson_doc currently backs CUTSCENE_LOADED_ITEMS' string
* fields (marker/cutscene-reference names point directly into it - see
* cutsceneCutsceneRefLoad/cutsceneMarkerLoad) and takes ownership of doc
* instead. Called by the cutscene asset loader once a fresh parse into
* CUTSCENE_LOADED_ITEMS/CUTSCENE_LOADED_POOL completes successfully, and
* from cutsceneSystemDispose to release the last one at shutdown.
*
* @param doc The new doc to take ownership of (NULL just frees/clears the
* current one).
*/
void cutsceneLoadedSetDoc(yyjson_doc *doc);
typedef struct { typedef struct {
const cutscene_t *scene; const cutscene_t *scene;
uint8_t currentItem; uint8_t currentItem;
@@ -18,6 +18,50 @@ typedef struct {
easingtype_t easing; easingtype_t easing;
} cutsceneaudiofade_t; } cutsceneaudiofade_t;
/**
* Longhand - starts CHANNEL fading from FROM to TO over DURATION seconds,
* eased by EASING. Doesn't wait for it - pair with
* CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) to block until it finishes. See
* CUTSCENE_AUDIO_FADE_OUT/CUTSCENE_AUDIO_FADE_IN below for the
* shorthands; use this directly for a custom range, e.g.
* CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.3f, 5.0f, EASING_LINEAR) to fade
* down to "playing quietly" rather than silent.
*
* @param CHANNEL audiomixerchannel_t to fade.
* @param FROM Starting volume (0.0-1.0).
* @param TO Ending volume (0.0-1.0).
* @param DURATION Duration in seconds.
* @param EASING easingtype_t to apply.
*/
#define CUTSCENE_AUDIO_FADE(CHANNEL, FROM, TO, DURATION, EASING) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_FADE, audioFade, { \
.channel = CHANNEL, \
.from = FROM, \
.to = TO, \
.duration = DURATION, \
.easing = EASING \
})
/**
* Shorthand: fade CHANNEL from full volume to silent over DURATION
* seconds.
*
* @param CHANNEL audiomixerchannel_t to fade.
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_AUDIO_FADE_OUT(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 1.0f, 0.0f, DURATION, EASING_LINEAR)
/**
* Shorthand: fade CHANNEL from silent to full volume over DURATION
* seconds.
*
* @param CHANNEL audiomixerchannel_t to fade.
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_AUDIO_FADE_IN(CHANNEL, DURATION) \
CUTSCENE_AUDIO_FADE(CHANNEL, 0.0f, 1.0f, DURATION, EASING_LINEAR)
/** /**
* Starts an audio fade step (starts the fade via audioMixerFadeTo() - * Starts an audio fade step (starts the fade via audioMixerFadeTo() -
* doesn't wait for it; pair with CUTSCENE_AUDIO_FADE_WAIT to block on it). * doesn't wait for it; pair with CUTSCENE_AUDIO_FADE_WAIT to block on it).
@@ -9,6 +9,15 @@
#include "audio/mixer/audiomixerchannel.h" #include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Waits until CHANNEL's fade (started elsewhere by CUTSCENE_AUDIO_FADE)
* has finished - a no-op wait if CHANNEL isn't fading.
*
* @param CHANNEL audiomixerchannel_t to wait on.
*/
#define CUTSCENE_AUDIO_FADE_WAIT(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT, audioFadeWaitChannel, CHANNEL)
/** /**
* Updates an audio fade-wait step, completing once the watched channel's * Updates an audio fade-wait step, completing once the watched channel's
* fade (started by a CUTSCENE_AUDIO_FADE elsewhere) finishes. Has no Start * fade (started by a CUTSCENE_AUDIO_FADE elsewhere) finishes. Has no Start
@@ -9,6 +9,14 @@
#include "audio/mixer/audiomixerchannel.h" #include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Pauses CHANNEL immediately.
*
* @param CHANNEL audiomixerchannel_t to pause.
*/
#define CUTSCENE_AUDIO_PAUSE(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_PAUSE, audioPauseChannel, CHANNEL)
/** /**
* Starts an audio pause step (pauses the channel immediately). * Starts an audio pause step (pauses the channel immediately).
* *
@@ -20,6 +20,55 @@ typedef struct {
float_t loopTo; float_t loopTo;
} cutsceneaudioplay_t; } cutsceneaudioplay_t;
/**
* Longhand - queues a sound via audioMixerQueuePlay() (see its own
* comment on when it actually starts). See CUTSCENE_AUDIO_PLAY_SIMPLE/
* CUTSCENE_AUDIO_PLAY_LOOPED below for the shorthands.
*
* @param FILE Audio file path.
* @param CHANNEL audiomixerchannel_t to play on.
* @param VOLUME Playback volume (0.0-1.0).
* @param PAN Stereo pan (-1.0 left to 1.0 right, 0.0 centered).
* @param LOOPING Whether the clip loops.
* @param LOOP_COUNT Number of loop repeats (0 = infinite, if LOOPING).
* @param LOOP_START Loop region start in seconds, or -1.0f for the clip
* start.
* @param LOOP_TO Loop region end/return point in seconds.
*/
#define CUTSCENE_AUDIO_PLAY( \
FILE, CHANNEL, VOLUME, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_PLAY, audioPlay, { \
.file = FILE, \
.channel = CHANNEL, \
.volume = VOLUME, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
})
/**
* Shorthand: play FILE on CHANNEL once, full volume, centered (0.0f, same
* as AUDIO_STREAM_CENTER), no loop.
*
* @param FILE Audio file path.
* @param CHANNEL audiomixerchannel_t to play on.
*/
#define CUTSCENE_AUDIO_PLAY_SIMPLE(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, false, 0, -1.0f, 0.0f)
/**
* Shorthand: play FILE on CHANNEL looping the whole clip forever, full
* volume, centered (0.0f, same as AUDIO_STREAM_CENTER).
*
* @param FILE Audio file path.
* @param CHANNEL audiomixerchannel_t to play on.
*/
#define CUTSCENE_AUDIO_PLAY_LOOPED(FILE, CHANNEL) \
CUTSCENE_AUDIO_PLAY(FILE, CHANNEL, 1.0f, 0.0f, true, 0, -1.0f, 0.0f)
/** /**
* Starts an audio play step (queues the sound via audioMixerQueuePlay() - * Starts an audio play step (queues the sound via audioMixerQueuePlay() -
* see its own comment on when it actually starts). * see its own comment on when it actually starts).
@@ -9,6 +9,14 @@
#include "audio/mixer/audiomixerchannel.h" #include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Resumes CHANNEL immediately.
*
* @param CHANNEL audiomixerchannel_t to resume.
*/
#define CUTSCENE_AUDIO_RESUME(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_RESUME, audioResumeChannel, CHANNEL)
/** /**
* Starts an audio resume step (resumes the channel immediately). * Starts an audio resume step (resumes the channel immediately).
* *
@@ -18,6 +18,30 @@ typedef struct {
float_t loopTo; float_t loopTo;
} cutsceneaudioset_t; } cutsceneaudioset_t;
/**
* Combined form of CUTSCENE_AUDIO_SET_PAN + CUTSCENE_AUDIO_SET_LOOP, for
* setting both at once rather than as two separate items.
*
* @param CHANNEL audiomixerchannel_t to adjust.
* @param PAN Stereo pan (-1.0 left to 1.0 right, 0.0 centered).
* @param LOOPING Whether the clip loops.
* @param LOOP_COUNT Number of loop repeats (0 = infinite, if LOOPING).
* @param LOOP_START Loop region start in seconds, or -1.0f for the clip
* start.
* @param LOOP_TO Loop region end/return point in seconds.
*/
#define CUTSCENE_AUDIO_SET( \
CHANNEL, PAN, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_SET, audioSet, { \
.channel = CHANNEL, \
.pan = PAN, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
})
/** /**
* Starts an audio set step - applies pan and looping behaviour together in * Starts an audio set step - applies pan and looping behaviour together in
* one item (via audioMixerSetPan()/audioMixerSetLoop()), for when you want * one item (via audioMixerSetPan()/audioMixerSetLoop()), for when you want
@@ -17,6 +17,27 @@ typedef struct {
float_t loopTo; float_t loopTo;
} cutsceneaudiosetloop_t; } cutsceneaudiosetloop_t;
/**
* Applies new looping behaviour immediately, via audioMixerSetLoop().
*
* @param CHANNEL audiomixerchannel_t to adjust.
* @param LOOPING Whether the clip loops.
* @param LOOP_COUNT Number of loop repeats (0 = infinite, if LOOPING).
* @param LOOP_START Loop region start in seconds, or -1.0f for the clip
* start.
* @param LOOP_TO Loop region end/return point in seconds.
*/
#define CUTSCENE_AUDIO_SET_LOOP( \
CHANNEL, LOOPING, LOOP_COUNT, LOOP_START, LOOP_TO \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP, audioSetLoop, { \
.channel = CHANNEL, \
.looping = LOOPING, \
.loopCount = LOOP_COUNT, \
.loopStart = LOOP_START, \
.loopTo = LOOP_TO \
})
/** /**
* Starts an audio set-loop step (applies the new looping behaviour * Starts an audio set-loop step (applies the new looping behaviour
* immediately, via audioMixerSetLoop()). * immediately, via audioMixerSetLoop()).
@@ -14,6 +14,17 @@ typedef struct {
float_t pan; float_t pan;
} cutsceneaudiosetpan_t; } cutsceneaudiosetpan_t;
/**
* Applies a new pan immediately, via audioMixerSetPan().
*
* @param CHANNEL audiomixerchannel_t to adjust.
* @param PAN Stereo pan (-1.0 left to 1.0 right, 0.0 centered).
*/
#define CUTSCENE_AUDIO_SET_PAN(CHANNEL, PAN) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN, audioSetPan, { \
.channel = CHANNEL, .pan = PAN \
})
/** /**
* Starts an audio set-pan step (applies the new pan immediately, via * Starts an audio set-pan step (applies the new pan immediately, via
* audioMixerSetPan()). * audioMixerSetPan()).
@@ -9,6 +9,14 @@
#include "audio/mixer/audiomixerchannel.h" #include "audio/mixer/audiomixerchannel.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Stops CHANNEL immediately.
*
* @param CHANNEL audiomixerchannel_t to stop.
*/
#define CUTSCENE_AUDIO_STOP(CHANNEL) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_AUDIO_STOP, audioStopChannel, CHANNEL)
/** /**
* Starts an audio stop step (stops the channel immediately). * Starts an audio stop step (stops the channel immediately).
* *
@@ -8,4 +8,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
cutscenestartbattle.c cutscenestartbattle.c
cutscenebattlewaitstate.c cutscenebattlewaitstate.c
cutscenebattleforceaction.c cutscenebattleforceaction.c
cutsceneregularbattle.c
) )
@@ -14,6 +14,18 @@ typedef struct {
uint8_t targetIndex; uint8_t targetIndex;
} cutscenebattleforceaction_t; } cutscenebattleforceaction_t;
/**
* Immediately queues an attack for FIGHTER_INDEX against TARGET_INDEX,
* bypassing normal player/AI selection for that fighter this round.
*
* @param FIGHTER_INDEX Attacking fighter's battle index.
* @param TARGET_INDEX Target fighter's battle index.
*/
#define CUTSCENE_BATTLE_FORCE_ACTION(FIGHTER_INDEX, TARGET_INDEX) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION, battleForceAction, { \
.fighterIndex = FIGHTER_INDEX, .targetIndex = TARGET_INDEX \
})
/** /**
* Starts a battle force-action step: immediately queues an attack for the * Starts a battle force-action step: immediately queues an attack for the
* given fighter against the given target, bypassing normal player/AI * given fighter against the given target, bypassing normal player/AI
@@ -13,6 +13,21 @@ typedef struct {
battlestate_t state; battlestate_t state;
} cutscenebattlewaitstate_t; } cutscenebattlewaitstate_t;
/**
* Waits until BATTLE.state reaches STATE. Put this BEFORE
* CUTSCENE_SET_PAUSE(CUTSCENE_PAUSE_BATTLE), not after -- pausing first
* freezes BATTLE.state wherever it already is, so it would never reach
* STATE on its own to satisfy the wait. Waiting unpaused, then pausing
* the moment it's satisfied, catches the battle right at STATE before it
* can advance further.
*
* @param STATE battlestate_t to wait for.
*/
#define CUTSCENE_BATTLE_WAIT_STATE(STATE) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE, battleWaitState, { \
.state = STATE \
})
/** /**
* Updates a battle wait-state step, completing once BATTLE.state reaches * Updates a battle wait-state step, completing once BATTLE.state reaches
* the watched state. Has no Start callback -- there's nothing to do until * the watched state. Has no Start callback -- there's nothing to do until
@@ -0,0 +1,15 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
bool_t cutsceneRegularBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
@@ -0,0 +1,29 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Updates a regular-battle step. By the time this item runs, the preceding
* START_BATTLE item has already waited out the whole encounter, synced
* party HP/MP, and returned to the overworld scene - so this is currently
* just a completes-immediately hook point for whatever regular-battle-
* specific follow-up (loot, post-battle dialogue, etc.) gets added later.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneRegularBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
// REGULAR_BATTLE has no fields of its own to parse yet - see
// cutsceneItemLoadNoop (cutsceneitembase.h), used directly as its .load
// callback.
@@ -8,8 +8,11 @@
#include "rpg/cutscene/item/cutsceneitem.h" #include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/party.h" #include "rpg/battle/party.h"
#include "scene/scene.h" #include "scene/scene.h"
#include "save/save.h"
#include "rpg/cutscene/item/json/cutscenejsonbattleencounter.h" #include "rpg/cutscene/item/json/cutscenejsonbattleencounter.h"
#include "rpg/cutscene/item/json/cutscenejsonbattleability.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h" #include "rpg/cutscene/item/json/cutscenejsonfield.h"
#include "util/memory.h"
void cutsceneStartBattleStart( void cutsceneStartBattleStart(
const cutsceneitem_t *item, const cutsceneitem_t *item,
@@ -19,8 +22,9 @@ void cutsceneStartBattleStart(
battleInit(); battleInit();
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) { for(uint8_t i = 0; i < config->playerCount; i++) {
battlefighter_t *member = partyGetOrderMember(i); battlefighter_t *member =
partyGetOrderMember(config->players[i]);
if(member == NULL) continue; if(member == NULL) continue;
battlefighter_t *fighter = battleAddFighter( battlefighter_t *fighter = battleAddFighter(
@@ -32,14 +36,18 @@ void cutsceneStartBattleStart(
fighter->health = member->health; fighter->health = member->health;
fighter->mp = member->mp; fighter->mp = member->mp;
fighter->status = member->status; fighter->status = member->status;
memoryCopy(fighter->abilities, member->abilities, sizeof(fighter->abilities));
} }
for(uint8_t i = 0; i < config->enemyCount; i++) { for(uint8_t i = 0; i < config->enemyCount; i++) {
const cutscenestartbattleenemy_t *enemy = &config->enemies[i]; const cutscenestartbattleenemy_t *enemy = &config->enemies[i];
battleAddFighter( battlefighter_t *fighter = battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI, BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemy->stats, enemy->healthMax, enemy->mpMax enemy->stats, enemy->healthMax, enemy->mpMax
); );
if(fighter == NULL) continue;
memoryCopy(fighter->abilities, enemy->abilities, sizeof(fighter->abilities));
} }
battleStart(config->encounterType, config->fleeAvailable); battleStart(config->encounterType, config->fleeAvailable);
@@ -52,13 +60,15 @@ bool_t cutsceneStartBattleUpdate(
) { ) {
if(BATTLE.result == BATTLE_RESULT_NONE) return false; if(BATTLE.result == BATTLE_RESULT_NONE) return false;
const cutscenestartbattle_t *config = &item->startBattle;
// Sync ally HP/MP back to the persistent party roster. Relies on // Sync ally HP/MP back to the persistent party roster. Relies on
// ally fighters having been added to BATTLE.fighters in the same // ally fighters having been added to BATTLE.fighters in the same
// order partyGetOrderMember() iterates, starting at index 0 (see // order config->players iterates (see cutsceneStartBattleStart).
// cutsceneStartBattleStart).
uint8_t allySlot = 0; uint8_t allySlot = 0;
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) { for(uint8_t i = 0; i < config->playerCount; i++) {
battlefighter_t *member = partyGetOrderMember(i); battlefighter_t *member =
partyGetOrderMember(config->players[i]);
if(member == NULL) continue; if(member == NULL) continue;
battlefighter_t *fighter = &BATTLE.fighters[allySlot++]; battlefighter_t *fighter = &BATTLE.fighters[allySlot++];
@@ -89,6 +99,38 @@ errorret_t cutsceneStartBattleLoad(
item->startBattle.fleeAvailable = item->startBattle.fleeAvailable =
cutsceneJsonGetBool(itemObj, "fleeAvailable", true); cutsceneJsonGetBool(itemObj, "fleeAvailable", true);
yyjson_val *players = yyjson_obj_get(itemObj, "players");
if(players == NULL) {
item->startBattle.playerCount = PARTY_ACTIVE_SIZE_MAX;
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
item->startBattle.players[i] = i;
}
} else {
size_t playerCount = yyjson_arr_size(players);
if(!yyjson_is_arr(players) || playerCount > PARTY_ACTIVE_SIZE_MAX) {
errorThrow(
"Cutscene item (START_BATTLE): 'players' must have 0-%u entries",
(uint32_t)PARTY_ACTIVE_SIZE_MAX
);
}
item->startBattle.playerCount = (uint8_t)playerCount;
yyjson_arr_iter playerIter = yyjson_arr_iter_with(players);
yyjson_val *playerVal;
size_t p = 0;
while((playerVal = yyjson_arr_iter_next(&playerIter)) != NULL) {
int64_t index = yyjson_get_int(playerVal);
if(index < 0 || index >= PARTY_ACTIVE_SIZE_MAX) {
errorThrow(
"Cutscene item (START_BATTLE): players[%u] must be 0-%u",
(uint32_t)p, (uint32_t)(PARTY_ACTIVE_SIZE_MAX - 1)
);
}
item->startBattle.players[p] = (uint8_t)index;
p++;
}
}
yyjson_val *enemies = yyjson_obj_get(itemObj, "enemies"); yyjson_val *enemies = yyjson_obj_get(itemObj, "enemies");
size_t enemyCount = yyjson_arr_size(enemies); size_t enemyCount = yyjson_arr_size(enemies);
if(!yyjson_is_arr(enemies) || enemyCount == 0 || if(!yyjson_is_arr(enemies) || enemyCount == 0 ||
@@ -126,6 +168,37 @@ errorret_t cutsceneStartBattleLoad(
(uint16_t)yyjson_get_int(yyjson_obj_get(enemyVal, "healthMax")); (uint16_t)yyjson_get_int(yyjson_obj_get(enemyVal, "healthMax"));
enemy->mpMax = enemy->mpMax =
(uint16_t)yyjson_get_int(yyjson_obj_get(enemyVal, "mpMax")); (uint16_t)yyjson_get_int(yyjson_obj_get(enemyVal, "mpMax"));
yyjson_val *abilities = yyjson_obj_get(enemyVal, "abilities");
if(abilities != NULL) {
size_t abilityCount = yyjson_arr_size(abilities);
if(!yyjson_is_arr(abilities) ||
abilityCount > BATTLE_FIGHTER_ABILITY_COUNT_MAX) {
errorThrow(
"Cutscene item (START_BATTLE): enemies[%u].abilities must have "
"0-%u entries",
(uint32_t)e, (uint32_t)BATTLE_FIGHTER_ABILITY_COUNT_MAX
);
}
yyjson_arr_iter abilityIter = yyjson_arr_iter_with(abilities);
yyjson_val *abilityVal;
size_t a = 0;
while((abilityVal = yyjson_arr_iter_next(&abilityIter)) != NULL) {
battleability_t ability;
if(!cutsceneJsonLookupBattleAbility(
yyjson_get_str(abilityVal), &ability
)) {
errorThrow(
"Cutscene item (START_BATTLE): enemies[%u].abilities[%u] is "
"invalid",
(uint32_t)e, (uint32_t)a
);
}
enemy->abilities[a] = ability;
a++;
}
}
e++; e++;
} }
@@ -7,6 +7,7 @@
#pragma once #pragma once
#include "rpg/battle/battle.h" #include "rpg/battle/battle.h"
#include "rpg/battle/party.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
#define CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX 4 #define CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX 4
@@ -15,6 +16,7 @@ typedef struct {
battlefighterstats_t stats; battlefighterstats_t stats;
uint16_t healthMax; uint16_t healthMax;
uint16_t mpMax; uint16_t mpMax;
battleability_t abilities[BATTLE_FIGHTER_ABILITY_COUNT_MAX];
} cutscenestartbattleenemy_t; } cutscenestartbattleenemy_t;
typedef struct { typedef struct {
@@ -22,6 +24,13 @@ typedef struct {
bool_t fleeAvailable; bool_t fleeAvailable;
uint8_t enemyCount; uint8_t enemyCount;
cutscenestartbattleenemy_t enemies[CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX]; cutscenestartbattleenemy_t enemies[CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX];
// Active party order slots (see party.h) to bring into the battle, in
// the order they should be added. Defaults to every active slot, 0
// through PARTY_ACTIVE_SIZE_MAX - 1 in order, when the item's JSON
// omits "players" - see cutsceneStartBattleLoad.
uint8_t players[PARTY_ACTIVE_SIZE_MAX];
uint8_t playerCount;
} cutscenestartbattle_t; } cutscenestartbattle_t;
/** /**
@@ -13,6 +13,22 @@
/** Maximum number of items that may run inside a CUTSCENE_CONCURRENT. */ /** Maximum number of items that may run inside a CUTSCENE_CONCURRENT. */
#define CUTSCENE_CONCURRENT_MAX 8 #define CUTSCENE_CONCURRENT_MAX 8
/**
* Runs all listed items simultaneously and waits until all are done.
* Concurrent items cannot be nested inside another CUTSCENE_CONCURRENT.
*
* @param ... Child cutsceneitem_t entries (e.g. CUTSCENE_WAIT(...),
* CUTSCENE_ENTITY_WALK_TO(...)) to run at the same time.
*/
#define CUTSCENE_CONCURRENT(...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_CONCURRENT, concurrent, { \
.items = (const cutsceneitem_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((cutsceneitem_t[]){ __VA_ARGS__ }) / \
sizeof(cutsceneitem_t) \
) \
})
/** /**
* Static (const) data for a concurrent cutscene item. * Static (const) data for a concurrent cutscene item.
*/ */
@@ -8,6 +8,14 @@
#pragma once #pragma once
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Blocks the cutscene here indefinitely - it never completes on its own,
* only cutsceneGoTo (called externally, e.g. from a UI callback) can move
* execution past it.
*/
#define CUTSCENE_IDLE() \
{ .type = CUTSCENE_ITEM_TYPE_IDLE }
/** /**
* Updates an idle item. Never completes on its own - the cutscene blocks * Updates an idle item. Never completes on its own - the cutscene blocks
* here indefinitely until something external (e.g. a UI callback) calls * here indefinitely until something external (e.g. a UI callback) calls
@@ -12,6 +12,17 @@ typedef struct {
const char_t *name; const char_t *name;
} cutscenemarker_t; } cutscenemarker_t;
/**
* A named, otherwise no-op position in the item list that cutsceneGoTo
* can jump execution straight to.
*
* @param NAME Marker name, matched with stringEquals (not pointer
* identity) - safe to use separate string literals with the same
* contents at the marker and at each call site.
*/
#define CUTSCENE_MARKER(NAME) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MARKER, marker, { .name = NAME })
/** /**
* Starts a marker item. A marker does nothing on its own - it exists * Starts a marker item. A marker does nothing on its own - it exists
* purely as a named position for cutsceneGoTo to jump to. * purely as a named position for cutsceneGoTo to jump to.
@@ -8,6 +8,13 @@
#pragma once #pragma once
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Restarts the currently running cutscene from its first item,
* preserving whatever interact/interacted entities triggered it.
*/
#define CUTSCENE_RESTART() \
{ .type = CUTSCENE_ITEM_TYPE_RESTART }
/** /**
* Starts a restart item (restarts the currently running cutscene from * Starts a restart item (restarts the currently running cutscene from
* its first item via cutsceneRestart). * its first item via cutsceneRestart).
@@ -13,6 +13,17 @@ typedef struct {
scenetype_t type; scenetype_t type;
} cutscenescene_t; } cutscenescene_t;
/**
* Requests a switch to a different SCENE_TYPE via sceneSet, then
* immediately continues on to whatever follows this item - the switch
* itself doesn't happen until the next sceneUpdate() tick, so it does
* not take effect this frame.
*
* @param TYPE Target scenetype_t to switch to.
*/
#define CUTSCENE_SCENE(TYPE) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SCENE, sceneChange, { .type = TYPE })
/** /**
* Starts a scene item (requests a switch to the given scene via * Starts a scene item (requests a switch to the given scene via
* sceneSet). The switch itself doesn't happen until the next * sceneSet). The switch itself doesn't happen until the next
@@ -9,6 +9,14 @@
#include "rpg/cutscene/cutscenepause.h" #include "rpg/cutscene/cutscenepause.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
/**
* Applies the given pause flags immediately.
*
* @param FLAGS CUTSCENE_PAUSE_* flags, OR'd together.
*/
#define CUTSCENE_SET_PAUSE(FLAGS) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SET_PAUSE, setPause, (FLAGS))
/** /**
* Starts a set-pause item (applies the new pause flags immediately). * Starts a set-pause item (applies the new pause flags immediately).
* *
@@ -11,6 +11,14 @@
typedef float_t cutscenewait_t; typedef float_t cutscenewait_t;
typedef float_t cutscenewaitdata_t; typedef float_t cutscenewaitdata_t;
/**
* Waits WAIT seconds before continuing.
*
* @param WAIT Duration in seconds.
*/
#define CUTSCENE_WAIT(WAIT) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_WAIT, wait, WAIT)
/** /**
* Starts a wait item (stores the duration in data). * Starts a wait item (stores the duration in data).
* *
@@ -10,6 +10,15 @@
typedef void (*cutscenecallback_t)(void *userData); typedef void (*cutscenecallback_t)(void *userData);
/**
* Invokes CALLBACK immediately, then continues on to whatever follows
* this item.
*
* @param CALLBACK A cutscenecallback_t function pointer.
*/
#define CUTSCENE_CALLBACK(CALLBACK) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_CALLBACK, callback, CALLBACK)
/** /**
* Starts a callback item (invokes the callback immediately). * Starts a callback item (invokes the callback immediately).
* *
+41 -13
View File
@@ -11,6 +11,7 @@
#include "asset/assetfile.h" #include "asset/assetfile.h"
#include "asset/loader/assetloader.h" #include "asset/loader/assetloader.h"
#include "util/string.h" #include "util/string.h"
#include "ui/overlay/uifatalerror.h"
cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = { cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
[CUTSCENE_ITEM_TYPE_NULL] = { 0 }, [CUTSCENE_ITEM_TYPE_NULL] = { 0 },
@@ -326,6 +327,12 @@ cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
.update = cutsceneUIShowUpdate, .update = cutsceneUIShowUpdate,
.jsonName = "UI_SHOW", .jsonName = "UI_SHOW",
.load = cutsceneUIShowLoad .load = cutsceneUIShowLoad
},
[CUTSCENE_ITEM_TYPE_REGULAR_BATTLE] = {
.update = cutsceneRegularBattleUpdate,
.jsonName = "REGULAR_BATTLE",
.load = cutsceneItemLoadNoop
} }
}; };
@@ -364,7 +371,17 @@ void cutsceneCutsceneStart(
const cutsceneitem_t *item, const cutsceneitem_t *item,
cutsceneitemdata_t *data cutsceneitemdata_t *data
) { ) {
if(item->cutscene != NULL) cutsceneSystemStartCutscene(item->cutscene); const cutscene_t *cutscene = item->cutsceneRef.cutscene;
if(cutscene == NULL && item->cutsceneRef.name != NULL) {
// Not cached back into item - with only one shared, fixed load buffer
// (see cutscenesystem.h's CUTSCENE_LOADED_ITEMS_MAX doc comment),
// every JSON-authored reference resolves to the same fixed address
// every time anyway, and item itself lives inside that very buffer -
// caching a pointer into it here would go stale (or, worse, get
// clobbered mid-resolve) the moment a later load overwrites it.
cutscene = cutsceneCutsceneResolve(item->cutsceneRef.name);
}
if(cutscene != NULL) cutsceneSystemStartCutscene(cutscene);
} }
bool_t cutsceneCutsceneUpdate( bool_t cutsceneCutsceneUpdate(
@@ -374,6 +391,24 @@ bool_t cutsceneCutsceneUpdate(
return false; return false;
} }
const cutscene_t * cutsceneCutsceneResolve(const char_t *name) {
char_t path[ASSET_FILE_NAME_MAX];
stringFormat(path, sizeof(path), "cutscenes/%s.jsonc", name);
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL);
errorret_t result = assetRequireLoaded(entry);
// Released the instant loading finishes - see cutsceneSystemLoad's doc
// comment for why nothing further depends on this entry once loaded.
assetUnlockEntry(entry);
if(errorIsNotOk(result)) {
errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL);
return NULL;
}
return &CUTSCENE_LOADED_SCENE;
}
errorret_t cutsceneCutsceneLoad( errorret_t cutsceneCutsceneLoad(
yyjson_val *itemObj, yyjson_val *itemObj,
cutsceneitem_t *item, cutsceneitem_t *item,
@@ -385,23 +420,16 @@ errorret_t cutsceneCutsceneLoad(
errorThrow("Cutscene item (CUTSCENE): missing 'name'"); errorThrow("Cutscene item (CUTSCENE): missing 'name'");
} }
// Referenced cutscene is a sibling asset (assets/cutscenes/<name>.jsonc), // Only validate that the eventual "cutscenes/<name>.jsonc" path would
// resolved to a stable pointer right now rather than deferred to // fit - the reference itself is not resolved/locked until this item
// runtime - assetRequireLoaded re-enters assetUpdate() safely from // actually runs (see cutsceneCutsceneStart/cutsceneCutsceneResolve).
// within this sync load (see its ASSET_ENTRY_STATE_LOADING_SYNC case),
// and the entry is locked forever (never unlocked) so the pointer
// stays valid for the process lifetime, same convention as
// ui/screen/mainmenu/uimainmenu.c's MAIN_MENU_CUTSCENE_ENTRY.
char_t path[ASSET_FILE_NAME_MAX];
int32_t pathLen = stringFormat(NULL, 0, "cutscenes/%s.jsonc", name); int32_t pathLen = stringFormat(NULL, 0, "cutscenes/%s.jsonc", name);
if(pathLen < 0 || (size_t)pathLen >= ASSET_FILE_NAME_MAX) { if(pathLen < 0 || (size_t)pathLen >= ASSET_FILE_NAME_MAX) {
errorThrow("Cutscene item (CUTSCENE): 'name' too long"); errorThrow("Cutscene item (CUTSCENE): 'name' too long");
} }
stringFormat(path, sizeof(path), "cutscenes/%s.jsonc", name);
assetentry_t *refEntry = assetLock(path, ASSET_LOADER_TYPE_CUTSCENE, NULL); item->cutsceneRef.cutscene = NULL;
errorChain(assetRequireLoaded(refEntry)); item->cutsceneRef.name = name;
item->cutscene = &refEntry->data.cutscene.cutscene;
errorOk(); errorOk();
} }
+41 -58
View File
@@ -8,6 +8,7 @@
#pragma once #pragma once
#include "error/error.h" #include "error/error.h"
#include "yyjson.h" #include "yyjson.h"
#include "cutsceneitembase.h"
#include "cutscenecallback.h" #include "cutscenecallback.h"
#include "cutsceneprint.h" #include "cutsceneprint.h"
#include "control/cutscenewait.h" #include "control/cutscenewait.h"
@@ -41,6 +42,7 @@
#include "battle/cutscenestartbattle.h" #include "battle/cutscenestartbattle.h"
#include "battle/cutscenebattlewaitstate.h" #include "battle/cutscenebattlewaitstate.h"
#include "battle/cutscenebattleforceaction.h" #include "battle/cutscenebattleforceaction.h"
#include "battle/cutsceneregularbattle.h"
#include "save/cutscenesavedevicecheck.h" #include "save/cutscenesavedevicecheck.h"
#include "save/cutscenesaveloadallslots.h" #include "save/cutscenesaveloadallslots.h"
#include "audio/cutsceneaudioplay.h" #include "audio/cutsceneaudioplay.h"
@@ -55,58 +57,19 @@
typedef struct cutscene_s cutscene_t; typedef struct cutscene_s cutscene_t;
typedef enum { // A CUTSCENE item's target. C-authored cutscenes (the CUTSCENE_CUTSCENE
CUTSCENE_ITEM_TYPE_NULL, // macro in cutscene.h) resolve cutscene at compile time and leave name
// NULL. JSON-authored cutscenes (cutsceneCutsceneLoad) do the opposite -
CUTSCENE_ITEM_TYPE_TEXT, // only name is set at parse time, since resolving/locking the referenced
CUTSCENE_ITEM_TYPE_TEXT_MINI, // asset there would eagerly load every cutscene a cutscene merely
CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE, // references, even ones never played. cutsceneCutsceneStart resolves
CUTSCENE_ITEM_TYPE_CALLBACK, // name to cutscene the first time this item actually runs (via
CUTSCENE_ITEM_TYPE_WAIT, // cutsceneCutsceneResolve) and caches the result back into this field so
CUTSCENE_ITEM_TYPE_CUTSCENE, // replaying the same item never re-resolves it.
CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT, typedef struct {
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, const cutscene_t *cutscene;
CUTSCENE_ITEM_TYPE_FADE, const char_t *name;
CUTSCENE_ITEM_TYPE_SET_PAUSE, } cutscenecutsceneref_t;
CUTSCENE_ITEM_TYPE_CONCURRENT,
CUTSCENE_ITEM_TYPE_ITEM_GIVE,
CUTSCENE_ITEM_TYPE_ENTITY_REMOVE,
CUTSCENE_ITEM_TYPE_ENTITY_ADD,
CUTSCENE_ITEM_TYPE_ENTITY_TURN,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY,
CUTSCENE_ITEM_TYPE_MAP_AREA_ADD,
CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE,
CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT,
CUTSCENE_ITEM_TYPE_START_BATTLE,
CUTSCENE_ITEM_TYPE_EMOJI,
CUTSCENE_ITEM_TYPE_SHAKE,
CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE,
CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION,
CUTSCENE_ITEM_TYPE_MODAL,
CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS,
CUTSCENE_ITEM_TYPE_MODAL_CLOSE,
CUTSCENE_ITEM_TYPE_PRINT,
CUTSCENE_ITEM_TYPE_MARKER,
CUTSCENE_ITEM_TYPE_RESTART,
CUTSCENE_ITEM_TYPE_QUIT_GAME,
CUTSCENE_ITEM_TYPE_SCENE,
CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK,
CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS,
CUTSCENE_ITEM_TYPE_KEYBOARD,
CUTSCENE_ITEM_TYPE_AUDIO_PLAY,
CUTSCENE_ITEM_TYPE_AUDIO_STOP,
CUTSCENE_ITEM_TYPE_AUDIO_PAUSE,
CUTSCENE_ITEM_TYPE_AUDIO_RESUME,
CUTSCENE_ITEM_TYPE_AUDIO_FADE,
CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT,
CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN,
CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP,
CUTSCENE_ITEM_TYPE_AUDIO_SET,
CUTSCENE_ITEM_TYPE_IDLE,
CUTSCENE_ITEM_TYPE_UI_SHOW,
CUTSCENE_ITEM_TYPE_COUNT
} cutsceneitemtype_t;
struct cutsceneitem_s { struct cutsceneitem_s {
cutsceneitemtype_t type; cutsceneitemtype_t type;
@@ -117,7 +80,7 @@ struct cutsceneitem_s {
cutscenetextminihide_t textMiniHide; cutscenetextminihide_t textMiniHide;
cutscenecallback_t callback; cutscenecallback_t callback;
cutscenewait_t wait; cutscenewait_t wait;
const cutscene_t *cutscene; cutscenecutsceneref_t cutsceneRef;
cutsceneentityteleport_t entityTeleport; cutsceneentityteleport_t entityTeleport;
cutsceneentitywalkto_t entityWalkTo; cutsceneentitywalkto_t entityWalkTo;
cutscenefade_t fade; cutscenefade_t fade;
@@ -235,7 +198,9 @@ bool_t cutsceneItemLookupType(
/** /**
* Starts a nested-cutscene item, handing control over to the * Starts a nested-cutscene item, handing control over to the
* referenced cutscene. * referenced cutscene. If item->cutsceneRef.cutscene hasn't been
* resolved yet (a JSON-authored reference, only known by name so far),
* resolves and caches it first via cutsceneCutsceneResolve.
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
@@ -245,6 +210,22 @@ void cutsceneCutsceneStart(
cutsceneitemdata_t *data cutsceneitemdata_t *data
); );
/**
* Resolves a JSON-authored CUTSCENE item's referenced cutscene by name,
* locking (forever - never unlocked, matching cutsceneCutsceneLoad's old
* convention) and blocking on assets/cutscenes/<name>.jsonc. Called
* lazily from cutsceneCutsceneStart the first time the item actually
* runs, not at parse time, so a cutscene referencing many others doesn't
* load every one of them up front. On failure, opens the fatal error
* overlay (matching cutsceneSystemLoad's runtime-failure handling) and
* returns NULL.
*
* @param name Bare cutscene name (without "cutscenes/" prefix or
* ".jsonc" suffix).
* @return The resolved cutscene, or NULL on failure.
*/
const cutscene_t * cutsceneCutsceneResolve(const char_t *name);
/** /**
* Updates a nested-cutscene item. By the time this would run, control * Updates a nested-cutscene item. By the time this would run, control
* has already moved on to the referenced cutscene, so this always * has already moved on to the referenced cutscene, so this always
@@ -262,10 +243,12 @@ bool_t cutsceneCutsceneUpdate(
/** /**
* Parses a CUTSCENE cutscene item's JSON fields into item. Kept inline here * Parses a CUTSCENE cutscene item's JSON fields into item. Kept inline here
* (rather than its own file) since it's tightly bound to the asset/loader * (rather than its own file) since it's tightly bound to the asset/loader
* system itself - it resolves its 'name' to a sibling * system itself. Only stores the 'name' string (which points into the
* assets/cutscenes/<name>.jsonc asset at parse time, mirroring how * cutscene asset's still-alive yyjson doc, so no copy is needed) -
* cutsceneCutsceneStart/cutsceneCutsceneUpdate stay inline in * resolving it to the referenced assets/cutscenes/<name>.jsonc asset is
* cutsceneitem.c rather than getting their own file. * deferred to cutsceneCutsceneStart, the first time this item actually
* runs, so a cutscene referencing many others doesn't pay to load every
* one of them up front.
* *
* @param itemObj The item's JSON object. * @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller. * @param item Destination item, already zeroed by the caller.
@@ -13,6 +13,75 @@
typedef struct cutsceneitem_s cutsceneitem_t; typedef struct cutsceneitem_s cutsceneitem_t;
typedef union cutsceneitemdata_u cutsceneitemdata_t; typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef enum {
CUTSCENE_ITEM_TYPE_NULL,
CUTSCENE_ITEM_TYPE_TEXT,
CUTSCENE_ITEM_TYPE_TEXT_MINI,
CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE,
CUTSCENE_ITEM_TYPE_CALLBACK,
CUTSCENE_ITEM_TYPE_WAIT,
CUTSCENE_ITEM_TYPE_CUTSCENE,
CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO,
CUTSCENE_ITEM_TYPE_FADE,
CUTSCENE_ITEM_TYPE_SET_PAUSE,
CUTSCENE_ITEM_TYPE_CONCURRENT,
CUTSCENE_ITEM_TYPE_ITEM_GIVE,
CUTSCENE_ITEM_TYPE_ENTITY_REMOVE,
CUTSCENE_ITEM_TYPE_ENTITY_ADD,
CUTSCENE_ITEM_TYPE_ENTITY_TURN,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY,
CUTSCENE_ITEM_TYPE_MAP_AREA_ADD,
CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE,
CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT,
CUTSCENE_ITEM_TYPE_START_BATTLE,
CUTSCENE_ITEM_TYPE_EMOJI,
CUTSCENE_ITEM_TYPE_SHAKE,
CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE,
CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION,
CUTSCENE_ITEM_TYPE_MODAL,
CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS,
CUTSCENE_ITEM_TYPE_MODAL_CLOSE,
CUTSCENE_ITEM_TYPE_PRINT,
CUTSCENE_ITEM_TYPE_MARKER,
CUTSCENE_ITEM_TYPE_RESTART,
CUTSCENE_ITEM_TYPE_QUIT_GAME,
CUTSCENE_ITEM_TYPE_SCENE,
CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK,
CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS,
CUTSCENE_ITEM_TYPE_KEYBOARD,
CUTSCENE_ITEM_TYPE_AUDIO_PLAY,
CUTSCENE_ITEM_TYPE_AUDIO_STOP,
CUTSCENE_ITEM_TYPE_AUDIO_PAUSE,
CUTSCENE_ITEM_TYPE_AUDIO_RESUME,
CUTSCENE_ITEM_TYPE_AUDIO_FADE,
CUTSCENE_ITEM_TYPE_AUDIO_FADE_WAIT,
CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN,
CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP,
CUTSCENE_ITEM_TYPE_AUDIO_SET,
CUTSCENE_ITEM_TYPE_IDLE,
CUTSCENE_ITEM_TYPE_UI_SHOW,
CUTSCENE_ITEM_TYPE_REGULAR_BATTLE,
CUTSCENE_ITEM_TYPE_COUNT
} cutsceneitemtype_t;
/**
* Shorthand for a cutsceneitem_t literal - used by each item type's own
* authoring macro (e.g. CUTSCENE_WAIT in cutscenewait.h) to fill in .type
* and its union member together.
*
* @param TYPE The item's CUTSCENE_ITEM_TYPE_* enum value.
* @param UNION_NAME Name of the cutsceneitem_t union member to fill.
* @param ... The union member's value. Passed through __VA_ARGS__ (rather
* than a single named parameter) so it may itself be a brace initializer
* with top-level commas, e.g.
* CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_FADE, fade, { .from = A, .to = B }).
*/
#define CUTSCENE_ITEM(TYPE, UNION_NAME, ...) \
{ .type = TYPE, .UNION_NAME = __VA_ARGS__ }
/** /**
* Shared no-op Load for item types with no JSON fields of their own to * Shared no-op Load for item types with no JSON fields of their own to
* parse (IDLE, RESTART, MODAL_CLOSE) - always succeeds without touching * parse (IDLE, RESTART, MODAL_CLOSE) - always succeeds without touching
@@ -14,6 +14,14 @@ typedef struct {
char_t text[CUTSCENE_PRINT_MAX_CHARS]; char_t text[CUTSCENE_PRINT_MAX_CHARS];
} cutsceneprint_t; } cutsceneprint_t;
/**
* Prints TEXT to the console.
*
* @param TEXT Text to print.
*/
#define CUTSCENE_PRINT(TEXT) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_PRINT, print, { .text = TEXT })
/** /**
* Starts a print item (prints the item's text to the console). * Starts a print item (prints the item's text to the console).
* *
@@ -15,6 +15,19 @@ typedef struct {
worldpos_t position; worldpos_t position;
} cutsceneentityadd_t; } cutsceneentityadd_t;
/**
* Spawns a new entity into the world immediately.
*
* @param TYPE Entity type to spawn.
* @param X Spawn world X.
* @param Y Spawn world Y.
* @param Z Spawn world Z.
*/
#define CUTSCENE_ENTITY_ADD(TYPE, X, Y, Z) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_ADD, entityAdd, { \
.entityType = TYPE, .position = { X, Y, Z } \
})
/** /**
* Starts an entity add step (spawns the entity into the world immediately). * Starts an entity add step (spawns the entity into the world immediately).
* *
@@ -12,6 +12,16 @@ typedef struct {
uint8_t entityIndex; uint8_t entityIndex;
} cutsceneentityremove_t; } cutsceneentityremove_t;
/**
* Removes an entity from the world immediately.
*
* @param ENTITY_INDEX Entity index to remove.
*/
#define CUTSCENE_ENTITY_REMOVE(ENTITY_INDEX) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_REMOVE, entityRemove, { \
.entityIndex = ENTITY_INDEX \
})
/** /**
* Starts an entity remove step (removes the entity from the world immediately). * Starts an entity remove step (removes the entity from the world immediately).
* *
@@ -14,6 +14,19 @@ typedef struct {
worldpos_t target; worldpos_t target;
} cutsceneentityteleport_t; } cutsceneentityteleport_t;
/**
* Teleports an entity to a world position immediately.
*
* @param ENTITY_INDEX Entity index to teleport.
* @param X Target world X.
* @param Y Target world Y.
* @param Z Target world Z.
*/
#define CUTSCENE_ENTITY_TELEPORT(ENTITY_INDEX, X, Y, Z) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT, entityTeleport, { \
.entityIndex = ENTITY_INDEX, .target = { X, Y, Z } \
})
/** /**
* Starts an entity teleport item (teleports the entity immediately). * Starts an entity teleport item (teleports the entity immediately).
* *
@@ -14,6 +14,17 @@ typedef struct {
entitydir_t direction; entitydir_t direction;
} cutsceneentityturn_t; } cutsceneentityturn_t;
/**
* Turns an entity to face a direction.
*
* @param ENTITY_INDEX Entity index to turn.
* @param DIRECTION Target entitydir_t to face.
*/
#define CUTSCENE_ENTITY_TURN(ENTITY_INDEX, DIRECTION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_TURN, entityTurn, { \
.entityIndex = ENTITY_INDEX, .direction = DIRECTION \
})
/** /**
* Starts an entity turn step. The turn itself is driven from Update, since * Starts an entity turn step. The turn itself is driven from Update, since
* the entity may still be finishing a previous action. * the entity may still be finishing a previous action.
@@ -20,6 +20,45 @@ typedef struct {
uint8_t currentIndex; uint8_t currentIndex;
} cutsceneentitywalktodata_t; } cutsceneentitywalktodata_t;
/**
* Walks an entity to a single world position, navigating around
* obstacles.
*
* @param ENTITY_INDEX Entity index to move.
* @param X Target world X.
* @param Y Target world Y.
* @param Z Target world Z.
*/
#define CUTSCENE_ENTITY_WALK_TO(ENTITY_INDEX, X, Y, Z) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, entityWalkTo, { \
.entityIndex = ENTITY_INDEX, \
.positions = (const worldpos_t[]){ { X, Y, Z } }, \
.count = 1, \
.walkAround = true \
})
/**
* Declares a standalone, named cutsceneitem_t (not a list entry) that
* walks an entity through a fixed sequence of waypoints.
*
* @param NAME Suffix for the generated CUTSCENE_##NAME item/positions
* statics.
* @param ENTITY_INDEX Entity index to move.
* @param ... One or more worldpos_t-shaped waypoint initializers, e.g.
* { X, Y, Z }, { X2, Y2, Z2 }.
*/
#define CUTSCENE_ENTITY_WALK_PATH(NAME, ENTITY_INDEX, ...) \
static const worldpos_t CUTSCENE_##NAME##_POSITIONS[] = { __VA_ARGS__ }; \
static const cutsceneitem_t CUTSCENE_##NAME = { \
.type = CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO, \
.entityWalkTo = { \
.entityIndex = ENTITY_INDEX, \
.positions = CUTSCENE_##NAME##_POSITIONS, \
.count = sizeof(CUTSCENE_##NAME##_POSITIONS) / sizeof(worldpos_t), \
.walkAround = true \
} \
};
/** /**
* Starts an entity walk-to item (resets the waypoint index). * Starts an entity walk-to item (resets the waypoint index).
* *
@@ -16,6 +16,27 @@ typedef struct {
worldunit_t offsetY; worldunit_t offsetY;
} cutsceneentitywalktoentity_t; } cutsceneentitywalktoentity_t;
/**
* Walks ENTITY_INDEX to stand beside TARGET_ENTITY_INDEX, offset by
* (OFFSET_X, OFFSET_Y) on the 2D plane. The destination Z is resolved
* from nearby terrain each frame, so ramps between the two entities are
* accounted for automatically.
*
* @param ENTITY_INDEX Entity index to move.
* @param TARGET_ENTITY_INDEX Entity index to walk toward.
* @param OFFSET_X X offset from the target entity's position.
* @param OFFSET_Y Y offset from the target entity's position.
*/
#define CUTSCENE_ENTITY_WALK_TO_ENTITY( \
ENTITY_INDEX, TARGET_ENTITY_INDEX, OFFSET_X, OFFSET_Y \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY, entityWalkToEntity, { \
.entityIndex = ENTITY_INDEX, \
.targetEntityIndex = TARGET_ENTITY_INDEX, \
.offsetX = OFFSET_X, \
.offsetY = OFFSET_Y \
})
/** /**
* Starts an entity walk-to-entity item. No setup is needed, the destination * Starts an entity walk-to-entity item. No setup is needed, the destination
* is recomputed from the target's live position every Update. * is recomputed from the target's live position every Update.
@@ -14,6 +14,17 @@ typedef struct {
uint8_t quantity; uint8_t quantity;
} cutsceneitemgive_t; } cutsceneitemgive_t;
/**
* Adds an item to the player's backpack immediately.
*
* @param ITEM_ID Item ID to give.
* @param QUANTITY Quantity to give.
*/
#define CUTSCENE_ITEM_GIVE(ITEM_ID, QUANTITY) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_ITEM_GIVE, itemGive, { \
.item = ITEM_ID, .quantity = QUANTITY \
})
/** /**
* Starts a give-item step (adds the item to the player's backpack immediately). * Starts a give-item step (adds the item to the player's backpack immediately).
* *
@@ -16,6 +16,7 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
cutscenejsonentitytype.c cutscenejsonentitytype.c
cutscenejsonentitydir.c cutscenejsonentitydir.c
cutscenejsonbattleencounter.c cutscenejsonbattleencounter.c
cutscenejsonbattleability.c
cutscenejsonbattlestate.c cutscenejsonbattlestate.c
cutscenejsonscenetype.c cutscenejsonscenetype.c
cutscenejsonuiscreentype.c cutscenejsonuiscreentype.c
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "cutscenejsonbattleability.h"
#include "cutscenejsonenum.h"
static const cutscenejsonenumentry_t CUTSCENE_JSON_BATTLE_ABILITY_TABLE[] = {
{ "FIRE", BATTLE_ABILITY_FIRE },
};
#define CUTSCENE_JSON_BATTLE_ABILITY_TABLE_COUNT \
(sizeof(CUTSCENE_JSON_BATTLE_ABILITY_TABLE) / \
sizeof(cutscenejsonenumentry_t))
bool_t cutsceneJsonLookupBattleAbility(
const char_t *name,
battleability_t *out
) {
int32_t value;
if(!cutsceneJsonLookupEnumInsensitive(
CUTSCENE_JSON_BATTLE_ABILITY_TABLE,
CUTSCENE_JSON_BATTLE_ABILITY_TABLE_COUNT, name, &value
)) {
return false;
}
*out = (battleability_t)value;
return true;
}
@@ -0,0 +1,22 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "rpg/battle/battleability.h"
/**
* Looks up name (case-insensitively) against the battle ability table.
*
* @param name Name to search for.
* @param out Set to the matching ability on success.
* @return true if a matching entry was found, false otherwise.
*/
bool_t cutsceneJsonLookupBattleAbility(
const char_t *name,
battleability_t *out
);
@@ -8,6 +8,8 @@
#pragma once #pragma once
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
#include "rpg/overworld/maparea.h" #include "rpg/overworld/maparea.h"
#include "rpg/cutscene/item/maparea/cutscenemapareawait.h"
#include "rpg/cutscene/item/maparea/cutscenemaparearemove.h"
typedef struct { typedef struct {
worldpos_t min; worldpos_t min;
@@ -17,6 +19,55 @@ typedef struct {
uint8_t trigger; uint8_t trigger;
} cutscenemapareaadd_t; } cutscenemapareaadd_t;
/**
* Adds a map area immediately, storing its ID in
* CUTSCENE_SYSTEM.areaLastCreated.
*
* @param MIN_X Area bounding box minimum world X.
* @param MIN_Y Area bounding box minimum world Y.
* @param MIN_Z Area bounding box minimum world Z.
* @param MAX_X Area bounding box maximum world X.
* @param MAX_Y Area bounding box maximum world Y.
* @param MAX_Z Area bounding box maximum world Z.
* @param CALLBACK mapareacallback_t to invoke when the area is triggered.
* @param NOTIFY Notify count/threshold passed to the area.
* @param TRIGGER Trigger count/threshold passed to the area.
*/
#define CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, CALLBACK, NOTIFY, TRIGGER \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MAP_AREA_ADD, mapAreaAdd, { \
.min = { MIN_X, MIN_Y, MIN_Z }, \
.max = { MAX_X, MAX_Y, MAX_Z }, \
.callback = CALLBACK, \
.notify = NOTIFY, \
.trigger = TRIGGER \
})
/**
* Adds a map area, waits for it to be triggered once, then removes it
* before the cutscene continues. Uses a no-op callback since the wait is
* driven by the area's trigger count rather than callback logic.
*
* @param MIN_X Area bounding box minimum world X.
* @param MIN_Y Area bounding box minimum world Y.
* @param MIN_Z Area bounding box minimum world Z.
* @param MAX_X Area bounding box maximum world X.
* @param MAX_Y Area bounding box maximum world Y.
* @param MAX_Z Area bounding box maximum world Z.
* @param NOTIFY Notify count/threshold passed to the area.
* @param TRIGGER Trigger count/threshold passed to the area.
*/
#define CUTSCENE_MAP_AREA_TRIGGER_ONCE( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, NOTIFY, TRIGGER \
) \
CUTSCENE_MAP_AREA_ADD( \
MIN_X, MIN_Y, MIN_Z, MAX_X, MAX_Y, MAX_Z, \
mapAreaNoopCallback, NOTIFY, TRIGGER \
), \
CUTSCENE_MAP_AREA_WAIT(CUTSCENE_AREA_LAST_CREATED), \
CUTSCENE_MAP_AREA_REMOVE(CUTSCENE_AREA_LAST_CREATED)
/** /**
* Starts a map area add step (adds the area immediately, storing its ID * Starts a map area add step (adds the area immediately, storing its ID
* in CUTSCENE_SYSTEM.areaLastCreated). * in CUTSCENE_SYSTEM.areaLastCreated).
@@ -12,6 +12,17 @@ typedef struct {
uint8_t areaId; uint8_t areaId;
} cutscenemaparearemove_t; } cutscenemaparearemove_t;
/**
* Removes a map area immediately.
*
* @param AREA_ID Area ID to remove, or CUTSCENE_AREA_LAST_CREATED in
* place of a literal area ID.
*/
#define CUTSCENE_MAP_AREA_REMOVE(AREA_ID) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE, mapAreaRemove, { \
.areaId = AREA_ID \
})
/** /**
* Starts a map area remove step (removes the area immediately). Accepts * Starts a map area remove step (removes the area immediately). Accepts
* CUTSCENE_AREA_LAST_CREATED in place of a literal area ID. * CUTSCENE_AREA_LAST_CREATED in place of a literal area ID.
@@ -20,6 +20,20 @@ typedef struct {
uint32_t baseline[CUTSCENE_MAP_AREA_WAIT_MAX]; uint32_t baseline[CUTSCENE_MAP_AREA_WAIT_MAX];
} cutscenemapareawaitdata_t; } cutscenemapareawaitdata_t;
/**
* Waits until any one of the given map area IDs has its callback invoked.
*
* @param ... One or more area IDs to watch. Accepts
* CUTSCENE_AREA_LAST_CREATED in place of a literal area ID.
*/
#define CUTSCENE_MAP_AREA_WAIT(...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT, mapAreaWait, { \
.areaIds = (const uint8_t[]){ __VA_ARGS__ }, \
.count = (uint8_t)( \
sizeof((const uint8_t[]){ __VA_ARGS__ }) / sizeof(uint8_t) \
) \
})
/** /**
* Starts a map area wait step, snapshotting each watched area's current * Starts a map area wait step, snapshotting each watched area's current
* trigger count. * trigger count.
@@ -13,6 +13,22 @@ typedef struct {
const char_t *failureMarker; const char_t *failureMarker;
} cutscenesavedevicecheck_t; } cutscenesavedevicecheck_t;
/**
* (Re)requests an available save device and jumps straight to
* SUCCESS_MARKER or FAILURE_MARKER once it resolves, same as a
* CUTSCENE_MODAL_OPTIONS callback - it does not fall through to
* whatever follows this item, so both markers must be scripted
* elsewhere in the same cutscene.
*
* @param SUCCESS_MARKER Marker to jump to if a device is available.
* @param FAILURE_MARKER Marker to jump to if no device is available.
*/
#define CUTSCENE_SAVE_DEVICE_CHECK(SUCCESS_MARKER, FAILURE_MARKER) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK, saveDeviceCheck, { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
})
/** /**
* Starts a save-device-check item: (re)requests an available save * Starts a save-device-check item: (re)requests an available save
* device via saveFindAvailableDevice. Never completes on its own - see * device via saveFindAvailableDevice. Never completes on its own - see
@@ -13,6 +13,22 @@ typedef struct {
const char_t *failureMarker; const char_t *failureMarker;
} cutscenesaveloadallslots_t; } cutscenesaveloadallslots_t;
/**
* (Re)loads every save slot via saveLoadAllSlots() and jumps straight to
* SUCCESS_MARKER or FAILURE_MARKER once it resolves, same shape as
* CUTSCENE_SAVE_DEVICE_CHECK - it does not fall through to whatever
* follows this item, so both markers must be scripted elsewhere in the
* same cutscene.
*
* @param SUCCESS_MARKER Marker to jump to on success.
* @param FAILURE_MARKER Marker to jump to on failure.
*/
#define CUTSCENE_SAVE_LOAD_ALL_SLOTS(SUCCESS_MARKER, FAILURE_MARKER) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS, saveLoadAllSlots, { \
.successMarker = SUCCESS_MARKER, \
.failureMarker = FAILURE_MARKER \
})
/** /**
* Starts a save-load-all-slots item: calls saveLoadAllSlots() and jumps * Starts a save-load-all-slots item: calls saveLoadAllSlots() and jumps
* straight to the item's successMarker or failureMarker via * straight to the item's successMarker or failureMarker via
@@ -15,6 +15,21 @@ typedef struct {
uiemojitype_t emojiType; uiemojitype_t emojiType;
} cutsceneemoji_t; } cutsceneemoji_t;
/**
* Shows an emoji above an entity for a duration, then completes
* immediately.
*
* @param ENTITY_INDEX Entity index to show the emoji above.
* @param EMOJI_TYPE uiemojitype_t to show.
* @param DURATION Duration in seconds to show it.
*/
#define CUTSCENE_EMOJI(ENTITY_INDEX, EMOJI_TYPE, DURATION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_EMOJI, emoji, { \
.entityIndex = ENTITY_INDEX, \
.emojiType = EMOJI_TYPE, \
.duration = DURATION \
})
/** /**
* Starts an emoji step (shows an emoji above the entity for the given * Starts an emoji step (shows an emoji above the entity for the given
* duration, then completes immediately). * duration, then completes immediately).
@@ -17,6 +17,52 @@ typedef struct {
easingtype_t easing; easingtype_t easing;
} cutscenefade_t; } cutscenefade_t;
/**
* Longhand - begins a full-screen overlay transition between two colors.
* See the CUTSCENE_FADE_(TO|FROM)_(BLACK|WHITE) shorthands below.
*
* @param FROM Starting color_t.
* @param TO Ending color_t.
* @param DURATION Duration in seconds.
* @param EASING easingtype_t to apply.
*/
#define CUTSCENE_FADE(FROM, TO, DURATION, EASING) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_FADE, fade, { \
.from = FROM, .to = TO, .duration = DURATION, .easing = EASING \
})
/**
* Shorthand: fades from transparent to black over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_TO_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_BLACK, COLOR_BLACK, DURATION, EASING_LINEAR)
/**
* Shorthand: fades from black to transparent over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_FROM_BLACK(DURATION) \
CUTSCENE_FADE(COLOR_BLACK, COLOR_TRANSPARENT_BLACK, DURATION, EASING_LINEAR)
/**
* Shorthand: fades from transparent to white over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_TO_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_TRANSPARENT_WHITE, COLOR_WHITE, DURATION, EASING_LINEAR)
/**
* Shorthand: fades from white to transparent over DURATION seconds.
*
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_FADE_FROM_WHITE(DURATION) \
CUTSCENE_FADE(COLOR_WHITE, COLOR_TRANSPARENT_WHITE, DURATION, EASING_LINEAR)
/** /**
* Starts a fade item (begins the overlay transition). * Starts a fade item (begins the overlay transition).
* *
@@ -14,6 +14,19 @@ typedef struct {
uikeyboardopen_t open; uikeyboardopen_t open;
} cutscenekeyboard_t; } cutscenekeyboard_t;
/**
* Opens the on-screen keyboard and blocks the cutscene until it closes,
* then caches whatever was typed - see cutsceneSystemGetTextCache to
* read it back afterwards.
*
* @param ... uikeyboardopen_t designated initializers, e.g.
* CUTSCENE_KEYBOARD(.cancel = true, .maxLength = 8).
*/
#define CUTSCENE_KEYBOARD(...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_KEYBOARD, keyboard, { \
.open = { __VA_ARGS__ } \
})
/** /**
* Starts a keyboard item (opens the on-screen keyboard with the item's * Starts a keyboard item (opens the on-screen keyboard with the item's
* open parameters, unmodified - see uiKeyboardOpen). * open parameters, unmodified - see uiKeyboardOpen).
@@ -41,6 +41,59 @@ typedef struct {
cutscenemodaloptioncallback_t callback; cutscenemodaloptioncallback_t callback;
} cutscenemodal_t; } cutscenemodal_t;
/**
* Shows a message-only modal (no option buttons) and immediately
* continues on to whatever follows this item - it does not wait for
* the dialog to be dismissed. Script the rest of the interaction (e.g.
* CUTSCENE_CALLBACK to kick off work, CUTSCENE_WAIT, then
* CUTSCENE_MODAL_CLOSE) as later items in the same cutscene.
*
* @param TITLE Modal title - displayed as-is unless it matches a locale
* message ID, in which case the translated string is shown - see
* uiModalLocalize.
* @param MESSAGE Modal message, same locale-matching rule as TITLE.
*/
#define CUTSCENE_MODAL(TITLE, MESSAGE) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL, modal, { \
.title = TITLE, .message = MESSAGE \
})
/**
* Shows a modal with option buttons and immediately continues on, same
* as CUTSCENE_MODAL - it does not block waiting for a selection.
* Back/cancel input is disabled while it's open (see
* uiMenuSetDisableBack), so it must be dismissed by picking one; CALLBACK
* then fires with the selected option index once the dialog closes.
*
* @param TITLE Modal title (locale-matched, see CUTSCENE_MODAL).
* @param MESSAGE Modal message (locale-matched, see CUTSCENE_MODAL).
* @param CALLBACK cutscenemodaloptioncallback_t fired with the selected
* option index once the dialog closes.
* @param ... Option label strings, e.g.
* CUTSCENE_MODAL_OPTIONS(title, message, callback, "Retry", "Cancel") -
* not copied by this item, so they must stay valid until the modal opens
* (string literals are fine). Each is translated if it matches a locale
* message ID, same as TITLE/MESSAGE.
*/
#define CUTSCENE_MODAL_OPTIONS(TITLE, MESSAGE, CALLBACK, ...) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL, modal, { \
.title = TITLE, .message = MESSAGE, \
.options = (const char_t *[]){ __VA_ARGS__ }, \
.optionCount = (uint8_t)( \
sizeof((const char_t *[]){ __VA_ARGS__ }) / sizeof(const char_t *) \
), \
.callback = CALLBACK \
})
/**
* Closes the currently open modal (if any). Useful when a modal was
* opened outside of a blocking CUTSCENE_MODAL item (e.g. directly via
* uiModalOpen) and this cutscene just needs to dismiss it and continue
* on to whatever follows this item in the sequence.
*/
#define CUTSCENE_MODAL_CLOSE() \
{ .type = CUTSCENE_ITEM_TYPE_MODAL_CLOSE }
/** /**
* Starts a modal item (shows the modal dialog with the item's title, * Starts a modal item (shows the modal dialog with the item's title,
* message, and options, wiring callback to fire with the selected * message, and options, wiring callback to fire with the selected
@@ -7,6 +7,7 @@
#pragma once #pragma once
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
#include "rpg/cutscene/item/ui/cutscenemodal.h"
// Backs CUTSCENE_MODAL_OPTIONS_ONE and CUTSCENE_MODAL_OPTIONS_TWO, so two // Backs CUTSCENE_MODAL_OPTIONS_ONE and CUTSCENE_MODAL_OPTIONS_TWO, so two
// is the most either macro ever needs. // is the most either macro ever needs.
@@ -25,6 +26,49 @@ typedef struct {
uint8_t optionCount; uint8_t optionCount;
} cutscenemodaloptionsmarkers_t; } cutscenemodaloptionsmarkers_t;
/**
* Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly one option and
* MARKER1 to jump straight to via cutsceneGoTo once it's selected - no
* callback function to write. Does not fall through to whatever follows
* this item, so MARKER1 must be scripted elsewhere in the same cutscene.
*
* @param TITLE Modal title (locale-matched, see CUTSCENE_MODAL).
* @param MESSAGE Modal message (locale-matched, see CUTSCENE_MODAL).
* @param OPTION1 The single option's label.
* @param MARKER1 Marker to jump to when OPTION1 is selected.
*/
#define CUTSCENE_MODAL_OPTIONS_ONE(TITLE, MESSAGE, OPTION1, MARKER1) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, modalOptionsMarkers, { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1 }, \
.markers = { MARKER1 }, \
.optionCount = 1 \
})
/**
* Same as CUTSCENE_MODAL_OPTIONS, but fixed to exactly two options,
* jumping straight to OPTION1_MARKER or OPTION2_MARKER via cutsceneGoTo
* once the corresponding option is selected - no callback function to
* write. Does not fall through to whatever follows this item, so both
* markers must be scripted elsewhere in the same cutscene.
*
* @param TITLE Modal title (locale-matched, see CUTSCENE_MODAL).
* @param MESSAGE Modal message (locale-matched, see CUTSCENE_MODAL).
* @param OPTION1 First option's label.
* @param OPTION1_MARKER Marker to jump to when OPTION1 is selected.
* @param OPTION2 Second option's label.
* @param OPTION2_MARKER Marker to jump to when OPTION2 is selected.
*/
#define CUTSCENE_MODAL_OPTIONS_TWO( \
TITLE, MESSAGE, OPTION1, OPTION1_MARKER, OPTION2, OPTION2_MARKER \
) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS, modalOptionsMarkers, { \
.title = TITLE, .message = MESSAGE, \
.options = { OPTION1, OPTION2 }, \
.markers = { OPTION1_MARKER, OPTION2_MARKER }, \
.optionCount = 2 \
})
/** /**
* Starts a modal-options-markers item (shows the modal dialog with the * Starts a modal-options-markers item (shows the modal dialog with the
* item's title, message, and options). * item's title, message, and options).
@@ -13,6 +13,18 @@ typedef struct {
float_t duration; float_t duration;
} cutsceneshake_t; } cutsceneshake_t;
/**
* Kicks off a camera shake immediately.
*
* @param AMOUNT Shake amount, 0 (no shake) to 4 (three tiles): 1 is half
* a tile, 2 is a full tile, 3 is two tiles, and 4 is three tiles.
* @param DURATION Duration in seconds.
*/
#define CUTSCENE_SHAKE(AMOUNT, DURATION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_SHAKE, shake, { \
.amount = AMOUNT, .duration = DURATION \
})
/** /**
* Starts a camera shake item (kicks off the shake on the RPG camera). * Starts a camera shake item (kicks off the shake on the RPG camera).
* *
@@ -14,6 +14,14 @@ typedef struct {
char_t text[CUTSCENE_TEXT_MAX_CHARS]; char_t text[CUTSCENE_TEXT_MAX_CHARS];
} cutscenetext_t; } cutscenetext_t;
/**
* Shows the textbox with TEXT, blocking until it's dismissed.
*
* @param TEXT Text to display.
*/
#define CUTSCENE_TEXT(TEXT) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_TEXT, text, { .text = TEXT })
/** /**
* Starts a text item (shows the textbox with the item's text). * Starts a text item (shows the textbox with the item's text).
* *
@@ -16,6 +16,23 @@ typedef struct {
float_t duration; float_t duration;
} cutscenetextmini_t; } cutscenetextmini_t;
/**
* Shows a mini textbox at a world position for a duration, then
* completes immediately.
*
* @param TEXT Text to display.
* @param X World X of the mini textbox.
* @param Y World Y of the mini textbox.
* @param Z World Z of the mini textbox.
* @param DURATION Duration in seconds to show it.
*/
#define CUTSCENE_TEXT_MINI(TEXT, X, Y, Z, DURATION) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_TEXT_MINI, textMini, { \
.text = TEXT, \
.position = { X, Y, Z }, \
.duration = DURATION \
})
/** /**
* Starts a mini text item (shows a mini textbox at the given world * Starts a mini text item (shows a mini textbox at the given world
* position for the given duration, then completes immediately). * position for the given duration, then completes immediately).
@@ -12,6 +12,16 @@ typedef struct {
uint8_t index; uint8_t index;
} cutscenetextminihide_t; } cutscenetextminihide_t;
/**
* Closes a mini textbox immediately.
*
* @param INDEX Mini textbox index to close.
*/
#define CUTSCENE_TEXT_MINI_HIDE(INDEX) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE, textMiniHide, { \
.index = INDEX \
})
/** /**
* Starts a mini text hide step (closes the mini textbox immediately). * Starts a mini text hide step (closes the mini textbox immediately).
* *
@@ -21,6 +21,15 @@ typedef struct {
uiscreentype_t screen; uiscreentype_t screen;
} cutsceneuishow_t; } cutsceneuishow_t;
/**
* Opens a full-screen UI panel (e.g. the main menu) declaratively, then
* immediately continues on to whatever follows this item.
*
* @param SCREEN uiscreentype_t to open.
*/
#define CUTSCENE_UI_SHOW(SCREEN) \
CUTSCENE_ITEM(CUTSCENE_ITEM_TYPE_UI_SHOW, uiShow, { .screen = SCREEN })
/** /**
* Starts a UI_SHOW item, opening the requested full-screen UI panel. * Starts a UI_SHOW item, opening the requested full-screen UI panel.
* *
@@ -8,6 +8,7 @@
#pragma once #pragma once
#include "entityglobaldefs.h" #include "entityglobaldefs.h"
#include "rpg/cutscene/scene/testcutscene.h" #include "rpg/cutscene/scene/testcutscene.h"
#include "rpg/cutscene/item/cutsceneitem.h"
ENTITY_GLOBAL_CALLBACK(3) { ENTITY_GLOBAL_CALLBACK(3) {
create->entity->data.npc.moveType = NPC_MOVE_TYPE_PATH; create->entity->data.npc.moveType = NPC_MOVE_TYPE_PATH;
@@ -20,11 +21,17 @@ ENTITY_GLOBAL_CALLBACK(3) {
create->entity->interact.data.cutscene = CUTSCENE_REFERENCE(TEST_TWO); create->entity->interact.data.cutscene = CUTSCENE_REFERENCE(TEST_TWO);
} }
ENTITY_GLOBAL_CALLBACK(4) {
create->entity->interact.type = ENTITY_INTERACT_CUTSCENE_NAME;
create->entity->interact.data.cutsceneName = "battletest";
}
static const entityglobaldef_t ENTITY_GLOBAL_LIST[] = { static const entityglobaldef_t ENTITY_GLOBAL_LIST[] = {
ENTITY_GLOBAL(ENTITY_GLOBAL_ID_NULL, ENTITY_TYPE_NULL, NULL), ENTITY_GLOBAL(ENTITY_GLOBAL_ID_NULL, ENTITY_TYPE_NULL, NULL),
ENTITY_GLOBAL(ENTITY_GLOBAL_ID_PLAYER, ENTITY_TYPE_PLAYER, NULL), ENTITY_GLOBAL(ENTITY_GLOBAL_ID_PLAYER, ENTITY_TYPE_PLAYER, NULL),
ENTITY_GLOBAL(3, ENTITY_TYPE_NPC, ENTITY_GLOBAL_REF(3)), ENTITY_GLOBAL(3, ENTITY_TYPE_NPC, ENTITY_GLOBAL_REF(3)),
ENTITY_GLOBAL(4, ENTITY_TYPE_NPC, ENTITY_GLOBAL_REF(4)),
}; };
//EOF //EOF
@@ -27,6 +27,15 @@ void entityInteractWith(entity_t *player, entity_t *target) {
); );
break; break;
case ENTITY_INTERACT_CUTSCENE_NAME: {
const cutscene_t *cutscene =
cutsceneCutsceneResolve(target->interact.data.cutsceneName);
if(cutscene != NULL) {
cutsceneSystemStartCutsceneWith(cutscene, player, target);
}
break;
}
case ENTITY_INTERACT_PRINT: case ENTITY_INTERACT_PRINT:
uiTextboxMainSetText(target->interact.data.message); uiTextboxMainSetText(target->interact.data.message);
@@ -18,6 +18,7 @@ typedef enum {
ENTITY_INTERACT_NULL = 0, ENTITY_INTERACT_NULL = 0,
ENTITY_INTERACT_CUTSCENE, ENTITY_INTERACT_CUTSCENE,
ENTITY_INTERACT_CUTSCENE_NAME,
ENTITY_INTERACT_PRINT, ENTITY_INTERACT_PRINT,
ENTITY_INTERACT_CALLBACK, ENTITY_INTERACT_CALLBACK,
@@ -28,7 +29,18 @@ typedef enum {
* Per-type data for an entity's interact component. * Per-type data for an entity's interact component.
*/ */
typedef union { typedef union {
// A compile-time cutscene_t* (e.g. CUTSCENE_REFERENCE(...)) - safe to
// hold onto indefinitely, since C-authored cutscenes are compiled
// directly into their own static const arrays, never the shared
// CUTSCENE_LOADED_ITEMS buffer (see cutscenesystem.h).
const cutscene_t *cutscene; const cutscene_t *cutscene;
// A bare cutscene name (as passed to cutsceneCutsceneResolve), resolved
// lazily at interact time rather than once up front - only one
// JSON-authored cutscene is ever resident at a time (see
// CUTSCENE_LOADED_ITEMS_MAX's doc comment), so resolving early and
// holding onto the result here would go stale the moment any other
// cutscene loads in the meantime.
const char_t *cutsceneName;
const char_t *message; const char_t *message;
void (*callback)(entity_t *player, entity_t *target); void (*callback)(entity_t *player, entity_t *target);
} entityinteractdata_t; } entityinteractdata_t;
+1 -3
View File
@@ -12,6 +12,7 @@
#include "rpg/cutscene/cutscenesystem.h" #include "rpg/cutscene/cutscenesystem.h"
#include "rpg/item/backpack.h" #include "rpg/item/backpack.h"
#include "rpg/battle/party.h" #include "rpg/battle/party.h"
#include "save/save.h"
#include "ui/rpg/textbox/uitextboxminilist.h" #include "ui/rpg/textbox/uitextboxminilist.h"
#include "time/time.h" #include "time/time.h"
#include "rpgcamera.h" #include "rpgcamera.h"
@@ -32,9 +33,6 @@ errorret_t rpgInit(void) {
errorChain(mapInit()); errorChain(mapInit());
rpgCameraInit(); rpgCameraInit();
// Init test world
errorChain(mapSetMap("overworld"));
// The player is the one entity that isn't sourced from map/chunk data - // The player is the one entity that isn't sourced from map/chunk data -
// every other entity (NPCs, items) and map area comes from the loaded // every other entity (NPCs, items) and map area comes from the loaded
// chunks' own spawn data (see rpg/overworld/map.c mapChunkLoaded). // chunks' own spawn data (see rpg/overworld/map.c mapChunkLoaded).
+5 -4
View File
@@ -21,7 +21,7 @@ errorret_t saveInit() {
// Initialize the slots and settings // Initialize the slots and settings
saveSettingsInit(&SAVE.settings); saveSettingsInit(&SAVE.settings);
saveSlotInit(&SAVE.slot); saveSlotInit();
// Update caches to match default data. // Update caches to match default data.
for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) { for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) {
@@ -226,7 +226,7 @@ errorret_t saveLoadSlot() {
if(SAVE.deviceCurrent == 0xFF) { if(SAVE.deviceCurrent == 0xFF) {
// No save device available, so we assume an empty slot. // No save device available, so we assume an empty slot.
saveSlotInit(&SAVE.slot); saveSlotInit();
SAVE.caches[SAVE.slotCurrent] = SAVE.slot.cachedData; SAVE.caches[SAVE.slotCurrent] = SAVE.slot.cachedData;
errorOk(); errorOk();
} }
@@ -245,7 +245,8 @@ errorret_t saveLoadSlot() {
"Save slot %u could not be loaded, treating as empty.\n", "Save slot %u could not be loaded, treating as empty.\n",
(uint32_t)SAVE.slotCurrent (uint32_t)SAVE.slotCurrent
); );
saveSlotInit(&SAVE.slot); saveSlotInit();
SAVE.slot.cachedData.corrupt = true;
} }
@@ -259,7 +260,7 @@ errorret_t saveLoadSlot() {
errorret_t saveLoadAllSlots() { errorret_t saveLoadAllSlots() {
for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) { for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) {
SAVE.slotCurrent = i; SAVE.slotCurrent = i;
saveSlotInit(&SAVE.slot); saveSlotInit();
errorChain(saveLoadSlot());// Load slot updates the cache. errorChain(saveLoadSlot());// Load slot updates the cache.
} }
+8 -1
View File
@@ -340,8 +340,15 @@ errorret_t saveDeviceRawStoreItem(
slotItems[i].ptr = oldSpans.slots[i].ptr; slotItems[i].ptr = oldSpans.slots[i].ptr;
slotItems[i].len = oldSpans.slots[i].len; slotItems[i].len = oldSpans.slots[i].len;
} else { } else {
// A raw reset, not saveSlotInit() - this fills in a slot index the
// current write isn't touching, and saveSlotInit() only ever
// operates on SAVE.slot now. A blank ("" name) slot never actually
// needs a properly-initialized party (see saveSlotReadJSON's early
// return for an unused slot), so this is equivalent for this
// filler-only purpose.
saveslot_t defaultSlot; saveslot_t defaultSlot;
saveSlotInit(&defaultSlot); memorySet(&defaultSlot, 0, sizeof(defaultSlot));
defaultSlot.version = 1;
char_t *json = NULL; char_t *json = NULL;
size_t len = 0; size_t len = 0;
errorret_t result = saveDeviceRawSerializeSlot(&defaultSlot, &json, &len); errorret_t result = saveDeviceRawSerializeSlot(&defaultSlot, &json, &len);
+136 -3
View File
@@ -353,6 +353,119 @@
} \ } \
} }
/**
* Attaches an already-built mutable value (e.g. a yyjson_mut_arr() of
* per-element objects the caller populated by hand) to the current JSON
* object under the given key.
*
* @param key The key to write to.
* @param value The yyjson_mut_val* to attach.
*/
#define writeValue(key, value) yyjson_mut_obj_add_val(doc, object, key, value)
/**
* Appends a new JSON object to the given mutable array as one element and
* declares `object` in the calling scope pointing at it, shadowing any
* outer `object` - so the writeX macros above, once called inside the loop
* that builds `arr`, populate this element instead of the outer object.
*
* @param arr The yyjson_mut_val* array (from yyjson_mut_arr()) to append to.
*/
#define writeArrayObject(arr) \
yyjson_mut_val *object = yyjson_mut_arr_add_obj(doc, arr)
/**
* Requires a key on the current JSON object to be a JSON array of exactly
* the given size, throwing otherwise. Declares `dest` (a yyjson_val*) in
* the calling scope pointing at the array, ready for the caller to iterate
* (e.g. with yyjson_arr_foreach) - unlike the readXArray macros, this
* doesn't copy the elements out itself, since each element here is a
* nested object the caller parses by hand.
*
* @param key The key to read from.
* @param dest The yyjson_val* variable to declare, pointing at the array.
* @param count The exact number of elements the array must have.
*/
#define requireArrayOfSize(key, dest, count) \
yyjson_val *dest = yyjson_obj_get(object, key); \
if((dest) == NULL) errorThrow("Save JSON missing '%s' key", key); \
if(yyjson_arr_size(dest) != (size_t)(count)) { \
errorThrow( \
"Save JSON array '%s' has wrong length, expected %d", \
key, (int)(count) \
); \
}
/**
* Checks if the given key exists on the current JSON object.
*
* @param key The key to check for.
*/
#define hasUInt8Array(key) (yyjson_obj_get(object, key) != NULL)
/**
* Errors if the given key does not exist on the current JSON object.
*
* @param key The key that must exist.
*/
#define requireUInt8Array(key) \
if(!hasUInt8Array(key)) errorThrow("Save JSON missing '%s' key", key)
/**
* Writes a uint8_t array to the current JSON object.
*
* @param key The key to write to.
* @param value The array to write.
* @param count Number of elements in the array.
*/
#define writeUInt8Array(key, value, count) { \
yyjson_mut_val *saveJsonArr = yyjson_mut_arr(doc); \
size_t saveJsonArrIdx = 0; \
while(saveJsonArrIdx < (size_t)(count)) { \
yyjson_mut_arr_add_uint( \
doc, saveJsonArr, (uint64_t)(value)[saveJsonArrIdx] \
); \
saveJsonArrIdx++; \
} \
yyjson_mut_obj_add_val(doc, object, key, saveJsonArr); \
}
/**
* Reads a uint8_t array from the current JSON object into dest, falling
* back to filling every element with def if the key is missing. Errors if
* the JSON array's length doesn't exactly match count.
*
* @param key The key to read from.
* @param dest The destination array to assign to.
* @param count Number of elements dest holds.
* @param def The default value to fill every element with if the key is
* missing.
*/
#define readUInt8Array(key, dest, count, def) { \
yyjson_val *saveJsonArr = yyjson_obj_get(object, key); \
if(saveJsonArr != NULL) { \
if(yyjson_arr_size(saveJsonArr) != (size_t)(count)) { \
errorThrow( \
"Save JSON array '%s' has wrong length, expected %d", \
key, (int)(count) \
); \
} \
size_t saveJsonArrIdx, saveJsonArrLen; \
yyjson_val *saveJsonArrElem; \
yyjson_arr_foreach( \
saveJsonArr, saveJsonArrIdx, saveJsonArrLen, saveJsonArrElem \
) { \
(dest)[saveJsonArrIdx] = (uint8_t)yyjson_get_uint(saveJsonArrElem); \
} \
} else { \
size_t saveJsonArrIdx = 0; \
while(saveJsonArrIdx < (size_t)(count)) { \
(dest)[saveJsonArrIdx] = (uint8_t)(def); \
saveJsonArrIdx++; \
} \
} \
}
/** /**
* Checks if the given key exists on the current JSON object. * Checks if the given key exists on the current JSON object.
* *
@@ -368,6 +481,26 @@
#define requireString(key) \ #define requireString(key) \
if(!hasString(key)) errorThrow("Save JSON missing '%s' key", key) if(!hasString(key)) errorThrow("Save JSON missing '%s' key", key)
/**
* Errors if the given key is missing, not a string, or a string shorter
* than the given minimum length - e.g. requireStrMin(key, 1) to reject a
* missing/null/empty string outright.
*
* @param key The key to check.
* @param len The minimum string length required.
*/
#define requireStrMin(key, len) { \
yyjson_val *saveJsonStrMinVal = yyjson_obj_get(object, key); \
if( \
saveJsonStrMinVal == NULL || !yyjson_is_str(saveJsonStrMinVal) || \
yyjson_get_len(saveJsonStrMinVal) < (size_t)(len) \
) { \
errorThrow( \
"Save JSON '%s' must be a string of at least length %d", key, (int)(len) \
); \
} \
}
/** /**
* Writes a string to the current JSON object. The string is copied, so it * Writes a string to the current JSON object. The string is copied, so it
* does not need to outlive the JSON document. * does not need to outlive the JSON document.
@@ -399,12 +532,12 @@
); \ ); \
} \ } \
stringCopy( \ stringCopy( \
saveJsonStringBuffer, yyjson_get_str(saveJsonStrVal), (maxLength) \ saveJsonStringBuffer, yyjson_get_str(saveJsonStrVal), (maxLength) + 1 \
); \ ); \
} else { \ } else { \
stringCopy(saveJsonStringBuffer, (def), (maxLength)); \ stringCopy(saveJsonStringBuffer, (def), (maxLength) + 1); \
} \ } \
stringCopy((dest), saveJsonStringBuffer, (maxLength)); \ stringCopy((dest), saveJsonStringBuffer, (maxLength) + 1); \
} }
/** /**
+34 -4
View File
@@ -7,14 +7,32 @@
#include "saveslot.h" #include "saveslot.h"
#include "save/slot/saveslotcurrent.h" #include "save/slot/saveslotcurrent.h"
#include "save/save.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h"
void saveSlotInit(saveslot_t *slot) { void saveSlotInit(void) {
assertNotNull(slot, "Slot cannot be null"); memorySet(&SAVE.slot, 0, sizeof(saveslot_t));
memorySet(slot, 0, sizeof(saveslot_t)); SAVE.slot.version = 1;
slot->version = 1;
partyInit();
}
void saveSlotNewGame(void) {
saveSlotInit();
stringCopy(
SAVE.slot.cachedData.mapName, SAVE_SLOT_MAP_NAME_DEFAULT,
sizeof(SAVE.slot.cachedData.mapName)
);
// TEMPORARY: placeholder starting party stats - replace once there's a
// real starting-party/character-creation flow.
const battlefighterstats_t startingStats =
{ .attack = 10, .defense = 5, .magic = 0, .speed = 10, .luck = 0 };
partyAddMember(startingStats, 30, 10);
} }
bool_t saveSlotInUse(saveslotcache_t *slot) { bool_t saveSlotInUse(saveslotcache_t *slot) {
@@ -37,6 +55,18 @@ errorret_t saveSlotWriteJSON(
} }
errorret_t saveSlotReadJSON(saveslot_t *slot, yyjson_val *object) { errorret_t saveSlotReadJSON(saveslot_t *slot, yyjson_val *object) {
assertNotNull(slot, "Slot cannot be null");
assertNotNull(object, "Object cannot be null");
// A plain reset, not saveSlotInit() - this may be reading into a slot
// other than SAVE.slot (e.g. a save-device round trip in a test), and
// saveSlotInit() only ever operates on SAVE.slot now. saveSlotCurrent
// ReadJSON() fully overwrites every field below anyway (including
// party.members/order), so this only needs to reset the bookkeeping
// fields (version/dataType) that aren't part of the JSON wire format.
memorySet(slot, 0, sizeof(saveslot_t));
slot->version = 1;
errorChain(saveSlotCurrentReadJSON(slot, object)); errorChain(saveSlotCurrentReadJSON(slot, object));
errorOk(); errorOk();
} }
+20 -14
View File
@@ -8,6 +8,7 @@
#pragma once #pragma once
#include "save/savedevice.h" #include "save/savedevice.h"
#include "rpg/overworld/map.h" #include "rpg/overworld/map.h"
#include "rpg/battle/party.h"
#include "time/timeepoch.h" #include "time/timeepoch.h"
#include "yyjson.h" #include "yyjson.h"
@@ -16,35 +17,40 @@
#define SAVE_SLOT_COUNT 3 #define SAVE_SLOT_COUNT 3
#endif #endif
// The stable, version-independent in-memory shape of a save slot - what the #define SAVE_SLOT_MAP_NAME_DEFAULT "overworld"
// rest of the engine actually reads/writes. Every save schema version
// (saveslotver1_t, ...) redefines its own copy of these same fields for its
// JSON wire format; saveSlotCurrentWriteJSON()/ReadJSON() (saveslotcurrent.c)
// manually copy field-by-field between this and whichever version is
// current, so a version's frozen on-disk shape can never drift just because
// this stable struct (or a live engine constant like MAP_NAME_MAX) changes.
typedef struct { typedef struct {
char_t name[SAVE_SLOT_NAME_LENGTH + 1];// 8 characters + null terminator char_t name[SAVE_SLOT_NAME_LENGTH + 1];// 8 characters + null terminator
dusktimeepoch_t time; dusktimeepoch_t time;
int32_t playerLevel; int32_t playerLevel;
char_t mapName[MAP_NAME_MAX]; char_t mapName[MAP_NAME_MAX];
bool_t corrupt;
} saveslotcache_t; } saveslotcache_t;
typedef struct saveslot_s { typedef struct saveslot_s {
uint8_t version; uint8_t version;
uint8_t dataType; uint8_t dataType;
saveslotcache_t cachedData; saveslotcache_t cachedData;
party_t party;
} saveslot_t; } saveslot_t;
/** /**
* Inits the save slot with the default state, this is functionally "new game" * Inits the current save slot (SAVE.slot) with the default state, this is
* but will not set the player name, as that is what we use to determine if a * functionally "new game" but will not set the player name, as that is
* save slot is "in use" or not. * what we use to determine if a save slot is "in use" or not.
*
* @param slot The save slot to init.
*/ */
void saveSlotInit(saveslot_t *slot); void saveSlotInit(void);
/**
* Sets up the current save slot (SAVE.slot) for a brand new game: calls
* saveSlotInit, then seeds it with a starting party. Use this (not
* saveSlotInit) whenever a new save is actually being created for a
* player - saveSlotInit alone leaves the party empty, which every other
* caller (resetting the slot before a load attempt, wiping a deleted
* slot) wants. Callers creating a new save at a specific index should set
* SAVE.slotCurrent first.
*/
void saveSlotNewGame(void);
/** /**
* Checks if the save slot is in use, this is determined by checking if the * Checks if the save slot is in use, this is determined by checking if the
+15
View File
@@ -8,6 +8,7 @@
#include "saveslotcurrent.h" #include "saveslotcurrent.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/string.h" #include "util/string.h"
#include "util/memory.h"
#include "time/time.h" #include "time/time.h"
errorret_t saveSlotCurrentWriteJSON( errorret_t saveSlotCurrentWriteJSON(
@@ -29,6 +30,11 @@ errorret_t saveSlotCurrentWriteJSON(
ver1.playerLevel = slot->cachedData.playerLevel; ver1.playerLevel = slot->cachedData.playerLevel;
stringCopy(ver1.mapName, slot->cachedData.mapName, sizeof(ver1.mapName)); stringCopy(ver1.mapName, slot->cachedData.mapName, sizeof(ver1.mapName));
memoryCopy(
ver1.partyMembers, slot->party.members, sizeof(ver1.partyMembers)
);
memoryCopy(ver1.partyOrder, slot->party.order, sizeof(ver1.partyOrder));
errorChain(saveSlotVer1WriteJSON(&ver1, doc, object)); errorChain(saveSlotVer1WriteJSON(&ver1, doc, object));
errorOk(); errorOk();
} }
@@ -37,7 +43,11 @@ errorret_t saveSlotCurrentReadJSON(saveslot_t *slot, yyjson_val *object) {
assertNotNull(slot, "Slot cannot be null"); assertNotNull(slot, "Slot cannot be null");
assertNotNull(object, "Object cannot be null"); assertNotNull(object, "Object cannot be null");
// Zeroed up front: saveSlotVer1ReadJSON returns early (leaving everything
// past "name" untouched) for a blank/never-used slot, so this must not be
// left as uninitialized stack garbage.
saveslotver1_t ver1; saveslotver1_t ver1;
memoryZero(&ver1, sizeof(ver1));
errorChain(saveSlotVer1ReadJSON(&ver1, object)); errorChain(saveSlotVer1ReadJSON(&ver1, object));
stringCopy(slot->cachedData.name, ver1.name, sizeof(slot->cachedData.name)); stringCopy(slot->cachedData.name, ver1.name, sizeof(slot->cachedData.name));
@@ -47,5 +57,10 @@ errorret_t saveSlotCurrentReadJSON(saveslot_t *slot, yyjson_val *object) {
slot->cachedData.mapName, ver1.mapName, sizeof(slot->cachedData.mapName) slot->cachedData.mapName, ver1.mapName, sizeof(slot->cachedData.mapName)
); );
memoryCopy(
slot->party.members, ver1.partyMembers, sizeof(slot->party.members)
);
memoryCopy(slot->party.order, ver1.partyOrder, sizeof(slot->party.order));
errorOk(); errorOk();
} }
+60
View File
@@ -24,6 +24,28 @@ errorret_t saveSlotVer1WriteJSON(
writeInt32("playerLevel", slot->playerLevel); writeInt32("playerLevel", slot->playerLevel);
writeString("mapName", slot->mapName); writeString("mapName", slot->mapName);
yyjson_mut_val *partyMembersArr = yyjson_mut_arr(doc);
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
battlefighter_t *member = &slot->partyMembers[i];
writeArrayObject(partyMembersArr);
writeUInt32("id", member->id);
writeUInt32("status", member->status);
writeUInt32("team", member->team);
writeUInt32("controller", member->controller);
writeUInt32("health", member->health);
writeUInt32("healthMax", member->healthMax);
writeUInt32("mp", member->mp);
writeUInt32("mpMax", member->mpMax);
writeUInt32("statAttack", member->stats.attack);
writeUInt32("statDefense", member->stats.defense);
writeUInt32("statMagic", member->stats.magic);
writeUInt32("statSpeed", member->stats.speed);
writeUInt32("statLuck", member->stats.luck);
}
writeValue("partyMembers", partyMembersArr);
writeUInt8Array("partyOrder", slot->partyOrder, PARTY_ACTIVE_SIZE_MAX);
errorOk(); errorOk();
} }
@@ -36,11 +58,49 @@ errorret_t saveSlotVer1ReadJSON(saveslotver1_t *slot, yyjson_val *object) {
requireVersion(SAVE_SLOT_CURRENT); requireVersion(SAVE_SLOT_CURRENT);
readString("name", slot->name, "", SAVE_SLOT_VER1_NAME_LENGTH); readString("name", slot->name, "", SAVE_SLOT_VER1_NAME_LENGTH);
if(slot->name[0] == '\0') errorOk();
readTime("time", slot->time); readTime("time", slot->time);
readInt32("playerLevel", slot->playerLevel, 1); readInt32("playerLevel", slot->playerLevel, 1);
requireStrMin("mapName", 1);
readString( readString(
"mapName", slot->mapName, "", SAVE_SLOT_VER1_MAP_NAME_MAX - 1 "mapName", slot->mapName, "", SAVE_SLOT_VER1_MAP_NAME_MAX - 1
); );
requireArrayOfSize(
"partyMembers", partyMembersArr, PARTY_MEMBER_COUNT_MAX
);
size_t memberIdx, memberLen;
yyjson_val *memberObj;
yyjson_arr_foreach(
partyMembersArr, memberIdx, memberLen, memberObj
) {
battlefighter_t *member = &slot->partyMembers[memberIdx];
// Shadows the outer `object` so readUInt32() below (which hardcodes
// that name) reads from this member's object instead.
yyjson_val *object = memberObj;
readUInt32("id", member->id, 0);
readUInt32("status", member->status, BATTLE_FIGHTER_STATUS_NULL);
readUInt32("team", member->team, BATTLE_FIGHTER_TEAM_ALLY);
readUInt32(
"controller", member->controller, BATTLE_FIGHTER_CONTROLLER_PLAYER
);
readUInt32("health", member->health, 0);
readUInt32("healthMax", member->healthMax, 0);
readUInt32("mp", member->mp, 0);
readUInt32("mpMax", member->mpMax, 0);
readUInt32("statAttack", member->stats.attack, 0);
readUInt32("statDefense", member->stats.defense, 0);
readUInt32("statMagic", member->stats.magic, 0);
readUInt32("statSpeed", member->stats.speed, 0);
readUInt32("statLuck", member->stats.luck, 0);
}
readUInt8Array(
"partyOrder", slot->partyOrder, PARTY_ACTIVE_SIZE_MAX,
PARTY_ORDER_EMPTY
);
errorOk(); errorOk();
} }
+8 -1
View File
@@ -9,12 +9,16 @@
#include "error/error.h" #include "error/error.h"
#include "time/timeepoch.h" #include "time/timeepoch.h"
#include "save/slot/saveslotver.h" #include "save/slot/saveslotver.h"
#include "rpg/battle/party.h"
#include "yyjson.h" #include "yyjson.h"
// This schema's own frozen copies of save/slot/saveslot.h's field sizes - // This schema's own frozen copies of save/slot/saveslot.h's field sizes -
// never reference SAVE_SLOT_NAME_LENGTH/MAP_NAME_MAX (or any other live // never reference SAVE_SLOT_NAME_LENGTH/MAP_NAME_MAX (or any other live
// constant) here. Once shipped, this file's on-disk shape must never change // constant) here. Once shipped, this file's on-disk shape must never change
// underneath old save files, even if the live engine constants do. // underneath old save files, even if the live engine constants do. The
// party arrays below are the exception - saveSlotVer1ReadJSON() checks their
// JSON array lengths explicitly, so PARTY_MEMBER_COUNT_MAX/
// PARTY_ACTIVE_SIZE_MAX (rpg/battle/party.h) can be referenced directly.
#define SAVE_SLOT_VER1_NAME_LENGTH 8 #define SAVE_SLOT_VER1_NAME_LENGTH 8
#define SAVE_SLOT_VER1_MAP_NAME_MAX 10 #define SAVE_SLOT_VER1_MAP_NAME_MAX 10
@@ -28,6 +32,9 @@ typedef struct saveslotver1_s {
dusktimeepoch_t time; dusktimeepoch_t time;
int32_t playerLevel; int32_t playerLevel;
char_t mapName[SAVE_SLOT_VER1_MAP_NAME_MAX]; char_t mapName[SAVE_SLOT_VER1_MAP_NAME_MAX];
battlefighter_t partyMembers[PARTY_MEMBER_COUNT_MAX];
uint8_t partyOrder[PARTY_ACTIVE_SIZE_MAX];
} saveslotver1_t; } saveslotver1_t;
/** /**
+13 -1
View File
@@ -57,6 +57,16 @@ void uiSaveSlotSetHighlighted(
saveSlot->highlighted = highlighted; saveSlot->highlighted = highlighted;
} }
bool_t uiSaveSlotIsCorrupt(const uisaveslot_t *saveSlot) {
assertNotNull(saveSlot, "Save slot cannot be NULL");
return saveSlot->corrupt;
}
void uiSaveSlotSetCorrupt(uisaveslot_t *saveSlot, const bool_t corrupt) {
assertNotNull(saveSlot, "Save slot cannot be NULL");
saveSlot->corrupt = corrupt;
}
uisaveslotdisplaytype_t uiSaveSlotGetDisplayType(const uisaveslot_t *saveSlot) { uisaveslotdisplaytype_t uiSaveSlotGetDisplayType(const uisaveslot_t *saveSlot) {
assertNotNull(saveSlot, "Save slot cannot be NULL"); assertNotNull(saveSlot, "Save slot cannot be NULL");
return saveSlot->displayType; return saveSlot->displayType;
@@ -85,7 +95,9 @@ errorret_t uiSaveSlotDraw(
const float_t contentY = y + UI_FRAME_START_Y; const float_t contentY = y + UI_FRAME_START_Y;
color_t color; color_t color;
if(saveSlot->highlighted) { if(saveSlot->corrupt) {
color = COLOR_RED;
} else if(saveSlot->highlighted) {
color = COLOR_RED; color = COLOR_RED;
} else if(saveSlot->displayType == UI_SAVE_SLOT_DISPLAY_TYPE_DELETE) { } else if(saveSlot->displayType == UI_SAVE_SLOT_DISPLAY_TYPE_DELETE) {
color = COLOR_ORANGE; color = COLOR_ORANGE;
+18
View File
@@ -42,6 +42,7 @@ typedef struct {
spritebatchsprite_t nameSprites[UI_SAVE_SLOT_NAME_SPRITES_MAX]; spritebatchsprite_t nameSprites[UI_SAVE_SLOT_NAME_SPRITES_MAX];
bool_t highlighted; bool_t highlighted;
bool_t corrupt;
} uisaveslot_t; } uisaveslot_t;
/** /**
@@ -75,6 +76,23 @@ bool_t uiSaveSlotIsHighlighted(const uisaveslot_t *saveSlot);
*/ */
void uiSaveSlotSetHighlighted(uisaveslot_t *saveSlot, const bool_t highlighted); void uiSaveSlotSetHighlighted(uisaveslot_t *saveSlot, const bool_t highlighted);
/**
* Returns whether the save slot widget is flagged as corrupt.
*
* @param saveSlot The save slot widget to query.
* @returns True if flagged as corrupt.
*/
bool_t uiSaveSlotIsCorrupt(const uisaveslot_t *saveSlot);
/**
* Sets whether the save slot widget is flagged as corrupt - drawn in red
* regardless of highlighted/display-type state, taking priority over both.
*
* @param saveSlot The save slot widget to update.
* @param corrupt The new corrupt state.
*/
void uiSaveSlotSetCorrupt(uisaveslot_t *saveSlot, const bool_t corrupt);
/** /**
* Returns the save slot widget's display type. * Returns the save slot widget's display type.
* *
+127 -83
View File
@@ -7,6 +7,7 @@
#include "uiselectsave.h" #include "uiselectsave.h"
#include "ui/widget/uiframe.h" #include "ui/widget/uiframe.h"
#include "ui/widget/uimodal.h"
#include "ui/dialog/uiconfirm.h" #include "ui/dialog/uiconfirm.h"
#include "ui/dialog/keyboard/uikeyboard.h" #include "ui/dialog/keyboard/uikeyboard.h"
#include "ui/overlay/uifatalerror.h" #include "ui/overlay/uifatalerror.h"
@@ -31,6 +32,14 @@ void uiSelectSaveFormatSlot(
) { ) {
saveslotcache_t *cache = &SAVE.caches[index]; saveslotcache_t *cache = &SAVE.caches[index];
if(cache->corrupt) {
errorret_t result = localeManagerGetString(
"ui.select_save.corrupt", buffer, bufferSize, 0
);
if(errorIsNotOk(result)) errorCatch(result);
return;
}
if(!saveSlotInUse(cache)) { if(!saveSlotInUse(cache)) {
errorret_t result = localeManagerGetString( errorret_t result = localeManagerGetString(
"ui.select_save.empty", buffer, bufferSize, 0 "ui.select_save.empty", buffer, bufferSize, 0
@@ -58,90 +67,9 @@ void uiSelectSaveRefreshSlot(const uint8_t index) {
UI_SELECT_SAVE.type == UI_SELECT_SAVE_TYPE_DELETE ? UI_SELECT_SAVE.type == UI_SELECT_SAVE_TYPE_DELETE ?
UI_SAVE_SLOT_DISPLAY_TYPE_DELETE : UI_SAVE_SLOT_DISPLAY_TYPE_NORMAL; UI_SAVE_SLOT_DISPLAY_TYPE_DELETE : UI_SAVE_SLOT_DISPLAY_TYPE_NORMAL;
uiSaveSlotSetDisplayType(&UI_SELECT_SAVE.slots[index], displayType); uiSaveSlotSetDisplayType(&UI_SELECT_SAVE.slots[index], displayType);
} uiSaveSlotSetCorrupt(
&UI_SELECT_SAVE.slots[index], SAVE.caches[index].corrupt
void uiSelectSaveDeleteConfirmed(const bool_t result, void *user) {
if(!result) return;
assertTrue(SAVE.deviceCurrent != 0xFF, "No current device");
const uint8_t index = UI_SELECT_SAVE.pendingDeleteIndex;
saveslot_t slot;
saveSlotInit(&slot);
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &slot, index
); );
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
return;
}
SAVE.caches[index] = slot.cachedData;
uiSelectSaveRefreshSlot(index);
uiSaveSlotSetHighlighted(&UI_SELECT_SAVE.slots[index], true);
}
void uiSelectSaveConfirmDelete(const uint8_t index) {
UI_SELECT_SAVE.pendingDeleteIndex = index;
uiConfirmOpen(
"ui.select_save.delete_confirm", uiSelectSaveDeleteConfirmed, NULL
);
}
void uiSelectSaveNameEntered(
const char_t *text,
const bool_t confirmed,
void *user
) {
if(!confirmed) return;
const uint8_t index = UI_SELECT_SAVE.pendingNameIndex;
saveslot_t slot;
saveSlotInit(&slot);
stringCopy(slot.cachedData.name, text, SAVE_SLOT_NAME_LENGTH);
// No save device available - proceed with an in-memory-only slot rather
// than writing to a device that doesn't exist (see saveLoadSlot()'s own
// comment on the same "continue without a save device" flow).
if(SAVE.deviceCurrent != 0xFF) {
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &slot, index
);
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
uiFatalErrorOpen(writeResult.state->message);
return;
}
}
SAVE.caches[index] = slot.cachedData;
uiSelectSaveRefreshSlot(index);
UI_SELECT_SAVE.result = index;
uiSelectSaveClose();
}
void uiSelectSaveNameEmptySlot(const uint8_t index) {
UI_SELECT_SAVE.pendingNameIndex = index;
char_t title[UI_KEYBOARD_TITLE_TEXT_MAX];
errorret_t result = localeManagerGetString(
"ui.select_save.name_title", title, sizeof(title), 0
);
if(errorIsNotOk(result)) errorCatch(result);
uikeyboardopen_t open = {
.title = title,
.onInput = uiSelectSaveNameEntered,
.cancel = true,
.maxLength = SAVE_SLOT_NAME_LENGTH,
.trimmed = true,
.allowBlank = false
};
uiKeyboardOpen(&open);
} }
void uiSelectSaveSetActionLabel(const uiselectsavetype_t type) { void uiSelectSaveSetActionLabel(const uiselectsavetype_t type) {
@@ -169,6 +97,116 @@ void uiSelectSaveSwitchType(const uiselectsavetype_t type) {
uiSelectSaveSetActionLabel(type); uiSelectSaveSetActionLabel(type);
} }
void uiSelectSaveDeleteConfirmed(const bool_t result, void *user) {
if(!result) return;
assertTrue(SAVE.deviceCurrent != 0xFF, "No current device");
const uint8_t index = UI_SELECT_SAVE.pendingDeleteIndex;
// uiSelectSaveOpen is only ever reached before any gameplay starts (see
// uimainmenu.c), so it's safe to reuse SAVE.slot as scratch for whichever
// index is being written here - nothing else is relying on it.
SAVE.slotCurrent = index;
saveSlotInit();
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &SAVE.slot, index
);
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
return;
}
SAVE.caches[index] = SAVE.slot.cachedData;
uiSelectSaveSwitchType(UI_SELECT_SAVE_TYPE_LOAD);
uiSelectSaveRefreshSlot(index);
uiSaveSlotSetHighlighted(&UI_SELECT_SAVE.slots[index], true);
}
void uiSelectSaveConfirmDelete(const uint8_t index) {
UI_SELECT_SAVE.pendingDeleteIndex = index;
uiConfirmOpen(
"ui.select_save.delete_confirm", uiSelectSaveDeleteConfirmed, NULL
);
}
void uiSelectSaveNameEntered(
const char_t *text,
const bool_t confirmed,
void *user
) {
if(!confirmed) return;
const uint8_t index = UI_SELECT_SAVE.pendingNameIndex;
// uiSelectSaveOpen is only ever reached before any gameplay starts (see
// uimainmenu.c), so it's safe to reuse SAVE.slot as scratch for whichever
// index is being written here - nothing else is relying on it.
SAVE.slotCurrent = index;
saveSlotNewGame();
stringCopy(SAVE.slot.cachedData.name, text, SAVE_SLOT_NAME_LENGTH);
// No save device available - proceed with an in-memory-only slot rather
// than writing to a device that doesn't exist (see saveLoadSlot()'s own
// comment on the same "continue without a save device" flow).
if(SAVE.deviceCurrent != 0xFF) {
errorret_t writeResult = saveDeviceSlotWrite(
&SAVE.devices[SAVE.deviceCurrent], &SAVE.slot, index
);
if(errorIsNotOk(writeResult)) {
errorCatch(errorPrint(writeResult));
uiFatalErrorOpen(writeResult.state->message);
return;
}
}
SAVE.caches[index] = SAVE.slot.cachedData;
uiSelectSaveRefreshSlot(index);
UI_SELECT_SAVE.result = index;
uiSelectSaveClose();
}
void uiSelectSaveNameEmptySlot(const uint8_t index) {
UI_SELECT_SAVE.pendingNameIndex = index;
char_t title[UI_KEYBOARD_TITLE_TEXT_MAX];
errorret_t result = localeManagerGetString(
"ui.select_save.name_title", title, sizeof(title), 0
);
if(errorIsNotOk(result)) errorCatch(result);
uikeyboardopen_t open = {
.title = title,
.onInput = uiSelectSaveNameEntered,
.cancel = true,
.maxLength = SAVE_SLOT_NAME_LENGTH,
.trimmed = true,
.allowBlank = false
};
uiKeyboardOpen(&open);
}
void uiSelectSaveWarnCorrupt(void) {
const char_t *options[] = { "ui.confirm.confirm" };
// Acknowledging just closes the warning - the player stays on the
// select-save list rather than being pushed into naming/overwriting
// the slot.
uiModalOpen(
"ui.select_save.corrupt", "ui.select_save.corrupt_warning",
options, 1,
NULL, NULL, NULL
);
}
bool_t uiSelectSaveMenuCancelled(const uimenu_t *menu) {
if(UI_SELECT_SAVE.type != UI_SELECT_SAVE_TYPE_DELETE) return false;
uiSelectSaveSwitchType(UI_SELECT_SAVE_TYPE_LOAD);
return true;
}
void uiSelectSaveSlotSelected( void uiSelectSaveSlotSelected(
const uimenu_t *menu, const uimenu_t *menu,
const uint8_t index, const uint8_t index,
@@ -187,6 +225,11 @@ void uiSelectSaveSlotSelected(
return; return;
} }
if(SAVE.caches[index].corrupt) {
uiSelectSaveWarnCorrupt();
return;
}
if(!saveSlotInUse(&SAVE.caches[index])) { if(!saveSlotInUse(&SAVE.caches[index])) {
uiSelectSaveNameEmptySlot(index); uiSelectSaveNameEmptySlot(index);
return; return;
@@ -244,6 +287,7 @@ errorret_t uiSelectSaveInit(void) {
&UI_SELECT_SAVE.slotMenu, uiSelectSaveSlotSelected, uiSelectSaveSlotClosed, &UI_SELECT_SAVE.slotMenu, uiSelectSaveSlotSelected, uiSelectSaveSlotClosed,
uiSelectSaveSlotChanged uiSelectSaveSlotChanged
); );
uiMenuSetCancelCallback(&UI_SELECT_SAVE.slotMenu, uiSelectSaveMenuCancelled);
uiMenuSetItems( uiMenuSetItems(
&UI_SELECT_SAVE.slotMenu, UI_SELECT_SAVE.slotItems, SAVE_SLOT_COUNT, 1 &UI_SELECT_SAVE.slotMenu, UI_SELECT_SAVE.slotItems, SAVE_SLOT_COUNT, 1
); );
+29 -23
View File
@@ -7,7 +7,6 @@
#include "uimainmenu.h" #include "uimainmenu.h"
#include "ui/widget/uiframe.h" #include "ui/widget/uiframe.h"
#include "rpg/battle/testbattle/testbattle.h"
#include "util/memory.h" #include "util/memory.h"
#include "display/spritebatch/spritebatch.h" #include "display/spritebatch/spritebatch.h"
#include "display/screen/screen.h" #include "display/screen/screen.h"
@@ -20,27 +19,22 @@
#include "scene/scene.h" #include "scene/scene.h"
#include "asset/asset.h" #include "asset/asset.h"
#include "save/save.h" #include "save/save.h"
#include "rpg/overworld/map.h"
#define UI_MAIN_MENU_INDEX_START_GAME 0 #define UI_MAIN_MENU_INDEX_START_GAME 0
#define UI_MAIN_MENU_INDEX_OPTIONS 1 #define UI_MAIN_MENU_INDEX_OPTIONS 1
#define UI_MAIN_MENU_INDEX_QUIT 2 #define UI_MAIN_MENU_INDEX_QUIT 2
uimainmenu_t UI_MAIN_MENU; uimainmenu_t UI_MAIN_MENU;
assetentry_t *MAIN_MENU_CUTSCENE_ENTRY = NULL;
cutscene_t *uiMainMenuLoadCutscene(void) { const cutscene_t *uiMainMenuLoadCutscene(void) {
if(MAIN_MENU_CUTSCENE_ENTRY == NULL) { // Delegates entirely to cutsceneCutsceneResolve rather than keeping our
MAIN_MENU_CUTSCENE_ENTRY = assetLock( // own locked-forever entry, since only one JSON-authored cutscene is
"cutscenes/main_menu.jsonc", ASSET_LOADER_TYPE_CUTSCENE, NULL // ever resident at a time (see CUTSCENE_LOADED_ITEMS_MAX's doc comment
); // in cutscenesystem.h) - caching an entry pointer here across calls
} // would go stale the moment any other cutscene loads in the meantime.
errorret_t result = assetRequireLoaded(MAIN_MENU_CUTSCENE_ENTRY); // May return NULL on failure (already reported via uiFatalErrorOpen).
if(errorIsNotOk(result)) { return cutsceneCutsceneResolve("main_menu");
errorCatch(errorPrint(result));
assertTrue(false, "Failed to load main menu cutscene asset");
}
return &MAIN_MENU_CUTSCENE_ENTRY->data.cutscene.cutscene;
} }
void uiMainMenuSelectSaveResult(const uint8_t slotIndex, void *user) { void uiMainMenuSelectSaveResult(const uint8_t slotIndex, void *user) {
@@ -50,7 +44,7 @@ void uiMainMenuSelectSaveResult(const uint8_t slotIndex, void *user) {
} }
SAVE.slotCurrent = slotIndex; SAVE.slotCurrent = slotIndex;
saveSlotInit(&SAVE.slot); saveSlotInit();
errorret_t result = saveLoadSlot(); errorret_t result = saveLoadSlot();
if(errorIsNotOk(result)) { if(errorIsNotOk(result)) {
errorCatch(errorPrint(result)); errorCatch(errorPrint(result));
@@ -58,6 +52,16 @@ void uiMainMenuSelectSaveResult(const uint8_t slotIndex, void *user) {
return; return;
} }
assertStrLenMin(
SAVE.slot.cachedData.mapName, 1, "Save slot has no map name"
);
errorret_t mapResult = mapSetMap(SAVE.slot.cachedData.mapName);
if(errorIsNotOk(mapResult)) {
errorCatch(errorPrint(mapResult));
uiFatalErrorOpen(mapResult.state->message);
return;
}
sceneSet(SCENE_TYPE_OVERWORLD); sceneSet(SCENE_TYPE_OVERWORLD);
} }
@@ -69,9 +73,9 @@ void uiMainMenuOpenSelectSave(void *userData) {
void uiMainMenuStartGame(void) { void uiMainMenuStartGame(void) {
if(CUTSCENE_SYSTEM.scene == NULL) { if(CUTSCENE_SYSTEM.scene == NULL) {
cutsceneSystemStartCutsceneAndGoToMarker( const cutscene_t *cutscene = uiMainMenuLoadCutscene();
uiMainMenuLoadCutscene(), "NEW_GAME" if(cutscene == NULL) return;
); cutsceneSystemStartCutsceneAndGoToMarker(cutscene, "NEW_GAME");
} else { } else {
cutsceneGoTo("NEW_GAME"); cutsceneGoTo("NEW_GAME");
} }
@@ -81,9 +85,9 @@ void uiMainMenuStartGame(void) {
void uiMainMenuOptions(void) { void uiMainMenuOptions(void) {
if(CUTSCENE_SYSTEM.scene == NULL) { if(CUTSCENE_SYSTEM.scene == NULL) {
cutsceneSystemStartCutsceneAndGoToMarker( const cutscene_t *cutscene = uiMainMenuLoadCutscene();
uiMainMenuLoadCutscene(), "OPTIONS" if(cutscene == NULL) return;
); cutsceneSystemStartCutsceneAndGoToMarker(cutscene, "OPTIONS");
} else { } else {
cutsceneGoTo("OPTIONS"); cutsceneGoTo("OPTIONS");
} }
@@ -91,7 +95,9 @@ void uiMainMenuOptions(void) {
void uiMainMenuQuit(void) { void uiMainMenuQuit(void) {
if(CUTSCENE_SYSTEM.scene == NULL) { if(CUTSCENE_SYSTEM.scene == NULL) {
cutsceneSystemStartCutsceneAndGoToMarker(uiMainMenuLoadCutscene(), "QUIT"); const cutscene_t *cutscene = uiMainMenuLoadCutscene();
if(cutscene == NULL) return;
cutsceneSystemStartCutsceneAndGoToMarker(cutscene, "QUIT");
} else { } else {
cutsceneGoTo("QUIT"); cutsceneGoTo("QUIT");
} }
+9 -8
View File
@@ -39,17 +39,18 @@ errorret_t uiMainMenuInit(void);
void uiMainMenuOpen(void); void uiMainMenuOpen(void);
/** /**
* Lazily locks/loads the main menu cutscene asset (assets/cutscenes/ * Loads (or re-loads) the main menu cutscene asset (assets/cutscenes/
* main_menu.jsonc, parsed directly at load time rather than compiled in) * main_menu.jsonc, parsed directly at load time rather than compiled in)
* and returns it, asserting on failure. Kept resident for the rest of the * and returns it - the shared accessor for the "Start Game"/Options/Quit
* process once loaded - the persistent cutscene is what actually drives * flows below to jump/restart it. Only one JSON-authored cutscene is ever
* this whole screen (opening this panel is its first item's job, see * resident at a time (see CUTSCENE_LOADED_ITEMS_MAX's doc comment in
* UI_SHOW/rpg/cutscene/item/ui/cutsceneuishow.h), this is just the shared * cutscenesystem.h), so this resolves fresh on every call rather than
* accessor for the "Start Game" flow below to jump/restart it. * caching anything.
* *
* @return The main menu cutscene. * @return The main menu cutscene, or NULL on failure (already reported via
* uiFatalErrorOpen).
*/ */
cutscene_t *uiMainMenuLoadCutscene(void); const cutscene_t *uiMainMenuLoadCutscene(void);
/** /**
* Starts the "Start Game" flow: jumps the already-running main menu * Starts the "Start Game" flow: jumps the already-running main menu
+106
View File
@@ -8,6 +8,27 @@
#include "memory.h" #include "memory.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/math.h" #include "util/math.h"
#include "log/log.h"
#ifdef DUSK_TRACK_MEMORY
// Fixed-size, pre-allocated table of live memoryAllocate() calls, keyed by
// pointer - deliberately never grows (backed by static storage, not
// malloc) so the tracker itself can never allocate, recurse or leak. Raise
// this if it's ever exhausted (see the assert in memoryAllocateTracked).
#define MEMORY_TRACK_MAX 16384
typedef struct {
void *ptr;
const char_t *file;
int_t line;
size_t size;
} memorytrackentry_t;
static memorytrackentry_t MEMORY_TRACK_ENTRIES[MEMORY_TRACK_MAX];
static size_t MEMORY_TRACK_COUNT = 0;
#endif
size_t memoryGetAllocatedCount(void) { size_t memoryGetAllocatedCount(void) {
return MEMORY_POINTERS_IN_USE; return MEMORY_POINTERS_IN_USE;
@@ -18,6 +39,32 @@ void memoryTrack(void *ptr) {
MEMORY_POINTERS_IN_USE++; MEMORY_POINTERS_IN_USE++;
} }
#ifdef DUSK_TRACK_MEMORY
void * memoryAllocateTracked(
const size_t size, const char_t *file, const int_t line
) {
assertTrue(size > 0, "Cannot allocate 0 bytes of memory.");
void *ptr = malloc(size);
assertNotNull(ptr, "Memory allocation failed.");
memoryTrack(ptr);
assertTrue(
MEMORY_TRACK_COUNT < MEMORY_TRACK_MAX,
"Memory tracking table is full - raise MEMORY_TRACK_MAX."
);
MEMORY_TRACK_ENTRIES[MEMORY_TRACK_COUNT++] = (memorytrackentry_t){
.ptr = ptr,
.file = file,
.line = line,
.size = size
};
return ptr;
}
#else
void * memoryAllocate(const size_t size) { void * memoryAllocate(const size_t size) {
assertTrue(size > 0, "Cannot allocate 0 bytes of memory."); assertTrue(size > 0, "Cannot allocate 0 bytes of memory.");
void *ptr = malloc(size); void *ptr = malloc(size);
@@ -26,6 +73,8 @@ void * memoryAllocate(const size_t size) {
return ptr; return ptr;
} }
#endif
void * memoryAlign(size_t alignment, size_t size) { void * memoryAlign(size_t alignment, size_t size) {
assertTrue(alignment > 0, "Alignment must be greater than 0."); assertTrue(alignment > 0, "Alignment must be greater than 0.");
assertTrue(size > 0, "Cannot allocate 0 bytes of memory."); assertTrue(size > 0, "Cannot allocate 0 bytes of memory.");
@@ -35,8 +84,65 @@ void * memoryAlign(size_t alignment, size_t size) {
return ptr; return ptr;
} }
void memoryCheckUnfreed(void) {
size_t count = memoryGetAllocatedCount();
if(count == 0) {
logDebug("memoryCheckUnfreed: no unfreed allocations.\n");
return;
}
#ifdef DUSK_TRACK_MEMORY
logDebug("memoryCheckUnfreed: %zu unfreed allocation(s):\n", count);
size_t trackedBytes = 0;
for(size_t i = 0; i < MEMORY_TRACK_COUNT; i++) {
memorytrackentry_t *entry = &MEMORY_TRACK_ENTRIES[i];
logDebug(
" - %zu bytes allocated at %s:%d\n",
entry->size, entry->file, entry->line
);
trackedBytes += entry->size;
}
logDebug(" (%zu bytes across %zu tracked allocations)\n",
trackedBytes, MEMORY_TRACK_COUNT
);
// memoryAlign()/memoryTrack() callers aren't recorded into
// MEMORY_TRACK_ENTRIES yet, so the tracked count can fall short of the
// real total - call that out rather than silently under-reporting.
size_t untracked = count - MEMORY_TRACK_COUNT;
if(untracked > 0) {
logDebug(
" + %zu more unfreed allocation(s) with no call site recorded "
"(from memoryAlign()/memoryTrack())\n",
untracked
);
}
#else
logDebug(
"memoryCheckUnfreed: %zu unfreed allocation(s) - rebuild with "
"DUSK_TRACK_MEMORY=ON for call site details.\n",
count
);
#endif
}
void memoryFree(void *ptr) { void memoryFree(void *ptr) {
assertNotNull(ptr, "Cannot free NULL memory."); assertNotNull(ptr, "Cannot free NULL memory.");
#ifdef DUSK_TRACK_MEMORY
// Only pointers from memoryAllocate() are in here (memoryAlign/
// memoryTrack callers aren't tracked yet), so a miss here is expected,
// not an error - just leave the table alone.
for(size_t i = 0; i < MEMORY_TRACK_COUNT; i++) {
if(MEMORY_TRACK_ENTRIES[i].ptr == ptr) {
// Swap-remove - order doesn't matter for leak tracking.
MEMORY_TRACK_ENTRIES[i] = MEMORY_TRACK_ENTRIES[--MEMORY_TRACK_COUNT];
break;
}
}
#endif
free(ptr); free(ptr);
MEMORY_POINTERS_IN_USE--; MEMORY_POINTERS_IN_USE--;
} }
+40 -2
View File
@@ -19,19 +19,57 @@ size_t memoryGetAllocatedCount(void);
/** /**
* Track a pointer that was malloc'd outside of the dusk engine. * Track a pointer that was malloc'd outside of the dusk engine.
* *
* @param ptr The pointer to track. * @param ptr The pointer to track.
*/ */
void memoryTrack(void *ptr); void memoryTrack(void *ptr);
/**
* Reports (via logDebug) whether any memoryAllocate()-family allocation is
* still outstanding - intended to be called once, near shutdown, after
* every subsystem has had a chance to dispose (see engineDispose). With
* DUSK_TRACK_MEMORY defined, prints exactly where (file:line) and how many
* bytes each still-unfreed allocation came from; without it, there's
* nowhere to report a call site from, so it only prints how many blocks
* remain outstanding.
*/
void memoryCheckUnfreed(void);
#ifdef DUSK_TRACK_MEMORY
/**
* Allocates memory, recording the call site (file/line) into a small
* fixed-size tracking table so a block still allocated at shutdown (see
* engineDispose's memoryGetAllocatedCount() check) can be traced back to
* where it came from. memoryFree removes the matching entry again once the
* pointer is freed. Only called via the memoryAllocate(size) macro below
* when DUSK_TRACK_MEMORY is defined - callers keep writing
* memoryAllocate(size) exactly as without it.
*
* @param size The size of the memory to allocate.
* @param file Call site file name (__FILE__).
* @param line Call site line number (__LINE__).
* @return The allocated memory.
*/
void * memoryAllocateTracked(
const size_t size, const char_t *file, const int_t line
);
#define memoryAllocate(size) \
memoryAllocateTracked((size), __FILE__, __LINE__)
#else
/** /**
* Allocates memory. * Allocates memory.
* *
* @param size The size of the memory to allocate. * @param size The size of the memory to allocate.
* @return The allocated memory. * @return The allocated memory.
*/ */
void * memoryAllocate(const size_t size); void * memoryAllocate(const size_t size);
#endif
/** /**
* Allocates aligned memory. * Allocates aligned memory.
* *
+18 -12
View File
@@ -298,7 +298,7 @@ static void test_saveSaveSlot_invalidSlotIndexAsserts(void **state) {
static void test_saveSaveSlot_success(void **state) { static void test_saveSaveSlot_success(void **state) {
makeDeviceAvailable(); makeDeviceAvailable();
SAVE.slotCurrent = 1; SAVE.slotCurrent = 1;
saveSlotInit(&SAVE.slot); saveSlotInit();
stringCopy( stringCopy(
SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name) SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
); );
@@ -311,8 +311,9 @@ static void test_saveSaveSlot_success(void **state) {
assert_true(stringEquals(SAVE.caches[1].name, "Hero")); assert_true(stringEquals(SAVE.caches[1].name, "Hero"));
assert_int_equal(SAVE.caches[1].playerLevel, 12); assert_int_equal(SAVE.caches[1].playerLevel, 12);
// No pre-init needed - saveSlotReadJSON() (via saveDeviceSlotRead) fully
// resets/overwrites its destination struct regardless of prior content.
saveslot_t onDisk; saveslot_t onDisk;
saveSlotInit(&onDisk);
errorret_t readRet = saveDeviceSlotRead(&SAVE.devices[0], &onDisk, 1); errorret_t readRet = saveDeviceSlotRead(&SAVE.devices[0], &onDisk, 1);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_true(stringEquals(onDisk.cachedData.name, "Hero")); assert_true(stringEquals(onDisk.cachedData.name, "Hero"));
@@ -331,15 +332,20 @@ static void test_saveLoadSlot_invalidSlotIndexAsserts(void **state) {
static void test_saveLoadSlot_success(void **state) { static void test_saveLoadSlot_success(void **state) {
makeDeviceAvailable(); makeDeviceAvailable();
saveslot_t onDisk; // Write slot 2's on-disk file via SAVE.slot itself (saveSlotInit() only
saveSlotInit(&onDisk); // ever operates on SAVE.slot now), then reset it again below - the
stringCopy(onDisk.cachedData.name, "Zelda", sizeof(onDisk.cachedData.name)); // write and the load-under-test don't overlap in time.
onDisk.cachedData.playerLevel = 30; SAVE.slotCurrent = 2;
errorret_t writeRet = saveDeviceSlotWrite(&SAVE.devices[0], &onDisk, 2); saveSlotInit();
stringCopy(
SAVE.slot.cachedData.name, "Zelda", sizeof(SAVE.slot.cachedData.name)
);
SAVE.slot.cachedData.playerLevel = 30;
errorret_t writeRet = saveDeviceSlotWrite(&SAVE.devices[0], &SAVE.slot, 2);
assert_true(errorIsOk(writeRet)); assert_true(errorIsOk(writeRet));
SAVE.slotCurrent = 2; SAVE.slotCurrent = 2;
saveSlotInit(&SAVE.slot); saveSlotInit();
SAVE.slotDirty = true; SAVE.slotDirty = true;
errorret_t ret = saveLoadSlot(); errorret_t ret = saveLoadSlot();
@@ -365,7 +371,7 @@ static void test_saveLoadSlot_deviceReadFails_cacheStaysStale(void **state) {
fclose(file); fclose(file);
SAVE.slotCurrent = 0; SAVE.slotCurrent = 0;
saveSlotInit(&SAVE.slot); saveSlotInit();
SAVE.caches[0].playerLevel = 77;// sentinel SAVE.caches[0].playerLevel = 77;// sentinel
errorret_t ret = saveLoadSlot(); errorret_t ret = saveLoadSlot();
@@ -385,7 +391,7 @@ static void test_saveLoadAllSlots_loadsAllAndEndsAtLastIndex(void **state) {
for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) { for(uint8_t i = 0; i < SAVE_SLOT_COUNT; i++) {
SAVE.slotCurrent = i; SAVE.slotCurrent = i;
saveSlotInit(&SAVE.slot); saveSlotInit();
SAVE.slot.cachedData.playerLevel = (int32_t)(i + 1); SAVE.slot.cachedData.playerLevel = (int32_t)(i + 1);
errorret_t saveRet = saveSaveSlot(); errorret_t saveRet = saveSaveSlot();
assert_true(errorIsOk(saveRet)); assert_true(errorIsOk(saveRet));
@@ -404,7 +410,7 @@ static void test_saveLoadAllSlots_missingFileLeavesInitDefaults(void **state) {
makeDeviceAvailable(); makeDeviceAvailable();
SAVE.slotCurrent = 0; SAVE.slotCurrent = 0;
saveSlotInit(&SAVE.slot); saveSlotInit();
SAVE.slot.cachedData.playerLevel = 5; SAVE.slot.cachedData.playerLevel = 5;
errorret_t saveRet = saveSaveSlot(); errorret_t saveRet = saveSaveSlot();
assert_true(errorIsOk(saveRet)); assert_true(errorIsOk(saveRet));
@@ -427,7 +433,7 @@ static void test_saveLoadAllSlots_middleSlotCorrupt_stopsAtFailingIndex(
makeDeviceAvailable(); makeDeviceAvailable();
SAVE.slotCurrent = 0; SAVE.slotCurrent = 0;
saveSlotInit(&SAVE.slot); saveSlotInit();
errorret_t saveRet = saveSaveSlot(); errorret_t saveRet = saveSaveSlot();
assert_true(errorIsOk(saveRet)); assert_true(errorIsOk(saveRet));
+10 -7
View File
@@ -10,6 +10,7 @@
#include "save/savedevice.h" #include "save/savedevice.h"
#include "save/slot/saveslot.h" #include "save/slot/saveslot.h"
#include "save/settings/savesettings.h" #include "save/settings/savesettings.h"
#include "save/save.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
@@ -155,8 +156,9 @@ static void test_saveDeviceCheckAvailability_resolvesSynchronouslyOnLinux(
static void test_saveDeviceSlotWrite_nullAsserts(void **state) { static void test_saveDeviceSlotWrite_nullAsserts(void **state) {
savedevice_t device; savedevice_t device;
// Content is never touched - both calls assert on a NULL argument
// before either device or slot would actually be read.
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceSlotWrite(NULL, &slot, 0)); expect_assert_failure(saveDeviceSlotWrite(NULL, &slot, 0));
expect_assert_failure(saveDeviceSlotWrite(&device, NULL, 0)); expect_assert_failure(saveDeviceSlotWrite(&device, NULL, 0));
@@ -165,7 +167,6 @@ static void test_saveDeviceSlotWrite_nullAsserts(void **state) {
static void test_saveDeviceSlotRead_nullAsserts(void **state) { static void test_saveDeviceSlotRead_nullAsserts(void **state) {
savedevice_t device; savedevice_t device;
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceSlotRead(NULL, &slot, 0)); expect_assert_failure(saveDeviceSlotRead(NULL, &slot, 0));
expect_assert_failure(saveDeviceSlotRead(&device, NULL, 0)); expect_assert_failure(saveDeviceSlotRead(&device, NULL, 0));
@@ -198,15 +199,17 @@ static void test_saveDeviceSlot_dispatchesToPlatform(void **state) {
saveDeviceCheckAvailability(&device, updateCallback, NULL); saveDeviceCheckAvailability(&device, updateCallback, NULL);
saveDeviceUpdate(&device); saveDeviceUpdate(&device);
saveslot_t written; // saveSlotInit() only ever operates on SAVE.slot now, so that's the
saveSlotInit(&written); // write source here.
written.cachedData.playerLevel = 21; saveSlotInit();
SAVE.slot.cachedData.playerLevel = 21;
errorret_t writeRet = saveDeviceSlotWrite(&device, &written, 0); errorret_t writeRet = saveDeviceSlotWrite(&device, &SAVE.slot, 0);
assert_true(errorIsOk(writeRet)); assert_true(errorIsOk(writeRet));
// No pre-init needed - saveSlotReadJSON() (via saveDeviceSlotRead) fully
// resets/overwrites its destination struct regardless of prior content.
saveslot_t read; saveslot_t read;
saveSlotInit(&read);
errorret_t readRet = saveDeviceSlotRead(&device, &read, 0); errorret_t readRet = saveDeviceSlotRead(&device, &read, 0);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
+18 -11
View File
@@ -11,6 +11,7 @@
#include "save/savedevicelinux.h" #include "save/savedevicelinux.h"
#include "save/slot/saveslot.h" #include "save/slot/saveslot.h"
#include "save/settings/savesettings.h" #include "save/settings/savesettings.h"
#include "save/save.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
#include <stdio.h> #include <stdio.h>
@@ -180,8 +181,9 @@ static void test_checkAvailability_mkdirpFails(void **state) {
static void test_slotWrite_nullAsserts(void **state) { static void test_slotWrite_nullAsserts(void **state) {
savedevice_t device; savedevice_t device;
// Content is never touched - both calls assert on a NULL argument
// before either device or slot would actually be read.
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceLinuxSlotWrite(NULL, &slot, 0)); expect_assert_failure(saveDeviceLinuxSlotWrite(NULL, &slot, 0));
expect_assert_failure(saveDeviceLinuxSlotWrite(&device, NULL, 0)); expect_assert_failure(saveDeviceLinuxSlotWrite(&device, NULL, 0));
@@ -190,7 +192,6 @@ static void test_slotWrite_nullAsserts(void **state) {
static void test_slotRead_nullAsserts(void **state) { static void test_slotRead_nullAsserts(void **state) {
savedevice_t device; savedevice_t device;
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
expect_assert_failure(saveDeviceLinuxSlotRead(NULL, &slot, 0)); expect_assert_failure(saveDeviceLinuxSlotRead(NULL, &slot, 0));
expect_assert_failure(saveDeviceLinuxSlotRead(&device, NULL, 0)); expect_assert_failure(saveDeviceLinuxSlotRead(&device, NULL, 0));
@@ -203,17 +204,21 @@ static void test_slotWriteRead_roundTrip(void **state) {
// saveDeviceLinuxCheckAvailability does this via mkdirp. // saveDeviceLinuxCheckAvailability does this via mkdirp.
checkAvailabilityAndDrain(&device); checkAvailabilityAndDrain(&device);
saveslot_t written; // saveSlotInit() only ever operates on SAVE.slot now, so that's the
saveSlotInit(&written); // write source here.
stringCopy(written.cachedData.name, "Hero", sizeof(written.cachedData.name)); saveSlotInit();
written.cachedData.playerLevel = 9; stringCopy(
SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
);
SAVE.slot.cachedData.playerLevel = 9;
errorret_t writeRet = saveDeviceLinuxSlotWrite(&device, &written, 1); errorret_t writeRet = saveDeviceLinuxSlotWrite(&device, &SAVE.slot, 1);
assert_true(errorIsOk(writeRet)); assert_true(errorIsOk(writeRet));
// No pre-init needed - saveSlotReadJSON() (via saveDeviceLinuxSlotRead)
// fully resets/overwrites its destination struct regardless of prior
// content.
saveslot_t read; saveslot_t read;
saveSlotInit(&read);
errorret_t readRet = saveDeviceLinuxSlotRead(&device, &read, 1); errorret_t readRet = saveDeviceLinuxSlotRead(&device, &read, 1);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
@@ -225,8 +230,11 @@ static void test_slotRead_noFileYet_leavesSlotUntouched(void **state) {
savedevice_t device; savedevice_t device;
memoryZero(&device, sizeof(device)); memoryZero(&device, sizeof(device));
// Deliberately not saveSlotInit()'d - a missing slot file means
// saveDeviceLinuxSlotRead never even calls saveSlotReadJSON, so slot
// must come in exactly as the caller left it and go out unchanged.
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot); memoryZero(&slot, sizeof(slot));
stringCopy(slot.cachedData.name, "sentinel", sizeof(slot.cachedData.name)); stringCopy(slot.cachedData.name, "sentinel", sizeof(slot.cachedData.name));
slot.cachedData.playerLevel = 555; slot.cachedData.playerLevel = 555;
@@ -260,7 +268,6 @@ static void test_slotRead_corruptFile_errors(void **state) {
fclose(file); fclose(file);
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = saveDeviceLinuxSlotRead(&device, &slot, 0); errorret_t ret = saveDeviceLinuxSlotRead(&device, &slot, 0);
assert_true(errorIsNotOk(ret)); assert_true(errorIsNotOk(ret));
+74 -51
View File
@@ -7,6 +7,7 @@
#include "dusktest.h" #include "dusktest.h"
#include "save/slot/saveslot.h" #include "save/slot/saveslot.h"
#include "save/save.h"
#include "save/savejson.h" #include "save/savejson.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
@@ -45,24 +46,19 @@ static errorret_t slotFromJSON(saveslot_t *slot, const char_t *json) {
} }
// ============================================================ // ============================================================
// saveSlotInit // saveSlotInit - only ever operates on SAVE.slot now.
// ============================================================ // ============================================================
static void test_saveSlotInit_defaults(void **state) { static void test_saveSlotInit_defaults(void **state) {
saveslot_t slot; memorySet(&SAVE.slot, 0xFF, sizeof(SAVE.slot));
memorySet(&slot, 0xFF, sizeof(slot));
saveSlotInit(&slot); saveSlotInit();
assert_int_equal(slot.version, 1); assert_int_equal(SAVE.slot.version, 1);
assert_int_equal(slot.dataType, 0); assert_int_equal(SAVE.slot.dataType, 0);
assert_int_equal(slot.cachedData.name[0], '\0'); assert_int_equal(SAVE.slot.cachedData.name[0], '\0');
assert_true(slot.cachedData.time.time == 0.0); assert_true(SAVE.slot.cachedData.time.time == 0.0);
assert_int_equal(slot.cachedData.playerLevel, 0); assert_int_equal(SAVE.slot.cachedData.playerLevel, 0);
}
static void test_saveSlotInit_nullAsserts(void **state) {
expect_assert_failure(saveSlotInit(NULL));
} }
// ============================================================ // ============================================================
@@ -70,13 +66,14 @@ static void test_saveSlotInit_nullAsserts(void **state) {
// ============================================================ // ============================================================
static void test_saveSlotInUse(void **state) { static void test_saveSlotInUse(void **state) {
saveslot_t slot; saveSlotInit();
saveSlotInit(&slot);
assert_false(saveSlotInUse(&slot.cachedData)); assert_false(saveSlotInUse(&SAVE.slot.cachedData));
stringCopy(slot.cachedData.name, "Hero", sizeof(slot.cachedData.name)); stringCopy(
assert_true(saveSlotInUse(&slot.cachedData)); SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
);
assert_true(saveSlotInUse(&SAVE.slot.cachedData));
} }
static void test_saveSlotInUse_nullAsserts(void **state) { static void test_saveSlotInUse_nullAsserts(void **state) {
@@ -84,18 +81,17 @@ static void test_saveSlotInUse_nullAsserts(void **state) {
} }
static void test_saveSlotHasSaved(void **state) { static void test_saveSlotHasSaved(void **state) {
saveslot_t slot; saveSlotInit();
saveSlotInit(&slot);
assert_false(saveSlotHasSaved(&slot.cachedData)); assert_false(saveSlotHasSaved(&SAVE.slot.cachedData));
// Writing to JSON stamps the current time as a side effect, so even a // Writing to JSON stamps the current time as a side effect, so even a
// pure serialize (no device write) flips "has ever saved" to true. // pure serialize (no device write) flips "has ever saved" to true.
char_t *json; char_t *json;
size_t len; size_t len;
errorret_t ret = slotToJSON(&slot, &json, &len); errorret_t ret = slotToJSON(&SAVE.slot, &json, &len);
assert_true(errorIsOk(ret)); assert_true(errorIsOk(ret));
assert_true(saveSlotHasSaved(&slot.cachedData)); assert_true(saveSlotHasSaved(&SAVE.slot.cachedData));
free(json); free(json);
} }
@@ -109,8 +105,9 @@ static void test_saveSlotHasSaved_nullAsserts(void **state) {
// ============================================================ // ============================================================
static void test_saveSlotWriteJSON_nullAsserts(void **state) { static void test_saveSlotWriteJSON_nullAsserts(void **state) {
// Content is never touched - both calls assert on a NULL doc/object
// argument before slot itself would actually be read.
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
writeInit(); writeInit();
expect_assert_failure(saveSlotWriteJSON(NULL, doc, object)); expect_assert_failure(saveSlotWriteJSON(NULL, doc, object));
@@ -126,7 +123,6 @@ static void test_saveSlotWriteJSON_nullAsserts(void **state) {
static void test_saveSlotReadJSON_nullAsserts(void **state) { static void test_saveSlotReadJSON_nullAsserts(void **state) {
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
yyjson_doc *readDoc = yyjson_read("{}", 2, 0); yyjson_doc *readDoc = yyjson_read("{}", 2, 0);
yyjson_val *readObject = yyjson_doc_get_root(readDoc); yyjson_val *readObject = yyjson_doc_get_root(readDoc);
@@ -138,55 +134,86 @@ static void test_saveSlotReadJSON_nullAsserts(void **state) {
} }
static void test_saveSlotReadJSON_roundTrip(void **state) { static void test_saveSlotReadJSON_roundTrip(void **state) {
saveslot_t written; // saveSlotInit() only ever operates on SAVE.slot now, so that's the
saveSlotInit(&written); // write source here.
written.version = 7;// deliberately non-default, not part of the JSON schema saveSlotInit();
stringCopy(written.cachedData.name, "Hero", sizeof(written.cachedData.name)); SAVE.slot.version = 7;// deliberately non-default, not part of the JSON schema
written.cachedData.playerLevel = 42; stringCopy(
SAVE.slot.cachedData.name, "Hero", sizeof(SAVE.slot.cachedData.name)
);
SAVE.slot.cachedData.playerLevel = 42;
// An in-use slot (non-empty name) requires a non-empty map name too -
// see saveSlotNewGame/requireStrMin("mapName", 1) in saveSlotVer1ReadJSON.
stringCopy(
SAVE.slot.cachedData.mapName, "overworld",
sizeof(SAVE.slot.cachedData.mapName)
);
char_t *json; char_t *json;
size_t len; size_t len;
errorret_t writeRet = slotToJSON(&written, &json, &len); errorret_t writeRet = slotToJSON(&SAVE.slot, &json, &len);
assert_true(errorIsOk(writeRet)); assert_true(errorIsOk(writeRet));
saveslot_t read; const dusktimeepoch_t writtenTime = SAVE.slot.cachedData.time;
saveSlotInit(&read);
// No pre-init needed - saveSlotReadJSON() fully resets/overwrites its
// destination struct regardless of prior content.
saveslot_t read;
errorret_t readRet = slotFromJSON(&read, json); errorret_t readRet = slotFromJSON(&read, json);
assert_true(errorIsOk(readRet)); assert_true(errorIsOk(readRet));
assert_true(stringEquals(read.cachedData.name, "Hero")); assert_true(stringEquals(read.cachedData.name, "Hero"));
assert_int_equal(read.cachedData.playerLevel, 42); assert_int_equal(read.cachedData.playerLevel, 42);
assert_true(read.cachedData.time.time == written.cachedData.time.time); assert_true(stringEquals(read.cachedData.mapName, "overworld"));
assert_true(read.cachedData.time.time == writtenTime.time);
// version/dataType are struct-only bookkeeping, never serialized - the // version/dataType are struct-only bookkeeping, never serialized - the
// reader keeps whatever saveSlotInit gave it regardless of the writer's // reader resets them to the default regardless of the writer's version.
// version.
assert_int_equal(read.version, 1); assert_int_equal(read.version, 1);
free(json); free(json);
} }
static void test_saveSlotReadJSON_missingFieldsUseDefaults(void **state) { static void test_saveSlotReadJSON_blankSlot_shortCircuits(void **state) {
// Deliberately not saveSlotInit()'d - saveSlotReadJSON() fully resets its
// destination struct itself before parsing, so these sentinel values are
// only here to prove they get overwritten, not preserved.
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot); memorySet(&slot, 0, sizeof(slot));
stringCopy(slot.cachedData.name, "sentinel", sizeof(slot.cachedData.name)); stringCopy(slot.cachedData.name, "sentinel", sizeof(slot.cachedData.name));
slot.cachedData.playerLevel = 999; slot.cachedData.playerLevel = 999;
errorret_t ret = slotFromJSON( // No "name" key (or an empty one) means a blank/never-used slot (see
&slot, // saveSlotInUse) - the reader returns right after reading that, without
"{\"version\":1," // needing or validating time/mapName/partyMembers/partyOrder at all, so
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}" // this succeeds despite omitting fields that would otherwise be required.
); errorret_t ret = slotFromJSON(&slot, "{\"version\":1}");
assert_true(errorIsOk(ret)); assert_true(errorIsOk(ret));
assert_int_equal(slot.cachedData.name[0], '\0'); assert_int_equal(slot.cachedData.name[0], '\0');
assert_int_equal(slot.cachedData.playerLevel, 1); assert_int_equal(slot.cachedData.mapName[0], '\0');
// Not readInt32's own default of 1 - the early return happens before
// playerLevel is ever read, leaving the zero-init saveSlotCurrentReadJSON
// seeds ver1 with (see the memoryZero in saveSlotCurrentReadJSON).
assert_int_equal(slot.cachedData.playerLevel, 0);
}
static void test_saveSlotReadJSON_inUseMissingMapName_errors(void **state) {
saveslot_t slot;
// "name" is present (in use) but "mapName" is missing - a real save
// (via saveSlotNewGame) always has both, so this is corrupt.
errorret_t ret = slotFromJSON(
&slot,
"{\"version\":1,\"name\":\"Hero\","
"\"time\":{\"time\":1.0,\"timeZone\":0.0,\"offsetTime\":0.0}}"
);
assert_true(errorIsNotOk(ret));
errorCatch(ret);
} }
static void test_saveSlotReadJSON_missingTimeKey_errors(void **state) { static void test_saveSlotReadJSON_missingTimeKey_errors(void **state) {
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON( errorret_t ret = slotFromJSON(
&slot, "{\"version\":1,\"name\":\"Hero\",\"playerLevel\":5}" &slot, "{\"version\":1,\"name\":\"Hero\",\"playerLevel\":5}"
@@ -197,7 +224,6 @@ static void test_saveSlotReadJSON_missingTimeKey_errors(void **state) {
static void test_saveSlotReadJSON_nameTooLong_errors(void **state) { static void test_saveSlotReadJSON_nameTooLong_errors(void **state) {
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON( errorret_t ret = slotFromJSON(
&slot, &slot,
@@ -210,7 +236,6 @@ static void test_saveSlotReadJSON_nameTooLong_errors(void **state) {
static void test_saveSlotReadJSON_nonObjectRoot_errors(void **state) { static void test_saveSlotReadJSON_nonObjectRoot_errors(void **state) {
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
// A non-object root has no keys, so every field falls back to its // A non-object root has no keys, so every field falls back to its
// default - except "version" and "time", which are required and error // default - except "version" and "time", which are required and error
@@ -226,7 +251,6 @@ static void test_saveSlotReadJSON_nonObjectRoot_errors(void **state) {
static void test_saveSlotReadJSON_versionMissing_errors(void **state) { static void test_saveSlotReadJSON_versionMissing_errors(void **state) {
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON( errorret_t ret = slotFromJSON(
&slot, &slot,
@@ -239,7 +263,6 @@ static void test_saveSlotReadJSON_versionMissing_errors(void **state) {
static void test_saveSlotReadJSON_versionMismatch_errors(void **state) { static void test_saveSlotReadJSON_versionMismatch_errors(void **state) {
saveslot_t slot; saveslot_t slot;
saveSlotInit(&slot);
errorret_t ret = slotFromJSON( errorret_t ret = slotFromJSON(
&slot, &slot,
@@ -254,7 +277,6 @@ int main(void) {
assertInit(); assertInit();
const struct CMUnitTest tests[] = { const struct CMUnitTest tests[] = {
cmocka_unit_test(test_saveSlotInit_defaults), cmocka_unit_test(test_saveSlotInit_defaults),
cmocka_unit_test(test_saveSlotInit_nullAsserts),
cmocka_unit_test(test_saveSlotInUse), cmocka_unit_test(test_saveSlotInUse),
cmocka_unit_test(test_saveSlotInUse_nullAsserts), cmocka_unit_test(test_saveSlotInUse_nullAsserts),
@@ -265,7 +287,8 @@ int main(void) {
cmocka_unit_test(test_saveSlotReadJSON_nullAsserts), cmocka_unit_test(test_saveSlotReadJSON_nullAsserts),
cmocka_unit_test(test_saveSlotReadJSON_roundTrip), cmocka_unit_test(test_saveSlotReadJSON_roundTrip),
cmocka_unit_test(test_saveSlotReadJSON_missingFieldsUseDefaults), cmocka_unit_test(test_saveSlotReadJSON_blankSlot_shortCircuits),
cmocka_unit_test(test_saveSlotReadJSON_inUseMissingMapName_errors),
cmocka_unit_test(test_saveSlotReadJSON_missingTimeKey_errors), cmocka_unit_test(test_saveSlotReadJSON_missingTimeKey_errors),
cmocka_unit_test(test_saveSlotReadJSON_nameTooLong_errors), cmocka_unit_test(test_saveSlotReadJSON_nameTooLong_errors),
cmocka_unit_test(test_saveSlotReadJSON_nonObjectRoot_errors), cmocka_unit_test(test_saveSlotReadJSON_nonObjectRoot_errors),