21 Commits
Author SHA1 Message Date
YourWishesandClaude Sonnet 5 3948607b1e Rename cutscenesystemrefs_t to cutsceneref_t, cutsceneRefsReset to cutsceneRefReset, and cutscenerefs.c/.h to cutsceneref.c/.h
Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-25 10:23:38 -05:00
YourWishes 6c180372fe First pass cleaning cutscene system. 2026-09-25 09:57:48 -05:00
YourWishesandClaude Sonnet 5 fed04b66b8 Persist and resume in-progress cutscene via save slot; add species stub
Save slots now track the currently-active cutscene file (defaulting to a
new placeholder new_game.jsonc intro) so loading a save resumes it;
cutsceneSystemStartCutsceneWith persists this on every cutscene start, and
a cutsceneSystemLoad ordering bug (loadedFile stamped after starting) is
fixed so the persisted path is always correct. Also adds a
battlefighterspecies_t/battlespeciesid_t stub for upcoming species data.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-22 18:44:45 -05:00
YourWishesandClaude Sonnet 5 a4ca718070 Add shared battleFighterParse/Serialize, use it everywhere a fighter is (de)serialized
Replaces three independently hand-rolled battlefighter_t JSON readers/
writers (party.jsonc roster loading, BATTLE_START enemy definitions, and
the v1 save-file party member format) with one generic pair in
battlefighter.c: battleFighterParse(fighter, obj) and its inverse
battleFighterSerialize(fighter, doc). Covers team/controller/status
(optional, default ally/player/normal), the 7 base stats (required),
current health/mp (optional, default to max), and an optional abilities
name array.

- party.c: partyInit now parses each roster member via battleFighterParse
  directly, dropping the old partyParseStats/partyParseStatField.
- cutscenebattlestart.c/.h: cutscenebattlestartenemy_t now embeds a full
  battlefighter_t, parsed once at Load time; Start just copies it into the
  enemy pool instead of re-initializing. battletest.jsonc's enemies are
  now flat (dropped the "stats" wrapper) to match.
- saveslotver1.c/.h: rewritten in place to use the shared parser/
  serializer, changing the v1 on-disk field names/shape (no migration -
  acceptable pre-release, documented in saveslotver1.h).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-22 14:20:45 -05:00
YourWishesandClaude Sonnet 5 8dbd3e1dd2 Key-based party roster, show party member names in battle UI
- party.jsonc's "members" is now a key/value object (e.g. "hero",
  "companion") instead of an array - partyInit seeds party_t.keys
  alongside members, and partyGetMemberIndexByKey/partyGetMemberKey do the
  lookups. Cutscene items (PARTY_ADD_MEMBER/PARTY_REMOVE_MEMBER/
  PARTY_HEAL_MEMBER) now take a "key" JSON field, resolved to a roster
  index at load time, instead of a raw index.
- Battle UI shows who's acting: uibattlemenu.c draws the current fighter's
  party key above the action menu, and uibattlehud.c draws each ally
  fighter's key as an extra line above their HP/MP.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-21 22:38:04 -05:00
YourWishesandClaude Sonnet 5 7a9a2b9832 Add order-based party roster, back-navigation in battle selection, fix win-state cutscene leak
- Battle selection menu can now go back a fighter to re-decide their move,
  and battle win/loss no longer leaks the round's remaining queued move
  cutscenes into the ending state (cutsceneSystemDiscardQueued).
- Party roster is now driven by party.jsonc: every defined member always
  exists (partyInit), while party->order alone determines who's currently
  active - partyAddMember/partyRemoveMember (and their cutscene items) now
  activate/deactivate an existing roster member by index instead of
  creating/destroying one, with removal compacting order to stay packed.
- New PARTY_ADD_MEMBER/PARTY_REMOVE_MEMBER/PARTY_HEAL_MEMBER/PARTY_HEAL_ALL
  cutscene items.
- saveSlotInit/partyInit now return errorret_t and take their target
  struct directly (saveslot_t*/party_t*) instead of implicitly operating
  on SAVE.slot; saveSlotReadJSON resets through saveSlotInit rather than
  duplicating the reset logic.
- Test coverage: stub the JSON asset loader in save test fixtures so
  partyInit's real party.jsonc load runs against an in-memory doc instead
  of hanging with no asset system initialized.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-21 22:27:46 -05:00
YourWishes e8757c33e3 Fix U_IDLE asset error from cutscene item pointer aliasing
cutsceneCutsceneResolve and cutsceneSystemLoad could be called with a
name/path pointer that aliases into CUTSCENE_SYSTEM.loadedItems (e.g. a
CUTSCENE item's own name field). cutsceneLoadParse then overwrites that
same buffer while loading the target cutscene, so the subsequent
stringCopy into loadedFile read stale, corrupted memory. Copy the
name/path into a local buffer before use in both functions.
2026-09-21 19:48:28 -05:00
YourWishes b498a12458 Merge branch 'battle-refactor' 2026-09-21 15:04:52 -05:00
YourWishesandClaude Sonnet 5 c9f098693c Wire up battle AI/scene-return, reclaim cutscene item slots, fix GOTO
- battleStateSelectionAiDecide: AI-controlled fighters now actually
  queue a basic attack against the first living enemy instead of doing
  nothing every round.
- battleStateEndingInit: disposes the battle and switches back to
  SCENE_TYPE_OVERWORLD instead of leaving the game stuck in the battle
  scene forever.
- cutsceneSystemNext now pops each finished item off the front of the
  running cutscene (cutsceneRemoveFront) instead of leaving it in place
  forever, so a long-running cutscene (many battle rounds splicing
  items in repeatedly) no longer grows scene->items unboundedly.
- cutsceneGoTo reworked to match: since consumed items are evicted, a
  marker behind the current position can't be found in the live queue
  anymore, so it now re-parses the cutscene fresh from its source file
  (cutsceneLoadParse, into a persistent scratch buffer, not the stack)
  and replaces the live queue with marker-onward from that fresh parse.
  Only supported when the running cutscene is the one
  cutsceneSystemLoad/cutsceneCutsceneResolve populated.
- Fixed a real bug this surfaced: cutsceneSystemPrepare unconditionally
  cleared loadedFile, which ran *after* cutsceneCutsceneResolve had
  just stamped it but *before* the cutscene started - wiping it out
  immediately and breaking cutsceneGoTo for any cutscene entered via a
  CUTSCENE item or cutsceneCutsceneResolve (e.g. the main menu's
  NEW_GAME/OPTIONS/QUIT navigation). Now only cleared when switching
  away from loadedScene entirely.
- Added cutsceneLoadParse, the shared "lock asset, require loaded,
  parse items, unlock" sequence, replacing four near-identical copies
  across cutsceneSystemLoad/cutsceneCutsceneResolve/
  cutsceneInsertResolveAndSplice/battleStateExecutingInit. Each call
  site handles its own fatal-error display; cutsceneLoadParse itself
  just propagates.
- Added test_cutscene.c (cutsceneRemoveFront) and a regression test for
  the loadedFile bug. Writing the zero-count RemoveFront test caught a
  real self-move bug (count == 0 passed dest == src into memoryMove).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-21 15:04:41 -05:00
YourWishesandClaude Sonnet 5 7aeffac9fc Add battle fighter damage/heal cutscene items, wire up battle results
BATTLE_FIGHTER_DAMAGE/BATTLE_FIGHTER_HEAL let a move's own cutscene
apply damage/healing to "target" or "user", resolved from
BATTLE_FIGHTER_POS_TARGET/USER sentinels against the current action by
battleStateExecutingInit. fire/slash now call BATTLE_FIGHTER_DAMAGE on
their target.

BATTLE_POST_MOVE checks fighter health after each move and sets
BATTLE.result (now a real field, previously commented out) to
win/loss, transitioning into BATTLE_STATE_WON/LOST; fleeing sets
BATTLE_RESULT_FLED. All three end states now show a textbox before
moving on to BATTLE_STATE_ENDING.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-20 21:14:00 -05:00
YourWishesandClaude Sonnet 5 37e7e95ace Resolve moves into per-move cutscenes during battle execution
Each queued action now resolves to its move's cutscene
(cutscenes/battle/moves/<name>.jsonc), spliced into the executing state
with a BATTLE_POST_MOVE checkpoint after each one. Fighter turn order is
tracked via fighterOrder/fighterOrderCount, and resolved actions/pending
counts are cleared so fighters aren't skipped in later rounds. Also fixes
a BATTLE_WAIT_SELECTION deadlock and adds an optional "blocking" flag to
MODAL cutscene items.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-20 17:49:06 -05:00
YourWishesandClaude Sonnet 5 e3f56c4d12 Drive battle rounds through cutscene items, fix render/init bugs
Adds BATTLE_START, BATTLE_SET_STATE and BATTLE_WAIT_SELECTION cutscene
items so a battle's state transitions (opening -> pre-round -> selection
-> executing) are chained through the running cutscene, with
cutsceneSystemInsertItemsNext/InsertItems splitting "splice" from
"splice and advance immediately". Adds battlestateselection's
get-current-fighter/player-attack/player-flee API backing the battle UI,
and battleMoveGetIdByName for JSON-authored ability lookups.

Fixes: off-by-one in battleMoveInit that let the first-defined move
alias BATTLE_MOVE_ID_NULL; a segfault in scenebattle.c from rendering
unfilled (NULL) fighter slots; stale battleGetCurrentFighter/
battlePlayerAttack/battlePlayerFlee references in the battle UI.

Adds assertions across the battle/scene/UI code for fighter-index
bounds and non-null invariants. Updates battletest.jsonc for the new
BATTLE_START item schema.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-20 13:32:52 -05:00
YourWishesandClaude Sonnet 5 3675ec634f Rework battle system: pointer-based fighters, per-state files, move split
Splits battlemoveaction_t into its own header, adds a per-state
struct/init/update/dispose file under rpg/battle/state driven by a
dispatch table, switches BATTLE.fighters to battlefighter_t* backed by a
pool, folds current/max health and mp into battlefighterstats_t, and adds
battleFighterDamage/Heal/AbilityAdd. Removes the now-unused battle
cutscene items (START_BATTLE, BATTLE_WAIT_STATE, BATTLE_FORCE_MOVE,
REGULAR_BATTLE) and their JSON lookup helpers, and adds JSON validation
to battleMoveInit. battle.h/battle.c are mid-rewrite around the new state
machine, so some UI consumers (uibattlehud.c, uibattlemenu.c) and
test_battle.c are currently out of sync with the new API.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-19 23:17:27 -05:00
YourWishes d8273a225c Battle changes, first pass. 2026-09-19 22:30:01 -05:00
YourWishesandClaude Sonnet 5 c1c8174b27 Use CUTSCENE/INSERT item names as full asset paths directly
cutsceneCutsceneResolve/cutsceneInsertResolveAndSplice no longer inject
a "cutscenes/%s.jsonc" prefix/suffix around an item's "name" field -
matching cutsceneSystemLoad, which already takes a full path. Fixes a
latent double-prefix bug in initial.jsonc's CUTSCENE reference (also had
a "jsonsc" typo) that this change would otherwise have exposed.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-19 21:38:09 -05:00
YourWishes 5697f5c064 Fix main menu crash 2026-09-19 21:33:21 -05:00
YourWishesandClaude Sonnet 5 3ce16cf7f4 Fix uilabel dirty bug and add word-wrap support
uiLabelInit now marks a fresh label dirty itself, instead of every call
site having to remember to do it. Adds uiLabelSetWrap (NULL buffer
disables wrapping, otherwise requires a positive width) built on the
existing textWrap(), and wires the fatal error overlay's message label
up to wrap at 80% of screen width.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-19 21:32:24 -05:00
YourWishes 2abd5b0c3c Beginning a bit of cleanup 2026-09-19 21:17:11 -05:00
YourWishesandClaude Sonnet 5 4b29bf7a30 Wire story flags into the save slot and add cutscene controls
Implements storyInit/storyGetFlagByName/storyGetFlagValue/etc, moves flag
storage into saveslot_t (persisted keyed by name so save files survive
flag reordering), and adds STORY_SET_FLAG/STORY_WAIT_FLAG cutscene items.
Also removes the now-superseded storyflag.c/h stub.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-19 20:39:53 -05:00
YourWishes 6f1bbe4f2f First pass story flags 2026-09-19 10:45:06 -05:00
YourWishesandClaude Sonnet 5 f64364f37d Trim cutscenesystem.h doc comments to the essentials
Comments-only change - drops implementation rationale/cross-referencing
detail in favor of shorter one-liners, matching the simplified style
already applied to part of the file.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-18 11:21:12 -05:00
162 changed files with 4858 additions and 2397 deletions

No files matched your search

+15 -5
View File
@@ -1,11 +1,21 @@
{ {
"moves": { "moves": {
"fire": { "fire": {
"ability": "FIRE", // Target flags
"power": 12, "enemies": true,
"mpCost": 4, "allies": true,
"target": "SINGLE_ENEMY", "multiple": false,
"cutscene": "battle/fire" "self": true,
"default": "enemy",
"target": "SINGLE_ENEMY"
},
"slash": {
"enemies": true,
"allies": true,
"self": false,
"default": "enemy",
"target": "SINGLE_ENEMY"
} }
} }
} }
+21
View File
@@ -0,0 +1,21 @@
{
"items": [
{
"type": "MODAL",
"title": "Fire",
"message": "A burst of flame scorches the target."
},
{
"type": "WAIT",
"seconds": 2
},
{
"type": "MODAL_CLOSE"
},
{
"type": "BATTLE_FIGHTER_DAMAGE",
"fighter": "target",
"amount": 12
}
]
}
+21
View File
@@ -0,0 +1,21 @@
{
"items": [
{
"type": "MODAL",
"title": "Slash",
"message": "A quick blade strike cuts across the target."
},
{
"type": "WAIT",
"seconds": 2
},
{
"type": "MODAL_CLOSE"
},
{
"type": "BATTLE_FIGHTER_DAMAGE",
"fighter": "target",
"amount": 8
}
]
}
+6 -12
View File
@@ -1,24 +1,18 @@
{ {
"items": [ "items": [
{ {
"type": "START_BATTLE", "type": "BATTLE_START",
"encounterType": "REGULAR",
"fleeAvailable": true,
"enemies": [ "enemies": [
{ {
"stats": { "attack": 8, "defense": 4, "magic": 0, "speed": 5, "luck": 2 }, "attack": 8, "defense": 4, "magic": 0, "speed": 5, "luck": 2,
"healthMax": 30, "healthMax": 30, "mpMax": 0,
"mpMax": 0 "abilities": ["fire"]
}, },
{ {
"stats": { "attack": 6, "defense": 3, "magic": 0, "speed": 7, "luck": 2 }, "attack": 6, "defense": 3, "magic": 0, "speed": 7, "luck": 2,
"healthMax": 20, "healthMax": 20, "mpMax": 0
"mpMax": 0
} }
] ]
},
{
"type": "REGULAR_BATTLE"
} }
] ]
} }
+1 -1
View File
@@ -62,7 +62,7 @@
}, },
{ {
"type": "CUTSCENE", "type": "CUTSCENE",
"name": "main_menu" "name": "cutscenes/main_menu.jsonc"
} }
] ]
} }
+11
View File
@@ -0,0 +1,11 @@
{
// Placeholder for the new-game intro flow - just shows a modal for now.
"items": [
{
"type": "MODAL",
"title": "New Game",
"message": "This is a placeholder for the new game intro.",
"blocking": true
}
]
}
+14 -1
View File
@@ -266,6 +266,10 @@ msgstr "loading"
msgid "ui.autosave.saving" msgid "ui.autosave.saving"
msgstr "SAVING" msgstr "SAVING"
#
# Items
#
msgid "item.potion.name" msgid "item.potion.name"
msgstr "Potion" msgstr "Potion"
@@ -273,4 +277,13 @@ msgid "item.potato.name"
msgstr "Potato" msgstr "Potato"
msgid "item.apple.name" msgid "item.apple.name"
msgstr "Apple" msgstr "Apple"
#
# Moves
#
msgid "move.fire.name"
msgstr "Fire"
msgid "move.slash.name"
msgstr "Slash"
+22
View File
@@ -0,0 +1,22 @@
{
"members": {
"hero": {
"attack": 10,
"defense": 5,
"magic": 0,
"speed": 10,
"luck": 0,
"healthMax": 30,
"mpMax": 10
},
"companion": {
"attack": 8,
"defense": 6,
"magic": 4,
"speed": 8,
"luck": 1,
"healthMax": 25,
"mpMax": 15
}
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"flags": {
"test": {
"initial": true
},
"test2": {
"initial": 1
}
}
}
+8 -5
View File
@@ -12,13 +12,16 @@
// "DSK2" - distinct from a plain zip's "PK\x03\x04" so a stray plain zip // "DSK2" - distinct from a plain zip's "PK\x03\x04" so a stray plain zip
// never gets misread as a valid dusk.dsk. // never gets misread as a valid dusk.dsk.
#define ASSET_DSK_MAGIC_SIZE 4 #define ASSET_DSK_MAGIC_SIZE 4
#define ASSET_DSK_MAGIC "DSK2" #define ASSET_DSK_MAGIC "DSK"
#define ASSET_DSK_VERSION 2 #define ASSET_DSK_VERSION 2
// magic(4) + version(4) + size(4) + checksum(4), all little-endian // Magic + version + size + checksum
// regardless of host - see assetDskParseHeader. The zip archive itself #define ASSET_DSK_HEADER_SIZE ( \
// starts immediately after, at ASSET_DSK_HEADER_SIZE. ASSET_DSK_MAGIC_SIZE + \
#define ASSET_DSK_HEADER_SIZE 16 sizeof(uint32_t) + \
sizeof(uint32_t) + \
sizeof(uint32_t) \
)
/** /**
* Parsed dusk.dsk (DSK2 format) header. dusk.dsk is a single uncompressed * Parsed dusk.dsk (DSK2 format) header. dusk.dsk is a single uncompressed
+4 -1
View File
@@ -7,6 +7,9 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
battle.c battle.c
battlefighter.c
party.c party.c
) )
add_subdirectory(fighter)
add_subdirectory(move)
add_subdirectory(state)
+42 -291
View File
@@ -9,320 +9,71 @@
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "rpg/cutscene/cutscenesystem.h" #include "rpg/cutscene/cutscenesystem.h"
#include "scene/scene.h"
battle_t BATTLE; battle_t BATTLE;
void battleInit(void) { void battleInit(void) {
memoryZero(&BATTLE, sizeof(battle_t)); memoryZero(&BATTLE, sizeof(battle_t));
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) {
BATTLE.fighters[i].id = i;
}
}
uint8_t battleGetAvailableFighter(void) {
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) {
if(BATTLE.fighters[i].status == BATTLE_FIGHTER_STATUS_NULL) return i;
}
return 0xFF;
}
battlefighter_t *battleAddFighter(
const battlefighterteam_t team,
const battlefightercontroller_t controller,
const battlefighterstats_t stats,
const uint16_t healthMax,
const uint16_t mpMax
) {
const uint8_t index = battleGetAvailableFighter();
if(index == 0xFF) return NULL;
battlefighter_t *fighter = &BATTLE.fighters[index];
battleFighterInit(fighter, team, controller, stats, healthMax, mpMax);
return fighter;
} }
void battleStart( void battleStart(
const battleencountertype_t encounterType, battlefighter_t *fighters[BATTLE_FIGHTER_POS_COUNT]
const bool_t fleeAvailable
) { ) {
assertTrue(encounterType < BATTLE_ENCOUNTER_COUNT, "Invalid encounter type"); assertNotNull(fighters, "Fighters cannot be NULL");
BATTLE.encounterType = encounterType; #if DUSK_ASSERTIONS
BATTLE.fleeAvailable = fleeAvailable; // Must be at least two non null fighter present, may need to ensure they
BATTLE.result = BATTLE_RESULT_NONE; // are from seperate teams also.
BATTLE.round = 1; uint8_t nonNullCount = 0;
for(uint8_t i = 0; i < BATTLE_FIGHTER_POS_COUNT; i++) {
battleSetState(BATTLE_STATE_OPENING); if(fighters[i] != NULL) nonNullCount++;
}
void battleDispose(void) {
battleInit();
}
battlefighter_t *battleGetCurrentFighter(void) {
if(BATTLE.state != BATTLE_STATE_PLAYER_SELECTION) return NULL;
if(BATTLE.selectionIndex >= BATTLE.executionCount) return NULL;
return &BATTLE.fighters[BATTLE.executionOrder[BATTLE.selectionIndex]];
}
uint8_t battleGetAliveCount(const battlefighterteam_t team) {
uint8_t count = 0;
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) {
if(BATTLE.fighters[i].team != team) continue;
if(!battleFighterIsAlive(&BATTLE.fighters[i])) continue;
count++;
}
return count;
}
void battleResolveAttack(
battlefighter_t *attacker,
battlefighter_t *defender
) {
assertNotNull(attacker, "Attacker cannot be NULL");
assertNotNull(defender, "Defender cannot be NULL");
const int32_t rawDamage =
(int32_t)attacker->stats.attack - (int32_t)defender->stats.defense;
const uint16_t damage = rawDamage > 0 ? (uint16_t)rawDamage : 1;
defender->health = damage >= defender->health ? 0 : defender->health - damage;
if(defender->health == 0) defender->status = BATTLE_FIGHTER_STATUS_DEAD;
}
battleresult_t battleCheckResult(void) {
if(BATTLE.result != BATTLE_RESULT_NONE) return BATTLE.result;
if(battleGetAliveCount(BATTLE_FIGHTER_TEAM_ALLY) == 0) {
battleSetResult(BATTLE_RESULT_LOSS);
} else if(battleGetAliveCount(BATTLE_FIGHTER_TEAM_ENEMY) == 0) {
battleSetResult(BATTLE_RESULT_WIN);
}
return BATTLE.result;
}
void battleQueueAction(
const uint8_t fighterIndex,
const battleactiontype_t type,
const uint8_t targetIndex
) {
battleaction_t *action = &BATTLE.actions[fighterIndex];
action->type = type;
action->targetIndex = targetIndex;
if(BATTLE.onActionDecided != NULL) {
BATTLE.onActionDecided(&BATTLE.fighters[fighterIndex], action);
}
}
void battlePlayerAttack(const uint8_t targetIndex) {
battlefighter_t *fighter = battleGetCurrentFighter();
if(fighter == NULL) return;
if(targetIndex >= BATTLE_FIGHTER_COUNT_MAX) return;
if(!battleFighterIsAlive(&BATTLE.fighters[targetIndex])) return;
battleQueueAction(fighter->id, BATTLE_ACTION_ATTACK, targetIndex);
BATTLE.selectionIndex++;
battleAdvanceSelection();
}
void battlePlayerFlee(void) {
battlefighter_t *fighter = battleGetCurrentFighter();
if(fighter == NULL) return;
if(!BATTLE.fleeAvailable) return;
battleSetResult(BATTLE_RESULT_FLED);
}
void battleUpdate(void) {
if(BATTLE.state == BATTLE_STATE_NONE) return;
if(BATTLE.state == BATTLE_STATE_ENDED) return;
if(CUTSCENE_SYSTEM.pause & CUTSCENE_PAUSE_BATTLE) return;
switch(BATTLE.state) {
case BATTLE_STATE_OPENING:
battleSetState(BATTLE_STATE_PRE_ROUND);
break;
case BATTLE_STATE_PRE_ROUND:
battleUpdatePreRound();
break;
case BATTLE_STATE_AI_SELECTION:
battleUpdateAiSelection();
break;
case BATTLE_STATE_MOVES_EXECUTING:
battleUpdateMovesExecuting();
break;
case BATTLE_STATE_POST_ROUND:
battleUpdatePostRound();
break;
default:
// BATTLE_STATE_PLAYER_SELECTION: waits on battlePlayerAttack/Flee.
// BATTLE_STATE_NONE/ENDED: handled above.
break;
}
}
void battleBuildExecutionOrder(const bool_t applyEncounterBias) {
BATTLE.executionCount = 0;
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) {
if(!battleFighterIsAlive(&BATTLE.fighters[i])) continue;
BATTLE.executionOrder[BATTLE.executionCount++] = i;
}
// Insertion sort by speed descending -- fine for BATTLE_FIGHTER_COUNT_MAX.
for(uint8_t i = 1; i < BATTLE.executionCount; i++) {
const uint8_t key = BATTLE.executionOrder[i];
const uint16_t keySpeed = BATTLE.fighters[key].stats.speed;
int8_t j = (int8_t)i - 1;
while(
j >= 0 &&
BATTLE.fighters[BATTLE.executionOrder[j]].stats.speed < keySpeed
) {
BATTLE.executionOrder[j + 1] = BATTLE.executionOrder[j];
j--;
} }
BATTLE.executionOrder[j + 1] = key; assertTrue(nonNullCount >= 2, "Must have at least two fighters");
} #endif
if(!applyEncounterBias) return;
if(BATTLE.encounterType == BATTLE_ENCOUNTER_PLAYER_ADVANTAGE) {
battleMoveTeamFirst(BATTLE_FIGHTER_TEAM_ALLY);
} else if(BATTLE.encounterType == BATTLE_ENCOUNTER_BACK_ATTACK) {
battleMoveTeamFirst(BATTLE_FIGHTER_TEAM_ENEMY);
}
}
void battleMoveTeamFirst(const battlefighterteam_t team) {
uint8_t sorted[BATTLE_FIGHTER_COUNT_MAX];
uint8_t count = 0;
for(uint8_t i = 0; i < BATTLE.executionCount; i++) {
if(BATTLE.fighters[BATTLE.executionOrder[i]].team != team) continue;
sorted[count++] = BATTLE.executionOrder[i];
}
for(uint8_t i = 0; i < BATTLE.executionCount; i++) {
if(BATTLE.fighters[BATTLE.executionOrder[i]].team == team) continue;
sorted[count++] = BATTLE.executionOrder[i];
}
// TODO: I may not need to zero entire battle.
memoryZero(&BATTLE, sizeof(battle_t));
memoryCopy( memoryCopy(
BATTLE.executionOrder, sorted, sizeof(uint8_t) * BATTLE.executionCount BATTLE.fighters,
fighters,
sizeof(battlefighter_t *) * BATTLE_FIGHTER_POS_COUNT
); );
}
battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter) { // Enter the opening state.
const battlefighterteam_t enemyTeam = battleSetState(BATTLE_STATE_OPENING);
fighter->team == BATTLE_FIGHTER_TEAM_ALLY ?
BATTLE_FIGHTER_TEAM_ENEMY : BATTLE_FIGHTER_TEAM_ALLY;
battlefighter_t *weakest = NULL; // Change scene
for(uint8_t i = 0; i < BATTLE_FIGHTER_COUNT_MAX; i++) { sceneSet(SCENE_TYPE_BATTLE);
battlefighter_t *candidate = &BATTLE.fighters[i];
if(candidate->team != enemyTeam) continue;
if(!battleFighterIsAlive(candidate)) continue;
if(weakest == NULL || candidate->health < weakest->health) {
weakest = candidate;
}
}
return weakest;
} }
void battleSetState(const battlestate_t next) { void battleSetState(const battlestate_t next) {
const battlestate_t previous = BATTLE.state; assertTrue(next < BATTLE_STATE_COUNT, "Invalid battle state");
assertNotNull(BATTLE_STATE_FUNCTIONS[next].init, "Missing state init function");
assertNotNull(BATTLE_STATE_FUNCTIONS[next].update, "Missing state update function");
assertNotNull(BATTLE_STATE_FUNCTIONS[next].dispose, "Missing state dispose function");
if(BATTLE.state != BATTLE_STATE_NULL) {
BATTLE_STATE_FUNCTIONS[BATTLE.state].dispose();
}
BATTLE.state = next; BATTLE.state = next;
if(BATTLE.onStateChanged != NULL) BATTLE.onStateChanged(previous, next); BATTLE_STATE_FUNCTIONS[BATTLE.state].init();
} }
void battleSetResult(const battleresult_t result) { void battleUpdate(void) {
BATTLE.result = result; if(BATTLE.state == BATTLE_STATE_NULL) return;
battleSetState(BATTLE_STATE_ENDED); assertTrue(BATTLE.state < BATTLE_STATE_COUNT, "Invalid battle state");
assertNotNull(BATTLE_STATE_FUNCTIONS[BATTLE.state].update, "Missing state update function");
BATTLE_STATE_FUNCTIONS[BATTLE.state].update();
} }
bool_t battleFighterNeedsDecision( void battleDispose(void) {
const uint8_t fighterIndex, if(BATTLE.state == BATTLE_STATE_NULL) return;
const battlefightercontroller_t controller assertTrue(BATTLE.state < BATTLE_STATE_COUNT, "Invalid battle state");
) { assertNotNull(BATTLE_STATE_FUNCTIONS[BATTLE.state].dispose, "Missing state dispose function");
return battleFighterIsAlive(&BATTLE.fighters[fighterIndex])
&& BATTLE.fighters[fighterIndex].controller == controller
&& BATTLE.actions[fighterIndex].type == BATTLE_ACTION_NONE;
}
void battleAdvanceSelection(void) { BATTLE_STATE_FUNCTIONS[BATTLE.state].dispose();
while(BATTLE.selectionIndex < BATTLE.executionCount) { memoryZero(&BATTLE, sizeof(battle_t));
const uint8_t fighterIndex = BATTLE.executionOrder[BATTLE.selectionIndex]; }
if(
battleFighterNeedsDecision(fighterIndex, BATTLE_FIGHTER_CONTROLLER_PLAYER)
) {
return;
}
BATTLE.selectionIndex++;
}
battleSetState(BATTLE_STATE_AI_SELECTION);
}
void battleUpdatePreRound(void) {
// No need to clear BATTLE.actions here: every living fighter's action is
// unconditionally reset to BATTLE_ACTION_NONE as it's processed in
// battleUpdateMovesExecuting, and round 1 starts pre-zeroed by
// battleInit(). Clearing it here would also wipe out any action a
// cutscene force-queued while parked at BATTLE_STATE_PRE_ROUND.
battleBuildExecutionOrder(BATTLE.round == 1);
BATTLE.selectionIndex = 0;
battleSetState(BATTLE_STATE_PLAYER_SELECTION);
battleAdvanceSelection();
}
void battleUpdateAiSelection(void) {
for(uint8_t i = 0; i < BATTLE.executionCount; i++) {
const uint8_t fighterIndex = BATTLE.executionOrder[i];
if(
!battleFighterNeedsDecision(fighterIndex, BATTLE_FIGHTER_CONTROLLER_AI)
) continue;
battlefighter_t *target =
battleAIChooseTarget(&BATTLE.fighters[fighterIndex]);
if(target == NULL) continue;
battleQueueAction(fighterIndex, BATTLE_ACTION_ATTACK, target->id);
}
BATTLE.executionIndex = 0;
battleSetState(BATTLE_STATE_MOVES_EXECUTING);
}
void battleUpdateMovesExecuting(void) {
if(BATTLE.executionIndex >= BATTLE.executionCount) {
battleSetState(BATTLE_STATE_POST_ROUND);
return;
}
const uint8_t fighterIndex = BATTLE.executionOrder[BATTLE.executionIndex++];
battlefighter_t *fighter = &BATTLE.fighters[fighterIndex];
if(!battleFighterIsAlive(fighter)) return;
battleaction_t *action = &BATTLE.actions[fighterIndex];
if(action->type == BATTLE_ACTION_ATTACK) {
battlefighter_t *target = &BATTLE.fighters[action->targetIndex];
if(battleFighterIsAlive(target)) battleResolveAttack(fighter, target);
}
action->type = BATTLE_ACTION_NONE;
battleCheckResult();
}
void battleUpdatePostRound(void) {
BATTLE.round++;
battleSetState(BATTLE_STATE_PRE_ROUND);
}
+29 -251
View File
@@ -6,73 +6,38 @@
*/ */
#pragma once #pragma once
#include "battlefighter.h" #include "rpg/battle/fighter/battlefighter.h"
#include "battleaction.h" #include "rpg/battle/move/battlemove.h"
#include "rpg/battle/move/battlemoveaction.h"
#define BATTLE_FIGHTER_COUNT_MAX 8 #include "rpg/battle/fighter/battlefighterpos.h"
#include "rpg/battle/state/battlestate.h"
typedef enum {
BATTLE_ENCOUNTER_REGULAR,
BATTLE_ENCOUNTER_PLAYER_ADVANTAGE,
BATTLE_ENCOUNTER_BACK_ATTACK,
BATTLE_ENCOUNTER_COUNT
} battleencountertype_t;
typedef enum { typedef enum {
BATTLE_RESULT_NONE, BATTLE_RESULT_NONE,
BATTLE_RESULT_WIN, BATTLE_RESULT_WIN,
BATTLE_RESULT_LOSS, BATTLE_RESULT_LOSS,
BATTLE_RESULT_FLED, BATTLE_RESULT_FLED,
BATTLE_RESULT_COUNT BATTLE_RESULT_COUNT
} battleresult_t; } battleresult_t;
// Where BATTLE currently is within a round. A cutscene can pause progression
// (CUTSCENE_PAUSE_BATTLE) and use CUTSCENE_BATTLE_WAIT_STATE to synchronize
// with any of these, or CUTSCENE_BATTLE_FORCE_ACTION to decide a fighter's
// action ahead of PLAYER_SELECTION/AI_SELECTION reaching them.
typedef enum {
BATTLE_STATE_NONE, // Battle inactive.
BATTLE_STATE_OPENING, // Entered once by battleStart().
BATTLE_STATE_PRE_ROUND, // Rebuilds execution order, clears the action queue.
BATTLE_STATE_PLAYER_SELECTION, // Waits on battlePlayerAttack/Flee.
BATTLE_STATE_AI_SELECTION, // Auto-queues every undecided AI fighter.
BATTLE_STATE_MOVES_EXECUTING, // Resolves one queued action per update.
BATTLE_STATE_POST_ROUND, // Round wrap-up; loops back to PRE_ROUND.
BATTLE_STATE_ENDED, // Terminal for WIN/LOSS/FLED alike -- see BATTLE.result.
BATTLE_STATE_COUNT
} battlestate_t;
typedef void (*battlestatechangedcallback_t)(
const battlestate_t previous,
const battlestate_t next
);
typedef struct { typedef struct {
battlefighter_t *fighters[BATTLE_FIGHTER_POS_COUNT];
// Order of who gets to act.
uint8_t fighterOrder[BATTLE_FIGHTER_POS_COUNT];
uint8_t fighterOrderCount;
// Actions to be executed.
battlemoveaction_t actionsPending[BATTLE_FIGHTER_POS_COUNT];
uint8_t actionsPendingCount;
battlestate_t state; battlestate_t state;
battlefighter_t fighters[BATTLE_FIGHTER_COUNT_MAX]; battlestatedata_t stateData;
battleaction_t actions[BATTLE_FIGHTER_COUNT_MAX];
battleencountertype_t encounterType; // Set once a side has been wiped out (see cutsceneBattlePostMoveStart)
bool_t fleeAvailable; // or the player has fled (see battleStateSelectionPlayerFlee). Stays
// BATTLE_RESULT_NONE for the rest of the battle otherwise.
battleresult_t result; battleresult_t result;
// Fighter indices (into fighters[]), sorted for the current round.
uint8_t executionOrder[BATTLE_FIGHTER_COUNT_MAX];
uint8_t executionCount;
uint8_t executionIndex;
uint16_t round;
// Cursor into executionOrder used by BATTLE_STATE_PLAYER_SELECTION to find
// the next player-controlled fighter that still needs a decision.
uint8_t selectionIndex;
battlestatechangedcallback_t onStateChanged;
battleactiondecidedcallback_t onActionDecided;
} battle_t; } battle_t;
extern battle_t BATTLE; extern battle_t BATTLE;
@@ -83,215 +48,28 @@ extern battle_t BATTLE;
void battleInit(void); void battleInit(void);
/** /**
* Gets an available (unused) fighter slot index. * Starts a battle.
* *
* @return The index of an available fighter slot, or 0xFF if none are * @param fighters Fighters in the battle.
* available.
*/
uint8_t battleGetAvailableFighter(void);
/**
* Adds a fighter to the battle in the next available slot.
*
* @param team The team the fighter belongs to.
* @param controller Who makes decisions for the fighter.
* @param stats The fighter's base combat stats.
* @param healthMax The fighter's maximum health.
* @param mpMax The fighter's maximum mp.
* @return Pointer to the newly added fighter, or NULL if the battle is
* already full.
*/
battlefighter_t *battleAddFighter(
const battlefighterteam_t team,
const battlefightercontroller_t controller,
const battlefighterstats_t stats,
const uint16_t healthMax,
const uint16_t mpMax
);
/**
* Starts the battle: enters BATTLE_STATE_OPENING and marks the battle
* active. Call once every fighter has been added via battleAddFighter.
*
* @param encounterType Determines the opening round's execution order.
* @param fleeAvailable Whether the party may attempt to flee this battle.
*/ */
void battleStart( void battleStart(
const battleencountertype_t encounterType, battlefighter_t *fighters[BATTLE_FIGHTER_POS_COUNT]
const bool_t fleeAvailable
); );
/** /**
* Disposes of the battle, clearing all fighters and marking it inactive. * Transitions the battle to a new state: disposes the current state (if
*/ * any) and initializes next.
void battleDispose(void);
/**
* Returns the fighter currently awaiting a player decision.
*
* @return Pointer to the fighter awaiting a decision, or NULL if the battle
* isn't in BATTLE_STATE_PLAYER_SELECTION or every player-controlled
* fighter has already decided.
*/
battlefighter_t *battleGetCurrentFighter(void);
/**
* Returns the number of living fighters on a team.
*
* @param team The team to count.
* @return Count of living fighters on that team.
*/
uint8_t battleGetAliveCount(const battlefighterteam_t team);
/**
* Resolves a physical attack from attacker onto defender: damage is the
* attacker's attack stat minus the defender's defense stat (minimum 1),
* subtracted from the defender's health. The defender is marked dead
* once health reaches 0.
*
* @param attacker The attacking fighter.
* @param defender The defending fighter.
*/
void battleResolveAttack(
battlefighter_t *attacker,
battlefighter_t *defender
);
/**
* Checks whether the battle has been won or lost, transitioning to
* BATTLE_STATE_ENDED and updating BATTLE.result if so. Does nothing if a
* result has already been set (e.g. by a successful flee).
*
* @return The battle's current result.
*/
battleresult_t battleCheckResult(void);
/**
* Queues an action for a fighter to perform once BATTLE_STATE_MOVES_EXECUTING
* reaches them this round, overwriting any action already queued for that
* fighter. Fires BATTLE.onActionDecided.
*
* @param fighterIndex Index into BATTLE.fighters of the deciding fighter.
* @param type The type of action to perform.
* @param targetIndex Index into BATTLE.fighters of the target, meaningful
* for BATTLE_ACTION_ATTACK.
*/
void battleQueueAction(
const uint8_t fighterIndex,
const battleactiontype_t type,
const uint8_t targetIndex
);
/**
* Submits the currently-selecting fighter's attack against a target, if the
* battle is in BATTLE_STATE_PLAYER_SELECTION and awaiting a decision.
* Queues the action and advances the selection cursor.
*
* @param targetIndex Index into BATTLE.fighters of the target.
*/
void battlePlayerAttack(const uint8_t targetIndex);
/**
* Submits a flee attempt for the currently-selecting fighter, if the battle
* is in BATTLE_STATE_PLAYER_SELECTION and fleeing is available for this
* battle. Always succeeds, ending the battle with BATTLE_RESULT_FLED.
*/
void battlePlayerFlee(void);
/**
* Updates the battle simulation for one frame, dispatching on BATTLE.state.
* No-op if the battle isn't active, has already ended, or
* CUTSCENE_PAUSE_BATTLE is set.
*/
void battleUpdate(void);
/**
* Rebuilds BATTLE.executionOrder/executionCount from every currently living
* fighter, sorted by speed descending.
*
* @param applyEncounterBias If true, reorders the freshly speed-sorted
* queue so BATTLE.encounterType's favoured team goes first (used only
* for the opening round).
*/
void battleBuildExecutionOrder(const bool_t applyEncounterBias);
/**
* Stably partitions BATTLE.executionOrder so every fighter on the given team
* comes first, preserving each side's relative (speed-sorted) order.
*
* @param team The team to move to the front of the execution order.
*/
void battleMoveTeamFirst(const battlefighterteam_t team);
/**
* Picks an AI target for fighter: the lowest-health living fighter on
* the opposing team.
*
* @param fighter The AI-controlled fighter choosing a target.
* @return The chosen target, or NULL if the opposing team has no
* living fighters.
*/
battlefighter_t *battleAIChooseTarget(const battlefighter_t *fighter);
/**
* Sets BATTLE.state and fires BATTLE.onStateChanged with the previous and
* new state.
* *
* @param next The state to transition to. * @param next The state to transition to.
*/ */
void battleSetState(const battlestate_t next); void battleSetState(const battlestate_t next);
/** /**
* Sets BATTLE.result and transitions to BATTLE_STATE_ENDED. * Updates the battle system.
*
* @param result The result to end the battle with.
*/ */
void battleSetResult(const battleresult_t result); void battleUpdate(void);
/** /**
* Checks whether a fighter is a live, undecided candidate for the given * Disposes of the battle, clearing all fighters and marking it inactive.
* controller -- i.e. whether PLAYER_SELECTION or AI_SELECTION should still
* be deciding an action for it this round.
*
* @param fighterIndex Index into BATTLE.fighters to check.
* @param controller The controller PLAYER_SELECTION/AI_SELECTION is
* currently deciding for.
* @return True if the fighter is alive, matches controller, and has no
* action queued yet.
*/ */
bool_t battleFighterNeedsDecision( void battleDispose(void);
const uint8_t fighterIndex,
const battlefightercontroller_t controller
);
/**
* Advances BATTLE.selectionIndex to the next player-controlled fighter that
* still needs a decision, or transitions to BATTLE_STATE_AI_SELECTION once
* none remain.
*/
void battleAdvanceSelection(void);
/**
* Handles BATTLE_STATE_PRE_ROUND: rebuilds the execution order and moves on
* to BATTLE_STATE_PLAYER_SELECTION, positioning the selection cursor.
*/
void battleUpdatePreRound(void);
/**
* Handles BATTLE_STATE_AI_SELECTION: queues an attack for every undecided
* AI-controlled fighter, then moves on to BATTLE_STATE_MOVES_EXECUTING.
*/
void battleUpdateAiSelection(void);
/**
* Handles BATTLE_STATE_MOVES_EXECUTING: resolves one queued action from
* BATTLE.executionOrder per call, or transitions to BATTLE_STATE_POST_ROUND
* once every fighter this round has been processed.
*/
void battleUpdateMovesExecuting(void);
/**
* Handles BATTLE_STATE_POST_ROUND: advances BATTLE.round and transitions
* back to BATTLE_STATE_PRE_ROUND.
*/
void battleUpdatePostRound(void);
-27
View File
@@ -1,27 +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"
#include "battlefighter.h"
typedef enum {
BATTLE_ACTION_NONE, // No action decided yet for this fighter this round.
BATTLE_ACTION_ATTACK,
BATTLE_ACTION_COUNT
} battleactiontype_t;
typedef struct {
battleactiontype_t type;
uint8_t targetIndex; // Meaningful for BATTLE_ACTION_ATTACK.
} battleaction_t;
typedef void (*battleactiondecidedcallback_t)(
const battlefighter_t *fighter,
const battleaction_t *action
);
-43
View File
@@ -1,43 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlefighter.h"
#include "assert/assert.h"
#include "util/memory.h"
void battleFighterInit(
battlefighter_t *fighter,
const battlefighterteam_t team,
const battlefightercontroller_t controller,
const battlefighterstats_t stats,
const uint16_t healthMax,
const uint16_t mpMax
) {
assertNotNull(fighter, "Fighter pointer cannot be NULL");
assertTrue(team < BATTLE_FIGHTER_TEAM_COUNT, "Invalid fighter team");
assertTrue(
controller < BATTLE_FIGHTER_CONTROLLER_COUNT,
"Invalid fighter controller"
);
const uint8_t id = fighter->id;
memoryZero(fighter, sizeof(battlefighter_t));
fighter->id = id;
fighter->status = BATTLE_FIGHTER_STATUS_NORMAL;
fighter->team = team;
fighter->controller = controller;
fighter->stats = stats;
fighter->healthMax = healthMax;
fighter->health = healthMax;
fighter->mpMax = mpMax;
fighter->mp = mpMax;
}
bool_t battleFighterIsAlive(const battlefighter_t *fighter) {
assertNotNull(fighter, "Fighter pointer cannot be NULL");
return fighter->status == BATTLE_FIGHTER_STATUS_NORMAL;
}
-91
View File
@@ -1,91 +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"
#include "battleability.h"
#define BATTLE_FIGHTER_ABILITY_COUNT_MAX 8
// An empty status means the slot in BATTLE.fighters is unused.
typedef enum {
BATTLE_FIGHTER_STATUS_NULL,
BATTLE_FIGHTER_STATUS_NORMAL,
BATTLE_FIGHTER_STATUS_DEAD,
BATTLE_FIGHTER_STATUS_COUNT
} battlefighterstatus_t;
typedef enum {
BATTLE_FIGHTER_TEAM_ALLY,
BATTLE_FIGHTER_TEAM_ENEMY,
BATTLE_FIGHTER_TEAM_COUNT
} battlefighterteam_t;
typedef enum {
BATTLE_FIGHTER_CONTROLLER_PLAYER,
BATTLE_FIGHTER_CONTROLLER_AI,
BATTLE_FIGHTER_CONTROLLER_COUNT
} battlefightercontroller_t;
// Base combat stats, kept separate from the resource pools (health/mp) on
// battlefighter_t so that equipment/buffs can later modify them without
// touching current health/mp state.
typedef struct {
uint16_t attack;
uint16_t defense;
uint16_t magic;
uint16_t speed;
uint16_t luck;
} battlefighterstats_t;
typedef struct {
uint8_t id;
battlefighterstatus_t status;
battlefighterteam_t team;
battlefightercontroller_t controller;
uint16_t health;
uint16_t healthMax;
uint16_t mp;
uint16_t mpMax;
battlefighterstats_t stats;
battleability_t abilities[BATTLE_FIGHTER_ABILITY_COUNT_MAX];
} battlefighter_t;
/**
* Initializes a battle fighter in place, filling health/mp to their maximum
* values and setting its status to normal.
*
* @param fighter Pointer to the fighter to initialize.
* @param team The team the fighter belongs to.
* @param controller Who makes decisions for the fighter.
* @param stats The fighter's base combat stats.
* @param healthMax The fighter's maximum health.
* @param mpMax The fighter's maximum mp.
*/
void battleFighterInit(
battlefighter_t *fighter,
const battlefighterteam_t team,
const battlefightercontroller_t controller,
const battlefighterstats_t stats,
const uint16_t healthMax,
const uint16_t mpMax
);
/**
* Returns true if the fighter is in a state where it can still act (i.e.
* is not dead).
*
* @param fighter Pointer to the fighter to check.
* @returns True if the fighter can act.
*/
bool_t battleFighterIsAlive(const battlefighter_t *fighter);
@@ -0,0 +1,10 @@
# 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
battlefighter.c
)
+230
View File
@@ -0,0 +1,230 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlefighter.h"
#include "assert/assert.h"
#include "util/memory.h"
errorret_t battleFighterParseStatField(
yyjson_val *obj,
const char_t *key,
uint16_t *out
) {
yyjson_val *val = yyjson_obj_get(obj, key);
if(!yyjson_is_int(val)) {
errorThrow("Fighter: missing/invalid '%s'", key);
}
const int64_t num = yyjson_get_sint(val);
if(num < 0 || num > UINT16_MAX) {
errorThrow("Fighter: '%s' must be between 0 and %u", key, UINT16_MAX);
}
*out = (uint16_t)num;
errorOk();
}
errorret_t battleFighterParseOptionalIntField(
yyjson_val *obj,
const char_t *key,
const int32_t defaultValue,
int32_t *out
) {
yyjson_val *val = yyjson_obj_get(obj, key);
if(val == NULL) {
*out = defaultValue;
errorOk();
}
if(!yyjson_is_int(val)) errorThrow("Fighter: invalid '%s'", key);
*out = (int32_t)yyjson_get_sint(val);
errorOk();
}
errorret_t battleFighterParse(battlefighter_t *fighter, yyjson_val *obj) {
assertNotNull(fighter, "Fighter cannot be NULL");
assertNotNull(obj, "JSON object cannot be NULL");
int32_t teamNum;
errorChain(battleFighterParseOptionalIntField(
obj, "team", BATTLE_FIGHTER_TEAM_ALLY, &teamNum
));
if(teamNum < 0 || teamNum >= BATTLE_FIGHTER_TEAM_COUNT) {
errorThrow("Fighter: invalid 'team'");
}
int32_t controllerNum;
errorChain(battleFighterParseOptionalIntField(
obj, "controller", BATTLE_FIGHTER_CONTROLLER_PLAYER, &controllerNum
));
if(controllerNum < 0 || controllerNum >= BATTLE_FIGHTER_CONTROLLER_COUNT) {
errorThrow("Fighter: invalid 'controller'");
}
battlefighterstats_t stats;
errorChain(battleFighterParseStatField(obj, "attack", &stats.attack));
errorChain(battleFighterParseStatField(obj, "defense", &stats.defense));
errorChain(battleFighterParseStatField(obj, "magic", &stats.magic));
errorChain(battleFighterParseStatField(obj, "speed", &stats.speed));
errorChain(battleFighterParseStatField(obj, "luck", &stats.luck));
errorChain(battleFighterParseStatField(obj, "healthMax", &stats.healthMax));
errorChain(battleFighterParseStatField(obj, "mpMax", &stats.mpMax));
battleFighterInit(
fighter, (battlefighterteam_t)teamNum,
(battlefightercontroller_t)controllerNum, stats
);
int32_t statusNum;
errorChain(battleFighterParseOptionalIntField(
obj, "status", BATTLE_FIGHTER_STATUS_NORMAL, &statusNum
));
if(statusNum < 0 || statusNum >= BATTLE_FIGHTER_STATUS_COUNT) {
errorThrow("Fighter: invalid 'status'");
}
fighter->status = (battlefighterstatus_t)statusNum;
int32_t health;
errorChain(
battleFighterParseOptionalIntField(obj, "health", stats.healthMax, &health)
);
if(health < 0 || health > stats.healthMax) {
errorThrow("Fighter: 'health' out of range");
}
fighter->stats.health = (uint16_t)health;
int32_t mp;
errorChain(battleFighterParseOptionalIntField(obj, "mp", stats.mpMax, &mp));
if(mp < 0 || mp > stats.mpMax) {
errorThrow("Fighter: 'mp' out of range");
}
fighter->stats.mp = (uint16_t)mp;
yyjson_val *abilities = yyjson_obj_get(obj, "abilities");
if(abilities != NULL) {
if(
!yyjson_is_arr(abilities) ||
yyjson_arr_size(abilities) > BATTLE_FIGHTER_ABILITY_COUNT_MAX
) {
errorThrow(
"Fighter: 'abilities' must have 0-%u entries",
BATTLE_FIGHTER_ABILITY_COUNT_MAX
);
}
yyjson_arr_iter iter = yyjson_arr_iter_with(abilities);
yyjson_val *abilityVal;
while((abilityVal = yyjson_arr_iter_next(&iter)) != NULL) {
const char_t *name = yyjson_get_str(abilityVal);
battlemoveid_t ability =
name == NULL ? BATTLE_MOVE_ID_NULL : battleMoveGetIdByName(name);
if(ability == BATTLE_MOVE_ID_NULL) {
errorThrow("Fighter: invalid entry in 'abilities'");
}
battleFighterAbilityAdd(fighter, ability);
}
}
errorOk();
}
yyjson_mut_val *battleFighterSerialize(
const battlefighter_t *fighter,
yyjson_mut_doc *doc
) {
assertNotNull(fighter, "Fighter cannot be NULL");
assertNotNull(doc, "Doc cannot be NULL");
yyjson_mut_val *obj = yyjson_mut_obj(doc);
yyjson_mut_obj_add_uint(doc, obj, "team", fighter->team);
yyjson_mut_obj_add_uint(doc, obj, "controller", fighter->controller);
yyjson_mut_obj_add_uint(doc, obj, "status", fighter->status);
yyjson_mut_obj_add_uint(doc, obj, "attack", fighter->stats.attack);
yyjson_mut_obj_add_uint(doc, obj, "defense", fighter->stats.defense);
yyjson_mut_obj_add_uint(doc, obj, "magic", fighter->stats.magic);
yyjson_mut_obj_add_uint(doc, obj, "speed", fighter->stats.speed);
yyjson_mut_obj_add_uint(doc, obj, "luck", fighter->stats.luck);
yyjson_mut_obj_add_uint(doc, obj, "healthMax", fighter->stats.healthMax);
yyjson_mut_obj_add_uint(doc, obj, "mpMax", fighter->stats.mpMax);
yyjson_mut_obj_add_uint(doc, obj, "health", fighter->stats.health);
yyjson_mut_obj_add_uint(doc, obj, "mp", fighter->stats.mp);
yyjson_mut_val *abilities = yyjson_mut_arr(doc);
for(uint8_t i = 0; i < fighter->abilityCount; i++) {
yyjson_mut_arr_add_str(doc, abilities, BATTLE_MOVES[fighter->abilities[i]].name);
}
yyjson_mut_obj_add_val(doc, obj, "abilities", abilities);
return obj;
}
void battleFighterInit(
battlefighter_t *fighter,
const battlefighterteam_t team,
const battlefightercontroller_t controller,
const battlefighterstats_t stats
) {
assertNotNull(fighter, "Fighter pointer cannot be NULL");
assertTrue(team < BATTLE_FIGHTER_TEAM_COUNT, "Invalid fighter team");
assertTrue(
controller < BATTLE_FIGHTER_CONTROLLER_COUNT,
"Invalid fighter controller"
);
const uint8_t id = fighter->id;
memoryZero(fighter, sizeof(battlefighter_t));
fighter->id = id;
fighter->status = BATTLE_FIGHTER_STATUS_NORMAL;
fighter->team = team;
fighter->controller = controller;
fighter->stats = stats;
fighter->stats.health = stats.healthMax;
fighter->stats.mp = stats.mpMax;
}
bool_t battleFighterIsAlive(const battlefighter_t *fighter) {
assertNotNull(fighter, "Fighter pointer cannot be NULL");
return fighter->status == BATTLE_FIGHTER_STATUS_NORMAL;
}
void battleFighterAbilityAdd(
battlefighter_t *fighter,
const battlemoveid_t ability
) {
assertNotNull(fighter, "Fighter pointer cannot be NULL");
assertTrue(
fighter->abilityCount < BATTLE_FIGHTER_ABILITY_COUNT_MAX,
"Fighter already has the maximum number of abilities"
);
fighter->abilities[fighter->abilityCount++] = ability;
}
void battleFighterDamage(
battlefighter_t *fighter,
const uint16_t amount
) {
assertNotNull(fighter, "Fighter pointer cannot be NULL");
fighter->stats.health =
amount >= fighter->stats.health ? 0 : fighter->stats.health - amount;
if(fighter->stats.health == 0) fighter->status = BATTLE_FIGHTER_STATUS_DEAD;
}
void battleFighterHeal(
battlefighter_t *fighter,
const uint16_t amount
) {
assertNotNull(fighter, "Fighter pointer cannot be NULL");
if(!battleFighterIsAlive(fighter)) return;
const uint32_t healed = (uint32_t)fighter->stats.health + amount;
fighter->stats.health = healed > fighter->stats.healthMax
? fighter->stats.healthMax : (uint16_t)healed;
}
+127
View File
@@ -0,0 +1,127 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "error/error.h"
#include "yyjson.h"
#include "rpg/battle/move/battlemove.h"
#include "rpg/battle/fighter/battlefighterstatus.h"
#include "rpg/battle/fighter/battlefighterteam.h"
#include "rpg/battle/fighter/battlefightercontroller.h"
#include "rpg/battle/fighter/battlefighterstats.h"
#include "rpg/battle/fighter/battlefighterpos.h"
#define BATTLE_FIGHTER_ABILITY_COUNT_MAX 8
typedef struct battlefighter_s {
uint8_t id;
battlefighterstatus_t status;
battlefighterteam_t team;
battlefightercontroller_t controller;
battlefighterstats_t stats;
battlemoveid_t abilities[BATTLE_FIGHTER_ABILITY_COUNT_MAX];
battlemoveid_t abilityCount;
} battlefighter_t;
/**
* Initializes a battle fighter in place, filling health/mp to the maximum
* values carried on stats and setting its status to normal.
*
* @param fighter Pointer to the fighter to initialize.
* @param team The team the fighter belongs to.
* @param controller Who makes decisions for the fighter.
* @param stats The fighter's base combat stats, including healthMax/mpMax.
*/
void battleFighterInit(
battlefighter_t *fighter,
const battlefighterteam_t team,
const battlefightercontroller_t controller,
const battlefighterstats_t stats
);
/**
* Generic battlefighter_t parser, shared by every place that builds a
* fighter from JSON (party.jsonc roster members, BATTLE_START enemy
* definitions, save-file party members) - see battleFighterSerialize for
* the inverse. Reads 'team'/'controller'/'status' as ints (each optional,
* defaulting to ALLY/PLAYER/NORMAL respectively - a caller that needs a
* different team/controller, e.g. BATTLE_START's enemies, sets those
* fields on fighter after this returns), 'attack'/'defense'/'magic'/
* 'speed'/'luck'/'healthMax'/'mpMax' as required ints in [0, UINT16_MAX],
* 'health'/'mp' as optional ints defaulting to healthMax/mpMax (a fresh
* fighter), and an optional 'abilities' array of move name strings. Does
* not touch fighter->id - set it (or leave it) before calling, same as
* battleFighterInit.
*
* @param fighter Pointer to the fighter to fill in.
* @param obj The JSON object to read fields from.
* @return Error if a required field is missing/invalid, or an abilities
* entry doesn't name a real move.
*/
errorret_t battleFighterParse(battlefighter_t *fighter, yyjson_val *obj);
/**
* Inverse of battleFighterParse: builds a new JSON object (not yet
* attached anywhere - the caller attaches it, e.g. via
* yyjson_mut_arr_add_val/yyjson_mut_obj_add_val) with every field
* battleFighterParse reads except id (see its doc comment for why).
*
* @param fighter The fighter to serialize.
* @param doc The mutable document to allocate the object in.
* @return The newly built object.
*/
yyjson_mut_val *battleFighterSerialize(
const battlefighter_t *fighter,
yyjson_mut_doc *doc
);
/**
* Returns true if the fighter is in a state where it can still act (i.e.
* is not dead).
*
* @param fighter Pointer to the fighter to check.
* @returns True if the fighter can act.
*/
bool_t battleFighterIsAlive(const battlefighter_t *fighter);
/**
* Appends an ability to the fighter's ability list.
*
* @param fighter Pointer to the fighter to add the ability to.
* @param ability The ability to add.
*/
void battleFighterAbilityAdd(
battlefighter_t *fighter,
const battlemoveid_t ability
);
/**
* Subtracts amount from the fighter's health (floored at 0), marking it
* dead once health reaches 0.
*
* @param fighter Pointer to the fighter to damage.
* @param amount The amount of damage to apply.
*/
void battleFighterDamage(
battlefighter_t *fighter,
const uint16_t amount
);
/**
* Adds amount to the fighter's health (capped at healthMax). No-op if the
* fighter isn't alive -- healing can't revive a dead fighter.
*
* @param fighter Pointer to the fighter to heal.
* @param amount The amount to heal.
*/
void battleFighterHeal(
battlefighter_t *fighter,
const uint16_t amount
);
@@ -0,0 +1,18 @@
/**
* 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_FIGHTER_CONTROLLER_NONE,
BATTLE_FIGHTER_CONTROLLER_PLAYER,
BATTLE_FIGHTER_CONTROLLER_AI,
BATTLE_FIGHTER_CONTROLLER_COUNT
} battlefightercontroller_t;
@@ -0,0 +1,35 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef uint8_t battlefighterpos_t;
#define BATTLE_FIGHTER_POS(x) ((battlefighterpos_t)(x))
// Left (Enemy side)
#define BATTLE_FIGHTER_POS_0 BATTLE_FIGHTER_POS(0)
#define BATTLE_FIGHTER_POS_1 BATTLE_FIGHTER_POS(1)
#define BATTLE_FIGHTER_POS_2 BATTLE_FIGHTER_POS(2)
#define BATTLE_FIGHTER_POS_3 BATTLE_FIGHTER_POS(3)
// Right (Ally side)
#define BATTLE_FIGHTER_POS_4 BATTLE_FIGHTER_POS(4)
#define BATTLE_FIGHTER_POS_5 BATTLE_FIGHTER_POS(5)
#define BATTLE_FIGHTER_POS_6 BATTLE_FIGHTER_POS(6)
#define BATTLE_FIGHTER_POS_7 BATTLE_FIGHTER_POS(7)
#define BATTLE_FIGHTER_POS_COUNT (BATTLE_FIGHTER_POS_7 + 1)
// Sentinels resolved by battleStateExecutingInit against the currently
// resolving action, for cutscene items authored inside a move's own
// cutscene (e.g. cutscenes/battle/moves/slash.jsonc) that need to refer
// to "whoever is being hit"/"whoever is attacking" without knowing their
// concrete BATTLE.fighters index ahead of time.
#define BATTLE_FIGHTER_POS_TARGET BATTLE_FIGHTER_POS(0xFE)
#define BATTLE_FIGHTER_POS_USER BATTLE_FIGHTER_POS(0xFD)
@@ -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/fighter/battlefighterstats.h"
#define BATTLE_FIGHTER_SPECIES_NAME_MAX 16
#define BATTLE_FIGHTER_SPECIES_COUNT_MAX 250
typedef uint8_t battlespeciesid_t;
#define BATTLE_SPECIES_ID_NULL ((battlespeciesid_t)0)
typedef struct {
char_t name[BATTLE_FIGHTER_SPECIES_NAME_MAX];
battlefighterstats_t baseStats;
} battlefighterspecies_t;
@@ -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"
typedef struct {
uint16_t health;
uint16_t mp;
uint16_t healthMax;
uint16_t mpMax;
uint16_t attack;
uint16_t defense;
uint16_t magic;
uint16_t speed;
uint16_t luck;
} battlefighterstats_t;
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef enum {
BATTLE_FIGHTER_STATUS_NULL,
BATTLE_FIGHTER_STATUS_NORMAL,
BATTLE_FIGHTER_STATUS_DEAD,
// Poisoned, burned, confused, etc.
BATTLE_FIGHTER_STATUS_COUNT
} battlefighterstatus_t;
@@ -6,12 +6,11 @@
*/ */
#pragma once #pragma once
#include "error/error.h" #include "dusk.h"
typedef enum { typedef enum {
BATTLE_ABILITY_NULL, BATTLE_FIGHTER_TEAM_ALLY,
BATTLE_FIGHTER_TEAM_ENEMY,
BATTLE_ABILITY_FIRE, BATTLE_FIGHTER_TEAM_COUNT
} battlefighterteam_t;
BATTLE_ABILITY_COUNT
} battleability_t;
+10
View File
@@ -0,0 +1,10 @@
# 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
battlemove.c
)
+139
View File
@@ -0,0 +1,139 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlemove.h"
#include "asset/asset.h"
#include "asset/loader/assetloader.h"
#include "assert/assert.h"
#include "util/memory.h"
#include "util/string.h"
#include <string.h>
battleability_t BATTLE_MOVES[BATTLE_MOVE_COUNT_MAX];
uint8_t BATTLE_MOVE_COUNT;
errorret_t battleMoveInit(void) {
memoryZero(BATTLE_MOVES, sizeof(BATTLE_MOVES));
BATTLE_MOVE_COUNT = BATTLE_MOVE_ID_NULL + 1;// Reserve NULL.
// Get moves JSON.
assetentry_t *entry = assetLock(
"battle/moves.jsonc", ASSET_LOADER_TYPE_JSON, NULL
);
errorret_t ret = assetRequireLoaded(entry);
if(errorIsNotOk(ret)) {
assetUnlockEntry(entry);
errorChain(ret);
}
yyjson_val *root = yyjson_doc_get_root(entry->data.json);
yyjson_val *moves = yyjson_obj_get(root, "moves");
yyjson_obj_iter iter = yyjson_obj_iter_with(moves);
yyjson_val *key;
while((key = yyjson_obj_iter_next(&iter))) {
if(BATTLE_MOVE_COUNT >= BATTLE_MOVE_COUNT_MAX) {
assetUnlockEntry(entry);
errorThrow(
"Battle move: too many moves defined (max %u)",
(uint32_t)BATTLE_MOVE_COUNT_MAX
);
}
battlemoveid_t id = BATTLE_MOVE_COUNT++;
battleability_t *move = &BATTLE_MOVES[id];
// Name
if(!yyjson_is_str(key)) {
assetUnlockEntry(entry);
errorThrow("Battle move: keys in 'moves' must be strings");
}
const char_t *name = yyjson_get_str(key);
stringCopy(move->name, name, BATTLE_MOVE_NAME_MAX);
if(strlen(name) >= BATTLE_MOVE_NAME_MAX) {
assetUnlockEntry(entry);
errorThrow(
"Battle move '%s': name must be less than %u characters",
name, (uint32_t)BATTLE_MOVE_NAME_MAX
);
}
// Must me object
yyjson_val *val = yyjson_obj_iter_get_val(key);
if(!yyjson_is_obj(val)) {
assetUnlockEntry(entry);
errorThrow("Battle move '%s': value must be an object", name);
}
// Valid targets
yyjson_val *enemies = yyjson_obj_get(val, "enemies");
if(enemies != NULL && !yyjson_is_bool(enemies)) {
assetUnlockEntry(entry);
errorThrow("Battle move '%s': 'enemies' must be a boolean", name);
}
yyjson_val *allies = yyjson_obj_get(val, "allies");
if(allies != NULL && !yyjson_is_bool(allies)) {
assetUnlockEntry(entry);
errorThrow("Battle move '%s': 'allies' must be a boolean", name);
}
yyjson_val *multiple = yyjson_obj_get(val, "multiple");
if(multiple != NULL && !yyjson_is_bool(multiple)) {
assetUnlockEntry(entry);
errorThrow("Battle move '%s': 'multiple' must be a boolean", name);
}
yyjson_val *self = yyjson_obj_get(val, "self");
if(self != NULL && !yyjson_is_bool(self)) {
assetUnlockEntry(entry);
errorThrow("Battle move '%s': 'self' must be a boolean", name);
}
battletarget_t target = 0;
if(yyjson_get_bool(enemies)) target |= BATTLE_TARGET_ENEMIES;
if(yyjson_get_bool(allies)) target |= BATTLE_TARGET_ALLIES;
if(yyjson_get_bool(multiple)) target |= BATTLE_TARGET_MULTIPLE;
if(yyjson_get_bool(self)) target |= BATTLE_TARGET_SELF;
move->target = target;
if(move->target == 0) {
assetUnlockEntry(entry);
errorThrow("Battle move '%s': missing target type", name);
}
// Default target (optional)
yyjson_val *defaultVal = yyjson_obj_get(val, "default");
if(defaultVal != NULL && !yyjson_is_str(defaultVal)) {
assetUnlockEntry(entry);
errorThrow("Battle move '%s': 'default' must be a string", name);
}
const char_t *defaultTarget = yyjson_get_str(defaultVal);
if(defaultTarget == NULL) {
move->targetDefault = 0;
} else if(stringCompareInsensitive(defaultTarget, "enemy") == 0) {
move->targetDefault = BATTLE_TARGET_ENEMIES;
} else if(stringCompareInsensitive(defaultTarget, "ally") == 0) {
move->targetDefault = BATTLE_TARGET_ALLIES;
} else if(stringCompareInsensitive(defaultTarget, "self") == 0) {
move->targetDefault = BATTLE_TARGET_SELF;
} else {
assetUnlockEntry(entry);
errorThrow("Battle move %s has invalid default target.", name);
}
}
assetUnlockEntry(entry);
errorOk();
}
battlemoveid_t battleMoveGetIdByName(const char_t *name) {
assertNotNull(name, "name must not be NULL");
for(battlemoveid_t id = BATTLE_MOVE_ID_NULL + 1; id < BATTLE_MOVE_COUNT; id++) {
if(stringEquals(BATTLE_MOVES[id].name, name)) return id;
}
return BATTLE_MOVE_ID_NULL;
}
+42
View File
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "asset/asset.h"
#include "battletarget.h"
typedef uint8_t battlemoveid_t;
#define BATTLE_MOVE_NAME_MAX 16
#define BATTLE_MOVE_COUNT_MAX 250
#define BATTLE_MOVE_ID_NULL ((battlemoveid_t)0)
extern uint8_t BATTLE_MOVE_COUNT;
typedef struct {
char_t name[BATTLE_MOVE_NAME_MAX];
battletarget_t target;
battletarget_t targetDefault;
} battleability_t;
extern battleability_t BATTLE_MOVES[BATTLE_MOVE_COUNT_MAX];
/**
* Initializes the battle move subsystem, loading assets/battle/moves.jsonc.
*
* @return Any error that occurs.
*/
errorret_t battleMoveInit(void);
/**
* Finds a move's id by name (exact match).
*
* @param name The move name to search for.
* @return The matching move's id, or BATTLE_MOVE_ID_NULL if not found.
*/
battlemoveid_t battleMoveGetIdByName(const char_t *name);
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/battle/move/battlemove.h"
#include "rpg/battle/fighter/battlefighterpos.h"
typedef struct battlefighter_s battlefighter_t;
typedef struct {
battlemoveid_t move;
battlefighterpos_t targets[BATTLE_FIGHTER_POS_COUNT];
battlefighter_t *user;
} battlemoveaction_t;
+16
View File
@@ -0,0 +1,16 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef uint8_t battletarget_t;
#define BATTLE_TARGET_ENEMIES (1 << 0)
#define BATTLE_TARGET_ALLIES (1 << 1)
#define BATTLE_TARGET_MULTIPLE (1 << 2)
#define BATTLE_TARGET_SELF (1 << 3)
+140 -29
View File
@@ -8,53 +8,125 @@
#include "party.h" #include "party.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h"
#include "save/save.h" #include "save/save.h"
#include "asset/asset.h"
#include "asset/loader/assetloader.h"
void partyInit(void) { errorret_t partyInit(party_t *party) {
party_t *party = &SAVE.slot.party; assertNotNull(party, "Party cannot be NULL");
memoryZero(party, sizeof(party_t)); memoryZero(party, sizeof(party_t));
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; 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) { assetentry_t *entry = assetLock("party.jsonc", ASSET_LOADER_TYPE_JSON, NULL);
const party_t *party = &SAVE.slot.party; errorret_t result = assetRequireLoaded(entry);
if(errorIsNotOk(result)) {
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) { assetUnlockEntry(entry);
if(party->members[i].status == BATTLE_FIGHTER_STATUS_NULL) return i; errorChain(result);
} }
return 0xFF; yyjson_val *root = yyjson_doc_get_root(entry->data.json);
yyjson_val *members = yyjson_obj_get(root, "members");
if(!yyjson_is_obj(members)) {
assetUnlockEntry(entry);
errorThrow("party.jsonc: missing/invalid 'members' object");
}
const size_t memberCount = yyjson_obj_size(members);
if(memberCount > PARTY_MEMBER_COUNT_MAX) {
assetUnlockEntry(entry);
errorThrow(
"party.jsonc: defines more than PARTY_MEMBER_COUNT_MAX (%u) members",
PARTY_MEMBER_COUNT_MAX
);
}
uint8_t idx = 0;
yyjson_val *key;
yyjson_val *memberObj;
yyjson_obj_iter iter = yyjson_obj_iter_with(members);
while((key = yyjson_obj_iter_next(&iter))) {
memberObj = yyjson_obj_iter_get_val(key);
if(yyjson_get_len(key) >= PARTY_KEY_LENGTH_MAX) {
assetUnlockEntry(entry);
errorThrow(
"party.jsonc: member key '%s' exceeds PARTY_KEY_LENGTH_MAX (%u)",
yyjson_get_str(key), PARTY_KEY_LENGTH_MAX
);
}
stringCopy(party->keys[idx], yyjson_get_str(key), PARTY_KEY_LENGTH_MAX - 1);
battlefighter_t *member = &party->members[idx];
member->id = idx;
errorret_t parseResult = battleFighterParse(member, memberObj);
if(errorIsNotOk(parseResult)) {
assetUnlockEntry(entry);
errorChain(parseResult);
}
idx++;
}
assetUnlockEntry(entry);
// TEST: only the first defined member starts active, in the first party
// position - replace once there's a real starting-party/character-
// creation flow. Deliberately separate from the roster seeding above:
// order (not a member's presence in the roster) is what determines who's
// currently in the party.
if(memberCount > 0) party->order[0] = 0;
errorOk();
} }
battlefighter_t *partyAddMember( uint8_t partyGetMemberIndexByKey(const char_t *key) {
const battlefighterstats_t stats, assertNotNull(key, "Key cannot be NULL");
const uint16_t healthMax,
const uint16_t mpMax const party_t *party = &SAVE.slot.party;
) { for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
if(stringEquals(party->keys[i], key)) return i;
}
return PARTY_MEMBER_NOT_FOUND;
}
const char_t *partyGetMemberKey(const uint8_t memberIndex) {
assertTrue(memberIndex < PARTY_MEMBER_COUNT_MAX, "Invalid party member index");
return SAVE.slot.party.keys[memberIndex];
}
bool_t partyIsMemberActive(const uint8_t memberIndex) {
assertTrue(memberIndex < PARTY_MEMBER_COUNT_MAX, "Invalid party member index");
const party_t *party = &SAVE.slot.party;
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
if(party->order[i] == memberIndex) return true;
}
return false;
}
void partyAddMember(const uint8_t memberIndex) {
assertTrue(memberIndex < PARTY_MEMBER_COUNT_MAX, "Invalid party member index");
party_t *party = &SAVE.slot.party; party_t *party = &SAVE.slot.party;
assertTrue(
const uint8_t index = partyGetAvailableMember(); party->members[memberIndex].status != BATTLE_FIGHTER_STATUS_NULL,
if(index == 0xFF) return NULL; "Member does not exist in the roster"
battlefighter_t *member = &party->members[index];
battleFighterInit(
member, BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
stats, healthMax, mpMax
); );
if(partyIsMemberActive(memberIndex)) return;
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] = memberIndex;
break; return;
} }
return member;
} }
battlefighter_t *partyGetOrderMember(const uint8_t slot) { battlefighter_t *partyGetOrderMember(const uint8_t slot) {
@@ -75,3 +147,42 @@ void partySetOrder(const uint8_t slot, const uint8_t memberIndex) {
SAVE.slot.party.order[slot] = memberIndex; SAVE.slot.party.order[slot] = memberIndex;
} }
void partyRemoveMember(const uint8_t memberIndex) {
assertTrue(memberIndex < PARTY_MEMBER_COUNT_MAX, "Invalid party member index");
party_t *party = &SAVE.slot.party;
uint8_t removedSlot = PARTY_ORDER_EMPTY;
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
if(party->order[i] != memberIndex) continue;
removedSlot = i;
break;
}
if(removedSlot == PARTY_ORDER_EMPTY) return;
for(uint8_t i = removedSlot; i < PARTY_ACTIVE_SIZE_MAX - 1; i++) {
party->order[i] = party->order[i + 1];
}
party->order[PARTY_ACTIVE_SIZE_MAX - 1] = PARTY_ORDER_EMPTY;
}
void partyHealMember(const uint8_t memberIndex) {
assertTrue(memberIndex < PARTY_MEMBER_COUNT_MAX, "Invalid party member index");
battlefighter_t *member = &SAVE.slot.party.members[memberIndex];
if(member->status == BATTLE_FIGHTER_STATUS_NULL) return;
member->status = BATTLE_FIGHTER_STATUS_NORMAL;
member->stats.health = member->stats.healthMax;
member->stats.mp = member->stats.mpMax;
}
void partyHealAll(void) {
const party_t *party = &SAVE.slot.party;
for(uint8_t i = 0; i < PARTY_MEMBER_COUNT_MAX; i++) {
if(party->members[i].status == BATTLE_FIGHTER_STATUS_NULL) continue;
partyHealMember(i);
}
}
+79 -29
View File
@@ -6,53 +6,76 @@
*/ */
#pragma once #pragma once
#include "battlefighter.h" #include "rpg/battle/fighter/battlefighter.h"
#include "yyjson.h"
#define PARTY_MEMBER_COUNT_MAX 4 #define PARTY_MEMBER_COUNT_MAX 10
#define PARTY_ACTIVE_SIZE_MAX 3 #define PARTY_ACTIVE_SIZE_MAX 4
#define PARTY_KEY_LENGTH_MAX 32
#define PARTY_ORDER_EMPTY 0xFF #define PARTY_ORDER_EMPTY 0xFF
#define PARTY_MEMBER_NOT_FOUND 0xFF
typedef struct { typedef struct {
battlefighter_t members[PARTY_MEMBER_COUNT_MAX]; battlefighter_t members[PARTY_MEMBER_COUNT_MAX];
char_t keys[PARTY_MEMBER_COUNT_MAX][PARTY_KEY_LENGTH_MAX];
// Maps an active battle slot to the roster member filling it, or
// PARTY_ORDER_EMPTY if the slot is unfilled. Only the first
// PARTY_ACTIVE_SIZE_MAX of the PARTY_MEMBER_COUNT_MAX roster members
// can be in the active lineup at once.
uint8_t order[PARTY_ACTIVE_SIZE_MAX]; uint8_t order[PARTY_ACTIVE_SIZE_MAX];
} party_t; } party_t;
/** /**
* Initializes the current save slot's party (SAVE.slot.party) with an * Initializes party with an empty order, then seeds every roster slot
* empty roster and order. * directly from party.jsonc's "members" object (each key/value pair fills
* the next members[]/keys[] slot in the object's iteration order, key
* copied into keys[] and value parsed via battleFighterParse) - unlike
* partyAddMember, this never touches order itself except for one
* placeholder default: if party.jsonc defines at least one member,
* order[0] is set to 0 (the first member starts active in the first party
* position). Replace this default once there's a real starting-party/
* character-creation flow.
*
* @param party The party to initialize.
* @return Error if party.jsonc fails to load/parse, defines more members
* than PARTY_MEMBER_COUNT_MAX has room for, or a key exceeds
* PARTY_KEY_LENGTH_MAX.
*/ */
void partyInit(void); errorret_t partyInit(party_t *party);
/** /**
* Gets an available (unused) member slot index in the current save slot's * Looks up a roster member's index by its party.jsonc key (see
* party. * party_t.keys).
* *
* @return The index of an available slot, or 0xFF if the party is full. * @param key The member's key to search for.
* @return The matching roster index, or PARTY_MEMBER_NOT_FOUND if no
* member has that key.
*/ */
uint8_t partyGetAvailableMember(void); uint8_t partyGetMemberIndexByKey(const char_t *key);
/** /**
* Adds a member to the current save slot's party roster in the next * Gets a roster member's party.jsonc key by index (see party_t.keys).
* available slot. Party members are always allies controlled by the
* 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 memberIndex The roster member index to query.
* @param healthMax The member's maximum health. * @return The member's key - "" if memberIndex is past however many
* @param mpMax The member's maximum mp. * members party.jsonc actually defines.
* @return Pointer to the newly added party member, or NULL if the party is
* already full.
*/ */
battlefighter_t *partyAddMember( const char_t *partyGetMemberKey(const uint8_t memberIndex);
const battlefighterstats_t stats,
const uint16_t healthMax, /**
const uint16_t mpMax * Checks whether memberIndex currently occupies a slot in the current save
); * slot's party order (i.e. is actively in the party right now).
*
* @param memberIndex The roster member index to check.
* @return True if memberIndex appears anywhere in order.
*/
bool_t partyIsMemberActive(const uint8_t memberIndex);
/**
* Adds an existing roster member (see partyInit - every roster slot
* always exists once initialized) to the current save slot's active party
* order, in the first free order slot. No-op if memberIndex is already
* active, or if there is no free order slot.
*
* @param memberIndex The roster member index to activate.
*/
void partyAddMember(const uint8_t memberIndex);
/** /**
* Gets the roster member currently occupying an active order slot in the * Gets the roster member currently occupying an active order slot in the
@@ -74,3 +97,30 @@ battlefighter_t *partyGetOrderMember(const uint8_t slot);
* PARTY_ORDER_EMPTY to clear the slot. * PARTY_ORDER_EMPTY to clear the slot.
*/ */
void partySetOrder(const uint8_t slot, const uint8_t memberIndex); void partySetOrder(const uint8_t slot, const uint8_t memberIndex);
/**
* Removes memberIndex from the current save slot's active party order -
* the roster member itself is untouched (it still exists, per partyInit;
* it's simply no longer active) - shifting every later order entry down
* one slot to close the gap, so order stays packed with no holes between
* active members. No-op if memberIndex isn't currently active.
*
* @param memberIndex The roster member index to deactivate.
*/
void partyRemoveMember(const uint8_t memberIndex);
/**
* Fully restores a roster member's health/mp to their max and clears a
* dead status back to normal - unlike battleFighterHeal, this can revive
* a dead member (there's no combat context here to keep them down). No-op
* if the slot is empty.
*
* @param memberIndex The roster member index to heal.
*/
void partyHealMember(const uint8_t memberIndex);
/**
* Calls partyHealMember for every occupied slot in the current save
* slot's party roster.
*/
void partyHealAll(void);
+19
View File
@@ -0,0 +1,19 @@
# 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
battlestate.c
battlestateopening.c
battlestatepreround.c
battlestateselection.c
battlestateexecuting.c
battlestatepostround.c
battlestatelost.c
battlestatewon.c
battlestatefled.c
battlestateending.c
)
+66
View File
@@ -0,0 +1,66 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestate.h"
battlestatefunctions_t BATTLE_STATE_FUNCTIONS[BATTLE_STATE_COUNT] = {
[BATTLE_STATE_NULL] = { 0 },
[BATTLE_STATE_OPENING] = {
.init = battleStateOpeningInit,
.update = battleStateOpeningUpdate,
.dispose = battleStateOpeningDispose
},
[BATTLE_STATE_PRE_ROUND] = {
.init = battleStatePreRoundInit,
.update = battleStatePreRoundUpdate,
.dispose = battleStatePreRoundDispose
},
[BATTLE_STATE_SELECTION] = {
.init = battleStateSelectionInit,
.update = battleStateSelectionUpdate,
.dispose = battleStateSelectionDispose
},
[BATTLE_STATE_EXECUTING] = {
.init = battleStateExecutingInit,
.update = battleStateExecutingUpdate,
.dispose = battleStateExecutingDispose
},
[BATTLE_STATE_POST_ROUND] = {
.init = battleStatePostRoundInit,
.update = battleStatePostRoundUpdate,
.dispose = battleStatePostRoundDispose
},
[BATTLE_STATE_LOST] = {
.init = battleStateLostInit,
.update = battleStateLostUpdate,
.dispose = battleStateLostDispose
},
[BATTLE_STATE_WON] = {
.init = battleStateWonInit,
.update = battleStateWonUpdate,
.dispose = battleStateWonDispose
},
[BATTLE_STATE_FLED] = {
.init = battleStateFledInit,
.update = battleStateFledUpdate,
.dispose = battleStateFledDispose
},
[BATTLE_STATE_ENDING] = {
.init = battleStateEndingInit,
.update = battleStateEndingUpdate,
.dispose = battleStateEndingDispose
}
};
+64
View File
@@ -0,0 +1,64 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "battlestateopening.h"
#include "battlestatepreround.h"
#include "battlestateselection.h"
#include "battlestateexecuting.h"
#include "battlestatepostround.h"
#include "battlestatelost.h"
#include "battlestatewon.h"
#include "battlestatefled.h"
#include "battlestateending.h"
typedef enum {
// No active battle.
BATTLE_STATE_NULL,
// Battle hasn't actually started yet, equiv to trainer intro in Pokemon.
BATTLE_STATE_OPENING,
// Pre round, anything that happens before AI or Player can act.
BATTLE_STATE_PRE_ROUND,
// Player is deciding what to do, waiting for their input
BATTLE_STATE_SELECTION,
// Currently executing the moves.
BATTLE_STATE_EXECUTING,
// Post round, anything that happens after AI or Player has acted, loops back
// after this point
BATTLE_STATE_POST_ROUND,
// Battle has ended with a player loss
BATTLE_STATE_LOST,
// Battle has ended with a player win
BATTLE_STATE_WON,
// Battle has ended with a player fleeing
BATTLE_STATE_FLED,
// Battle state is done, this is fade out or whatever.
BATTLE_STATE_ENDING,
BATTLE_STATE_COUNT
} battlestate_t;
typedef union {
battlestateopening_t opening;
battlestatepreround_t preRound;
battlestateselection_t selection;
battlestateexecuting_t executing;
battlestatepostround_t postRound;
battlestatelost_t lost;
battlestatewon_t won;
battlestatefled_t fled;
battlestateending_t ending;
} battlestatedata_t;
typedef struct {
void (*init)();
void (*update)();
void (*dispose)();
} battlestatefunctions_t;
extern battlestatefunctions_t BATTLE_STATE_FUNCTIONS[BATTLE_STATE_COUNT];
@@ -0,0 +1,28 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestateending.h"
#include "rpg/battle/battle.h"
#include "scene/scene.h"
void battleStateEndingInit(void) {
// Tear down the battle and hand control back to the overworld. The
// overworld scene keeps no state of its own in scenedata_t (player/map
// state lives in the separate global entity/map systems, untouched by
// switching to/from SCENE_TYPE_BATTLE), so there's nothing else to
// restore here.
battleDispose();
sceneSet(SCENE_TYPE_OVERWORLD);
}
void battleStateEndingUpdate(void) {
}
void battleStateEndingDispose(void) {
}
@@ -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 "dusk.h"
typedef struct {
} battlestateending_t;
/**
* Called when the battle enters BATTLE_STATE_ENDING. Disposes the battle
* (see battleDispose) and switches back to SCENE_TYPE_OVERWORLD.
*/
void battleStateEndingInit(void);
/**
* Updates BATTLE_STATE_ENDING for one frame.
*/
void battleStateEndingUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_ENDING.
*/
void battleStateEndingDispose(void);
@@ -0,0 +1,116 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestateexecuting.h"
#include "rpg/battle/battle.h"
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/cutscene/cutscene.h"
#include "asset/assetfile.h"
#include "ui/overlay/uifatalerror.h"
#include "assert/assert.h"
#include "util/string.h"
void battleStateExecutingResolveFighterIndex(
battlefighterpos_t *fighterIndex,
const uint8_t userIndex,
const battlemoveaction_t *action
) {
if(*fighterIndex == BATTLE_FIGHTER_POS_TARGET) {
*fighterIndex = action->targets[0];
} else if(*fighterIndex == BATTLE_FIGHTER_POS_USER) {
*fighterIndex = userIndex;
}
}
void battleStateExecutingInit(void) {
cutsceneitem_t items[BATTLE_STATE_EXECUTING_ITEMS_MAX];
uint8_t itemsCount = 0;
// For each action (just queued during selection). actionsPending is
// indexed by fighter position, not sequentially, so scan every position
// and stop early once every pending action has been processed.
uint8_t processed = 0;
for(
uint8_t i = 0;
i < BATTLE_FIGHTER_POS_COUNT && processed < BATTLE.actionsPendingCount;
i++
) {
// Get action.
battlemoveaction_t *action = &BATTLE.actionsPending[i];
if(action->move == BATTLE_MOVE_ID_NULL) continue;
processed++;
assertTrue(action->move < BATTLE_MOVE_COUNT, "Invalid move id");
// Get ability.
battleability_t *ability = &BATTLE_MOVES[action->move];
assertStrLenMin(ability->name, 1, "Invalid move name");
// Determine cutscene path
char_t path[ASSET_FILE_NAME_MAX];
stringFormat(
path, ASSET_FILE_NAME_MAX - 1,
"cutscenes/battle/moves/%s.jsonc", ability->name
);
// Load and parse the move's cutscene straight into the tail of items.
const uint8_t moveItemsStart = itemsCount;
cutscene_t scene;
errorret_t result = cutsceneLoadParse(
path, &scene, &items[itemsCount],
BATTLE_STATE_EXECUTING_ITEMS_MAX - itemsCount
);
if(errorIsNotOk(result)) {
errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL);
continue;
}
itemsCount += scene.itemCount;
// Resolve BATTLE_FIGHTER_POS_TARGET/USER sentinels against this
// action, now that its user/target fighters are known.
for(uint8_t j = moveItemsStart; j < itemsCount; j++) {
cutsceneitem_t *moveItem = &items[j];
if(moveItem->type == CUTSCENE_ITEM_TYPE_BATTLE_FIGHTER_DAMAGE) {
battleStateExecutingResolveFighterIndex(
&moveItem->battleFighterDamage.fighterIndex, i, action
);
} else if(moveItem->type == CUTSCENE_ITEM_TYPE_BATTLE_FIGHTER_HEAL) {
battleStateExecutingResolveFighterIndex(
&moveItem->battleFighterHeal.fighterIndex, i, action
);
}
}
// Insert end of attack cutscene item.
items[itemsCount++] = (cutsceneitem_t){
.type = CUTSCENE_ITEM_TYPE_BATTLE_POST_MOVE
};
// This action has now been resolved - clear it so it isn't
// re-executed (and doesn't block re-selection) next round.
action->move = BATTLE_MOVE_ID_NULL;
}
BATTLE.actionsPendingCount = 0;
// After all moves completed, transition to pre-round for next round.
items[itemsCount++] = (cutsceneitem_t){
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = { .state = BATTLE_STATE_PRE_ROUND }
};
cutsceneSystemInsertItemsNext(items, itemsCount);
}
void battleStateExecutingUpdate(void) {
}
void battleStateExecutingDispose(void) {
}
@@ -0,0 +1,50 @@
/**
* 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/fighter/battlefighterpos.h"
#include "rpg/battle/move/battlemoveaction.h"
typedef struct {
} battlestateexecuting_t;
#define BATTLE_STATE_EXECUTING_ITEMS_MAX 64
/**
* Called when the battle enters BATTLE_STATE_EXECUTING.
*/
void battleStateExecutingInit(void);
/**
* Resolves a BATTLE_FIGHTER_POS_TARGET/BATTLE_FIGHTER_POS_USER sentinel
* (as parsed onto a BATTLE_FIGHTER_DAMAGE/BATTLE_FIGHTER_HEAL item inside
* a move's own cutscene) against the action currently being resolved
* into cutscene items. Leaves fighterIndex untouched if it's already a
* concrete BATTLE.fighters index.
*
* @param fighterIndex The field to resolve in place.
* @param userIndex Index into BATTLE.fighters of the fighter performing
* the action.
* @param action The action being resolved.
*/
void battleStateExecutingResolveFighterIndex(
battlefighterpos_t *fighterIndex,
const uint8_t userIndex,
const battlemoveaction_t *action
);
/**
* Updates BATTLE_STATE_EXECUTING for one frame.
*/
void battleStateExecutingUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_EXECUTING.
*/
void battleStateExecutingDispose(void);
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestatefled.h"
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
void battleStateFledInit(void) {
const cutsceneitem_t items[] = {
{
.type = CUTSCENE_ITEM_TYPE_TEXT,
.text = { .text = "Got away safely!" }
},
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = { .state = BATTLE_STATE_ENDING }
}
};
cutsceneSystemInsertItemsNext(items, sizeof(items) / sizeof(cutsceneitem_t));
}
void battleStateFledUpdate(void) {
}
void battleStateFledDispose(void) {
}
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct {
} battlestatefled_t;
/**
* Called when the battle enters BATTLE_STATE_FLED. Queues a textbox
* announcing the escape, then transitions to BATTLE_STATE_ENDING once
* dismissed.
*/
void battleStateFledInit(void);
/**
* Updates BATTLE_STATE_FLED for one frame.
*/
void battleStateFledUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_FLED.
*/
void battleStateFledDispose(void);
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestatelost.h"
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
void battleStateLostInit(void) {
const cutsceneitem_t items[] = {
{
.type = CUTSCENE_ITEM_TYPE_TEXT,
.text = { .text = "You were defeated..." }
},
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = { .state = BATTLE_STATE_ENDING }
}
};
cutsceneSystemInsertItemsNext(items, sizeof(items) / sizeof(cutsceneitem_t));
}
void battleStateLostUpdate(void) {
}
void battleStateLostDispose(void) {
}
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct {
} battlestatelost_t;
/**
* Called when the battle enters BATTLE_STATE_LOST. Queues a textbox
* announcing the loss, then transitions to BATTLE_STATE_ENDING once
* dismissed.
*/
void battleStateLostInit(void);
/**
* Updates BATTLE_STATE_LOST for one frame.
*/
void battleStateLostUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_LOST.
*/
void battleStateLostDispose(void);
@@ -0,0 +1,28 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestateopening.h"
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
void battleStateOpeningInit(void) {
const cutsceneitem_t items[] = {
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = { .state = BATTLE_STATE_PRE_ROUND }
}
};
cutsceneSystemInsertItemsNext(items, sizeof(items) / sizeof(cutsceneitem_t));
}
void battleStateOpeningUpdate(void) {
}
void battleStateOpeningDispose(void) {
}
@@ -0,0 +1,28 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct {
} battlestateopening_t;
/**
* Called when the battle enters BATTLE_STATE_OPENING.
*/
void battleStateOpeningInit(void);
/**
* Updates BATTLE_STATE_OPENING for one frame.
*/
void battleStateOpeningUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_OPENING.
*/
void battleStateOpeningDispose(void);
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestatepostround.h"
void battleStatePostRoundInit(void) {
}
void battleStatePostRoundUpdate(void) {
}
void battleStatePostRoundDispose(void) {
}
@@ -0,0 +1,28 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct {
} battlestatepostround_t;
/**
* Called when the battle enters BATTLE_STATE_POST_ROUND.
*/
void battleStatePostRoundInit(void);
/**
* Updates BATTLE_STATE_POST_ROUND for one frame.
*/
void battleStatePostRoundUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_POST_ROUND.
*/
void battleStatePostRoundDispose(void);
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestatepreround.h"
#include "rpg/battle/battle.h"
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
void battleStatePreRoundInit(void) {
// TODO: Determine selection order and who gets to act.
BATTLE.fighterOrderCount = 0;
for(uint8_t i = 0; i < BATTLE_FIGHTER_POS_COUNT; i++) {
if(BATTLE.fighters[i] == NULL) continue;
if(!battleFighterIsAlive(BATTLE.fighters[i])) continue;
BATTLE.fighterOrder[BATTLE.fighterOrderCount++] = i;
}
// Queue up the set state and wait for selection to stop cutscene ending.
cutsceneitem_t items[] = {
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = { .state = BATTLE_STATE_SELECTION }
},
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_WAIT_SELECTION
}
};
cutsceneSystemInsertItemsNext(items, sizeof(items) / sizeof(cutsceneitem_t));
}
void battleStatePreRoundUpdate(void) {
}
void battleStatePreRoundDispose(void) {
}
@@ -0,0 +1,28 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct {
} battlestatepreround_t;
/**
* Called when the battle enters BATTLE_STATE_PRE_ROUND.
*/
void battleStatePreRoundInit(void);
/**
* Updates BATTLE_STATE_PRE_ROUND for one frame.
*/
void battleStatePreRoundUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_PRE_ROUND.
*/
void battleStatePreRoundDispose(void);
@@ -0,0 +1,146 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestateselection.h"
#include "rpg/battle/battle.h"
#include "assert/assert.h"
void battleStateSelectionInit(void) {
BATTLE.stateData.selection.selectionIndex = 0;
}
bool_t battleStateSelectionFighterHasDecided(const uint8_t fighterIndex) {
assertTrue(fighterIndex < BATTLE_FIGHTER_POS_COUNT, "Fighter OOB");
return BATTLE.actionsPending[fighterIndex].move != BATTLE_MOVE_ID_NULL;
}
bool_t battleStateSelectionFighterNeedsDecision(const uint8_t fighterIndex) {
assertTrue(fighterIndex < BATTLE_FIGHTER_POS_COUNT, "Fighter OOB");
battlefighter_t *fighter = BATTLE.fighters[fighterIndex];
if(fighter == NULL) return false;
if(!battleFighterIsAlive(fighter)) return false;
return !battleStateSelectionFighterHasDecided(fighterIndex);
}
bool_t battleStateSelectionIsComplete(void) {
return BATTLE.stateData.selection.selectionIndex >= BATTLE.fighterOrderCount;
}
void battleStateSelectionAiDecide(const uint8_t fighterIndex) {
battlefighter_t *fighter = BATTLE.fighters[fighterIndex];
const battlefighterteam_t enemyTeam =
fighter->team == BATTLE_FIGHTER_TEAM_ALLY ?
BATTLE_FIGHTER_TEAM_ENEMY : BATTLE_FIGHTER_TEAM_ALLY;
// Simple placeholder AI: attack the first living fighter on the
// opposing team. No move variety or target scoring yet.
for(uint8_t i = 0; i < BATTLE_FIGHTER_POS_COUNT; i++) {
battlefighter_t *candidate = BATTLE.fighters[i];
if(candidate == NULL) continue;
if(candidate->team != enemyTeam) continue;
if(!battleFighterIsAlive(candidate)) continue;
battleStateSelectionQueueAttack(fighterIndex, i);
return;
}
}
void battleStateSelectionUpdate(void) {
battlestateselection_t *state = &BATTLE.stateData.selection;
// Are we still waiting for a selection?
while(state->selectionIndex < BATTLE.fighterOrderCount) {
const uint8_t fighterIndex = BATTLE.fighterOrder[state->selectionIndex];
// Is this fighter still owed a decision?
if(!battleStateSelectionFighterNeedsDecision(fighterIndex)) {
state->selectionIndex++;
continue;
}
// Players will act on their own.
battlefighter_t *fighter = BATTLE.fighters[fighterIndex];
if(fighter->controller != BATTLE_FIGHTER_CONTROLLER_AI) return;
battleStateSelectionAiDecide(fighterIndex);
state->selectionIndex++;
}
}
void battleStateSelectionDispose(void) {
}
void battleStateSelectionQueueAttack(
const uint8_t fighterIndex,
const uint8_t targetIndex
) {
assertTrue(fighterIndex < BATTLE_FIGHTER_POS_COUNT, "Fighter OOB");
assertTrue(targetIndex < BATTLE_FIGHTER_POS_COUNT, "Target OOB");
assertNotNull(BATTLE.fighters[fighterIndex], "Fighter cannot be NULL");
assertNotNull(BATTLE.fighters[targetIndex], "Target cannot be NULL");
const battlemoveid_t move = battleMoveGetIdByName("slash");
assertTrue(move != BATTLE_MOVE_ID_NULL, "Missing 'slash' battle move");
battlemoveaction_t *action = &BATTLE.actionsPending[fighterIndex];
if(action->move == BATTLE_MOVE_ID_NULL) BATTLE.actionsPendingCount++;
action->move = move;
action->targets[0] = targetIndex;
action->user = BATTLE.fighters[fighterIndex];
}
battlefighter_t *battleStateSelectionGetCurrentFighter(void) {
if(BATTLE.state != BATTLE_STATE_SELECTION) return NULL;
const uint8_t index = BATTLE.stateData.selection.selectionIndex;
if(index >= BATTLE.fighterOrderCount) return NULL;
return BATTLE.fighters[BATTLE.fighterOrder[index]];
}
void battleStateSelectionPlayerAttack(const uint8_t targetIndex) {
battlefighter_t *fighter = battleStateSelectionGetCurrentFighter();
if(fighter == NULL) return;
const uint8_t selectionIndex = BATTLE.stateData.selection.selectionIndex;
const uint8_t fighterIndex = BATTLE.fighterOrder[selectionIndex];
battleStateSelectionQueueAttack(fighterIndex, targetIndex);
BATTLE.stateData.selection.selectionIndex++;
}
void battleStateSelectionGoBack(void) {
battlestateselection_t *state = &BATTLE.stateData.selection;
uint8_t index = state->selectionIndex;
while(index > 0) {
index--;
const uint8_t fighterIndex = BATTLE.fighterOrder[index];
battlefighter_t *fighter = BATTLE.fighters[fighterIndex];
if(fighter == NULL) continue;
if(fighter->controller != BATTLE_FIGHTER_CONTROLLER_PLAYER) continue;
if(!battleStateSelectionFighterHasDecided(fighterIndex)) continue;
battlemoveaction_t *action = &BATTLE.actionsPending[fighterIndex];
action->move = BATTLE_MOVE_ID_NULL;
BATTLE.actionsPendingCount--;
state->selectionIndex = index;
return;
}
}
void battleStateSelectionPlayerFlee(void) {
battlefighter_t *fighter = battleStateSelectionGetCurrentFighter();
if(fighter == NULL) return;
BATTLE.result = BATTLE_RESULT_FLED;
battleSetState(BATTLE_STATE_FLED);
}
@@ -0,0 +1,120 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/battle/fighter/battlefighter.h"
typedef struct {
// Cursor into BATTLE.fighters (by position index) for the fighter
// currently deciding a move this round.
uint8_t selectionIndex;
} battlestateselection_t;
/**
* Called when the battle enters BATTLE_STATE_SELECTION.
*/
void battleStateSelectionInit(void);
/**
* Updates BATTLE_STATE_SELECTION for one frame: auto-decides (see
* battleStateSelectionAiDecide) for every AI-controlled fighter the
* cursor passes, stopping once it reaches a player-controlled fighter
* awaiting input (see battleStateSelectionGetCurrentFighter). Once every
* position has decided, BATTLE_WAIT_SELECTION (see
* cutsceneBattleWaitSelectionUpdate) queues the move to
* BATTLE_STATE_EXECUTING.
*/
void battleStateSelectionUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_SELECTION.
*/
void battleStateSelectionDispose(void);
/**
* Checks whether the fighter at fighterIndex has already queued a move
* this round.
*
* @param fighterIndex Index into BATTLE.fighters to check.
* @return True if an action is already pending for this fighter.
*/
bool_t battleStateSelectionFighterHasDecided(const uint8_t fighterIndex);
/**
* Checks whether the fighter at fighterIndex is a live, undecided
* candidate that BATTLE_STATE_SELECTION should still be deciding a move
* for.
*
* @param fighterIndex Index into BATTLE.fighters to check.
* @return True if the fighter is alive and has no move queued yet.
*/
bool_t battleStateSelectionFighterNeedsDecision(const uint8_t fighterIndex);
/**
* Decides and queues a move for an AI-controlled fighter: currently
* always a basic attack against the first living fighter on the
* opposing team (see battleStateSelectionQueueAttack). No-ops if there's
* no living target (the battle should already be over by then via
* BATTLE_POST_MOVE).
*
* @param fighterIndex Index into BATTLE.fighters of the deciding fighter.
*/
void battleStateSelectionAiDecide(const uint8_t fighterIndex);
/**
* Checks whether every fighter in BATTLE.fighterOrder has decided a move
* this round.
*
* @return True once the selection cursor has passed every fighter.
*/
bool_t battleStateSelectionIsComplete(void);
/**
* Queues a basic attack (the "slash" move) from fighterIndex against
* targetIndex.
*
* @param fighterIndex Index into BATTLE.fighters of the deciding fighter.
* @param targetIndex Index into BATTLE.fighters of the target.
*/
void battleStateSelectionQueueAttack(
const uint8_t fighterIndex,
const uint8_t targetIndex
);
/**
* Returns the fighter currently awaiting a decision in
* BATTLE_STATE_SELECTION.
*
* @return Pointer to the fighter awaiting a decision, or NULL if the
* battle isn't in BATTLE_STATE_SELECTION or every position has
* already decided.
*/
battlefighter_t *battleStateSelectionGetCurrentFighter(void);
/**
* Submits the currently-selecting fighter's attack against a target, if
* the battle is in BATTLE_STATE_SELECTION and awaiting a decision. Queues
* the move and advances the selection cursor.
*
* @param targetIndex Index into BATTLE.fighters of the target.
*/
void battleStateSelectionPlayerAttack(const uint8_t targetIndex);
/**
* Ends the battle immediately with BATTLE_STATE_FLED, if the battle is in
* BATTLE_STATE_SELECTION and awaiting a decision.
*/
void battleStateSelectionPlayerFlee(void);
/**
* Rewinds the selection cursor to the nearest earlier player-controlled
* fighter that has already decided a move this round, clearing its
* pending action so it can be re-decided. AI-decided fighters along the
* way are left alone (skipped over, not rewound onto). No-ops if there's
* no such fighter (e.g. already at the first decision of the round).
*/
void battleStateSelectionGoBack(void);
@@ -0,0 +1,32 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "battlestatewon.h"
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
void battleStateWonInit(void) {
const cutsceneitem_t items[] = {
{
.type = CUTSCENE_ITEM_TYPE_TEXT,
.text = { .text = "You won the battle!" }
},
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = { .state = BATTLE_STATE_ENDING }
}
};
cutsceneSystemInsertItemsNext(items, sizeof(items) / sizeof(cutsceneitem_t));
}
void battleStateWonUpdate(void) {
}
void battleStateWonDispose(void) {
}
@@ -0,0 +1,30 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct {
} battlestatewon_t;
/**
* Called when the battle enters BATTLE_STATE_WON. Queues a textbox
* announcing the win, then transitions to BATTLE_STATE_ENDING once
* dismissed.
*/
void battleStateWonInit(void);
/**
* Updates BATTLE_STATE_WON for one frame.
*/
void battleStateWonUpdate(void);
/**
* Called when the battle leaves BATTLE_STATE_WON.
*/
void battleStateWonDispose(void);
+1
View File
@@ -7,6 +7,7 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
cutscene.c cutscene.c
cutsceneref.c
cutscenesystem.c cutscenesystem.c
) )
+32 -8
View File
@@ -9,6 +9,8 @@
#include "item/json/cutscenejsonpauseflags.h" #include "item/json/cutscenejsonpauseflags.h"
#include "util/memory.h" #include "util/memory.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "asset/asset.h"
#include "asset/loader/assetloader.h"
errorret_t cutsceneParseItem( errorret_t cutsceneParseItem(
yyjson_val *itemObj, yyjson_val *itemObj,
@@ -83,13 +85,6 @@ errorret_t cutsceneParseDoc(
} }
} }
// Everything structural has validated by this point, so it's safe to
// start overwriting items - a per-item parse failure past this point
// still leaves it partially overwritten, but that's fine: any load
// failure here already sends the game into the fatal-error overlay (see
// cutsceneSystemLoad/cutsceneCutsceneResolve/
// cutsceneInsertResolveAndSplice), so nothing keeps running against
// stale data.
memoryZero(items, itemCount * sizeof(cutsceneitem_t)); memoryZero(items, itemCount * sizeof(cutsceneitem_t));
yyjson_arr_iter itemIter = yyjson_arr_iter_with(itemsArr); yyjson_arr_iter itemIter = yyjson_arr_iter_with(itemsArr);
@@ -140,7 +135,6 @@ void cutsceneAppend(
const cutsceneitem_t *items, const cutsceneitem_t *items,
const uint8_t count const uint8_t count
) { ) {
assertNotNull(scene, "Scene cannot be NULL");
cutsceneAppendAt(scene, scene->itemCount, items, count); cutsceneAppendAt(scene, scene->itemCount, items, count);
} }
@@ -152,3 +146,33 @@ void cutsceneAppendNext(
) { ) {
cutsceneAppendAt(scene, (uint8_t)(currentIndex + 1), items, count); cutsceneAppendAt(scene, (uint8_t)(currentIndex + 1), items, count);
} }
errorret_t cutsceneLoadParse(
const char_t *path,
cutscene_t *scene,
cutsceneitem_t *items,
const size_t itemsMax
) {
assertNotNull(path, "Path cannot be NULL");
assertNotNull(scene, "Scene cannot be NULL");
assertNotNull(items, "Items cannot be NULL");
// Lock the asset, require it loaded.
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_JSON, NULL);
errorret_t result = assetRequireLoaded(entry);
if(errorIsNotOk(result)) {
assetUnlockEntry(entry);
errorChain(result);
}
// Parse the loaded JSON
errorret_t parseResult = cutsceneParseDoc(
entry->data.json, scene, items, itemsMax
);
// Free up the asset entry.
assetUnlockEntry(entry);
errorChain(parseResult);
errorOk();
}
+25
View File
@@ -127,3 +127,28 @@ void cutsceneAppendNext(
const cutsceneitem_t *items, const cutsceneitem_t *items,
const uint8_t count const uint8_t count
); );
/**
* Loads a cutscene JSON asset by path and parses it into scene/items (see
* cutsceneParseDoc) - the common "lock the asset, require it loaded,
* parse its 'items' array, unlock it again" sequence shared by every
* place that resolves a cutscene by file path (cutsceneSystemLoad,
* cutsceneCutsceneResolve, cutsceneInsertResolveAndSplice,
* battleStateExecutingInit, cutsceneSystemGoTo's reload). Purely propagates the
* error on failure (like cutsceneParseDoc) - this is core cutscene logic,
* not UI, so it doesn't reach for uiFatalErrorOpen itself; each caller
* decides how to surface the failure (typically errorCatch(errorPrint())
* + uiFatalErrorOpen(NULL), same as any other asset load failure).
*
* @param path Asset path of the cutscene JSON file to load.
* @param scene Destination scene - itemCount/itemsMax/pause overwritten.
* @param items Destination item array, capacity itemsMax.
* @param itemsMax Capacity of items.
* @return Error code indicating success or failure of the load/parse.
*/
errorret_t cutsceneLoadParse(
const char_t *path,
cutscene_t *scene,
cutsceneitem_t *items,
const size_t itemsMax
);
+24
View File
@@ -0,0 +1,24 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "cutsceneref.h"
#include "assert/assert.h"
void cutsceneRefReset(
cutsceneref_t *refs,
entity_t *interact,
entity_t *interacted
) {
assertNotNull(refs, "Refs cannot be null");
refs->entityInteract = interact;
refs->entityInteracted = interacted;
refs->entityLastCreated = NULL;
refs->entityLastRef = NULL;
refs->areaLastCreated = CUTSCENE_REF_AREA_LAST_CREATED;
refs->textMiniLastCreated = CUTSCENE_REF_TEXT_MINI_LAST_CREATED;
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
typedef struct entity_s entity_t;
#define CUTSCENE_REF_AREA_LAST_CREATED ((uint8_t)0xFF)
#define CUTSCENE_REF_TEXT_MINI_LAST_CREATED ((uint8_t)0xFA)
typedef struct {
entity_t *entityInteract;
entity_t *entityInteracted;
entity_t *entityLastCreated;
entity_t *entityLastRef;
uint8_t areaLastCreated;
uint8_t textMiniLastCreated;
} cutsceneref_t;
/**
* Resets refs to an empty state.
*
* @param refs Refs to reset.
* @param interact The entity that initiated the interaction, or NULL.
* @param interacted The entity being interacted with, or NULL.
*/
void cutsceneRefReset(
cutsceneref_t *refs,
entity_t *interact,
entity_t *interacted
);
+161 -130
View File
@@ -10,9 +10,8 @@
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
#include "assert/assert.h" #include "assert/assert.h"
#include "asset/asset.h"
#include "asset/loader/assetloader.h"
#include "ui/overlay/uifatalerror.h" #include "ui/overlay/uifatalerror.h"
#include "save/slot/saveslot.h"
cutscenesystem_t CUTSCENE_SYSTEM; cutscenesystem_t CUTSCENE_SYSTEM;
@@ -22,16 +21,18 @@ void cutsceneSystemInit() {
CUTSCENE_SYSTEM.loadedScene.itemsMax = CUTSCENE_LOADED_ITEMS_MAX; CUTSCENE_SYSTEM.loadedScene.itemsMax = CUTSCENE_LOADED_ITEMS_MAX;
} }
void cutsceneSystemUpdate() {
if(CUTSCENE_SYSTEM.scene == NULL) return;
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem();
if(cutsceneItemUpdate(item, &CUTSCENE_SYSTEM.data)) cutsceneSystemNext();
}
void cutsceneSystemDispose() { void cutsceneSystemDispose() {
CUTSCENE_SYSTEM.scene = NULL; CUTSCENE_SYSTEM.scene = NULL;
CUTSCENE_SYSTEM.currentItem = 0xFF; CUTSCENE_SYSTEM.currentItem = CUTSCENE_CURRENT_ITEM_NONE;
CUTSCENE_SYSTEM.pause = CUTSCENE_PAUSE_NONE; CUTSCENE_SYSTEM.pause = CUTSCENE_PAUSE_NONE;
CUTSCENE_SYSTEM.entityInteract = NULL; cutsceneRefReset(&CUTSCENE_SYSTEM.refs, NULL, NULL);
CUTSCENE_SYSTEM.entityInteracted = NULL;
CUTSCENE_SYSTEM.entityLastCreated = NULL;
CUTSCENE_SYSTEM.entityLastRef = NULL;
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_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;
CUTSCENE_SYSTEM.loadedFile[0] = '\0'; CUTSCENE_SYSTEM.loadedFile[0] = '\0';
@@ -46,16 +47,17 @@ void cutsceneSystemPrepare(
CUTSCENE_SYSTEM.scene = cutscene; CUTSCENE_SYSTEM.scene = cutscene;
CUTSCENE_SYSTEM.pause = cutscene->pause; CUTSCENE_SYSTEM.pause = cutscene->pause;
CUTSCENE_SYSTEM.entityInteract = interact; cutsceneRefReset(&CUTSCENE_SYSTEM.refs, interact, interacted);
CUTSCENE_SYSTEM.entityInteracted = interacted;
CUTSCENE_SYSTEM.entityLastCreated = NULL;
CUTSCENE_SYSTEM.entityLastRef = NULL;
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
CUTSCENE_SYSTEM.textCache[0] = '\0'; CUTSCENE_SYSTEM.textCache[0] = '\0';
CUTSCENE_SYSTEM.currentItem = 0xFF;// Set to 0xFF so Next wraps to 0.
CUTSCENE_SYSTEM.onComplete = NULL; CUTSCENE_SYSTEM.onComplete = NULL;
CUTSCENE_SYSTEM.loadedFile[0] = '\0';
// cutsceneNext will cause overflow to index 0 (intentional).
CUTSCENE_SYSTEM.currentItem = CUTSCENE_CURRENT_ITEM_NONE;
// Clear loaded file if cutscene not running from file.
if(cutscene != &CUTSCENE_SYSTEM.loadedScene) {
CUTSCENE_SYSTEM.loadedFile[0] = '\0';
}
} }
void cutsceneSystemStartCutscene(cutscene_t *cutscene) { void cutsceneSystemStartCutscene(cutscene_t *cutscene) {
@@ -73,7 +75,9 @@ void cutsceneSystemStartCutsceneWith(
"Cutscene itemCount exceeds itemsMax" "Cutscene itemCount exceeds itemsMax"
); );
// Prep cutscene, save it to the save slot, and advance, aka overflow to 0.
cutsceneSystemPrepare(cutscene, interact, interacted); cutsceneSystemPrepare(cutscene, interact, interacted);
saveSlotSetCurrentCutscene(CUTSCENE_SYSTEM.loadedFile);
cutsceneSystemNext(); cutsceneSystemNext();
} }
@@ -83,90 +87,99 @@ void cutsceneSystemStartCutsceneAndGoToMarker(
) { ) {
assertNotNull(marker, "Marker cannot be NULL"); assertNotNull(marker, "Marker cannot be NULL");
// Restarts the cutscene
cutsceneSystemPrepare(cutscene, NULL, NULL); cutsceneSystemPrepare(cutscene, NULL, NULL);
cutsceneGoTo(marker); cutsceneSystemGoTo(marker);
}
void cutsceneSystemInsertItemsNext(
const cutsceneitem_t *items,
const size_t itemCount
) {
assertNotNull(items, "Items cannot be NULL");
assertNotNull(
CUTSCENE_SYSTEM.scene,
"cutsceneSystemInsertItemsNext called with no cutscene running"
);
cutsceneAppendNext(
CUTSCENE_SYSTEM.scene, CUTSCENE_SYSTEM.currentItem, items, itemCount
);
}
void cutsceneSystemInsertItems(
const cutsceneitem_t *items,
const size_t itemCount
) {
cutsceneSystemInsertItemsNext(items, itemCount);
cutsceneSystemNext();
} }
void cutsceneSystemInsertCutscene(const cutscene_t *cutscene) { void cutsceneSystemInsertCutscene(const cutscene_t *cutscene) {
assertNotNull(cutscene, "Cutscene cannot be NULL"); assertNotNull(cutscene, "Cutscene cannot be NULL");
cutsceneSystemInsertItems(cutscene->items, cutscene->itemCount);
}
void cutsceneSystemClearAfter(const uint8_t index) {
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.scene, CUTSCENE_SYSTEM.scene,
"cutsceneSystemInsertCutscene called with no cutscene running" "cutsceneSystemClearAfter called with no cutscene running"
);
assertTrue(
index < CUTSCENE_SYSTEM.scene->itemCount,
"cutsceneSystemClearAfter index out of range"
); );
cutsceneAppendNext( CUTSCENE_SYSTEM.scene->itemCount = index + 1;
CUTSCENE_SYSTEM.scene, CUTSCENE_SYSTEM.currentItem,
cutscene->items, cutscene->itemCount
);
cutsceneSystemNext();
} }
void cutsceneSystemLoad(const char_t *file) { void cutsceneSystemLoad(const char_t *file) {
assertNotNull(file, "File cannot be NULL"); assertNotNull(file, "File cannot be NULL");
char_t path[ASSET_FILE_NAME_MAX]; // Take a copy of file, as it may be a part of the cutscene itself.
stringFormat(path, sizeof(path), "cutscenes/%s", file); char_t fileCopy[ASSET_FILE_NAME_MAX];
stringCopy(fileCopy, file, ASSET_FILE_NAME_MAX - 1);
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_JSON, NULL); // Load the cutscene asset, parse it, and start it.
errorret_t result = assetRequireLoaded(entry); errorret_t result = cutsceneLoadParse(
fileCopy, &CUTSCENE_SYSTEM.loadedScene, CUTSCENE_SYSTEM.loadedItems,
CUTSCENE_LOADED_ITEMS_MAX
);
if(errorIsNotOk(result)) { if(errorIsNotOk(result)) {
assetUnlockEntry(entry);
errorCatch(errorPrint(result)); errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL); uiFatalErrorOpen(NULL);
return; return;
} }
// Parse straight out of the entry's own doc while still locked - every // Store the loaded file so we can restart if needed.
// cutsceneitem_t field that could reference it owns its string data by stringCopy(CUTSCENE_SYSTEM.loadedFile, fileCopy, ASSET_FILE_NAME_MAX - 1);
// value (see cutscenecutsceneref_t/cutscenemarker_t's doc comments), so
// nothing needs to survive past this call and the entry can just be
// unlocked like any other asset once parsing finishes.
errorret_t parseResult = cutsceneParseDoc(
entry->data.json, &CUTSCENE_SYSTEM.loadedScene, CUTSCENE_SYSTEM.loadedItems,
CUTSCENE_LOADED_ITEMS_MAX
);
assetUnlockEntry(entry);
if(errorIsNotOk(parseResult)) {
errorCatch(errorPrint(parseResult));
uiFatalErrorOpen(NULL);
return;
}
cutsceneSystemStartCutscene(&CUTSCENE_SYSTEM.loadedScene); cutsceneSystemStartCutscene(&CUTSCENE_SYSTEM.loadedScene);
stringCopy(CUTSCENE_SYSTEM.loadedFile, file, ASSET_FILE_NAME_MAX - 1);
} }
void cutsceneRestart(void) { void cutsceneRestart(void) {
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.scene, "cutsceneRestart called with no cutscene running" CUTSCENE_SYSTEM.scene, "cutsceneRestart called with no cutscene running"
); );
assertTrue(
// A restart is the same logical run trying again (e.g. retrying a failed CUTSCENE_SYSTEM.scene == &CUTSCENE_SYSTEM.loadedScene,
// save-device check), not a fresh unrelated start, so it should not "cutsceneRestart called with a cutscene not loaded from file"
// silently drop a completion callback the caller already armed, or the );
// entities that triggered it - both cutsceneSystemStartCutsceneWith and assertTrue(
// cutsceneSystemLoad (via cutsceneSystemPrepare) forget them. CUTSCENE_SYSTEM.loadedFile[0] != '\0',
"cutsceneRestart called with no loaded file"
);
// Copy the refs and callbacks
cutscenecallback_t onComplete = CUTSCENE_SYSTEM.onComplete; cutscenecallback_t onComplete = CUTSCENE_SYSTEM.onComplete;
entity_t *entityInteract = CUTSCENE_SYSTEM.entityInteract; cutsceneref_t refs = CUTSCENE_SYSTEM.refs;
entity_t *entityInteracted = CUTSCENE_SYSTEM.entityInteracted;
if(CUTSCENE_SYSTEM.loadedFile[0] != '\0') { // Reload the file.
// Came from a cutscene asset - re-read+re-parse it from scratch char_t file[ASSET_FILE_NAME_MAX];
// rather than just rerunning whatever's still resident in stringCopy(file, CUTSCENE_SYSTEM.loadedFile, ASSET_FILE_NAME_MAX - 1);
// loadedScene/loadedItems, so a restart always reflects the file's cutsceneSystemLoad(file);
// current contents.
char_t file[ASSET_FILE_NAME_MAX];
stringCopy(file, CUTSCENE_SYSTEM.loadedFile, ASSET_FILE_NAME_MAX - 1);
cutsceneSystemLoad(file);
} else {
cutsceneSystemStartCutsceneWith(
CUTSCENE_SYSTEM.scene, entityInteract, entityInteracted
);
}
// Restore the refs and callbacks.
CUTSCENE_SYSTEM.onComplete = onComplete; CUTSCENE_SYSTEM.onComplete = onComplete;
CUTSCENE_SYSTEM.entityInteract = entityInteract; CUTSCENE_SYSTEM.refs = refs;
CUTSCENE_SYSTEM.entityInteracted = entityInteracted;
} }
void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete) { void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete) {
@@ -182,28 +195,28 @@ entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex) {
if(entityIndex == CUTSCENE_ENTITY_INTERACT) { if(entityIndex == CUTSCENE_ENTITY_INTERACT) {
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.entityInteract, CUTSCENE_SYSTEM.refs.entityInteract,
"CUTSCENE_ENTITY_INTERACT used but no interact entity is set" "CUTSCENE_ENTITY_INTERACT used but no interact entity is set"
); );
entity = CUTSCENE_SYSTEM.entityInteract; entity = CUTSCENE_SYSTEM.refs.entityInteract;
} else if(entityIndex == CUTSCENE_ENTITY_INTERACTED) { } else if(entityIndex == CUTSCENE_ENTITY_INTERACTED) {
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.entityInteracted, CUTSCENE_SYSTEM.refs.entityInteracted,
"CUTSCENE_ENTITY_INTERACTED used but no interacted entity is set" "CUTSCENE_ENTITY_INTERACTED used but no interacted entity is set"
); );
entity = CUTSCENE_SYSTEM.entityInteracted; entity = CUTSCENE_SYSTEM.refs.entityInteracted;
} else if(entityIndex == CUTSCENE_ENTITY_LAST_CREATED) { } else if(entityIndex == CUTSCENE_ENTITY_LAST_CREATED) {
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.entityLastCreated, CUTSCENE_SYSTEM.refs.entityLastCreated,
"CUTSCENE_ENTITY_LAST_CREATED used but no entity has been created" "CUTSCENE_ENTITY_LAST_CREATED used but no entity has been created"
); );
entity = CUTSCENE_SYSTEM.entityLastCreated; entity = CUTSCENE_SYSTEM.refs.entityLastCreated;
} else if(entityIndex == CUTSCENE_ENTITY_LAST_REF) { } else if(entityIndex == CUTSCENE_ENTITY_LAST_REF) {
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.entityLastRef, CUTSCENE_SYSTEM.refs.entityLastRef,
"CUTSCENE_ENTITY_LAST_REF used but no entity has been referenced" "CUTSCENE_ENTITY_LAST_REF used but no entity has been referenced"
); );
entity = CUTSCENE_SYSTEM.entityLastRef; entity = CUTSCENE_SYSTEM.refs.entityLastRef;
} else { } else {
assertTrue( assertTrue(
entityIndex < ENTITY_COUNT, entityIndex < ENTITY_COUNT,
@@ -212,29 +225,30 @@ entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex) {
entity = &ENTITIES[entityIndex]; entity = &ENTITIES[entityIndex];
} }
CUTSCENE_SYSTEM.entityLastRef = entity; CUTSCENE_SYSTEM.refs.entityLastRef = entity;
return entity; return entity;
} }
uint8_t cutsceneSystemGetAreaId(const uint8_t areaId) { uint8_t cutsceneSystemGetAreaId(const uint8_t areaId) {
if(areaId == CUTSCENE_AREA_LAST_CREATED) { if(areaId == CUTSCENE_REF_AREA_LAST_CREATED) {
assertTrue( assertTrue(
CUTSCENE_SYSTEM.areaLastCreated != CUTSCENE_AREA_LAST_CREATED, CUTSCENE_SYSTEM.refs.areaLastCreated != CUTSCENE_REF_AREA_LAST_CREATED,
"CUTSCENE_AREA_LAST_CREATED used but no map area has been created" "CUTSCENE_REF_AREA_LAST_CREATED used but no map area has been created"
); );
return CUTSCENE_SYSTEM.areaLastCreated; return CUTSCENE_SYSTEM.refs.areaLastCreated;
} }
return areaId; return areaId;
} }
uint8_t cutsceneSystemGetTextMiniId(const uint8_t index) { uint8_t cutsceneSystemGetTextMiniId(const uint8_t index) {
if(index == CUTSCENE_TEXT_MINI_LAST_CREATED) { if(index == CUTSCENE_REF_TEXT_MINI_LAST_CREATED) {
assertTrue( assertTrue(
CUTSCENE_SYSTEM.textMiniLastCreated != CUTSCENE_TEXT_MINI_LAST_CREATED, CUTSCENE_SYSTEM.refs.textMiniLastCreated !=
"CUTSCENE_TEXT_MINI_LAST_CREATED used but no mini textbox has been " CUTSCENE_REF_TEXT_MINI_LAST_CREATED,
"CUTSCENE_REF_TEXT_MINI_LAST_CREATED used but no mini textbox has been "
"shown" "shown"
); );
return CUTSCENE_SYSTEM.textMiniLastCreated; return CUTSCENE_SYSTEM.refs.textMiniLastCreated;
} }
return index; return index;
} }
@@ -254,74 +268,91 @@ void cutsceneSystemSetTextCache(const char_t *text) {
void cutsceneSystemNext() { void cutsceneSystemNext() {
if(CUTSCENE_SYSTEM.scene == NULL) return; if(CUTSCENE_SYSTEM.scene == NULL) return;
CUTSCENE_SYSTEM.currentItem++; // Pop the just-finished item off the front.
if(CUTSCENE_SYSTEM.currentItem == CUTSCENE_CURRENT_ITEM_NONE) {
CUTSCENE_SYSTEM.currentItem = 0;
} else {
cutscene_t *scene = CUTSCENE_SYSTEM.scene;
const size_t tailCount = (size_t)scene->itemCount - 1;
if(tailCount > 0) {
memoryMove(
&scene->items[0], &scene->items[1], tailCount * sizeof(cutsceneitem_t)
);
}
scene->itemCount--;
}
// End of the cutscene? Note that a CUTSCENE_ITEM_TYPE_INSERT item's // End of the cutscene?
// spliced-in items are physically part of this same array (see if(CUTSCENE_SYSTEM.scene->itemCount == 0) {
// cutsceneSystemInsertCutscene), so there's no separate "parent scene"
// to fall back into here - itemCount already accounts for them.
if(
CUTSCENE_SYSTEM.currentItem >= CUTSCENE_SYSTEM.scene->itemCount
) {
// Saved and cleared before firing so a callback that immediately
// starts another cutscene (or sets its own onComplete) isn't clobbered
// by this function's own cleanup running after it - same reentrancy
// hazard as uiFocusPop, see src/dusk/ui/focus/uifocus.c.
cutscenecallback_t onComplete = CUTSCENE_SYSTEM.onComplete; cutscenecallback_t onComplete = CUTSCENE_SYSTEM.onComplete;
CUTSCENE_SYSTEM.scene = NULL; CUTSCENE_SYSTEM.scene = NULL;
CUTSCENE_SYSTEM.currentItem = 0xFF;
CUTSCENE_SYSTEM.pause = CUTSCENE_PAUSE_NONE; CUTSCENE_SYSTEM.pause = CUTSCENE_PAUSE_NONE;
CUTSCENE_SYSTEM.entityInteract = NULL;
CUTSCENE_SYSTEM.entityInteracted = NULL;
CUTSCENE_SYSTEM.entityLastCreated = NULL;
CUTSCENE_SYSTEM.entityLastRef = NULL;
CUTSCENE_SYSTEM.areaLastCreated = CUTSCENE_AREA_LAST_CREATED;
CUTSCENE_SYSTEM.textMiniLastCreated = CUTSCENE_TEXT_MINI_LAST_CREATED;
CUTSCENE_SYSTEM.textCache[0] = '\0';
CUTSCENE_SYSTEM.onComplete = NULL;
if(onComplete != NULL) onComplete(NULL); if(onComplete != NULL) onComplete(NULL);
return; return;
} }
// Start item. // Start next (now current) item
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem(); const cutsceneitem_t *item = cutsceneSystemGetCurrentItem();
memset(&CUTSCENE_SYSTEM.data, 0, sizeof(CUTSCENE_SYSTEM.data)); memset(&CUTSCENE_SYSTEM.data, 0, sizeof(CUTSCENE_SYSTEM.data));
cutsceneItemStart(item, &CUTSCENE_SYSTEM.data); cutsceneItemStart(item, &CUTSCENE_SYSTEM.data);
} }
void cutsceneGoTo(const char_t *name) { void cutsceneSystemGoTo(const char_t *name) {
assertNotNull(name, "Name cannot be NULL"); assertNotNull(name, "Name cannot be NULL");
assertNotNull( assertNotNull(
CUTSCENE_SYSTEM.scene, "cutsceneGoTo called with no cutscene running" CUTSCENE_SYSTEM.scene, "cutsceneSystemGoTo called with no cutscene running"
);
assertTrue(
CUTSCENE_SYSTEM.scene == &CUTSCENE_SYSTEM.loadedScene,
"cutsceneSystemGoTo requires the running cutscene file reference (1)"
);
assertTrue(
CUTSCENE_SYSTEM.loadedFile[0] != '\0',
"cutsceneSystemGoTo requires the running cutscene file reference (2)"
); );
for(uint8_t i = 0; i < CUTSCENE_SYSTEM.scene->itemCount; i++) { cutscene_t freshScene = { .items = CUTSCENE_SYSTEM.gotoScratchItems };
const cutsceneitem_t *item = &CUTSCENE_SYSTEM.scene->items[i]; errorret_t result = cutsceneLoadParse(
if( CUTSCENE_SYSTEM.loadedFile, &freshScene, CUTSCENE_SYSTEM.gotoScratchItems,
item->type == CUTSCENE_ITEM_TYPE_MARKER && CUTSCENE_LOADED_ITEMS_MAX
stringEquals(item->marker.name, name) );
) { if(errorIsNotOk(result)) {
CUTSCENE_SYSTEM.currentItem = i; errorCatch(errorPrint(result));
memoryZero(&CUTSCENE_SYSTEM.data, sizeof(CUTSCENE_SYSTEM.data)); uiFatalErrorOpen(NULL);
cutsceneItemStart(item, &CUTSCENE_SYSTEM.data); return;
return;
}
} }
assertTrue(false, "cutsceneGoTo: no marker found with that name"); // Search for the marker with the given name...
} for(uint8_t i = 0; i < freshScene.itemCount; i++) {
const cutsceneitem_t *item = &freshScene.items[i];
if(
item->type != CUTSCENE_ITEM_TYPE_MARKER ||
!stringEquals(item->marker.name, name)
) continue;
void cutsceneSystemUpdate() { // Found, so splice the cutscene at that point and start it, the remaining
if(CUTSCENE_SYSTEM.scene == NULL) return; // items being the rest of the cutscene after the marker.
const uint8_t remaining = freshScene.itemCount - i;
memoryCopy(
CUTSCENE_SYSTEM.loadedItems, &freshScene.items[i],
remaining * sizeof(cutsceneitem_t)
);
CUTSCENE_SYSTEM.loadedScene.itemCount = remaining;
CUTSCENE_SYSTEM.currentItem = 0;
const cutsceneitem_t *item = cutsceneSystemGetCurrentItem(); memoryZero(&CUTSCENE_SYSTEM.data, sizeof(CUTSCENE_SYSTEM.data));
if(cutsceneItemUpdate(item, &CUTSCENE_SYSTEM.data)) cutsceneSystemNext(); cutsceneItemStart(
&CUTSCENE_SYSTEM.loadedItems[0], &CUTSCENE_SYSTEM.data
);
return;
}
assertTrue(false, "cutsceneSystemGoTo: no marker found with that name");
} }
const cutsceneitem_t * cutsceneSystemGetCurrentItem() { const cutsceneitem_t * cutsceneSystemGetCurrentItem() {
if(CUTSCENE_SYSTEM.scene == NULL) return NULL; if(CUTSCENE_SYSTEM.scene == NULL) return NULL;
return &CUTSCENE_SYSTEM.scene->items[0];
return &CUTSCENE_SYSTEM.scene->items[CUTSCENE_SYSTEM.currentItem];
} }
+76 -122
View File
@@ -7,41 +7,27 @@
#pragma once #pragma once
#include "cutscene.h" #include "cutscene.h"
#include "cutsceneref.h"
typedef struct entity_s entity_t; #define CUTSCENE_ENTITY_INTERACT ((uint8_t)0xFE)
#define CUTSCENE_ENTITY_INTERACTED ((uint8_t)0xFD)
// Sentinels accepted in place of a literal index/ID by the cutsceneSystemGet* #define CUTSCENE_ENTITY_LAST_CREATED ((uint8_t)0xFC)
// resolvers below. #define CUTSCENE_ENTITY_LAST_REF ((uint8_t)0xFB)
#define CUTSCENE_ENTITY_INTERACT ((uint8_t)0xFE) #define CUTSCENE_CURRENT_ITEM_NONE ((uint8_t)0xFF)
#define CUTSCENE_ENTITY_INTERACTED ((uint8_t)0xFD)
#define CUTSCENE_ENTITY_LAST_CREATED ((uint8_t)0xFC)
#define CUTSCENE_ENTITY_LAST_REF ((uint8_t)0xFB)
#define CUTSCENE_AREA_LAST_CREATED ((uint8_t)0xFF)
#define CUTSCENE_TEXT_MINI_LAST_CREATED ((uint8_t)0xFA)
#define CUTSCENE_TEXT_CACHE_MAX 64 #define CUTSCENE_TEXT_CACHE_MAX 64
#define CUTSCENE_LOADED_ITEMS_MAX 128 #define CUTSCENE_LOADED_ITEMS_MAX 128
// Scratch capacity for resolving a JSON-authored CUTSCENE_ITEM_TYPE_INSERT
// target - see cutsceneSystemInsertCutscene. Sized small deliberately -
// an inserted snippet is meant to be a short splice, not a full cutscene.
#define CUTSCENE_INSERT_ITEMS_MAX 16 #define CUTSCENE_INSERT_ITEMS_MAX 16
typedef struct { typedef struct {
cutscene_t *scene; cutscene_t *scene;
uint8_t currentItem; uint8_t currentItem;
cutscenepause_t pause; cutscenepause_t pause;
entity_t *entityInteract;
entity_t *entityInteracted;
entity_t *entityLastCreated;
entity_t *entityLastRef;
uint8_t areaLastCreated;
uint8_t textMiniLastCreated;
// Free-form text cache, e.g. holding whatever was last typed via a cutsceneref_t refs;
// CUTSCENE_ITEM_TYPE_KEYBOARD item - see cutsceneSystemGetTextCache/
// cutsceneSystemSetTextCache. Not tied to any one item type; any item // Free-form text cache for the running cutscene - see
// may read or write it. // cutsceneSystemGetTextCache/cutsceneSystemSetTextCache.
char_t textCache[CUTSCENE_TEXT_CACHE_MAX]; char_t textCache[CUTSCENE_TEXT_CACHE_MAX];
// Runtime data for the current item. // Runtime data for the current item.
@@ -50,18 +36,13 @@ typedef struct {
// See cutsceneSystemSetOnComplete. // See cutsceneSystemSetOnComplete.
cutscenecallback_t onComplete; cutscenecallback_t onComplete;
// Cache and storage used for the dynamically loaded cutscenes.
cutsceneitem_t loadedItems[CUTSCENE_LOADED_ITEMS_MAX]; cutsceneitem_t loadedItems[CUTSCENE_LOADED_ITEMS_MAX];
cutscene_t loadedScene; cutscene_t loadedScene;
// Filename last passed to cutsceneSystemLoad, e.g. "main_menu.jsonc" -
// set right after it starts loadedScene running. Empty ("") for a
// cutscene started directly via cutsceneSystemStartCutscene* instead
// (a C-authored one, or loadedScene reused without going through
// cutsceneSystemLoad again), and cleared by cutsceneSystemPrepare on
// every fresh start so it never lingers from a previous file load. See
// cutsceneRestart, which re-loads (rather than just rerunning) whatever
// this names.
char_t loadedFile[ASSET_FILE_NAME_MAX]; char_t loadedFile[ASSET_FILE_NAME_MAX];
// Cutscene items scratch, mostly used for CUTSCENE_INSERT items.
cutsceneitem_t gotoScratchItems[CUTSCENE_LOADED_ITEMS_MAX];
} cutscenesystem_t; } cutscenesystem_t;
extern cutscenesystem_t CUTSCENE_SYSTEM; extern cutscenesystem_t CUTSCENE_SYSTEM;
@@ -78,11 +59,7 @@ void cutsceneSystemDispose();
/** /**
* Resets CUTSCENE_SYSTEM to run cutscene from its first item, binding * Resets CUTSCENE_SYSTEM to run cutscene from its first item, binding
* interact/interacted entities - shared setup used by * interact/interacted entities. Does not itself advance to the first item.
* cutsceneSystemStartCutsceneWith and
* cutsceneSystemStartCutsceneAndGoToMarker. Does not itself advance to the
* first item; callers do that afterward (via cutsceneSystemNext or
* cutsceneGoTo).
* *
* @param cutscene Pointer to the cutscene to prepare. * @param cutscene Pointer to the cutscene to prepare.
* @param interact The entity that initiated the interaction (player), or * @param interact The entity that initiated the interaction (player), or
@@ -117,13 +94,11 @@ void cutsceneSystemStartCutsceneWith(
/** /**
* Starts a cutscene with no bound entities, jumping straight to the * Starts a cutscene with no bound entities, jumping straight to the
* CUTSCENE_MARKER item with the given name instead of running from the * marker with the given name instead of running from the first item.
* first item - as if cutsceneGoTo(marker) had been called immediately * Asserts if no marker with that name exists.
* after cutsceneSystemStartCutscene. Asserts if no marker with that
* name exists in the cutscene.
* *
* @param cutscene Pointer to the cutscene to start. * @param cutscene Pointer to the cutscene to start.
* @param marker Marker name to jump to, matched with stringEquals. * @param marker Marker name to jump to.
*/ */
void cutsceneSystemStartCutsceneAndGoToMarker( void cutsceneSystemStartCutsceneAndGoToMarker(
cutscene_t *cutscene, cutscene_t *cutscene,
@@ -131,87 +106,76 @@ void cutsceneSystemStartCutsceneAndGoToMarker(
); );
/** /**
* Splices cutscene's items into the running cutscene (CUTSCENE_SYSTEM.scene) * Splices items into the running cutscene so that items[0] becomes the
* in place, right after the currently-executing item, via cutsceneAppendNext * very next item, without otherwise disturbing the currently-running
* - unlike cutsceneSystemStartCutscene (a one-way jump that replaces the * item's progress.
* running cutscene outright), the inserted items simply become part of the *
* running scene's own item array, so there's nothing separate to "return" * @param items Items to splice in.
* to once they finish - whatever already followed the CUTSCENE_ITEM_TYPE_ * @param itemCount Number of items in items.
* INSERT item continues normally, now shifted further down the same array. */
* Then immediately advances into the first inserted item (see void cutsceneSystemInsertItemsNext(
* cutsceneSystemNext), so the splice takes effect within this same call. const cutsceneitem_t *items,
* Deliberately does not touch pause flags, interact entities, "last const size_t itemCount
* created" state, or the text cache - those all keep whatever the );
* outer cutscene set, since this is meant to feel like pasting cutscene's
* items in place rather than starting an independent cutscene. Because of /**
* this, cutscene's own .pause is ignored. Asserts if no cutscene is * Splices items into the running cutscene right after the current item
* currently running, or if the running scene's own itemsMax has no room * (see cutsceneSystemInsertItemsNext), then immediately advances into the
* left for cutscene's items (see cutscene_t.itemsMax's doc comment - a * first spliced item.
* cutscene that expects to have items inserted into it at runtime needs to *
* be declared with spare capacity up front). * @param items Items to splice in.
* @param itemCount Number of items in items.
*/
void cutsceneSystemInsertItems(
const cutsceneitem_t *items,
const size_t itemCount
);
/**
* Splices cutscene's items into the running cutscene.
* *
* @param cutscene The cutscene whose items to splice in. * @param cutscene The cutscene whose items to splice in.
*/ */
void cutsceneSystemInsertCutscene(const cutscene_t *cutscene); void cutsceneSystemInsertCutscene(const cutscene_t *cutscene);
/** /**
* Loads and immediately starts a cutscene asset by file name, e.g. * Discards every item queued after index (e.g. index 0 keeps only the
* cutsceneSystemLoad("main_menu.jsonc") loads and starts * currently-running item and drops everything spliced in behind it),
* assets/cutscenes/main_menu.jsonc, parsing it into * without disturbing index's own progress - e.g. so a callback that
* CUTSCENE_SYSTEM.loadedScene/loadedItems. Locks the underlying JSON * decides the rest of a batch-spliced sequence is now moot (a battle
* asset entry just long enough to parse it, then unlocks it like any * ending mid-round, with other fighters' still-queued move cutscenes and
* other asset - every cutsceneitem_t field that could reference the * the round's trailing state transition left behind) can drop it before
* parsed doc owns its string data by value (see cutscenecutsceneref_t/ * splicing in its own follow-up items, instead of leaving it to run
* cutscenemarker_t's doc comments), so nothing needs to keep it resident * afterward against torn-down state.
* past this call, and a later load of the same file is a normal cache
* hit (or a fresh re-read, if the entry was reaped meanwhile) rather than
* something this function has to force either way. Opens the fatal error
* overlay (see uiFatalErrorOpen) instead of starting anything if the
* asset fails to load. Records file into CUTSCENE_SYSTEM.loadedFile once
* it starts running.
* *
* @param file Cutscene file name (with .jsonc extension), relative to * @param index Index to keep - everything after it is discarded. Must be
* assets/cutscenes/. * < the running cutscene's current item count.
*/
void cutsceneSystemClearAfter(const uint8_t index);
/**
* Loads and immediately starts a cutscene asset by file name.
*
* @param file Cutscene file name.
*/ */
void cutsceneSystemLoad(const char_t *file); void cutsceneSystemLoad(const char_t *file);
/** /**
* Restarts the currently running cutscene from its first item, * Restarts the currently running cutscene. Will perform a load if the cutscene
* preserving whatever interact/interacted entities triggered it and * was initially from a file.
* whatever completion callback was armed. If CUTSCENE_SYSTEM.loadedFile
* is set (i.e. the running cutscene came from cutsceneSystemLoad), this
* re-invokes cutsceneSystemLoad on that same filename rather than just
* rerunning whatever's still resident in loadedScene/loadedItems -
* otherwise it's just cutsceneSystemStartCutsceneWith on the same
* cutscene_t. Asserts if no cutscene is running.
*/ */
void cutsceneRestart(void); void cutsceneRestart(void);
/** /**
* Sets a native callback to fire once when the currently running cutscene * Sets a native callback to fire once when the currently running cutscene
* finishes by running off the end of its item list. A fresh * finishes.
* cutsceneSystemStartCutscene* call clears any previously set callback, so
* call this again after starting a new cutscene to arm it - but
* cutsceneRestart() preserves whatever was armed, since a restart (e.g.
* retrying a failed check) is the same logical run trying again, not a new
* one. Invoked with NULL, same as CUTSCENE_CALLBACK.
* *
* Exists so a runtime-loaded cutscene file (which can't store a native * @param onComplete Callback to fire on completion.
* function pointer) can still hand off to native code once it's done,
* without needing a whole name->function registry: the file just ends
* normally, and whoever started it supplies what happens next.
*
* @param onComplete Callback to fire on natural completion. May be NULL
* to clear a previously set one.
*/ */
void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete); void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete);
/** /**
* Resolves a raw entity index (or sentinel) to an entity pointer. * Resolves a raw entity index (or sentinel) to an entity pointer.
* Handles CUTSCENE_ENTITY_INTERACT, CUTSCENE_ENTITY_INTERACTED,
* CUTSCENE_ENTITY_LAST_CREATED and CUTSCENE_ENTITY_LAST_REF.
* Updates CUTSCENE_SYSTEM.entityLastRef to the resolved entity.
* Asserts the resolved entity is within bounds.
* *
* @param entityIndex Raw entity index or sentinel value. * @param entityIndex Raw entity index or sentinel value.
* @returns Pointer to the resolved entity. * @returns Pointer to the resolved entity.
@@ -219,7 +183,7 @@ void cutsceneSystemSetOnComplete(cutscenecallback_t onComplete);
entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex); entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
/** /**
* Resolves a raw map area ID (or CUTSCENE_AREA_LAST_CREATED sentinel) to * Resolves a raw map area ID (or CUTSCENE_REF_AREA_LAST_CREATED sentinel) to
* a concrete map area ID. * a concrete map area ID.
* *
* @param areaId Raw map area ID or sentinel value. * @param areaId Raw map area ID or sentinel value.
@@ -228,7 +192,7 @@ entity_t * cutsceneSystemGetEntity(const uint8_t entityIndex);
uint8_t cutsceneSystemGetAreaId(const uint8_t areaId); uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
/** /**
* Resolves a raw mini textbox slot index (or CUTSCENE_TEXT_MINI_LAST_CREATED * Resolves a raw mini textbox slot index (or CUTSCENE_REF_TEXT_MINI_LAST_CREATED
* sentinel) to a concrete UI_TEXTBOX_MINI_LIST slot index. * sentinel) to a concrete UI_TEXTBOX_MINI_LIST slot index.
* *
* @param index Raw slot index or sentinel value. * @param index Raw slot index or sentinel value.
@@ -237,23 +201,17 @@ uint8_t cutsceneSystemGetAreaId(const uint8_t areaId);
uint8_t cutsceneSystemGetTextMiniId(const uint8_t index); uint8_t cutsceneSystemGetTextMiniId(const uint8_t index);
/** /**
* Returns CUTSCENE_SYSTEM.textCache - whatever was last written there via * Returns the running cutscene's cached text - see
* cutsceneSystemSetTextCache (e.g. by a CUTSCENE_ITEM_TYPE_KEYBOARD item * cutsceneSystemSetTextCache. Empty ("") if nothing has been cached yet.
* once its keyboard closes). Empty ("") if nothing has been cached yet
* for the running cutscene.
* *
* @returns The cached text. * @returns The cached text.
*/ */
const char_t * cutsceneSystemGetTextCache(void); const char_t * cutsceneSystemGetTextCache(void);
/** /**
* Overwrites CUTSCENE_SYSTEM.textCache with a copy of text. Any item may * Overwrites the running cutscene's cached text.
* call this - it isn't tied to any one item type - so later items can
* read back whatever the caller wants to pass along, up to
* CUTSCENE_TEXT_CACHE_MAX - 1 characters.
* *
* @param text The text to cache; copied internally, safe to be * @param text The text to cache; copied internally.
* transient. Must not exceed CUTSCENE_TEXT_CACHE_MAX - 1 characters.
*/ */
void cutsceneSystemSetTextCache(const char_t *text); void cutsceneSystemSetTextCache(const char_t *text);
@@ -263,16 +221,12 @@ void cutsceneSystemSetTextCache(const char_t *text);
void cutsceneSystemNext(); void cutsceneSystemNext();
/** /**
* Jumps the running cutscene directly to the CUTSCENE_MARKER item with * Jumps to a cutscene marker directly. If the cutscene is a loaded cutscene,
* the given name and starts it immediately, as if cutsceneSystemNext() * this will result in it being reloaded (due to unshift nature of cutscenes).
* had advanced straight to it. Intended to be called from within
* another item's start/update (e.g. a CUTSCENE_CALLBACK) to implement
* flow control. Asserts if no cutscene is running or no marker with
* that name exists in it.
* *
* @param name Marker name to search for, matched with stringEquals. * @param name Marker name to search for.
*/ */
void cutsceneGoTo(const char_t *name); void cutsceneSystemGoTo(const char_t *name);
/** /**
* Update the cutscene system for one frame. * Update the cutscene system for one frame.
@@ -20,3 +20,5 @@ add_subdirectory(battle)
add_subdirectory(save) add_subdirectory(save)
add_subdirectory(audio) add_subdirectory(audio)
add_subdirectory(json) add_subdirectory(json)
add_subdirectory(story)
add_subdirectory(party)
@@ -5,8 +5,10 @@
target_sources(${DUSK_LIBRARY_TARGET_NAME} target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC PUBLIC
cutscenestartbattle.c cutscenebattlestart.c
cutscenebattlewaitstate.c cutscenebattlesetstate.c
cutscenebattleforceaction.c cutscenebattlewaitselection.c
cutsceneregularbattle.c cutscenebattlepostmove.c
cutscenebattlefighterdamage.c
cutscenebattlefighterheal.c
) )
@@ -0,0 +1,68 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/battle.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
#include "assert/assert.h"
#include "util/string.h"
#define CUTSCENE_BATTLE_FIGHTER_REF_MAX 16
void cutsceneBattleFighterDamageStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
const cutscenebattlefighterdamage_t *damage = &item->battleFighterDamage;
assertTrue(
damage->fighterIndex < BATTLE_FIGHTER_POS_COUNT,
"fighterIndex sentinel was never resolved"
);
battlefighter_t *fighter = BATTLE.fighters[damage->fighterIndex];
assertNotNull(fighter, "Fighter cannot be NULL");
battleFighterDamage(fighter, damage->amount);
}
bool_t cutsceneBattleFighterDamageUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneBattleFighterDamageLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
char_t fighterRef[CUTSCENE_BATTLE_FIGHTER_REF_MAX];
if(!cutsceneJsonCopyString(
itemObj, "fighter", NULL, fighterRef, CUTSCENE_BATTLE_FIGHTER_REF_MAX
)) {
errorThrow("Cutscene item (BATTLE_FIGHTER_DAMAGE): missing 'fighter'");
}
if(stringEquals(fighterRef, "target")) {
item->battleFighterDamage.fighterIndex = BATTLE_FIGHTER_POS_TARGET;
} else if(stringEquals(fighterRef, "user")) {
item->battleFighterDamage.fighterIndex = BATTLE_FIGHTER_POS_USER;
} else {
errorThrow(
"Cutscene item (BATTLE_FIGHTER_DAMAGE): 'fighter' must be "
"'target' or 'user'"
);
}
const int32_t amount = cutsceneJsonGetInt(itemObj, "amount", -1);
if(amount < 0 || amount > UINT16_MAX) {
errorThrow(
"Cutscene item (BATTLE_FIGHTER_DAMAGE): invalid/missing 'amount'"
);
}
item->battleFighterDamage.amount = (uint16_t)amount;
errorOk();
}
@@ -0,0 +1,55 @@
/**
* 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"
#include "rpg/battle/fighter/battlefighterpos.h"
typedef struct {
// Index into BATTLE.fighters of the fighter to damage, or one of
// BATTLE_FIGHTER_POS_TARGET/BATTLE_FIGHTER_POS_USER, resolved against
// the currently-executing action by battleStateExecutingInit before
// this item ever runs.
battlefighterpos_t fighterIndex;
uint16_t amount;
} cutscenebattlefighterdamage_t;
/**
* Starts a BATTLE_FIGHTER_DAMAGE item, applying the configured damage to
* BATTLE.fighters[fighterIndex] immediately.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneBattleFighterDamageStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a BATTLE_FIGHTER_DAMAGE item (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneBattleFighterDamageUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses a BATTLE_FIGHTER_DAMAGE cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneBattleFighterDamageLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
);
@@ -0,0 +1,68 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/battle.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
#include "assert/assert.h"
#include "util/string.h"
#define CUTSCENE_BATTLE_FIGHTER_REF_MAX 16
void cutsceneBattleFighterHealStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
const cutscenebattlefighterheal_t *heal = &item->battleFighterHeal;
assertTrue(
heal->fighterIndex < BATTLE_FIGHTER_POS_COUNT,
"fighterIndex sentinel was never resolved"
);
battlefighter_t *fighter = BATTLE.fighters[heal->fighterIndex];
assertNotNull(fighter, "Fighter cannot be NULL");
battleFighterHeal(fighter, heal->amount);
}
bool_t cutsceneBattleFighterHealUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneBattleFighterHealLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
char_t fighterRef[CUTSCENE_BATTLE_FIGHTER_REF_MAX];
if(!cutsceneJsonCopyString(
itemObj, "fighter", NULL, fighterRef, CUTSCENE_BATTLE_FIGHTER_REF_MAX
)) {
errorThrow("Cutscene item (BATTLE_FIGHTER_HEAL): missing 'fighter'");
}
if(stringEquals(fighterRef, "target")) {
item->battleFighterHeal.fighterIndex = BATTLE_FIGHTER_POS_TARGET;
} else if(stringEquals(fighterRef, "user")) {
item->battleFighterHeal.fighterIndex = BATTLE_FIGHTER_POS_USER;
} else {
errorThrow(
"Cutscene item (BATTLE_FIGHTER_HEAL): 'fighter' must be "
"'target' or 'user'"
);
}
const int32_t amount = cutsceneJsonGetInt(itemObj, "amount", -1);
if(amount < 0 || amount > UINT16_MAX) {
errorThrow(
"Cutscene item (BATTLE_FIGHTER_HEAL): invalid/missing 'amount'"
);
}
item->battleFighterHeal.amount = (uint16_t)amount;
errorOk();
}
@@ -0,0 +1,55 @@
/**
* 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"
#include "rpg/battle/fighter/battlefighterpos.h"
typedef struct {
// Index into BATTLE.fighters of the fighter to heal, or one of
// BATTLE_FIGHTER_POS_TARGET/BATTLE_FIGHTER_POS_USER, resolved against
// the currently-executing action by battleStateExecutingInit before
// this item ever runs.
battlefighterpos_t fighterIndex;
uint16_t amount;
} cutscenebattlefighterheal_t;
/**
* Starts a BATTLE_FIGHTER_HEAL item, applying the configured heal to
* BATTLE.fighters[fighterIndex] immediately.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneBattleFighterHealStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a BATTLE_FIGHTER_HEAL item (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneBattleFighterHealUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses a BATTLE_FIGHTER_HEAL cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneBattleFighterHealLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
);
@@ -1,37 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
void cutsceneBattleForceActionStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
battleQueueAction(
item->battleForceAction.fighterIndex, BATTLE_ACTION_ATTACK,
item->battleForceAction.targetIndex
);
}
bool_t cutsceneBattleForceActionUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneBattleForceActionLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
item->battleForceAction.fighterIndex =
(uint8_t)yyjson_get_int(yyjson_obj_get(itemObj, "fighterIndex"));
item->battleForceAction.targetIndex =
(uint8_t)yyjson_get_int(yyjson_obj_get(itemObj, "targetIndex"));
errorOk();
}
@@ -0,0 +1,60 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/battle.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "console/console.h"
void cutsceneBattlePostMoveStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
consolePrint("BATTLE_POST_MOVE\n");
// Once a result has already been decided (e.g. the player fled), there
// is nothing left to check.
if(BATTLE.result != BATTLE_RESULT_NONE) return;
bool_t allyAlive = false;
bool_t enemyAlive = false;
for(uint8_t i = 0; i < BATTLE_FIGHTER_POS_COUNT; i++) {
battlefighter_t *fighter = BATTLE.fighters[i];
if(fighter == NULL) continue;
if(!battleFighterIsAlive(fighter)) continue;
if(fighter->team == BATTLE_FIGHTER_TEAM_ALLY) allyAlive = true;
else enemyAlive = true;
}
if(allyAlive && enemyAlive) return;
BATTLE.result = allyAlive ? BATTLE_RESULT_WIN : BATTLE_RESULT_LOSS;
// Drop the rest of this round's already-spliced items (other fighters'
// still-pending move cutscenes, the trailing BATTLE_SET_STATE(PRE_ROUND) -
// see battleStateExecutingInit) - the battle is over, so none of that
// should run against the WON/LOST/ENDING transition about to replace it.
cutsceneSystemClearAfter(CUTSCENE_SYSTEM.currentItem);
const cutsceneitem_t items[] = {
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = {
.state = allyAlive ? BATTLE_STATE_WON : BATTLE_STATE_LOST
}
}
};
cutsceneSystemInsertItemsNext(items, sizeof(items) / sizeof(cutsceneitem_t));
}
bool_t cutsceneBattlePostMoveUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
@@ -0,0 +1,37 @@
/**
* 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"
/**
* Starts a BATTLE_POST_MOVE item. Runs after each queued move's cutscene
* finishes: checks whether every ally or every enemy fighter has been
* knocked out and, if so, sets BATTLE.result and splices in a
* BATTLE_SET_STATE to BATTLE_STATE_WON/LOST. No-ops the health check if
* BATTLE.result is already set (e.g. the player fled). Not
* JSON-authorable -- constructed dynamically by battleStateExecutingInit.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneBattlePostMoveStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a BATTLE_POST_MOVE item (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneBattlePostMoveUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/battle.h"
#include "rpg/cutscene/item/json/cutscenejsonbattlestate.h"
#include "assert/assert.h"
void cutsceneBattleSetStateStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
assertNotNull(item, "item cannot be NULL");
battleSetState(item->battleSetState.state);
}
bool_t cutsceneBattleSetStateUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneBattleSetStateLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
battlestate_t state;
if(!cutsceneJsonLookupBattleState(
yyjson_get_str(yyjson_obj_get(itemObj, "state")), &state
)) {
errorThrow("Cutscene item (BATTLE_SET_STATE): invalid 'state'");
}
item->battleSetState.state = state;
errorOk();
}
@@ -6,47 +6,45 @@
*/ */
#pragma once #pragma once
#include "rpg/battle/battle.h" #include "rpg/battle/state/battlestate.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
typedef struct { typedef struct {
uint8_t fighterIndex; battlestate_t state;
uint8_t targetIndex; } cutscenebattlesetstate_t;
} cutscenebattleforceaction_t;
/** /**
* Starts a battle force-action step: immediately queues an attack for the * Starts a BATTLE_SET_STATE item, transitioning the battle to the
* given fighter against the given target, bypassing normal player/AI * configured state immediately.
* selection for that fighter this round.
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
*/ */
void cutsceneBattleForceActionStart( void cutsceneBattleSetStateStart(
const cutsceneitem_t *item, const cutsceneitem_t *item,
cutsceneitemdata_t *data cutsceneitemdata_t *data
); );
/** /**
* Updates a battle force-action step (always completes immediately). * Updates a BATTLE_SET_STATE item (always completes immediately).
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
* @returns true always. * @returns true always.
*/ */
bool_t cutsceneBattleForceActionUpdate( bool_t cutsceneBattleSetStateUpdate(
const cutsceneitem_t *item, const cutsceneitem_t *item,
cutsceneitemdata_t *data cutsceneitemdata_t *data
); );
/** /**
* Parses a BATTLE_FORCE_ACTION cutscene item's JSON fields into item. * Parses a BATTLE_SET_STATE cutscene item's JSON fields into item.
* *
* @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.
* @return Error code indicating success or failure of the parse. * @return Error code indicating success or failure of the parse.
*/ */
errorret_t cutsceneBattleForceActionLoad( errorret_t cutsceneBattleSetStateLoad(
yyjson_val *itemObj, yyjson_val *itemObj,
cutsceneitem_t *item cutsceneitem_t *item
); );
@@ -0,0 +1,95 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/battle.h"
#include "rpg/battle/party.h"
#include "assert/assert.h"
#include "util/memory.h"
battlefighter_t CUTSCENE_BATTLE_START_ENEMY_POOL[
CUTSCENE_BATTLE_START_ENEMY_COUNT_MAX
];
void cutsceneBattleStartStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
assertNotNull(item, "item cannot be NULL");
const cutscenebattlestart_t *config = &item->battleStart;
assertTrue(
config->enemyCount <= CUTSCENE_BATTLE_START_ENEMY_COUNT_MAX,
"enemyCount out of bounds"
);
battlefighter_t *fighters[BATTLE_FIGHTER_POS_COUNT] = { 0 };
memoryZero(
CUTSCENE_BATTLE_START_ENEMY_POOL,
sizeof(CUTSCENE_BATTLE_START_ENEMY_POOL)
);
for(uint8_t i = 0; i < config->enemyCount; i++) {
battlefighter_t *enemy = &CUTSCENE_BATTLE_START_ENEMY_POOL[i];
*enemy = config->enemies[i].fighter;
fighters[i] = enemy;
}
for(uint8_t i = 0; i < PARTY_ACTIVE_SIZE_MAX; i++) {
battlefighter_t *member = partyGetOrderMember(i);
if(member == NULL) continue;
fighters[BATTLE_FIGHTER_POS_4 + i] = member;
}
battleStart(fighters);
}
bool_t cutsceneBattleStartUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutsceneBattleStartLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
yyjson_val *enemies = yyjson_obj_get(itemObj, "enemies");
size_t enemyCount = yyjson_arr_size(enemies);
if(
!yyjson_is_arr(enemies) || enemyCount == 0 ||
enemyCount > CUTSCENE_BATTLE_START_ENEMY_COUNT_MAX
) {
errorThrow(
"Cutscene item (BATTLE_START): 'enemies' must have 1-%u entries",
(uint32_t)CUTSCENE_BATTLE_START_ENEMY_COUNT_MAX
);
}
item->battleStart.enemyCount = (uint8_t)enemyCount;
yyjson_arr_iter iter = yyjson_arr_iter_with(enemies);
yyjson_val *enemyVal;
size_t e = 0;
while((enemyVal = yyjson_arr_iter_next(&iter)) != NULL) {
cutscenebattlestartenemy_t *enemy = &item->battleStart.enemies[e];
errorret_t parseResult = battleFighterParse(&enemy->fighter, enemyVal);
if(errorIsNotOk(parseResult)) errorChain(parseResult);
// Enemy JSON never specifies team/controller (battleFighterParse just
// defaulted them to ALLY/PLAYER) - BATTLE_START enemies are always
// ENEMY/AI.
enemy->fighter.team = BATTLE_FIGHTER_TEAM_ENEMY;
enemy->fighter.controller = BATTLE_FIGHTER_CONTROLLER_AI;
e++;
}
errorOk();
}
@@ -0,0 +1,64 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/battle/fighter/battlefighter.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
// Enemies always occupy the left-side positions (BATTLE_FIGHTER_POS_0-3).
#define CUTSCENE_BATTLE_START_ENEMY_COUNT_MAX 4
typedef struct {
// Fully parsed at Load time via battleFighterParse (team/controller
// forced to ENEMY/AI right after, since enemy JSON only ever supplies
// stats/abilities) - Start splices this directly into
// CUTSCENE_BATTLE_START_ENEMY_POOL, no further init needed.
battlefighter_t fighter;
} cutscenebattlestartenemy_t;
typedef struct {
cutscenebattlestartenemy_t enemies[CUTSCENE_BATTLE_START_ENEMY_COUNT_MAX];
uint8_t enemyCount;
} cutscenebattlestart_t;
/**
* Starts a BATTLE_START item: spawns the configured enemies, fills the
* remaining positions with the active party (via partyGetOrderMember), and
* calls battleStart. Always completes immediately - the battle scene takes
* over from here.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneBattleStartStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Updates a BATTLE_START item (always completes immediately).
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true always.
*/
bool_t cutsceneBattleStartUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses a BATTLE_START cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneBattleStartLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
);
@@ -0,0 +1,29 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/battle/battle.h"
#include "rpg/battle/state/battlestateselection.h"
bool_t cutsceneBattleWaitSelectionUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
if(BATTLE.state != BATTLE_STATE_SELECTION) return true;
if(!battleStateSelectionIsComplete()) return false;
// Every fighter has decided - queue the move to BATTLE_STATE_EXECUTING.
const cutsceneitem_t items[] = {
{
.type = CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
.battleSetState = { .state = BATTLE_STATE_EXECUTING }
}
};
cutsceneSystemInsertItemsNext(items, sizeof(items) / sizeof(cutsceneitem_t));
return true;
}
@@ -0,0 +1,27 @@
/**
* 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 BATTLE_WAIT_SELECTION step, completing once every fighter has
* decided a move this round (letting the queued BATTLE_SET_STATE step
* that follows move the battle on to BATTLE_STATE_EXECUTING) or once the
* selecting fighter has fled (moving on to BATTLE_STATE_FLED). Has no
* Start callback -- there's nothing to do until selection actually
* finishes.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true once selection has completed or the battle has left
* BATTLE_STATE_SELECTION.
*/
bool_t cutsceneBattleWaitSelectionUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
@@ -1,31 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/cutscene/item/json/cutscenejsonbattlestate.h"
bool_t cutsceneBattleWaitStateUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return BATTLE.state == item->battleWaitState.state;
}
errorret_t cutsceneBattleWaitStateLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
battlestate_t stateValue;
if(!cutsceneJsonLookupBattleState(
yyjson_get_str(yyjson_obj_get(itemObj, "state")), &stateValue
)) {
errorThrow("Cutscene item (BATTLE_WAIT_STATE): invalid 'state'");
}
item->battleWaitState.state = stateValue;
errorOk();
}
@@ -1,29 +0,0 @@
/**
* 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.
@@ -1,204 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/party.h"
#include "scene/scene.h"
#include "save/save.h"
#include "rpg/cutscene/item/json/cutscenejsonbattleencounter.h"
#include "rpg/cutscene/item/json/cutscenejsonbattleability.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
#include "util/memory.h"
void cutsceneStartBattleStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
const cutscenestartbattle_t *config = &item->startBattle;
battleInit();
for(uint8_t i = 0; i < config->playerCount; i++) {
battlefighter_t *member =
partyGetOrderMember(config->players[i]);
if(member == NULL) continue;
battlefighter_t *fighter = battleAddFighter(
BATTLE_FIGHTER_TEAM_ALLY, BATTLE_FIGHTER_CONTROLLER_PLAYER,
member->stats, member->healthMax, member->mpMax
);
if(fighter == NULL) continue;
fighter->health = member->health;
fighter->mp = member->mp;
fighter->status = member->status;
memoryCopy(fighter->abilities, member->abilities, sizeof(fighter->abilities));
}
for(uint8_t i = 0; i < config->enemyCount; i++) {
const cutscenestartbattleenemy_t *enemy = &config->enemies[i];
battlefighter_t *fighter = battleAddFighter(
BATTLE_FIGHTER_TEAM_ENEMY, BATTLE_FIGHTER_CONTROLLER_AI,
enemy->stats, enemy->healthMax, enemy->mpMax
);
if(fighter == NULL) continue;
memoryCopy(fighter->abilities, enemy->abilities, sizeof(fighter->abilities));
}
battleStart(config->encounterType, config->fleeAvailable);
sceneSet(SCENE_TYPE_BATTLE);
}
bool_t cutsceneStartBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
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
// ally fighters having been added to BATTLE.fighters in the same
// order config->players iterates (see cutsceneStartBattleStart).
uint8_t allySlot = 0;
for(uint8_t i = 0; i < config->playerCount; i++) {
battlefighter_t *member =
partyGetOrderMember(config->players[i]);
if(member == NULL) continue;
battlefighter_t *fighter = &BATTLE.fighters[allySlot++];
member->health = fighter->health;
member->mp = fighter->mp;
member->status = fighter->status;
}
sceneSet(SCENE_TYPE_OVERWORLD);
battleDispose();
return true;
}
errorret_t cutsceneStartBattleLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
battleencountertype_t encounterValue;
if(!cutsceneJsonLookupBattleEncounter(
yyjson_get_str(yyjson_obj_get(itemObj, "encounterType")), &encounterValue
)) {
errorThrow("Cutscene item (START_BATTLE): invalid 'encounterType'");
}
item->startBattle.encounterType = encounterValue;
item->startBattle.fleeAvailable =
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");
size_t enemyCount = yyjson_arr_size(enemies);
if(!yyjson_is_arr(enemies) || enemyCount == 0 ||
enemyCount > CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX) {
errorThrow(
"Cutscene item (START_BATTLE): 'enemies' must have 1-%u entries",
(uint32_t)CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX
);
}
item->startBattle.enemyCount = (uint8_t)enemyCount;
yyjson_arr_iter iter = yyjson_arr_iter_with(enemies);
yyjson_val *enemyVal;
size_t e = 0;
while((enemyVal = yyjson_arr_iter_next(&iter)) != NULL) {
yyjson_val *stats = yyjson_obj_get(enemyVal, "stats");
if(!yyjson_is_obj(stats)) {
errorThrow(
"Cutscene item (START_BATTLE): enemies[%u] is missing 'stats'",
(uint32_t)e
);
}
cutscenestartbattleenemy_t *enemy = &item->startBattle.enemies[e];
enemy->stats.attack =
(uint16_t)yyjson_get_int(yyjson_obj_get(stats, "attack"));
enemy->stats.defense =
(uint16_t)yyjson_get_int(yyjson_obj_get(stats, "defense"));
enemy->stats.magic =
(uint16_t)yyjson_get_int(yyjson_obj_get(stats, "magic"));
enemy->stats.speed =
(uint16_t)yyjson_get_int(yyjson_obj_get(stats, "speed"));
enemy->stats.luck =
(uint16_t)yyjson_get_int(yyjson_obj_get(stats, "luck"));
enemy->healthMax =
(uint16_t)yyjson_get_int(yyjson_obj_get(enemyVal, "healthMax"));
enemy->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++;
}
errorOk();
}
@@ -1,72 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/battle/battle.h"
#include "rpg/battle/party.h"
#include "rpg/cutscene/item/cutsceneitembase.h"
#define CUTSCENE_START_BATTLE_ENEMY_COUNT_MAX 4
typedef struct {
battlefighterstats_t stats;
uint16_t healthMax;
uint16_t mpMax;
battleability_t abilities[BATTLE_FIGHTER_ABILITY_COUNT_MAX];
} cutscenestartbattleenemy_t;
typedef struct {
battleencountertype_t encounterType;
bool_t fleeAvailable;
uint8_t enemyCount;
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;
/**
* Starts a battle: seeds BATTLE with the party's active order members
* and the item's configured enemies, then switches to the battle
* scene.
*
* @param item The cutscene item.
* @param data Runtime data storage.
*/
void cutsceneStartBattleStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Waits for the battle to produce a result, syncs ally HP/MP back to
* the party roster, then returns to the overworld scene.
*
* @param item The cutscene item.
* @param data Runtime data storage.
* @returns true once the battle has ended.
*/
bool_t cutsceneStartBattleUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
);
/**
* Parses a START_BATTLE cutscene item's JSON fields into item.
*
* @param itemObj The item's JSON object.
* @param item Destination item, already zeroed by the caller.
* @return Error code indicating success or failure of the parse.
*/
errorret_t cutsceneStartBattleLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
);
@@ -11,7 +11,7 @@
/** /**
* 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
* cutsceneGoTo to jump elsewhere. * cutsceneSystemGoTo to jump elsewhere.
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
@@ -19,7 +19,7 @@ typedef struct {
/** /**
* 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 cutsceneSystemGoTo to jump to.
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
+276 -233
View File
@@ -7,9 +7,6 @@
#include "rpg/cutscene/cutscenesystem.h" #include "rpg/cutscene/cutscenesystem.h"
#include "rpg/cutscene/item/cutsceneitembase.h" #include "rpg/cutscene/item/cutsceneitembase.h"
#include "asset/asset.h"
#include "asset/assetfile.h"
#include "asset/loader/assetloader.h"
#include "util/memory.h" #include "util/memory.h"
#include "util/string.h" #include "util/string.h"
#include "ui/overlay/uifatalerror.h" #include "ui/overlay/uifatalerror.h"
@@ -17,27 +14,7 @@
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 },
[CUTSCENE_ITEM_TYPE_TEXT] = { // Control
.init = cutsceneTextStart,
.update = cutsceneTextUpdate,
.jsonName = "TEXT",
.load = cutsceneTextLoad
},
[CUTSCENE_ITEM_TYPE_TEXT_MINI] = {
.init = cutsceneTextMiniStart,
.update = cutsceneTextMiniUpdate,
.jsonName = "TEXT_MINI",
.load = cutsceneTextMiniLoad
},
[CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE] = {
.init = cutsceneTextMiniHideStart,
.update = cutsceneTextMiniHideUpdate,
.jsonName = "TEXT_MINI_HIDE",
.load = cutsceneTextMiniHideLoad
},
[CUTSCENE_ITEM_TYPE_CALLBACK] = { [CUTSCENE_ITEM_TYPE_CALLBACK] = {
.init = cutsceneCallbackStart, .init = cutsceneCallbackStart,
.update = cutsceneCallbackUpdate .update = cutsceneCallbackUpdate
@@ -57,25 +34,11 @@ cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
.load = cutsceneCutsceneLoad .load = cutsceneCutsceneLoad
}, },
[CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT] = { [CUTSCENE_ITEM_TYPE_INSERT] = {
.init = cutsceneEntityTeleportStart, .init = cutsceneInsertStart,
.update = cutsceneEntityTeleportUpdate, .update = cutsceneInsertUpdate,
.jsonName = "ENTITY_TELEPORT", .jsonName = "INSERT",
.load = cutsceneEntityTeleportLoad .load = cutsceneInsertLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO] = {
.init = cutsceneEntityWalkToStart,
.update = cutsceneEntityWalkToUpdate,
.jsonName = "ENTITY_WALK_TO",
.load = cutsceneEntityWalkToLoad
},
[CUTSCENE_ITEM_TYPE_FADE] = {
.init = cutsceneFadeStart,
.update = cutsceneFadeUpdate,
.jsonName = "FADE",
.load = cutsceneFadeLoad
}, },
[CUTSCENE_ITEM_TYPE_SET_PAUSE] = { [CUTSCENE_ITEM_TYPE_SET_PAUSE] = {
@@ -90,122 +53,6 @@ cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
.update = cutsceneConcurrentUpdate .update = cutsceneConcurrentUpdate
}, },
[CUTSCENE_ITEM_TYPE_ITEM_GIVE] = {
.init = cutsceneItemGiveStart,
.update = cutsceneItemGiveUpdate,
.jsonName = "ITEM_GIVE",
.load = cutsceneItemGiveLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_REMOVE] = {
.init = cutsceneEntityRemoveStart,
.update = cutsceneEntityRemoveUpdate,
.jsonName = "ENTITY_REMOVE",
.load = cutsceneEntityRemoveLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_ADD] = {
.init = cutsceneEntityAddStart,
.update = cutsceneEntityAddUpdate,
.jsonName = "ENTITY_ADD",
.load = cutsceneEntityAddLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_TURN] = {
.init = cutsceneEntityTurnStart,
.update = cutsceneEntityTurnUpdate,
.jsonName = "ENTITY_TURN",
.load = cutsceneEntityTurnLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY] = {
.init = cutsceneEntityWalkToEntityStart,
.update = cutsceneEntityWalkToEntityUpdate,
.jsonName = "ENTITY_WALK_TO_ENTITY",
.load = cutsceneEntityWalkToEntityLoad
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_ADD] = {
.init = cutsceneMapAreaAddStart,
.update = cutsceneMapAreaAddUpdate
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE] = {
.init = cutsceneMapAreaRemoveStart,
.update = cutsceneMapAreaRemoveUpdate,
.jsonName = "MAP_AREA_REMOVE",
.load = cutsceneMapAreaRemoveLoad
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT] = {
.init = cutsceneMapAreaWaitStart,
.update = cutsceneMapAreaWaitUpdate,
.jsonName = "MAP_AREA_WAIT",
.load = cutsceneMapAreaWaitLoad
},
[CUTSCENE_ITEM_TYPE_START_BATTLE] = {
.init = cutsceneStartBattleStart,
.update = cutsceneStartBattleUpdate,
.jsonName = "START_BATTLE",
.load = cutsceneStartBattleLoad
},
[CUTSCENE_ITEM_TYPE_EMOJI] = {
.init = cutsceneEmojiStart,
.update = cutsceneEmojiUpdate,
.jsonName = "EMOJI",
.load = cutsceneEmojiLoad
},
[CUTSCENE_ITEM_TYPE_SHAKE] = {
.init = cutsceneShakeStart,
.update = cutsceneShakeUpdate,
.jsonName = "SHAKE",
.load = cutsceneShakeLoad
},
[CUTSCENE_ITEM_TYPE_BATTLE_WAIT_STATE] = {
.update = cutsceneBattleWaitStateUpdate,
.jsonName = "BATTLE_WAIT_STATE",
.load = cutsceneBattleWaitStateLoad
},
[CUTSCENE_ITEM_TYPE_BATTLE_FORCE_ACTION] = {
.init = cutsceneBattleForceActionStart,
.update = cutsceneBattleForceActionUpdate,
.jsonName = "BATTLE_FORCE_ACTION",
.load = cutsceneBattleForceActionLoad
},
[CUTSCENE_ITEM_TYPE_MODAL] = {
.init = cutsceneModalStart,
.update = cutsceneModalUpdate,
.jsonName = "MODAL",
.load = cutsceneModalLoad
},
[CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS] = {
.init = cutsceneModalOptionsMarkersStart,
.update = cutsceneModalOptionsMarkersUpdate,
.jsonName = "MODAL_OPTIONS_MARKERS",
.load = cutsceneModalOptionsMarkersLoad
},
[CUTSCENE_ITEM_TYPE_MODAL_CLOSE] = {
.init = cutsceneModalCloseStart,
.update = cutsceneModalCloseUpdate,
.jsonName = "MODAL_CLOSE",
.load = cutsceneItemLoadNoop
},
[CUTSCENE_ITEM_TYPE_PRINT] = {
.init = cutscenePrintStart,
.update = cutscenePrintUpdate,
.jsonName = "PRINT",
.load = cutscenePrintLoad
},
[CUTSCENE_ITEM_TYPE_MARKER] = { [CUTSCENE_ITEM_TYPE_MARKER] = {
.init = cutsceneMarkerStart, .init = cutsceneMarkerStart,
.update = cutsceneMarkerUpdate, .update = cutsceneMarkerUpdate,
@@ -234,6 +81,207 @@ cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
.load = cutsceneSceneLoad .load = cutsceneSceneLoad
}, },
[CUTSCENE_ITEM_TYPE_IDLE] = {
.update = cutsceneIdleUpdate,
.jsonName = "IDLE",
.load = cutsceneItemLoadNoop
},
// Entity
[CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT] = {
.init = cutsceneEntityTeleportStart,
.update = cutsceneEntityTeleportUpdate,
.jsonName = "ENTITY_TELEPORT",
.load = cutsceneEntityTeleportLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO] = {
.init = cutsceneEntityWalkToStart,
.update = cutsceneEntityWalkToUpdate,
.jsonName = "ENTITY_WALK_TO",
.load = cutsceneEntityWalkToLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY] = {
.init = cutsceneEntityWalkToEntityStart,
.update = cutsceneEntityWalkToEntityUpdate,
.jsonName = "ENTITY_WALK_TO_ENTITY",
.load = cutsceneEntityWalkToEntityLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_REMOVE] = {
.init = cutsceneEntityRemoveStart,
.update = cutsceneEntityRemoveUpdate,
.jsonName = "ENTITY_REMOVE",
.load = cutsceneEntityRemoveLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_ADD] = {
.init = cutsceneEntityAddStart,
.update = cutsceneEntityAddUpdate,
.jsonName = "ENTITY_ADD",
.load = cutsceneEntityAddLoad
},
[CUTSCENE_ITEM_TYPE_ENTITY_TURN] = {
.init = cutsceneEntityTurnStart,
.update = cutsceneEntityTurnUpdate,
.jsonName = "ENTITY_TURN",
.load = cutsceneEntityTurnLoad
},
// UI
[CUTSCENE_ITEM_TYPE_TEXT] = {
.init = cutsceneTextStart,
.update = cutsceneTextUpdate,
.jsonName = "TEXT",
.load = cutsceneTextLoad
},
[CUTSCENE_ITEM_TYPE_TEXT_MINI] = {
.init = cutsceneTextMiniStart,
.update = cutsceneTextMiniUpdate,
.jsonName = "TEXT_MINI",
.load = cutsceneTextMiniLoad
},
[CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE] = {
.init = cutsceneTextMiniHideStart,
.update = cutsceneTextMiniHideUpdate,
.jsonName = "TEXT_MINI_HIDE",
.load = cutsceneTextMiniHideLoad
},
[CUTSCENE_ITEM_TYPE_PRINT] = {
.init = cutscenePrintStart,
.update = cutscenePrintUpdate,
.jsonName = "PRINT",
.load = cutscenePrintLoad
},
[CUTSCENE_ITEM_TYPE_FADE] = {
.init = cutsceneFadeStart,
.update = cutsceneFadeUpdate,
.jsonName = "FADE",
.load = cutsceneFadeLoad
},
[CUTSCENE_ITEM_TYPE_EMOJI] = {
.init = cutsceneEmojiStart,
.update = cutsceneEmojiUpdate,
.jsonName = "EMOJI",
.load = cutsceneEmojiLoad
},
[CUTSCENE_ITEM_TYPE_SHAKE] = {
.init = cutsceneShakeStart,
.update = cutsceneShakeUpdate,
.jsonName = "SHAKE",
.load = cutsceneShakeLoad
},
[CUTSCENE_ITEM_TYPE_MODAL] = {
.init = cutsceneModalStart,
.update = cutsceneModalUpdate,
.jsonName = "MODAL",
.load = cutsceneModalLoad
},
[CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS] = {
.init = cutsceneModalOptionsMarkersStart,
.update = cutsceneModalOptionsMarkersUpdate,
.jsonName = "MODAL_OPTIONS_MARKERS",
.load = cutsceneModalOptionsMarkersLoad
},
[CUTSCENE_ITEM_TYPE_MODAL_CLOSE] = {
.init = cutsceneModalCloseStart,
.update = cutsceneModalCloseUpdate,
.jsonName = "MODAL_CLOSE",
.load = cutsceneItemLoadNoop
},
[CUTSCENE_ITEM_TYPE_KEYBOARD] = {
.init = cutsceneKeyboardStart,
.update = cutsceneKeyboardUpdate
},
[CUTSCENE_ITEM_TYPE_UI_SHOW] = {
.init = cutsceneUIShowStart,
.update = cutsceneUIShowUpdate,
.jsonName = "UI_SHOW",
.load = cutsceneUIShowLoad
},
// Item
[CUTSCENE_ITEM_TYPE_ITEM_GIVE] = {
.init = cutsceneItemGiveStart,
.update = cutsceneItemGiveUpdate,
.jsonName = "ITEM_GIVE",
.load = cutsceneItemGiveLoad
},
// Map area
[CUTSCENE_ITEM_TYPE_MAP_AREA_ADD] = {
.init = cutsceneMapAreaAddStart,
.update = cutsceneMapAreaAddUpdate
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE] = {
.init = cutsceneMapAreaRemoveStart,
.update = cutsceneMapAreaRemoveUpdate,
.jsonName = "MAP_AREA_REMOVE",
.load = cutsceneMapAreaRemoveLoad
},
[CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT] = {
.init = cutsceneMapAreaWaitStart,
.update = cutsceneMapAreaWaitUpdate,
.jsonName = "MAP_AREA_WAIT",
.load = cutsceneMapAreaWaitLoad
},
// Battle
[CUTSCENE_ITEM_TYPE_BATTLE_START] = {
.init = cutsceneBattleStartStart,
.update = cutsceneBattleStartUpdate,
.jsonName = "BATTLE_START",
.load = cutsceneBattleStartLoad
},
[CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE] = {
.init = cutsceneBattleSetStateStart,
.update = cutsceneBattleSetStateUpdate,
.jsonName = "BATTLE_SET_STATE",
.load = cutsceneBattleSetStateLoad
},
[CUTSCENE_ITEM_TYPE_BATTLE_WAIT_SELECTION] = {
.update = cutsceneBattleWaitSelectionUpdate,
.jsonName = "BATTLE_WAIT_SELECTION",
.load = cutsceneItemLoadNoop
},
[CUTSCENE_ITEM_TYPE_BATTLE_POST_MOVE] = {
.init = cutsceneBattlePostMoveStart,
.update = cutsceneBattlePostMoveUpdate
},
[CUTSCENE_ITEM_TYPE_BATTLE_FIGHTER_DAMAGE] = {
.init = cutsceneBattleFighterDamageStart,
.update = cutsceneBattleFighterDamageUpdate,
.jsonName = "BATTLE_FIGHTER_DAMAGE",
.load = cutsceneBattleFighterDamageLoad
},
[CUTSCENE_ITEM_TYPE_BATTLE_FIGHTER_HEAL] = {
.init = cutsceneBattleFighterHealStart,
.update = cutsceneBattleFighterHealUpdate,
.jsonName = "BATTLE_FIGHTER_HEAL",
.load = cutsceneBattleFighterHealLoad
},
// Save
[CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK] = { [CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK] = {
.init = cutsceneSaveDeviceCheckStart, .init = cutsceneSaveDeviceCheckStart,
.update = cutsceneSaveDeviceCheckUpdate, .update = cutsceneSaveDeviceCheckUpdate,
@@ -248,11 +296,7 @@ cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
.load = cutsceneSaveLoadAllSlotsLoad .load = cutsceneSaveLoadAllSlotsLoad
}, },
[CUTSCENE_ITEM_TYPE_KEYBOARD] = { // Audio
.init = cutsceneKeyboardStart,
.update = cutsceneKeyboardUpdate
},
[CUTSCENE_ITEM_TYPE_AUDIO_PLAY] = { [CUTSCENE_ITEM_TYPE_AUDIO_PLAY] = {
.init = cutsceneAudioPlayStart, .init = cutsceneAudioPlayStart,
.update = cutsceneAudioPlayUpdate, .update = cutsceneAudioPlayUpdate,
@@ -315,30 +359,47 @@ cutsceneitemcallbacks_t CUTSCENE_ITEM_CALLBACKS[CUTSCENE_ITEM_TYPE_COUNT] = {
.load = cutsceneAudioSetLoad .load = cutsceneAudioSetLoad
}, },
[CUTSCENE_ITEM_TYPE_IDLE] = { // Story
.update = cutsceneIdleUpdate, [CUTSCENE_ITEM_TYPE_STORY_SET_FLAG] = {
.jsonName = "IDLE", .init = cutsceneStorySetFlagStart,
.update = cutsceneStorySetFlagUpdate,
.jsonName = "STORY_SET_FLAG",
.load = cutsceneStorySetFlagLoad
},
[CUTSCENE_ITEM_TYPE_STORY_WAIT_FLAG] = {
.update = cutsceneStoryWaitFlagUpdate,
.jsonName = "STORY_WAIT_FLAG",
.load = cutsceneStoryWaitFlagLoad
},
// Party
[CUTSCENE_ITEM_TYPE_PARTY_ADD_MEMBER] = {
.init = cutscenePartyAddMemberStart,
.update = cutscenePartyAddMemberUpdate,
.jsonName = "PARTY_ADD_MEMBER",
.load = cutscenePartyAddMemberLoad
},
[CUTSCENE_ITEM_TYPE_PARTY_REMOVE_MEMBER] = {
.init = cutscenePartyRemoveMemberStart,
.update = cutscenePartyRemoveMemberUpdate,
.jsonName = "PARTY_REMOVE_MEMBER",
.load = cutscenePartyRemoveMemberLoad
},
[CUTSCENE_ITEM_TYPE_PARTY_HEAL_MEMBER] = {
.init = cutscenePartyHealMemberStart,
.update = cutscenePartyHealMemberUpdate,
.jsonName = "PARTY_HEAL_MEMBER",
.load = cutscenePartyHealMemberLoad
},
[CUTSCENE_ITEM_TYPE_PARTY_HEAL_ALL] = {
.init = cutscenePartyHealAllStart,
.update = cutscenePartyHealAllUpdate,
.jsonName = "PARTY_HEAL_ALL",
.load = cutsceneItemLoadNoop .load = cutsceneItemLoadNoop
},
[CUTSCENE_ITEM_TYPE_UI_SHOW] = {
.init = cutsceneUIShowStart,
.update = cutsceneUIShowUpdate,
.jsonName = "UI_SHOW",
.load = cutsceneUIShowLoad
},
[CUTSCENE_ITEM_TYPE_REGULAR_BATTLE] = {
.update = cutsceneRegularBattleUpdate,
.jsonName = "REGULAR_BATTLE",
.load = cutsceneItemLoadNoop
},
[CUTSCENE_ITEM_TYPE_INSERT] = {
.init = cutsceneInsertStart,
.update = cutsceneInsertUpdate,
.jsonName = "INSERT",
.load = cutsceneInsertLoad
} }
}; };
@@ -398,33 +459,32 @@ bool_t cutsceneCutsceneUpdate(
} }
cutscene_t * cutsceneCutsceneResolve(const char_t *name) { cutscene_t * cutsceneCutsceneResolve(const char_t *name) {
char_t path[ASSET_FILE_NAME_MAX]; // Copy name out before it can be invalidated: this is commonly called
stringFormat(path, sizeof(path), "cutscenes/%s.jsonc", name); // with a pointer into CUTSCENE_SYSTEM.loadedItems itself (a running
// CUTSCENE/INSERT item's own cutsceneRef.name/insert.name field, when
// the running cutscene IS loadedScene, e.g. initial.jsonc's closing
// CUTSCENE item into main_menu.jsonc) - cutsceneLoadParse below parses
// straight into that same shared loadedItems buffer, overwriting the
// very memory name points into with the target cutscene's own first
// item before this function is done reading name.
char_t nameCopy[ASSET_FILE_NAME_MAX];
stringCopy(nameCopy, name, ASSET_FILE_NAME_MAX - 1);
assetentry_t *entry = assetLock(path, ASSET_LOADER_TYPE_JSON, NULL); errorret_t result = cutsceneLoadParse(
errorret_t result = assetRequireLoaded(entry); nameCopy, &CUTSCENE_SYSTEM.loadedScene, CUTSCENE_SYSTEM.loadedItems,
CUTSCENE_LOADED_ITEMS_MAX
);
if(errorIsNotOk(result)) { if(errorIsNotOk(result)) {
assetUnlockEntry(entry);
errorCatch(errorPrint(result)); errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL); uiFatalErrorOpen(NULL);
return NULL; return NULL;
} }
// Parse straight out of the entry's own doc while still locked - every // Shares loadedScene/loadedItems with cutsceneSystemLoad, so track the
// cutsceneitem_t field that could reference it owns its string data by // source the same way it does - cutsceneSystemGoTo needs this to reload the
// value (see cutscenecutsceneref_t/cutscenemarker_t's doc comments), so // untouched original when jumping to a marker behind the current
// nothing needs to survive past this call and the entry can just be // position (see cutsceneSystemGoTo's doc comment).
// unlocked like any other asset once parsing finishes. stringCopy(CUTSCENE_SYSTEM.loadedFile, nameCopy, ASSET_FILE_NAME_MAX - 1);
errorret_t parseResult = cutsceneParseDoc(
entry->data.json, &CUTSCENE_SYSTEM.loadedScene, CUTSCENE_SYSTEM.loadedItems,
CUTSCENE_LOADED_ITEMS_MAX
);
assetUnlockEntry(entry);
if(errorIsNotOk(parseResult)) {
errorCatch(errorPrint(parseResult));
uiFatalErrorOpen(NULL);
return NULL;
}
return &CUTSCENE_SYSTEM.loadedScene; return &CUTSCENE_SYSTEM.loadedScene;
} }
@@ -446,11 +506,11 @@ errorret_t cutsceneCutsceneRefLoad(
errorThrow("Cutscene item (%s): missing 'name'", itemTypeLabel); errorThrow("Cutscene item (%s): missing 'name'", itemTypeLabel);
} }
// Only validate that the eventual "cutscenes/<name>.jsonc" path would // Only validate that name itself would fit - the reference itself is
// fit - the reference itself is not resolved/locked until this item // not resolved/locked until this item actually runs (see
// actually runs (see cutsceneCutsceneStart/cutsceneCutsceneResolve). // cutsceneCutsceneStart/cutsceneCutsceneResolve).
int32_t pathLen = stringFormat(NULL, 0, "cutscenes/%s.jsonc", name); int32_t nameLen = stringFormat(NULL, 0, "%s", name);
if(pathLen < 0 || (size_t)pathLen >= ASSET_FILE_NAME_MAX) { if(nameLen < 0 || (size_t)nameLen >= CUTSCENE_CUTSCENE_REF_NAME_MAX) {
errorThrow("Cutscene item (%s): 'name' too long", itemTypeLabel); errorThrow("Cutscene item (%s): 'name' too long", itemTypeLabel);
} }
@@ -479,31 +539,14 @@ bool_t cutsceneInsertUpdate(
} }
void cutsceneInsertResolveAndSplice(const char_t *name) { void cutsceneInsertResolveAndSplice(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_JSON, NULL);
errorret_t result = assetRequireLoaded(entry);
if(errorIsNotOk(result)) {
assetUnlockEntry(entry);
errorCatch(errorPrint(result));
uiFatalErrorOpen(NULL);
return;
}
// Local scratch, not a shared buffer - this target is spliced straight // Local scratch, not a shared buffer - this target is spliced straight
// into the running scene below and never referenced again afterward, so // into the running scene below and never referenced again afterward, so
// it only needs to live for the rest of this call. Parsed straight out // it only needs to live for the rest of this call.
// of the entry's own doc while still locked, then unlocked like any
// other asset - see cutsceneCutsceneResolve's matching comment for why
// nothing needs to keep the doc itself resident past the parse.
cutsceneitem_t items[CUTSCENE_INSERT_ITEMS_MAX]; cutsceneitem_t items[CUTSCENE_INSERT_ITEMS_MAX];
cutscene_t scene = { .items = items }; cutscene_t scene = { .items = items };
errorret_t parseResult = errorret_t result = cutsceneLoadParse(name, &scene, items, CUTSCENE_INSERT_ITEMS_MAX);
cutsceneParseDoc(entry->data.json, &scene, items, CUTSCENE_INSERT_ITEMS_MAX); if(errorIsNotOk(result)) {
assetUnlockEntry(entry); errorCatch(errorPrint(result));
if(errorIsNotOk(parseResult)) {
errorCatch(errorPrint(parseResult));
uiFatalErrorOpen(NULL); uiFatalErrorOpen(NULL);
return; return;
} }
+39 -28
View File
@@ -40,10 +40,12 @@
#include "maparea/cutscenemapareaadd.h" #include "maparea/cutscenemapareaadd.h"
#include "maparea/cutscenemaparearemove.h" #include "maparea/cutscenemaparearemove.h"
#include "maparea/cutscenemapareawait.h" #include "maparea/cutscenemapareawait.h"
#include "battle/cutscenestartbattle.h" #include "battle/cutscenebattlestart.h"
#include "battle/cutscenebattlewaitstate.h" #include "battle/cutscenebattlesetstate.h"
#include "battle/cutscenebattleforceaction.h" #include "battle/cutscenebattlewaitselection.h"
#include "battle/cutsceneregularbattle.h" #include "battle/cutscenebattlepostmove.h"
#include "battle/cutscenebattlefighterdamage.h"
#include "battle/cutscenebattlefighterheal.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,12 +57,17 @@
#include "audio/cutsceneaudiosetpan.h" #include "audio/cutsceneaudiosetpan.h"
#include "audio/cutsceneaudiosetloop.h" #include "audio/cutsceneaudiosetloop.h"
#include "audio/cutsceneaudioset.h" #include "audio/cutsceneaudioset.h"
#include "story/cutscenestorysetflag.h"
#include "story/cutscenestorywaitflag.h"
#include "party/cutscenepartyaddmember.h"
#include "party/cutscenepartyremovemember.h"
#include "party/cutscenepartyhealmember.h"
#include "party/cutscenepartyhealall.h"
typedef struct cutscene_s cutscene_t; typedef struct cutscene_s cutscene_t;
// Max length of a CUTSCENE/INSERT item's "name" field - bounded by what // Max length of a CUTSCENE/INSERT item's "name" field - it's the full
// fits in the "cutscenes/<name>.jsonc" path built from it (see // asset path to load, so this is bounded by ASSET_FILE_NAME_MAX directly.
// cutsceneCutsceneRefLoad), so this is never reached in practice.
#define CUTSCENE_CUTSCENE_REF_NAME_MAX ASSET_FILE_NAME_MAX #define CUTSCENE_CUTSCENE_REF_NAME_MAX ASSET_FILE_NAME_MAX
// A CUTSCENE (or INSERT) item's target. A C-authored cutscene_t* set // A CUTSCENE (or INSERT) item's target. A C-authored cutscene_t* set
@@ -115,11 +122,12 @@ struct cutsceneitem_s {
cutscenemapareaadd_t mapAreaAdd; cutscenemapareaadd_t mapAreaAdd;
cutscenemaparearemove_t mapAreaRemove; cutscenemaparearemove_t mapAreaRemove;
cutscenemapareawait_t mapAreaWait; cutscenemapareawait_t mapAreaWait;
cutscenestartbattle_t startBattle; cutscenebattlestart_t battleStart;
cutscenebattlesetstate_t battleSetState;
cutscenebattlefighterdamage_t battleFighterDamage;
cutscenebattlefighterheal_t battleFighterHeal;
cutsceneemoji_t emoji; cutsceneemoji_t emoji;
cutsceneshake_t shake; cutsceneshake_t shake;
cutscenebattlewaitstate_t battleWaitState;
cutscenebattleforceaction_t battleForceAction;
cutscenemodal_t modal; cutscenemodal_t modal;
cutscenemodaloptionsmarkers_t modalOptionsMarkers; cutscenemodaloptionsmarkers_t modalOptionsMarkers;
cutsceneprint_t print; cutsceneprint_t print;
@@ -138,6 +146,11 @@ struct cutsceneitem_s {
cutsceneaudiosetloop_t audioSetLoop; cutsceneaudiosetloop_t audioSetLoop;
cutsceneaudioset_t audioSet; cutsceneaudioset_t audioSet;
cutsceneuishow_t uiShow; cutsceneuishow_t uiShow;
cutscenestorysetflag_t storySetFlag;
cutscenestorywaitflag_t storyWaitFlag;
cutscenepartyaddmember_t partyAddMember;
cutscenepartyremovemember_t partyRemoveMember;
cutscenepartyhealmember_t partyHealMember;
}; };
}; };
@@ -226,7 +239,7 @@ void cutsceneCutsceneStart(
/** /**
* Resolves a JSON-authored CUTSCENE item's referenced cutscene by name: * Resolves a JSON-authored CUTSCENE item's referenced cutscene by name:
* locks+loads assets/cutscenes/<name>.jsonc, parses it into * locks+loads name as a plain ASSET_LOADER_TYPE_JSON asset, parses it into
* CUTSCENE_SYSTEM.loadedItems/loadedScene, then unlocks the asset entry * CUTSCENE_SYSTEM.loadedItems/loadedScene, then unlocks the asset entry
* like any other asset - the parsed items don't reference the doc past * like any other asset - the parsed items don't reference the doc past
* that (see cutsceneInsertResolveAndSplice's matching comment for why). * that (see cutsceneInsertResolveAndSplice's matching comment for why).
@@ -236,8 +249,7 @@ void cutsceneCutsceneStart(
* error overlay (matching cutsceneSystemLoad's runtime-failure handling) * error overlay (matching cutsceneSystemLoad's runtime-failure handling)
* and returns NULL. * and returns NULL.
* *
* @param name Bare cutscene name (without "cutscenes/" prefix or * @param name Full asset path to the referenced cutscene's JSON file.
* ".jsonc" suffix).
* @return The resolved cutscene, or NULL on failure. * @return The resolved cutscene, or NULL on failure.
*/ */
cutscene_t * cutsceneCutsceneResolve(const char_t *name); cutscene_t * cutsceneCutsceneResolve(const char_t *name);
@@ -261,10 +273,9 @@ bool_t cutsceneCutsceneUpdate(
* (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. Only stores the 'name' string (which points into the * system itself. Only stores the 'name' string (which points into the
* cutscene asset's still-alive yyjson doc, so no copy is needed) - * cutscene asset's still-alive yyjson doc, so no copy is needed) -
* resolving it to the referenced assets/cutscenes/<name>.jsonc asset is * resolving it to the referenced asset is deferred to cutsceneCutsceneStart,
* deferred to cutsceneCutsceneStart, the first time this item actually * the first time this item actually runs, so a cutscene referencing many
* runs, so a cutscene referencing many others doesn't pay to load every * others doesn't pay to load every one of them up front.
* 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.
@@ -277,9 +288,10 @@ errorret_t cutsceneCutsceneLoad(
/** /**
* Shared JSON parsing body for both CUTSCENE and INSERT items - both need * Shared JSON parsing body for both CUTSCENE and INSERT items - both need
* exactly a 'name' string field, validated to fit the eventual * exactly a 'name' string field, the full asset path to the referenced
* "cutscenes/<name>.jsonc" asset path. Only stores the name (see * cutscene's JSON file, validated to fit CUTSCENE_CUTSCENE_REF_NAME_MAX.
* cutsceneCutsceneLoad for why resolving is deferred). * Only stores the name (see cutsceneCutsceneLoad for why resolving is
* deferred).
* *
* @param itemObj The item's JSON object. * @param itemObj The item's JSON object.
* @param outRef Destination ref, already zeroed by the caller. * @param outRef Destination ref, already zeroed by the caller.
@@ -314,19 +326,18 @@ void cutsceneInsertStart(
/** /**
* Resolves a JSON-authored INSERT item's referenced cutscene by name and * Resolves a JSON-authored INSERT item's referenced cutscene by name and
* splices it into the running cutscene (CUTSCENE_SYSTEM.scene): locks+ * splices it into the running cutscene (CUTSCENE_SYSTEM.scene): locks+
* loads assets/cutscenes/<name>.jsonc as a plain ASSET_LOADER_TYPE_JSON * loads name as a plain ASSET_LOADER_TYPE_JSON asset, parses it into a
* asset, parses it into a small scratch buffer local to this call * small scratch buffer local to this call (capacity
* (capacity CUTSCENE_INSERT_ITEMS_MAX) straight out of the asset entry's * CUTSCENE_INSERT_ITEMS_MAX) straight out of the asset entry's own doc,
* own doc, then unlocks the entry like any other asset - nothing needs * then unlocks the entry like any other asset - nothing needs to keep the
* to keep the doc itself resident past the parse: every cutscene item * doc itself resident past the parse: every cutscene item field that could
* field that could reference it owns its string data by value (see * reference it owns its string data by value (see
* cutscenecutsceneref_t/cutscenemarker_t's doc comments), and * cutscenecutsceneref_t/cutscenemarker_t's doc comments), and
* cutsceneSystemInsertCutscene copies the scratch items into the running * cutsceneSystemInsertCutscene copies the scratch items into the running
* scene's own array right after. On failure, opens the fatal error * scene's own array right after. On failure, opens the fatal error
* overlay, matching cutsceneCutsceneResolve. * overlay, matching cutsceneCutsceneResolve.
* *
* @param name Bare cutscene name (without "cutscenes/" prefix or * @param name Full asset path to the referenced cutscene's JSON file.
* ".jsonc" suffix).
*/ */
void cutsceneInsertResolveAndSplice(const char_t *name); void cutsceneInsertResolveAndSplice(const char_t *name);
+55 -28
View File
@@ -16,41 +16,62 @@ typedef union cutsceneitemdata_u cutsceneitemdata_t;
typedef enum { typedef enum {
CUTSCENE_ITEM_TYPE_NULL, CUTSCENE_ITEM_TYPE_NULL,
CUTSCENE_ITEM_TYPE_TEXT, // Control
CUTSCENE_ITEM_TYPE_TEXT_MINI,
CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE,
CUTSCENE_ITEM_TYPE_CALLBACK, CUTSCENE_ITEM_TYPE_CALLBACK,
CUTSCENE_ITEM_TYPE_WAIT, CUTSCENE_ITEM_TYPE_WAIT,
CUTSCENE_ITEM_TYPE_CUTSCENE, CUTSCENE_ITEM_TYPE_CUTSCENE,
CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT, CUTSCENE_ITEM_TYPE_INSERT,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO,
CUTSCENE_ITEM_TYPE_FADE,
CUTSCENE_ITEM_TYPE_SET_PAUSE, CUTSCENE_ITEM_TYPE_SET_PAUSE,
CUTSCENE_ITEM_TYPE_CONCURRENT, 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_MARKER,
CUTSCENE_ITEM_TYPE_RESTART, CUTSCENE_ITEM_TYPE_RESTART,
CUTSCENE_ITEM_TYPE_QUIT_GAME, CUTSCENE_ITEM_TYPE_QUIT_GAME,
CUTSCENE_ITEM_TYPE_SCENE, CUTSCENE_ITEM_TYPE_SCENE,
CUTSCENE_ITEM_TYPE_IDLE,
// Entity
CUTSCENE_ITEM_TYPE_ENTITY_TELEPORT,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO,
CUTSCENE_ITEM_TYPE_ENTITY_WALK_TO_ENTITY,
CUTSCENE_ITEM_TYPE_ENTITY_REMOVE,
CUTSCENE_ITEM_TYPE_ENTITY_ADD,
CUTSCENE_ITEM_TYPE_ENTITY_TURN,
// UI
CUTSCENE_ITEM_TYPE_TEXT,
CUTSCENE_ITEM_TYPE_TEXT_MINI,
CUTSCENE_ITEM_TYPE_TEXT_MINI_HIDE,
CUTSCENE_ITEM_TYPE_PRINT,
CUTSCENE_ITEM_TYPE_FADE,
CUTSCENE_ITEM_TYPE_EMOJI,
CUTSCENE_ITEM_TYPE_SHAKE,
CUTSCENE_ITEM_TYPE_MODAL,
CUTSCENE_ITEM_TYPE_MODAL_OPTIONS_MARKERS,
CUTSCENE_ITEM_TYPE_MODAL_CLOSE,
CUTSCENE_ITEM_TYPE_KEYBOARD,
CUTSCENE_ITEM_TYPE_UI_SHOW,
// Item
CUTSCENE_ITEM_TYPE_ITEM_GIVE,
// Map area
CUTSCENE_ITEM_TYPE_MAP_AREA_ADD,
CUTSCENE_ITEM_TYPE_MAP_AREA_REMOVE,
CUTSCENE_ITEM_TYPE_MAP_AREA_WAIT,
// Battle
CUTSCENE_ITEM_TYPE_BATTLE_START,
CUTSCENE_ITEM_TYPE_BATTLE_SET_STATE,
CUTSCENE_ITEM_TYPE_BATTLE_WAIT_SELECTION,
CUTSCENE_ITEM_TYPE_BATTLE_POST_MOVE,
CUTSCENE_ITEM_TYPE_BATTLE_FIGHTER_DAMAGE,
CUTSCENE_ITEM_TYPE_BATTLE_FIGHTER_HEAL,
// Save
CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK, CUTSCENE_ITEM_TYPE_SAVE_DEVICE_CHECK,
CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS, CUTSCENE_ITEM_TYPE_SAVE_LOAD_ALL_SLOTS,
CUTSCENE_ITEM_TYPE_KEYBOARD,
// Audio
CUTSCENE_ITEM_TYPE_AUDIO_PLAY, CUTSCENE_ITEM_TYPE_AUDIO_PLAY,
CUTSCENE_ITEM_TYPE_AUDIO_STOP, CUTSCENE_ITEM_TYPE_AUDIO_STOP,
CUTSCENE_ITEM_TYPE_AUDIO_PAUSE, CUTSCENE_ITEM_TYPE_AUDIO_PAUSE,
@@ -60,10 +81,16 @@ typedef enum {
CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN, CUTSCENE_ITEM_TYPE_AUDIO_SET_PAN,
CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP, CUTSCENE_ITEM_TYPE_AUDIO_SET_LOOP,
CUTSCENE_ITEM_TYPE_AUDIO_SET, CUTSCENE_ITEM_TYPE_AUDIO_SET,
CUTSCENE_ITEM_TYPE_IDLE,
CUTSCENE_ITEM_TYPE_UI_SHOW, // Story
CUTSCENE_ITEM_TYPE_REGULAR_BATTLE, CUTSCENE_ITEM_TYPE_STORY_SET_FLAG,
CUTSCENE_ITEM_TYPE_INSERT, CUTSCENE_ITEM_TYPE_STORY_WAIT_FLAG,
// Party
CUTSCENE_ITEM_TYPE_PARTY_ADD_MEMBER,
CUTSCENE_ITEM_TYPE_PARTY_REMOVE_MEMBER,
CUTSCENE_ITEM_TYPE_PARTY_HEAL_MEMBER,
CUTSCENE_ITEM_TYPE_PARTY_HEAL_ALL,
CUTSCENE_ITEM_TYPE_COUNT CUTSCENE_ITEM_TYPE_COUNT
} cutsceneitemtype_t; } cutsceneitemtype_t;
@@ -25,8 +25,8 @@ void cutsceneEntityAddStart(
entityInit(entity, item->entityAdd.entityType); entityInit(entity, item->entityAdd.entityType);
entityPositionSet(entity, item->entityAdd.position);// Also assigns chunk. entityPositionSet(entity, item->entityAdd.position);// Also assigns chunk.
CUTSCENE_SYSTEM.entityLastCreated = entity; CUTSCENE_SYSTEM.refs.entityLastCreated = entity;
CUTSCENE_SYSTEM.entityLastRef = entity; CUTSCENE_SYSTEM.refs.entityLastRef = entity;
} }
bool_t cutsceneEntityAddUpdate( bool_t cutsceneEntityAddUpdate(
@@ -14,10 +14,9 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
cutscenejsonemoji.c cutscenejsonemoji.c
cutscenejsonentitytype.c cutscenejsonentitytype.c
cutscenejsonentitydir.c cutscenejsonentitydir.c
cutscenejsonbattleencounter.c
cutscenejsonbattleability.c
cutscenejsonbattlestate.c cutscenejsonbattlestate.c
cutscenejsonscenetype.c cutscenejsonscenetype.c
cutscenejsonuiscreentype.c cutscenejsonuiscreentype.c
cutscenejsonaudiochannel.c cutscenejsonaudiochannel.c
cutscenejsonstoryflag.c
) )
@@ -10,7 +10,7 @@
#include "yyjson.h" #include "yyjson.h"
// Sentinel accepted in place of a literal area id - see cutscenesystem.h's // Sentinel accepted in place of a literal area id - see cutscenesystem.h's
// CUTSCENE_AREA_LAST_CREATED. Kept local since it's a JSON-authoring // CUTSCENE_REF_AREA_LAST_CREATED. Kept local since it's a JSON-authoring
// convenience, not part of the item struct definitions themselves. // convenience, not part of the item struct definitions themselves.
#define CUTSCENE_JSON_AREA_SENTINEL_LAST_CREATED ((uint8_t)0xFF) #define CUTSCENE_JSON_AREA_SENTINEL_LAST_CREATED ((uint8_t)0xFF)
@@ -1,31 +0,0 @@
/**
* 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;
}
@@ -1,22 +0,0 @@
/**
* 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
);
@@ -1,34 +0,0 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "cutscenejsonbattleencounter.h"
#include "cutscenejsonenum.h"
static const cutscenejsonenumentry_t
CUTSCENE_JSON_BATTLE_ENCOUNTER_TABLE[] = {
{ "REGULAR", BATTLE_ENCOUNTER_REGULAR },
{ "PLAYER_ADVANTAGE", BATTLE_ENCOUNTER_PLAYER_ADVANTAGE },
{ "BACK_ATTACK", BATTLE_ENCOUNTER_BACK_ATTACK },
};
#define CUTSCENE_JSON_BATTLE_ENCOUNTER_TABLE_COUNT \
(sizeof(CUTSCENE_JSON_BATTLE_ENCOUNTER_TABLE) / \
sizeof(cutscenejsonenumentry_t))
bool_t cutsceneJsonLookupBattleEncounter(
const char_t *name,
battleencountertype_t *out
) {
int32_t value;
if(!cutsceneJsonLookupEnumInsensitive(
CUTSCENE_JSON_BATTLE_ENCOUNTER_TABLE,
CUTSCENE_JSON_BATTLE_ENCOUNTER_TABLE_COUNT, name, &value
)) {
return false;
}
*out = (battleencountertype_t)value;
return true;
}
@@ -1,23 +0,0 @@
/**
* 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/battle.h"
/**
* Looks up name (case-insensitively) against the battle encounter type
* table.
*
* @param name Name to search for.
* @param out Set to the matching encounter type on success.
* @return true if a matching entry was found, false otherwise.
*/
bool_t cutsceneJsonLookupBattleEncounter(
const char_t *name,
battleencountertype_t *out
);
@@ -9,23 +9,27 @@
#include "cutscenejsonenum.h" #include "cutscenejsonenum.h"
static const cutscenejsonenumentry_t CUTSCENE_JSON_BATTLE_STATE_TABLE[] = { static const cutscenejsonenumentry_t CUTSCENE_JSON_BATTLE_STATE_TABLE[] = {
{ "NONE", BATTLE_STATE_NONE },
{ "OPENING", BATTLE_STATE_OPENING }, { "OPENING", BATTLE_STATE_OPENING },
{ "PRE_ROUND", BATTLE_STATE_PRE_ROUND }, { "PRE_ROUND", BATTLE_STATE_PRE_ROUND },
{ "PLAYER_SELECTION", BATTLE_STATE_PLAYER_SELECTION }, { "SELECTION", BATTLE_STATE_SELECTION },
{ "AI_SELECTION", BATTLE_STATE_AI_SELECTION }, { "EXECUTING", BATTLE_STATE_EXECUTING },
{ "MOVES_EXECUTING", BATTLE_STATE_MOVES_EXECUTING },
{ "POST_ROUND", BATTLE_STATE_POST_ROUND }, { "POST_ROUND", BATTLE_STATE_POST_ROUND },
{ "ENDED", BATTLE_STATE_ENDED }, { "LOST", BATTLE_STATE_LOST },
{ "WON", BATTLE_STATE_WON },
{ "FLED", BATTLE_STATE_FLED },
{ "ENDING", BATTLE_STATE_ENDING },
}; };
#define CUTSCENE_JSON_BATTLE_STATE_TABLE_COUNT \ #define CUTSCENE_JSON_BATTLE_STATE_TABLE_COUNT \
(sizeof(CUTSCENE_JSON_BATTLE_STATE_TABLE) / sizeof(cutscenejsonenumentry_t)) (sizeof(CUTSCENE_JSON_BATTLE_STATE_TABLE) / sizeof(cutscenejsonenumentry_t))
bool_t cutsceneJsonLookupBattleState(const char_t *name, battlestate_t *out) { bool_t cutsceneJsonLookupBattleState(
const char_t *name,
battlestate_t *out
) {
int32_t value; int32_t value;
if(!cutsceneJsonLookupEnumInsensitive( if(!cutsceneJsonLookupEnumInsensitive(
CUTSCENE_JSON_BATTLE_STATE_TABLE, CUTSCENE_JSON_BATTLE_STATE_TABLE_COUNT, CUTSCENE_JSON_BATTLE_STATE_TABLE,
name, &value CUTSCENE_JSON_BATTLE_STATE_TABLE_COUNT, name, &value
)) { )) {
return false; return false;
} }
@@ -6,14 +6,16 @@
*/ */
#pragma once #pragma once
#include "dusk.h" #include "rpg/battle/state/battlestate.h"
#include "rpg/battle/battle.h"
/** /**
* Looks up name (case-insensitively) against the battle state table. * Looks up name (case-insensitive) against every battlestate_t name.
* *
* @param name Name to search for. * @param name Name to search for.
* @param out Set to the matching battle state on success. * @param out Set to the matching state on success.
* @return true if a matching entry was found, false otherwise. * @return true if a matching entry was found, false otherwise.
*/ */
bool_t cutsceneJsonLookupBattleState(const char_t *name, battlestate_t *out); bool_t cutsceneJsonLookupBattleState(
const char_t *name,
battlestate_t *out
);
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "cutscenejsonstoryflag.h"
bool_t cutsceneJsonGetStoryFlag(yyjson_val *val, storyflag_t *outFlag) {
if(!yyjson_is_str(val)) return false;
storyflag_t flag = storyGetFlagByName(yyjson_get_str(val));
if(flag >= STORY_FLAG_COUNT) return false;
*outFlag = flag;
return true;
}
@@ -0,0 +1,21 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "dusk.h"
#include "yyjson.h"
#include "rpg/story/story.h"
/**
* Resolves a JSON string value naming a story flag (via storyGetFlagByName)
* into a storyflag_t.
*
* @param val JSON value to resolve (a string).
* @param outFlag Set to the resolved story flag id on success.
* @return true if val resolved to a known story flag, false otherwise.
*/
bool_t cutsceneJsonGetStoryFlag(yyjson_val *val, storyflag_t *outFlag);
@@ -12,7 +12,7 @@ void cutsceneMapAreaAddStart(
const cutsceneitem_t *item, const cutsceneitem_t *item,
cutsceneitemdata_t *data cutsceneitemdata_t *data
) { ) {
CUTSCENE_SYSTEM.areaLastCreated = mapAreaAdd( CUTSCENE_SYSTEM.refs.areaLastCreated = mapAreaAdd(
item->mapAreaAdd.min, item->mapAreaAdd.min,
item->mapAreaAdd.max, item->mapAreaAdd.max,
item->mapAreaAdd.callback, item->mapAreaAdd.callback,
@@ -21,7 +21,7 @@ typedef struct {
/** /**
* 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.refs.areaLastCreated).
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
@@ -14,7 +14,7 @@ typedef struct {
/** /**
* 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_REF_AREA_LAST_CREATED in place of a literal area ID.
* *
* @param item The cutscene item. * @param item The cutscene item.
* @param data Runtime data storage. * @param data Runtime data storage.
@@ -0,0 +1,12 @@
# Copyright (c) 2026 Dominic Masters
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
cutscenepartyaddmember.c
cutscenepartyremovemember.c
cutscenepartyhealmember.c
cutscenepartyhealall.c
)
@@ -0,0 +1,42 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "rpg/cutscene/item/cutsceneitem.h"
#include "rpg/battle/party.h"
#include "rpg/cutscene/item/json/cutscenejsonfield.h"
void cutscenePartyAddMemberStart(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
partyAddMember(item->partyAddMember.memberIndex);
}
bool_t cutscenePartyAddMemberUpdate(
const cutsceneitem_t *item,
cutsceneitemdata_t *data
) {
return true;
}
errorret_t cutscenePartyAddMemberLoad(
yyjson_val *itemObj,
cutsceneitem_t *item
) {
char_t key[PARTY_KEY_LENGTH_MAX];
if(!cutsceneJsonCopyString(itemObj, "key", NULL, key, PARTY_KEY_LENGTH_MAX)) {
errorThrow("Cutscene item (PARTY_ADD_MEMBER): missing/invalid 'key'");
}
const uint8_t memberIndex = partyGetMemberIndexByKey(key);
if(memberIndex == PARTY_MEMBER_NOT_FOUND) {
errorThrow("Cutscene item (PARTY_ADD_MEMBER): no member with key '%s'", key);
}
item->partyAddMember.memberIndex = memberIndex;
errorOk();
}
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more