7 Commits

Author SHA1 Message Date
YourWishes 4d95415232 Move global item collected-state, deadzone, and story flags into save file
Adds three new pieces of save-file state, all following the same shape:
the save file is the single source of truth, not a separate live runtime
copy that gets synced in/out.

- globalitemstore.h/.c: per-global-entity-ID "collected" flags
  (savefile_t.globalItemCollected), so a global item entity's init
  callback can check whether it was already picked up in a prior session
  without needing to keep the entity itself alive to remember that.

- Gamepad deadzone: removed input_t.deadzone entirely. The setting UI and
  every platform's actual deadzone-applying code (inputGetDeadzoneDolphin/
  SDL2, previously hardcoded per-platform literals that the settings menu
  didn't actually affect) now read savefile_t.deadzone directly via
  saveGet(SAVE_ACTIVE_SLOT). Default lives in savefile.h
  (SAVE_DEADZONE_DEFAULT), stamped onto every slot in saveInit().

- Story flags: STORY_FLAG_VALUES (a live, codegen-initialized array) is
  replaced by savefile_t.storyFlags, read/written via the existing
  storyFlagGet()/storyFlagSet() call sites (now macros/functions over the
  active save file instead of a separate array). tools/story.py now
  generates STORY_FLAG_DEFAULTS (const) instead; storyFlagInitDefaults()
  stamps those onto a save the first time it's used (file->exists false),
  called from rpgInit().

Added SAVE_ACTIVE_SLOT (0) to savefile.h as the one shared "which slot is
actually being played" constant, replacing three different local/implicit
0s (uigamemenu.c, rpg.c, and now the settings/input call sites).

Verified round-trip on Linux (all three together in one save/load cycle);
both Linux and PSP build clean.
2026-08-04 11:10:44 -05:00
YourWishes 2cbd80a004 Check for existing save data before saving, confirm before creating new
uiGameMenuSave() now attempts a real load first (via the existing generic
saveLoad()/saveExists() primitives) instead of writing blind. If a save
already exists, it saves straight over it as before. If not, it prompts
via the existing uiConfirm dialog ("No save data found. Create a new
save?") before writing - this is exactly the flow GameCube needs (no
native OS save browser to lean on, unlike PSP), but implemented generically
so it also applies correctly on every other platform without any
platform-specific UI code: saveIsAvailable()/saveExists() already reflect
each platform's real state (e.g. Dolphin's memory-card presence and
existing-file checks), so the same logic just does the right thing
everywhere.

Verified the two branches directly on Linux (temporarily wiring the same
saveLoad -> check -> uiConfirmOpen sequence into rpgInit): with no save
file, saveExists() is false and the confirm dialog opens; with one already
written, it's true and the confirm dialog is correctly skipped. Not
verified via actual menu navigation (no input-injection tooling available
here) or on Dolphin (no devkitPPC toolchain in this environment).
2026-08-04 10:33:57 -05:00
YourWishes 9abf8101da PSP: save through the real sceUtilitySavedata API, not raw file I/O
Rewrote savepsp.c/savestreampsp.c to use sceUtilitySavedataInitStart/
Update/GetStatus/ShutdownStart instead of sceIoOpen/Read/Write, so PSP
saves get a proper OS-generated PARAM.SFO (title/savedataTitle/detail) and
show up correctly in the native save browser.

This dialog spans multiple frames and, per this project's prior experience
with the network config dialog, must be pumped non-blocking one step per
real engine frame rather than blocked on synchronously - a raw-sceGu
blocking loop already froze the app on real hardware for that dialog,
since pspGL owns the GU context. So save.h's saveWrite()/saveLoad() are
now callback-based (savecallback_t onComplete) instead of returning a
result directly, mirroring networkRequestConnection()'s shape, with a new
saveUpdate() (wired into engineUpdate()) pumping the active op each frame.
Linux/Dolphin behavior is unchanged - their fallback path in save.c still
completes synchronously, just via an immediate callback call instead of a
direct return.

Two real bugs found via PPSSPP testing (not just code review): SAVE/LOAD
modes show a confirm screen even for brand-new data, which blocks forever
headlessly - switched to AUTOSAVE/AUTOLOAD, which write/read silently and
generate the identical PARAM.SFO. And PPSSPP's dialog status goes straight
from QUIT to NONE without a separately observable FINISHED in between,
which the first version misread as "disappeared without a result" even on
a successful save - fixed by tracking whether QUIT was already seen.

Confirmed end-to-end in PPSSPP: write, dialog completes, PARAM.SFO +
encrypted save.bin appear on the virtual memory stick, and a subsequent
load decrypts/deserializes back to the exact original data. Not tested on
real PSP hardware.
2026-08-04 09:54:45 -05:00
YourWishes 24badd06a5 Add player name field to save file, save it out as a round-trip test
Adds savefile_t.playerName (SAVE_PLAYER_NAME_MAX) serialized via the
existing saveFileReadString/WriteString helpers, and stamps + saves it in
rpgInit() as a test that the save system now persists actual game data,
not just the header/version. Verified manually: written bytes end in
"Dusk\0" immediately after the version field, and loading it back returns
the same string.
2026-08-04 08:59:29 -05:00
YourWishes 7a03ef8eaf Re-enable save system, fix header/version stamping, handle missing media
- Fixed the actual reason saving never worked on any platform: saveWrite()
  never stamped file->header/file->version before serializing, so every
  written save file had a zeroed magic header and failed its own
  validation on the next load. Confirmed via a manual write/load round
  trip that this alone fully explains "saving doesn't work."
- Re-enabled saveInit()/saveDispose() in engine.c (previously commented out
  under "Temporarily disable save code").
- Added SAVE.available + saveIsAvailable(), refreshed by every real
  save/load/delete attempt. saveInit() no longer treats an unreachable
  save medium as fatal to booting - it logs and continues, since a missing
  memory card/stick shouldn't prevent playing.
- Hardened PSP's saveInitPSP() to actually detect a missing memory stick
  (sceIoGetstat on ms0:/) instead of assuming success, and fixed
  single-level sceIoMkdir to build the full PSP/SAVEDATA directory chain.
- Added busy-retry (CARD_ERROR_BUSY) and a not-mounted guard to Dolphin's
  live savestreamdolphin.c path, extending the same handling already
  backported into savedolphin.c.
- Added a "Save" entry to the game menu wired to saveWrite(0), showing a
  clear message on success, on failure, and when saveIsAvailable() is false.
2026-08-04 08:30:24 -05:00
YourWishes f3ea507313 Fixed save crash
Backported from branch ac2 (commit 85b61097) - CARD_Mount was being called
without CARD_Init first, leaving per-channel control blocks and the DSP
unlock sequence unset. On real Dolphin/hardware this surfaced as a hard
MMIO crash instead of a clean CARD_ERROR_* failure.

Co-Authored-By: Dominic Masters <dominic@domsplace.com>
2026-08-04 08:12:57 -05:00
YourWishes 4b0388a0e1 Chunk streaming concurrency, entity slot fix, and map-data-driven spawns
- Allow 2 chunks to be mid-load concurrently instead of 1 (MAP_CHUNK_LOAD_CONCURRENCY).
- Fix entitySetChunk silently losing track of an entity when its target chunk's
  entity slots are full - it now stays detached (and retries later) instead of
  claiming a chunk that never actually registered it.
- DCF format bumped to v5: chunks can now declare entity spawns (global/NPC via
  the existing entityglobal registry, or one-shot item pickups) and map area
  triggers, resolved via a new callback-ID registry (mapareagloballist.h)
  mirroring the entity one. rpg.c's hardcoded TEST entity/item/area spawns are
  gone - chunk_0_0_0.json now carries that data instead. The player is still
  bootstrapped in code since it isn't map-authored content.
2026-08-04 07:37:48 -05:00
54 changed files with 1535 additions and 365 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+4
View File
@@ -56,6 +56,10 @@ msgstr "Items"
msgid "ui.game_menu.settings"
msgstr "Settings"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save"
msgstr "Save"
msgid "item.potion.name"
msgstr "Potion"
+4
View File
@@ -57,6 +57,10 @@ msgstr "Objetos"
msgid "ui.game_menu.settings"
msgstr "Configuración"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save"
msgstr "Guardar"
#: src/dusk/rpg/item/item.json
msgid "item.potion.name"
msgstr "Poción"
+4
View File
@@ -57,6 +57,10 @@ msgstr "アイテム"
msgid "ui.game_menu.settings"
msgstr "設定"
#: src/dusk/ui/frame/game/uigamemenu.c
msgid "ui.game_menu.save"
msgstr "セーブ"
#: src/dusk/rpg/item/item.json
msgid "item.potion.name"
msgstr "ポーション"
+22
View File
@@ -2179,5 +2179,27 @@
0
]
}
],
"entities": [
{
"type": "global",
"globalId": 3,
"pos": [8, 8, 1]
},
{
"type": "item",
"itemId": 1,
"quantity": 1,
"pos": [12, 2, 0]
}
],
"areas": [
{
"min": [11, 3, 0],
"max": [16, 9, 10],
"callbackId": 1,
"notify": 3,
"trigger": 6
}
]
}
@@ -14,6 +14,26 @@
#include "asset/loader/assetloader.h"
#include "asset/asset.h"
// Reads a little-endian int16 from a potentially-unaligned offset into a
// worldunit_t, advancing *offset past it.
static worldunit_t assetChunkReadWorldUnit(
const uint8_t *data,
size_t *offset
) {
int16_t value;
memoryCopy(&value, data + *offset, sizeof(int16_t));
*offset += sizeof(int16_t);
return (worldunit_t)endianLittleToHost16((uint16_t)value);
}
static worldpos_t assetChunkReadWorldPos(const uint8_t *data, size_t *offset) {
worldpos_t pos;
pos.x = assetChunkReadWorldUnit(data, offset);
pos.y = assetChunkReadWorldUnit(data, offset);
pos.z = assetChunkReadWorldUnit(data, offset);
return pos;
}
errorret_t assetChunkLoaderAsync(assetloading_t *loading) {
assertNotNull(loading, "Loading cannot be NULL");
assertNotMainThread("Should be called from an async thread.");
@@ -146,6 +166,62 @@ errorret_t assetChunkLoaderSync(assetloading_t *loading) {
out->meshOffsets[m][2] = endianLittleToHostFloat(out->meshOffsets[m][2]);
}
out->entitySpawnCount = data[offset];
offset += sizeof(uint8_t);
assertTrue(
out->entitySpawnCount <= CHUNK_ENTITY_SPAWN_COUNT_MAX,
"Chunk entity spawn count exceeds maximum."
);
for(uint8_t s = 0; s < out->entitySpawnCount; s++) {
chunkentityspawn_t *spawn = &out->entitySpawns[s];
spawn->kind = (chunkentityspawnkind_t)data[offset];
offset += sizeof(uint8_t);
uint16_t a;
memoryCopy(&a, data + offset, sizeof(uint16_t));
a = endianLittleToHost16(a);
offset += sizeof(uint16_t);
uint8_t b = data[offset];
offset += sizeof(uint8_t);
if(spawn->kind == CHUNK_ENTITY_SPAWN_KIND_ITEM) {
spawn->globalId = 0;
spawn->itemId = a;
spawn->itemQuantity = b;
} else {
spawn->globalId = a;
spawn->itemId = 0;
spawn->itemQuantity = 0;
}
spawn->position = assetChunkReadWorldPos(data, &offset);
}
out->areaSpawnCount = data[offset];
offset += sizeof(uint8_t);
assertTrue(
out->areaSpawnCount <= CHUNK_AREA_COUNT_MAX,
"Chunk area spawn count exceeds maximum."
);
for(uint8_t s = 0; s < out->areaSpawnCount; s++) {
chunkareaspawn_t *area = &out->areaSpawns[s];
area->min = assetChunkReadWorldPos(data, &offset);
area->max = assetChunkReadWorldPos(data, &offset);
uint16_t callbackId;
memoryCopy(&callbackId, data + offset, sizeof(uint16_t));
area->callbackId = endianLittleToHost16(callbackId);
offset += sizeof(uint16_t);
area->notify = data[offset];
offset += sizeof(uint8_t);
area->trigger = data[offset];
offset += sizeof(uint8_t);
}
memoryFree(data);
loading->loading.chunk.data = NULL;
+28 -1
View File
@@ -9,7 +9,7 @@
#include "asset/assetfile.h"
#include "rpg/overworld/chunk.h"
#define ASSET_CHUNK_FILE_VERSION 4
#define ASSET_CHUNK_FILE_VERSION 5
typedef struct assetloading_s assetloading_t;
typedef struct assetentry_s assetentry_t;
@@ -33,12 +33,39 @@ typedef struct {
uint8_t modelIndex;
} assetchunkloaderloading_t;
typedef enum {
CHUNK_ENTITY_SPAWN_KIND_GLOBAL,
CHUNK_ENTITY_SPAWN_KIND_ITEM
} chunkentityspawnkind_t;
typedef struct {
chunkentityspawnkind_t kind;
uint16_t globalId; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_GLOBAL.
uint16_t itemId; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_ITEM.
uint8_t itemQuantity; // Valid when kind == CHUNK_ENTITY_SPAWN_KIND_ITEM.
worldpos_t position;
} chunkentityspawn_t;
typedef struct {
worldpos_t min;
worldpos_t max;
uint16_t callbackId; // Index into MAP_AREA_CALLBACK_LIST.
uint8_t notify;
uint8_t trigger;
} chunkareaspawn_t;
typedef struct {
tile_t *tiles;
uint8_t meshCount;
char_t modelNames[CHUNK_MESH_COUNT_MAX][CHUNK_MESH_NAME_MAX];
vec3 meshOffsets[CHUNK_MESH_COUNT_MAX];
assetentry_t *modelEntries[CHUNK_MESH_COUNT_MAX];
uint8_t entitySpawnCount;
chunkentityspawn_t entitySpawns[CHUNK_ENTITY_SPAWN_COUNT_MAX];
uint8_t areaSpawnCount;
chunkareaspawn_t areaSpawns[CHUNK_AREA_COUNT_MAX];
} assetchunkoutput_t;
/**
+3 -2
View File
@@ -37,7 +37,7 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorChain(systemInit());
errorChain(inputInit());
errorChain(assetInit());
// errorChain(saveInit());
errorChain(saveInit());
errorChain(localeManagerInit());
errorChain(displayInit());
errorChain(uiInit());
@@ -62,6 +62,7 @@ errorret_t engineInit(const int32_t argc, const char_t **argv) {
errorret_t engineUpdate(void) {
// Order here is important.
errorChain(networkUpdate());
errorChain(saveUpdate());
timeUpdate();
inputUpdate();
consoleUpdate();
@@ -88,7 +89,7 @@ errorret_t engineDispose(void) {
errorChain(uiDispose());
consoleDispose();
errorChain(displayDispose());
// errorChain(saveDispose());
errorChain(saveDispose());
errorChain(assetDispose());
errorOk();
-1
View File
@@ -17,7 +17,6 @@ input_t INPUT;
errorret_t inputInit(void) {
memoryZero(&INPUT, sizeof(input_t));
INPUT.deadzone = INPUT_DEADZONE_DEFAULT;
for(uint8_t i = 0; i < INPUT_ACTION_COUNT; i++) {
INPUT.actions[i].action = (inputaction_t)i;
-4
View File
@@ -12,15 +12,11 @@
#define INPUT_LISTENER_PRESSED_MAX 16
#define INPUT_LISTENER_RELEASED_MAX INPUT_LISTENER_PRESSED_MAX
#define INPUT_DEADZONE_DEFAULT 0.1f
typedef struct {
inputactiondata_t actions[INPUT_ACTION_COUNT];
inputplatform_t platform;
/** User-configured gamepad axis deadzone (0.0f to 1.0f). */
float_t deadzone;
} input_t;
extern input_t INPUT;
+13 -1
View File
@@ -10,6 +10,7 @@
#include "util/memory.h"
#include "time/time.h"
#include "util/math.h"
#include "console/console.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/maparea.h"
#include "rpg/overworld/chunk.h"
@@ -292,7 +293,10 @@ void entitySetChunk(entity_t *entity, const uint8_t chunkIndex) {
}
}
entity->chunkIndex = chunkIndex;
// Only claim the new chunk once actually inserted into one of its slots -
// otherwise entity->chunkIndex would point at a chunk that doesn't know
// about this entity, so it would never be torn down on unload.
entity->chunkIndex = 0xFF;
if(chunkIndex != 0xFF) {
chunk_t *next = mapGetChunk(chunkIndex);
@@ -300,8 +304,16 @@ void entitySetChunk(entity_t *entity, const uint8_t chunkIndex) {
for(uint8_t i = 0; i < CHUNK_ENTITY_COUNT_MAX; i++) {
if(next->entities[i] != 0xFF) continue;
next->entities[i] = entity->id;
entity->chunkIndex = chunkIndex;
break;
}
if(entity->chunkIndex != chunkIndex) {
consolePrint(
"entitySetChunk: chunk %u has no free entity slots, entity %u "
"left untracked",
chunkIndex, entity->id
);
}
}
}
}
+4 -1
View File
@@ -142,7 +142,10 @@ uint8_t entityGetAvailable();
/**
* Assigns an entity to a chunk, removing it from its current chunk first.
* Pass 0xFF as chunkIndex to detach the entity from any chunk.
* Pass 0xFF as chunkIndex to detach the entity from any chunk. If the
* target chunk has no free entity slots, the entity is left detached
* (chunkIndex 0xFF) rather than assigned to a chunk that isn't actually
* tracking it - entityUpdateChunk will keep retrying on subsequent moves.
*
* @param entity Pointer to the entity.
* @param chunkIndex Index of the chunk to assign to, or 0xFF for none.
@@ -6,4 +6,5 @@
# Sources
target_sources(${DUSK_LIBRARY_TARGET_NAME}
PUBLIC
globalitemstore.c
)
@@ -0,0 +1,25 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#include "globalitemstore.h"
#include "assert/assert.h"
bool_t globalItemStoreIsCollected(
const savefile_t *file, const entityglobalid_t id
) {
assertNotNull(file, "Save file cannot be NULL");
assertTrue(id < SAVE_GLOBAL_ITEM_COUNT_MAX, "Global item ID out of range");
return file->globalItemCollected[id];
}
void globalItemStoreSetCollected(
savefile_t *file, const entityglobalid_t id, const bool_t collected
) {
assertNotNull(file, "Save file cannot be NULL");
assertTrue(id < SAVE_GLOBAL_ITEM_COUNT_MAX, "Global item ID out of range");
file->globalItemCollected[id] = collected;
}
@@ -0,0 +1,40 @@
/**
* 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 "save/savefile.h"
#include "rpg/entity/entity.h"
/**
* Checks whether the global entity with the given ID has already been
* marked collected in the given save file's data - e.g. so a global item
* entity's init callback (see rpg/entity/global/entitygloballist.h) can
* skip spawning itself if the player already picked it up in a prior
* session, without needing to keep the entity itself alive to remember
* that (which would need render/collision special-casing - this doesn't).
*
* @param file The save file to check.
* @param id The global entity ID to check.
* @return True if already marked collected.
*/
bool_t globalItemStoreIsCollected(
const savefile_t *file, const entityglobalid_t id
);
/**
* Marks the global entity with the given ID as collected (or not) in the
* given save file's data. Does not itself write the save to disk - call
* saveWrite() separately once ready to persist it.
*
* @param file The save file to write into.
* @param id The global entity ID to mark.
* @param collected The new collected state.
*/
void globalItemStoreSetCollected(
savefile_t *file, const entityglobalid_t id, const bool_t collected
);
+2
View File
@@ -14,3 +14,5 @@ target_sources(${DUSK_LIBRARY_TARGET_NAME}
tileshape.c
)
add_subdirectory(global)
+9
View File
@@ -12,6 +12,8 @@
#define CHUNK_MESH_COUNT_MAX 10
#define CHUNK_MESH_NAME_MAX 64
#define CHUNK_ENTITY_COUNT_MAX 10
#define CHUNK_ENTITY_SPAWN_COUNT_MAX 8
#define CHUNK_AREA_COUNT_MAX 4
typedef struct assetentry_s assetentry_t;
@@ -28,6 +30,13 @@ typedef struct chunk_s {
assetentry_t *modelEntries[CHUNK_MESH_COUNT_MAX];
uint8_t entities[CHUNK_ENTITY_COUNT_MAX];
// Map area IDs (into MAP_AREAS) spawned from this chunk's file data.
// Removed via mapAreaRemove when this chunk unloads, and re-added if it
// streams back in - unlike entities (tracked by current position via
// entities[] above), areas have no position-based ownership mechanism of
// their own, so the owning chunk must track and tear them down directly.
uint8_t areas[CHUNK_AREA_COUNT_MAX];
} chunk_t;
/**
@@ -0,0 +1,9 @@
# 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
)
@@ -0,0 +1,17 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "mapareaglobaldefs.h"
#include "mapareagloballist.h"
#define MAP_AREA_CALLBACK_LIST_COUNT ( \
sizeof(MAP_AREA_CALLBACK_LIST) / \
sizeof(MAP_AREA_CALLBACK_LIST[0]) \
)
//EOF
@@ -0,0 +1,17 @@
/**
* Copyright (c) 2026 Dominic Masters
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
#pragma once
#include "rpg/overworld/maparea.h"
#define MAP_AREA_CALLBACK(id) \
static void MAP_AREA_CALLBACK_##id(entity_t *entity, const uint8_t trigger)
#define MAP_AREA_CALLBACK_REF(id) \
MAP_AREA_CALLBACK_##id
//EOF
@@ -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 "mapareaglobaldefs.h"
#include "console/console.h"
MAP_AREA_CALLBACK(1) {
consolePrint("mapAreaGlobalCallback 1: trigger=%u", trigger);
}
// Index 0 is reserved (not a valid callback ID) - see mapAreaAddGlobal.
static const mapareacallback_t MAP_AREA_CALLBACK_LIST[] = {
NULL,
MAP_AREA_CALLBACK_REF(1),
};
//EOF
+84 -12
View File
@@ -14,9 +14,20 @@
#include "event/event.h"
#include "util/string.h"
#include "rpg/entity/global/entityglobal.h"
#include "rpg/entity/item/entityitem.h"
#include "rpg/overworld/maparea.h"
map_t MAP;
// Clears chunk's mid-load slot, if it currently holds one.
static void mapChunkLoadingSlotClear(chunk_t *chunk) {
for(uint32_t i = 0; i < MAP_CHUNK_LOAD_CONCURRENCY; i++) {
if(MAP.loadingChunks[i] != chunk) continue;
MAP.loadingChunks[i] = NULL;
return;
}
}
errorret_t mapInit() {
memoryZero(&MAP, sizeof(map_t));
MAP.loaded = true;
@@ -105,7 +116,7 @@ errorret_t mapDispose() {
void mapChunkUnload(chunk_t *chunk) {
mapChunkLoadQueueRemove(chunk);
if(MAP.loadingChunk == chunk) MAP.loadingChunk = NULL;
mapChunkLoadingSlotClear(chunk);
for(uint8_t i = 0; i < CHUNK_ENTITY_COUNT_MAX; i++) {
if(chunk->entities[i] == 0xFF) continue;
@@ -119,6 +130,12 @@ void mapChunkUnload(chunk_t *chunk) {
memorySet(chunk->entities, 0xFF, sizeof(chunk->entities));
for(uint8_t i = 0; i < CHUNK_AREA_COUNT_MAX; i++) {
if(chunk->areas[i] == 0xFF) continue;
mapAreaRemove(chunk->areas[i]);
}
memorySet(chunk->areas, 0xFF, sizeof(chunk->areas));
if(chunk->dcfEntry != NULL) {
eventUnsubscribe(&chunk->dcfEntry->onLoaded, mapChunkLoaded);
eventUnsubscribe(&chunk->dcfEntry->onError, mapChunkLoadError);
@@ -139,7 +156,7 @@ errorret_t mapChunkLoad(chunk_t *chunk) {
if(!mapIsLoaded()) errorThrow("No map loaded");
mapChunkLoadQueueRemove(chunk);
if(MAP.loadingChunk == chunk) MAP.loadingChunk = NULL;
mapChunkLoadingSlotClear(chunk);
if(chunk->dcfEntry != NULL) {
eventUnsubscribe(&chunk->dcfEntry->onLoaded, mapChunkLoaded);
@@ -149,6 +166,16 @@ errorret_t mapChunkLoad(chunk_t *chunk) {
}
memorySet(chunk->entities, 0xFF, sizeof(chunk->entities));
// Normally already empty (mapChunkUnload clears these before a chunk is
// handed back for reuse), but cleared defensively here too so a reload
// never leaks a MAP_AREAS slot referenced by a stale owned area ID.
for(uint8_t i = 0; i < CHUNK_AREA_COUNT_MAX; i++) {
if(chunk->areas[i] == 0xFF) continue;
mapAreaRemove(chunk->areas[i]);
}
memorySet(chunk->areas, 0xFF, sizeof(chunk->areas));
chunk->meshCount = 0;
char_t name[64];
@@ -178,7 +205,8 @@ errorret_t mapChunkLoad(chunk_t *chunk) {
}
void mapChunkLoadNext() {
if(MAP.loadingChunk != NULL) return;
for(uint32_t slot = 0; slot < MAP_CHUNK_LOAD_CONCURRENCY; slot++) {
if(MAP.loadingChunks[slot] != NULL) continue;
if(MAP.loadQueueCount == 0) return;
chunk_t *chunk = MAP.loadQueue[0];
@@ -186,7 +214,7 @@ void mapChunkLoadNext() {
MAP.loadQueue[i - 1] = MAP.loadQueue[i];
}
MAP.loadQueueCount--;
MAP.loadingChunk = chunk;
MAP.loadingChunks[slot] = chunk;
char_t name[64];
stringFormat(
@@ -201,22 +229,25 @@ void mapChunkLoadNext() {
assertNotNull(entry, "Failed to get chunk asset entry");
chunk->dcfEntry = entry;
// The entry may already be resident from an earlier load that hasn't been
// reaped yet - in that case onLoaded/onError already fired once and never
// will again, so handle the terminal state directly instead of waiting on
// a subscription that would never trigger.
// The entry may already be resident from an earlier load that hasn't
// been reaped yet - in that case onLoaded/onError already fired once
// and never will again, so handle the terminal state directly instead
// of waiting on a subscription that would never trigger. Both of these
// recurse back into mapChunkLoadNext once they clear this slot, so the
// outer loop just continues on to try filling the next one.
if(entry->state == ASSET_ENTRY_STATE_LOADED) {
mapChunkLoaded(entry, chunk);
return;
continue;
}
if(entry->state == ASSET_ENTRY_STATE_ERROR) {
mapChunkLoadError(entry, chunk);
return;
continue;
}
eventSubscribe(&entry->onLoaded, mapChunkLoaded, chunk);
eventSubscribe(&entry->onError, mapChunkLoadError, chunk);
}
}
void mapChunkLoadQueueRemove(chunk_t *chunk) {
for(uint32_t i = 0; i < MAP.loadQueueCount; i++) {
@@ -372,7 +403,7 @@ void mapChunkLoadError(void *params, void *user) {
chunk->dcfEntry = NULL;
memorySet(chunk->tiles, 0x00, sizeof(chunk->tiles));
if(MAP.loadingChunk == chunk) MAP.loadingChunk = NULL;
mapChunkLoadingSlotClear(chunk);
mapChunkLoadNext();
}
@@ -433,6 +464,47 @@ void mapChunkLoaded(void *params, void *user) {
// this chunk_t is displaying it. Released in mapChunkUnload instead.
chunk->meshCount = meshCount;
if(MAP.loadingChunk == chunk) MAP.loadingChunk = NULL;
// Spawn entities declared by this chunk's file. Global entities are
// deduped by mapSpawnEntity itself (a persistent NPC that streams back
// in won't be duplicated); item entities have no persistent identity, so
// each reload spawns a fresh one - picking an item up and then leaving
// and re-entering its chunk will currently respawn it, since nothing
// tracks "already collected" across a chunk unload/reload yet.
for(uint8_t s = 0; s < entry->data.chunk.entitySpawnCount; s++) {
chunkentityspawn_t *spawn = &entry->data.chunk.entitySpawns[s];
if(spawn->kind == CHUNK_ENTITY_SPAWN_KIND_GLOBAL) {
mapSpawnEntity((entityglobalid_t)spawn->globalId, spawn->position);
continue;
}
uint8_t index = entityGetAvailable();
assertTrue(index != 0xFF, "No available entity slots for chunk spawn");
entity_t *itemEntity = &ENTITIES[index];
entityInit(itemEntity, ENTITY_TYPE_ITEM);
entityItemSet(
itemEntity, (itemid_t)spawn->itemId, spawn->itemQuantity
);
entityPositionSet(itemEntity, spawn->position);
}
// Spawn map areas declared by this chunk's file, tracked as owned by
// this chunk so mapChunkUnload can tear them down again.
for(uint8_t s = 0; s < entry->data.chunk.areaSpawnCount; s++) {
chunkareaspawn_t *area = &entry->data.chunk.areaSpawns[s];
uint8_t areaId = mapAreaAddGlobal(
area->min, area->max, area->callbackId, area->notify, area->trigger
);
uint8_t slot = 0xFF;
for(uint8_t i = 0; i < CHUNK_AREA_COUNT_MAX; i++) {
if(chunk->areas[i] != 0xFF) continue;
slot = i;
break;
}
assertTrue(slot != 0xFF, "Chunk has no free owned-area slots");
chunk->areas[slot] = areaId;
}
mapChunkLoadingSlotClear(chunk);
mapChunkLoadNext();
}
+8 -6
View File
@@ -12,6 +12,10 @@
#define MAP_FILE_PATH_MAX 128
// Number of chunks that may be mid-load (asset locked & awaiting onLoaded/
// onError) at the same time - everything past this waits in loadQueue.
#define MAP_CHUNK_LOAD_CONCURRENCY 2
typedef struct map_s {
bool_t loaded;
@@ -19,11 +23,9 @@ typedef struct map_s {
chunk_t *chunkOrder[MAP_CHUNK_COUNT];
chunkpos_t chunkPosition;
// Only one chunk may be mid-load (asset locked & awaiting onLoaded/
// onError) at any given time - everything else waits here in FIFO order.
chunk_t *loadQueue[MAP_CHUNK_COUNT];
uint32_t loadQueueCount;
chunk_t *loadingChunk;
chunk_t *loadingChunks[MAP_CHUNK_LOAD_CONCURRENCY];
} map_t;
extern map_t MAP;
@@ -80,9 +82,9 @@ void mapChunkUnload(chunk_t* chunk);
errorret_t mapChunkLoad(chunk_t* chunk);
/**
* Starts loading the next queued chunk, if no chunk is currently mid-load.
* Called after mapChunkLoad enqueues a chunk, and again after the
* currently-loading chunk finishes (or is unloaded) to advance the queue.
* Starts loading queued chunks until MAP_CHUNK_LOAD_CONCURRENCY chunks are
* mid-load. Called after mapChunkLoad enqueues a chunk, and again after a
* mid-load chunk finishes (or is unloaded) to advance the queue.
*/
void mapChunkLoadNext();
+18
View File
@@ -10,6 +10,7 @@
#include "util/math.h"
#include "util/memory.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/global/mapareaglobal.h"
maparea_t MAP_AREAS[MAP_AREA_COUNT_MAX];
@@ -148,3 +149,20 @@ void mapAreaCheckEntity(entity_t *entity) {
void mapAreaNoopCallback(entity_t *entity, const uint8_t trigger) {
}
uint8_t mapAreaAddGlobal(
const worldpos_t min,
const worldpos_t max,
const uint16_t callbackId,
const uint8_t notify,
const uint8_t trigger
) {
assertTrue(callbackId > 0, "Map area callback ID 0 is reserved");
assertTrue(
callbackId < MAP_AREA_CALLBACK_LIST_COUNT,
"Map area callback ID is out of range"
);
return mapAreaAdd(
min, max, MAP_AREA_CALLBACK_LIST[callbackId], notify, trigger
);
}
+25
View File
@@ -159,3 +159,28 @@ void mapAreaCheckEntity(entity_t *entity);
* @param trigger Which MAP_TRIGGER_* condition invoked the callback.
*/
void mapAreaNoopCallback(entity_t *entity, const uint8_t trigger);
/**
* Adds a map area using a compiled-in callback referenced by ID (see
* MAP_AREA_CALLBACK_LIST in rpg/overworld/global/mapareagloballist.h),
* rather than a direct function pointer. This is what lets chunk file
* data - which can only reference compiled code by a small integer ID,
* not a function pointer - declare map areas.
*
* @param min The minimum world position of the area.
* @param max The maximum world position of the area.
* @param callbackId Index into MAP_AREA_CALLBACK_LIST. Must be greater
* than 0 (0 is reserved) and within range.
* @param notify Bitwise MAP_AREA_NOTIFY_* flags for which entity types
* should trigger the callback.
* @param trigger Bitwise MAP_TRIGGER_* flags for which conditions should
* invoke the callback.
* @returns The ID of the newly added map area.
*/
uint8_t mapAreaAddGlobal(
const worldpos_t min,
const worldpos_t max,
const uint16_t callbackId,
const uint8_t notify,
const uint8_t trigger
);
+21 -27
View File
@@ -7,12 +7,9 @@
#include "rpg.h"
#include "entity/entity.h"
#include "rpg/entity/npc/npcpath.h"
#include "rpg/entity/item/entityitem.h"
#include "rpg/overworld/map.h"
#include "rpg/overworld/maparea.h"
#include "rpg/cutscene/cutscenesystem.h"
#include "rpg/cutscene/scene/testcutscene.h"
#include "rpg/item/backpack.h"
#include "rpg/battle/party.h"
#include "ui/rpg/textbox/uitextboxminilist.h"
@@ -21,18 +18,25 @@
#include "util/memory.h"
#include "util/string.h"
#include "assert/assert.h"
#include "console/console.h"
#include "save/save.h"
#include "error/error.h"
#include "ui/rpg/uiemoji.h"
#include "rpg/story/storyflag.h"
void rpgTestAreaCallback(entity_t *entity, const uint8_t trigger) {
consolePrint("rpgTestAreaCallback: trigger=%u", trigger);
static void rpgTestSaveComplete(errorret_t result, void *user) {
if(errorIsNotOk(result)) errorCatch(errorPrint(result));
}
errorret_t rpgInit(void) {
memoryZero(ENTITIES, sizeof(ENTITIES));
memoryZero(MAP_AREAS, sizeof(MAP_AREAS));
// Must run before any code reads a story flag - stamps CSV-defined
// defaults onto the active save slot if it's never actually been
// loaded from disk yet.
storyFlagInitDefaults(saveGet(SAVE_ACTIVE_SLOT));
backpackInit();
partyInit();
cutsceneSystemInit();
@@ -43,7 +47,9 @@ errorret_t rpgInit(void) {
// Init world
errorChain(mapPositionSet((chunkpos_t){ 0, 0, 0 }));
// TEST: Create some entities.
// The player is the one entity that isn't sourced from map/chunk data -
// every other entity (NPCs, items) and map area comes from the loaded
// chunks' own spawn data (see rpg/overworld/map.c mapChunkLoaded).
uint8_t entIndex = entityGetAvailable();
assertTrue(entIndex != 0xFF, "No available entity slots!.");
entity_t *ent = &ENTITIES[entIndex];
@@ -52,30 +58,18 @@ errorret_t rpgInit(void) {
RPG_CAMERA.mode = RPG_CAMERA_MODE_FOLLOW_ENTITY;
RPG_CAMERA.followEntity.followEntityId = ent->id;
mapSpawnEntity(3, (worldpos_t){ 8, 8, 1 });
// TEST: Place an item entity.
uint8_t itemEntIndex = entityGetAvailable();
assertTrue(itemEntIndex != 0xFF, "No available entity slots!.");
entity_t *itemEnt = &ENTITIES[itemEntIndex];
entityInit(itemEnt, ENTITY_TYPE_ITEM);
entityItemSet(itemEnt, ITEM_ID_POTION, 1);
entityPositionSet(itemEnt, (worldpos_t){ 12, 2, 0 });
// TEST: Give the player a starting assortment of items.
// Starting inventory.
backpackAdd(ITEM_ID_POTION, 5);
backpackAdd(ITEM_ID_POTATO, 3);
backpackAdd(ITEM_ID_APPLE, 8);
// TEST: Create a test map area.
uint8_t areaIndex = mapAreaAdd(
(worldpos_t){ 11, 3, 0 },
(worldpos_t){ 16, 9, 10 },
rpgTestAreaCallback,
MAP_AREA_NOTIFY_ALL,
MAP_TRIGGER_ENTER | MAP_TRIGGER_EXIT
);
assertTrue(areaIndex != 0xFF, "No available map area slots!.");
// TEST: Verify the save system round-trips real game data, not just the
// header/version. Remove once there's an actual name-entry flow. On PSP
// this shows the real native save dialog every boot - expected while
// testing that path, not something to ship as-is.
savefile_t *saveFile = saveGet(SAVE_ACTIVE_SLOT);
stringCopy(saveFile->playerName, "Dusk", SAVE_PLAYER_NAME_MAX);
saveWrite(SAVE_ACTIVE_SLOT, rpgTestSaveComplete, NULL);
// All Good!
errorOk();
+13 -1
View File
@@ -10,5 +10,17 @@
void storyFlagSet(const storyflag_t flag, const storyflagvalue_t value) {
assertTrue(flag > STORY_FLAG_NULL && flag < STORY_FLAG_COUNT, "Bad Flag");
STORY_FLAG_VALUES[flag] = value;
saveGet(SAVE_ACTIVE_SLOT)->storyFlags[flag] = value;
}
void storyFlagInitDefaults(savefile_t *file) {
assertNotNull(file, "Save file cannot be NULL");
if(file->exists) return;
assertTrue(
STORY_FLAG_COUNT <= SAVE_STORY_FLAG_COUNT_MAX,
"Too many story flags for the save format - bump SAVE_STORY_FLAG_COUNT_MAX"
);
for(storyflag_t i = 0; i < STORY_FLAG_COUNT; i++) {
file->storyFlags[i] = STORY_FLAG_DEFAULTS[i];
}
}
+18 -3
View File
@@ -7,19 +7,34 @@
#pragma once
#include "rpg/story/storyflagvalue.h"
#include "save/save.h"
/**
* Gets the value of a story flag.
* Gets the value of a story flag. Reads directly from the active save
* file (see SAVE_ACTIVE_SLOT) - flag values have no separate live copy.
*
* @param flag The story flag to get.
* @return The value of the story flag.
*/
#define storyFlagGet(flag) (STORY_FLAG_VALUES[(flag)])
#define storyFlagGet(flag) (saveGet(SAVE_ACTIVE_SLOT)->storyFlags[(flag)])
/**
* Sets the value of a story flag.
* Sets the value of a story flag, directly in the active save file (see
* SAVE_ACTIVE_SLOT). Does not itself write the save to disk - call
* saveWrite() separately once ready to persist it.
*
* @param flag The story flag to set.
* @param value The value to set the story flag to.
*/
void storyFlagSet(const storyflag_t flag, const storyflagvalue_t value);
/**
* Stamps each story flag's CSV-defined default (STORY_FLAG_DEFAULTS) onto
* the given save file, but only if it hasn't actually been loaded from
* disk yet (file->exists is false) - otherwise leaves already-played
* progress alone. Call once, e.g. during rpgInit(), before any gameplay
* code reads a story flag.
*
* @param file The save file to stamp defaults onto.
*/
void storyFlagInitDefaults(savefile_t *file);
+75 -17
View File
@@ -9,19 +9,38 @@
#include "save/savestream.h"
#include "util/memory.h"
#include "assert/assert.h"
#include "error/error.h"
save_t SAVE;
errorret_t saveInit(void) {
memoryZero(&SAVE, sizeof(save_t));
// Establishes the default for a slot that hasn't actually been loaded
// from disk yet - saveLoad() overwrites this the moment a real file is
// found, so this only matters for a brand new save.
for(uint8_t i = 0; i < SAVE_FILE_COUNT_MAX; i++) {
SAVE.files[i].deadzone = SAVE_DEADZONE_DEFAULT;
}
#ifdef saveInitPlatform
errorChain(saveInitPlatform());
// A missing/unreachable save medium is expected, recoverable state,
// not a reason to fail booting the whole game - log it and carry on
// with SAVE.available false instead of chaining the error upward.
errorret_t result = saveInitPlatform();
SAVE.available = errorIsOk(result);
if(!SAVE.available) errorCatch(errorPrint(result));
#else
SAVE.available = false;
#endif
errorOk();
}
bool_t saveIsAvailable(void) {
return SAVE.available;
}
errorret_t saveDispose(void) {
#ifdef saveDisposePlatform
errorChain(saveDisposePlatform());
@@ -29,20 +48,46 @@ errorret_t saveDispose(void) {
errorOk();
}
errorret_t saveLoad(const uint8_t slot) {
errorret_t saveUpdate(void) {
#ifdef savePlatformUpdate
errorChain(savePlatformUpdate());
#endif
errorOk();
}
bool_t saveIsBusy(void) {
#ifdef saveIsBusyPlatform
return saveIsBusyPlatform();
#else
return false;
#endif
}
void saveLoad(const uint8_t slot, savecallback_t onComplete, void *user) {
assertTrue(slot < SAVE_FILE_COUNT_MAX, "slot exceeds SAVE_FILE_COUNT_MAX");
assertNotNull(onComplete, "onComplete cannot be NULL");
savefile_t *file = &SAVE.files[slot];
file->exists = false;
// Some platforms (PSP's native save dialog) can't complete within this
// call - they take over entirely and invoke onComplete later, from
// saveUpdate(), once their own multi-frame flow finishes.
#ifdef saveAsyncLoadPlatform
saveAsyncLoadPlatform(slot, onComplete, user);
return;
#endif
savestream_t stream;
memoryZero(&stream, sizeof(savestream_t));
#ifdef saveStreamOpenReadPlatform
errorChain(saveStreamOpenReadPlatform(&stream, slot));
errorret_t openRet = saveStreamOpenReadPlatform(&stream, slot);
SAVE.available = errorIsOk(openRet);
if(errorIsNotOk(openRet)) { onComplete(openRet, user); return; }
#endif
if(!stream.found) errorOk();
if(!stream.found) { onComplete(errorOkImpl(), user); return; }
errorret_t ret = saveFileLoad(&stream, file);
@@ -50,24 +95,37 @@ errorret_t saveLoad(const uint8_t slot) {
saveStreamClosePlatform(&stream);
#endif
if(errorIsNotOk(ret)) return ret;
errorChain(saveStreamVerifyChecksumImpl(&stream, slot));
file->exists = true;
errorOk();
if(errorIsOk(ret)) ret = saveStreamVerifyChecksumImpl(&stream, slot);
file->exists = errorIsOk(ret);
onComplete(ret, user);
}
errorret_t saveWrite(const uint8_t slot) {
void saveWrite(const uint8_t slot, savecallback_t onComplete, void *user) {
assertTrue(slot < SAVE_FILE_COUNT_MAX, "slot exceeds SAVE_FILE_COUNT_MAX");
assertNotNull(onComplete, "onComplete cannot be NULL");
savefile_t *file = &SAVE.files[slot];
// These are metadata about the file itself, not game data - always stamp
// the current magic/version on every write rather than relying on
// whatever happened to already be in memory (zeroed at saveInit, or
// whatever version an old loaded file had), otherwise the written file
// fails its own header check the next time it's loaded.
memoryCopy(file->header, SAVE_FILE_HEADER, SAVE_FILE_HEADER_SIZE);
file->version = SAVE_FILE_VERSION;
// See saveLoad() - some platforms take over and complete later.
#ifdef saveAsyncWritePlatform
saveAsyncWritePlatform(slot, onComplete, user);
return;
#endif
savestream_t stream;
memoryZero(&stream, sizeof(savestream_t));
#ifdef saveStreamOpenWritePlatform
errorChain(saveStreamOpenWritePlatform(&stream, slot));
errorret_t openRet = saveStreamOpenWritePlatform(&stream, slot);
SAVE.available = errorIsOk(openRet);
if(errorIsNotOk(openRet)) { onComplete(openRet, user); return; }
#endif
errorret_t ret = saveFileWrite(&stream, file);
@@ -80,17 +138,17 @@ errorret_t saveWrite(const uint8_t slot) {
saveStreamClosePlatform(&stream);
#endif
if(errorIsNotOk(ret)) return ret;
file->exists = true;
errorOk();
file->exists = errorIsOk(ret);
onComplete(ret, user);
}
errorret_t saveDelete(const uint8_t slot) {
assertTrue(slot < SAVE_FILE_COUNT_MAX, "slot exceeds SAVE_FILE_COUNT_MAX");
#ifdef saveDeletePlatform
errorChain(saveDeletePlatform(slot));
errorret_t deleteRet = saveDeletePlatform(slot);
SAVE.available = errorIsOk(deleteRet);
errorChain(deleteRet);
#endif
SAVE.files[slot].exists = false;
+67 -9
View File
@@ -15,17 +15,46 @@ typedef struct {
savefile_t files[SAVE_FILE_COUNT_MAX];
/** Platform-specific save system state (paths, card handles, etc.). */
saveplatform_t platform;
/**
* True if the save medium (memory card/stick/disk) was reachable the
* last time it was checked - at saveInit(), and refreshed by every
* subsequent saveLoad()/saveWrite() attempt. Starting the game with no
* card/stick inserted, or one being removed mid-session, are both
* expected conditions here, not fatal errors - see saveIsAvailable().
*/
bool_t available;
/**
* Scratch error state used by platforms whose save/load completes
* asynchronously (see saveIsBusy()) to construct a result to hand to a
* savecallback_t from inside saveUpdate(), rather than from a direct
* errorThrow() return - mirrors network_t.errorState for the same reason.
*/
errorstate_t errorState;
} save_t;
extern save_t SAVE;
/**
* Initializes the save system.
* Initializes the save system. Never fails the way saveWrite/saveLoad can -
* if the platform's save medium isn't reachable (e.g. no memory card/stick
* inserted), that's logged and reflected in saveIsAvailable() rather than
* treated as fatal, since the game should still be playable without save
* support.
*
* @return An error code if initialization fails.
* @return An error code only for unexpected platform failures.
*/
errorret_t saveInit(void);
/**
* Checks whether the save medium was reachable as of the last save/load
* attempt (or saveInit(), if none has been attempted yet). Intended for UI
* to decide whether to offer saving/loading at all, or to explain why it
* isn't available right now - e.g. "No memory card inserted".
*
* @return true if the save medium was available last time it was checked.
*/
bool_t saveIsAvailable(void);
/**
* Disposes of the save system.
*
@@ -34,20 +63,49 @@ errorret_t saveInit(void);
errorret_t saveDispose(void);
/**
* Loads the save file for a given slot from persistent storage.
* Updates the save manager, pumping any in-progress async save/load and
* dispatching its callback once complete. No-op on platforms where
* saveWrite()/saveLoad() always complete synchronously (see saveIsBusy()).
* Must be called every engine frame for platforms that need it (PSP's
* native save dialog spans multiple frames).
*
* @param slot The save slot index (0 to SAVE_FILE_COUNT_MAX - 1).
* @return An error code if the load fails.
* @return An error code indicating success or failure.
*/
errorret_t saveLoad(const uint8_t slot);
errorret_t saveUpdate(void);
/**
* Writes the save file for a given slot to persistent storage.
* True while an async saveWrite()/saveLoad() is in progress (e.g. PSP's
* native save dialog is open). Calling saveWrite()/saveLoad() again while
* this is true is undefined behavior - wait for the previous call's
* callback first.
*
* @return True if a save/load request is currently in progress.
*/
bool_t saveIsBusy(void);
/**
* Loads the save file for a given slot from persistent storage. Slow/async
* on some platforms (PSP's native save dialog spans multiple frames) - on
* others (Linux, Dolphin) onComplete is invoked before this call returns.
* See saveIsBusy().
*
* @param slot The save slot index (0 to SAVE_FILE_COUNT_MAX - 1).
* @return An error code if the write fails.
* @param onComplete Callback invoked with the result once loading finishes.
* @param user User data passed through to onComplete.
*/
errorret_t saveWrite(const uint8_t slot);
void saveLoad(const uint8_t slot, savecallback_t onComplete, void *user);
/**
* Writes the save file for a given slot to persistent storage. Slow/async
* on some platforms (PSP's native save dialog spans multiple frames) - on
* others (Linux, Dolphin) onComplete is invoked before this call returns.
* See saveIsBusy().
*
* @param slot The save slot index (0 to SAVE_FILE_COUNT_MAX - 1).
* @param onComplete Callback invoked with the result once writing finishes.
* @param user User data passed through to onComplete.
*/
void saveWrite(const uint8_t slot, savecallback_t onComplete, void *user);
/**
* Deletes the save file for a given slot from persistent storage.
+65
View File
@@ -20,6 +20,44 @@
/** Maximum number of independent save slots supported. */
#define SAVE_FILE_COUNT_MAX 3
/**
* The save slot actually used for gameplay right now - there's no slot
* select/multi-save UX yet (SAVE_FILE_COUNT_MAX > 1 exists for later), so
* every part of the game that needs "the" save file (settings, the game
* menu's Save button, etc.) reads/writes this one slot.
*/
#define SAVE_ACTIVE_SLOT 0
/** Maximum length of a saved player name, including the null terminator. */
#define SAVE_PLAYER_NAME_MAX 32
/**
* Maximum number of global entities whose "collected" state can be
* tracked - see rpg/entity/global/globalitemstore.h. Bounded/fixed here
* rather than tied to ENTITY_GLOBAL_LIST_COUNT, since savefile.h is a
* leaf header with no dependency on the entity system (and no reason to
* take one just for a size constant).
*/
#define SAVE_GLOBAL_ITEM_COUNT_MAX 64
/**
* Default gamepad deadzone for a save slot that's never actually been
* loaded from disk yet (see saveInit(), which stamps this onto every
* slot up front) - defined here, rather than by the input system, since
* the save file is now the single source of truth for this value (see
* savefile_t.deadzone) - nothing else stores or defaults it.
*/
#define SAVE_DEADZONE_DEFAULT 0.1f
/**
* Maximum number of story flags the save format can hold - see
* rpg/story/storyflag.h. Bounded/fixed here (with real headroom over the
* current flag count) rather than tied to STORY_FLAG_COUNT, since
* savefile.h is a leaf header with no dependency on generated story
* content, matching SAVE_GLOBAL_ITEM_COUNT_MAX's reasoning.
*/
#define SAVE_STORY_FLAG_COUNT_MAX 128
typedef struct {
/** Magic header bytes read from the file; must equal SAVE_FILE_HEADER. */
char_t header[SAVE_FILE_HEADER_SIZE];
@@ -27,4 +65,31 @@ typedef struct {
uint32_t version;
/** Runtime flag - true if this slot was successfully loaded or written. */
bool_t exists;
/** The player's saved name. */
char_t playerName[SAVE_PLAYER_NAME_MAX];
/** Per-global-ID "already collected" flags - see globalitemstore.h. */
bool_t globalItemCollected[SAVE_GLOBAL_ITEM_COUNT_MAX];
/**
* User-configured gamepad deadzone (0.0f-1.0f) - the save file is the
* only place this lives; read it directly via saveGet(SAVE_ACTIVE_SLOT)
* ->deadzone rather than caching it anywhere else.
*/
float_t deadzone;
/**
* Story flag values, indexed by storyflag_t - the save file is the only
* place these live; read/write via storyFlagGet()/storyFlagSet() (see
* rpg/story/storyflag.h), not directly.
*/
uint8_t storyFlags[SAVE_STORY_FLAG_COUNT_MAX];
} savefile_t;
/**
* Callback invoked when an async saveWrite()/saveLoad() request completes.
* Declared here (rather than save.h) so platform save headers - which
* save.h's platform indirection pulls in before save.h finishes defining
* anything else - can reference it without a circular include.
*
* @param result Whether the request succeeded.
* @param user User data passed through from the original call.
*/
typedef void (*savecallback_t)(errorret_t result, void *user);
+16
View File
@@ -330,11 +330,27 @@ errorret_t saveStreamWriteDateImpl(
errorret_t saveFileLoad(savestream_t *stream, savefile_t *file) {
saveFileReadHeader(stream, file->header);
saveFileReadVersion(stream, &file->version);
saveFileReadString(stream, file->playerName, SAVE_PLAYER_NAME_MAX);
for(size_t i = 0; i < SAVE_GLOBAL_ITEM_COUNT_MAX; i++) {
saveFileReadBool(stream, &file->globalItemCollected[i]);
}
saveFileReadFloat(stream, &file->deadzone);
for(size_t i = 0; i < SAVE_STORY_FLAG_COUNT_MAX; i++) {
saveFileReadUInt8(stream, &file->storyFlags[i]);
}
errorOk();
}
errorret_t saveFileWrite(savestream_t *stream, savefile_t *file) {
saveFileWriteHeader(stream, file->header);
saveFileWriteVersion(stream, &file->version);
saveFileWriteString(stream, file->playerName, SAVE_PLAYER_NAME_MAX);
for(size_t i = 0; i < SAVE_GLOBAL_ITEM_COUNT_MAX; i++) {
saveFileWriteBool(stream, &file->globalItemCollected[i]);
}
saveFileWriteFloat(stream, &file->deadzone);
for(size_t i = 0; i < SAVE_STORY_FLAG_COUNT_MAX; i++) {
saveFileWriteUInt8(stream, &file->storyFlags[i]);
}
errorOk();
}
+79
View File
@@ -7,18 +7,88 @@
#include "uigamemenu.h"
#include "ui/frame/uiframe.h"
#include "ui/frame/uiconfirm.h"
#include "ui/frame/settings/uisettings.h"
#include "ui/frame/backpack/uibackpack.h"
#include "ui/rpg/textbox/uitextboxmain.h"
#include "util/memory.h"
#include "display/spritebatch/spritebatch.h"
#include "display/screen/screen.h"
#include "assert/assert.h"
#include "locale/localemanager.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "save/save.h"
#include "error/error.h"
#include "util/string.h"
#define UI_GAME_MENU_INDEX_CHARACTERS 0
#define UI_GAME_MENU_INDEX_ITEMS 1
#define UI_GAME_MENU_INDEX_SETTINGS 2
#define UI_GAME_MENU_INDEX_SAVE 3
static void uiGameMenuSaveWriteComplete(errorret_t result, void *user) {
if(errorIsNotOk(result)) {
// Generously sized - stringFormat asserts (crashes) rather than
// truncating if the message doesn't fit, so this must comfortably fit
// the longest platform save-error message plus this prefix.
char_t msg[256];
stringFormat(
msg, sizeof(msg), "Save failed: %s", result.state->message
);
errorCatch(result);
uiTextboxMainSetText(msg);
return;
}
uiTextboxMainSetText("Game saved.");
}
static void uiGameMenuSaveCreateConfirmed(const bool_t confirmed, void *user) {
if(!confirmed) {
uiTextboxMainSetText("Save cancelled.");
return;
}
saveWrite(SAVE_ACTIVE_SLOT, uiGameMenuSaveWriteComplete, NULL);
}
// Determines whether there's actually save data to overwrite (not just
// whether the medium is present) by attempting a real load first - this is
// what lets a fresh memory card/stick, with no prior save on it yet, be
// told apart from one that already has our data on it. Cheap either way
// (a single sector/file read), and correct on every platform without any
// platform-specific UI code - saveExists() already reflects each
// platform's own notion of "found something."
static void uiGameMenuSaveCheckComplete(errorret_t result, void *user) {
if(errorIsNotOk(result)) {
char_t msg[256];
stringFormat(msg, sizeof(msg), "Can't save: %s", result.state->message);
errorCatch(result);
uiTextboxMainSetText(msg);
return;
}
if(saveExists(SAVE_ACTIVE_SLOT)) {
saveWrite(SAVE_ACTIVE_SLOT, uiGameMenuSaveWriteComplete, NULL);
return;
}
uiConfirmOpen(
"No save data found. Create a new save?",
uiGameMenuSaveCreateConfirmed,
NULL
);
}
static void uiGameMenuSave(void) {
if(!saveIsAvailable()) {
uiTextboxMainSetText("Can't save - no save device found.");
return;
}
if(saveIsBusy()) return;// A save/load dialog (e.g. on PSP) is already up.
saveLoad(SAVE_ACTIVE_SLOT, uiGameMenuSaveCheckComplete, NULL);
}
uigamemenu_t UI_GAME_MENU;
@@ -29,6 +99,7 @@ void uiGameMenuSelected(
) {
if(index == UI_GAME_MENU_INDEX_ITEMS) uiBackpackOpen();
if(index == UI_GAME_MENU_INDEX_SETTINGS) uiSettingsOpen();
if(index == UI_GAME_MENU_INDEX_SAVE) uiGameMenuSave();
}
errorret_t uiGameMenuInit(void) {
@@ -55,6 +126,13 @@ errorret_t uiGameMenuInit(void) {
UI_GAME_MENU.settingsLabel,
UI_GAME_MENU_LABEL_MAX
));
errorChain(assetLocaleGetString(
&LOCALE.entry->data.locale,
"ui.game_menu.save",
0,
UI_GAME_MENU.saveLabel,
UI_GAME_MENU_LABEL_MAX
));
MENU_BEGIN(
&UI_GAME_MENU.menu, UI_GAME_MENU.items, uiGameMenuSelected, NULL, NULL
@@ -62,6 +140,7 @@ errorret_t uiGameMenuInit(void) {
MENU_BUTTON(UI_GAME_MENU.charactersLabel);
MENU_BUTTON(UI_GAME_MENU.itemsLabel);
MENU_BUTTON(UI_GAME_MENU.settingsLabel);
MENU_BUTTON(UI_GAME_MENU.saveLabel);
MENU_END(UI_GAME_MENU.items, 1);
+2 -1
View File
@@ -9,7 +9,7 @@
#include "error/error.h"
#include "ui/widget/uimenu.h"
#define UI_GAME_MENU_ITEM_COUNT 3
#define UI_GAME_MENU_ITEM_COUNT 4
#define UI_GAME_MENU_WIDTH 150.0f
#define UI_GAME_MENU_LABEL_MAX 32
@@ -19,6 +19,7 @@ typedef struct {
char_t charactersLabel[UI_GAME_MENU_LABEL_MAX];
char_t itemsLabel[UI_GAME_MENU_LABEL_MAX];
char_t settingsLabel[UI_GAME_MENU_LABEL_MAX];
char_t saveLabel[UI_GAME_MENU_LABEL_MAX];
} uigamemenu_t;
extern uigamemenu_t UI_GAME_MENU;
+5 -5
View File
@@ -11,7 +11,7 @@
#include "util/memory.h"
#include "locale/localemanager.h"
#include "asset/loader/locale/assetlocaleloader.h"
#include "input/input.h"
#include "save/save.h"
void uiSettingsInputSelected(
const uimenu_t *menu,
@@ -39,7 +39,7 @@ errorret_t uiSettingsInputInit(uisettingsdata_t *data) {
UI_SETTINGS_INPUT_LABEL_MAX
));
MENU_SLIDER_FLOAT(
input->deadzoneLabel, INPUT_DEADZONE_DEFAULT, 0.0f, 1.0f, 0.05f
input->deadzoneLabel, SAVE_DEADZONE_DEFAULT, 0.0f, 1.0f, 0.05f
);
#else
MENU_LABEL("No input settings yet");
@@ -55,14 +55,14 @@ void uiSettingsInputLoad(void) {
#ifdef DUSK_INPUT_GAMEPAD
uiSliderSetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider,
INPUT.deadzone
saveGet(SAVE_ACTIVE_SLOT)->deadzone
);
#endif
}
void uiSettingsInputApply(void) {
#ifdef DUSK_INPUT_GAMEPAD
INPUT.deadzone = uiSliderGetFloat(
saveGet(SAVE_ACTIVE_SLOT)->deadzone = uiSliderGetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider
);
#endif
@@ -73,7 +73,7 @@ bool_t uiSettingsInputHasChanges(void) {
#ifdef DUSK_INPUT_GAMEPAD
if(uiSliderGetFloat(
&UI_SETTINGS.data.input.items[UI_SETTINGS_INPUT_INDEX_DEADZONE].slider
) != INPUT.deadzone) return true;
) != saveGet(SAVE_ACTIVE_SLOT)->deadzone) return true;
#endif
return false;
+2 -1
View File
@@ -9,6 +9,7 @@
#include "assert/assert.h"
#include "log/log.h"
#include "util/string.h"
#include "save/save.h"
inputbuttondata_t INPUT_BUTTON_DATA[] = {
#ifdef DUSK_INPUT_GAMEPAD
@@ -187,5 +188,5 @@ float_t inputButtonGetValueDolphin(const inputbutton_t button) {
}
float_t inputGetDeadzoneDolphin(const inputbutton_t button) {
return 0.2f;
return saveGet(SAVE_ACTIVE_SLOT)->deadzone;
}
+99 -24
View File
@@ -9,23 +9,48 @@
#include "util/memory.h"
#include "util/string.h"
static void _saveGetFileName(
const uint8_t slot, char_t *out, const size_t max
) {
snprintf(out, max, "%s_%u", SAVE_DOLPHIN_GAME_CODE, (uint32_t)slot);
}
errorret_t saveInitDolphin(void) {
SAVE.platform.mounted = false;
int32_t result = CARD_Mount(
// Must run once before any other CARD_* call: sets up card_inited,
// the per-channel control blocks (wait queues, alarms) CARD_Mount reads,
// and initializes the DSP (needed for the card unlock sequence).
// Skipping this leaves those structures unset, so CARD_Mount ends up
// touching hardware state that was never brought up -- e.g. Dolphin's
// "Trying to read 32 bits from an invalid MMIO" error -- rather than
// failing cleanly with a CARD_ERROR_* code.
int32_t result = CARD_Init(SAVE_DOLPHIN_GAME_CODE, NULL);
if(result < 0) {
errorThrow("Failed to initialize memory card subsystem: %s (%d)",
saveCardErrorStringDolphin(result), result
);
}
do {
result = CARD_Mount(
SAVE_DOLPHIN_CHANNEL,
SAVE.platform.cardBuffer,
NULL
);
} while(result == CARD_ERROR_BUSY);
// Special-case the failures a player can actually act on; everything
// else falls through to the generic, fully-enumerated message below.
switch(result) {
case CARD_ERROR_NOCARD:
errorThrow("No memory card inserted in the slot");
case CARD_ERROR_WRONGDEVICE:
errorThrow("Unsupported device inserted in the memory card slot");
case CARD_ERROR_BROKEN:
errorThrow("Memory card is damaged or unformatted");
default:
break;
}
if(result < 0) {
errorThrow("Failed to mount memory card (error %d)", result);
errorThrow("Failed to mount memory card: %s (%d)",
saveCardErrorStringDolphin(result), result
);
}
SAVE.platform.mounted = true;
@@ -42,19 +67,22 @@ errorret_t saveDisposeDolphin(void) {
errorret_t saveLoadDolphin(const uint8_t slot, savefile_t *file) {
char_t fileName[SAVE_DOLPHIN_FILE_NAME_MAX];
_saveGetFileName(slot, fileName, SAVE_DOLPHIN_FILE_NAME_MAX);
saveGetFileNameDolphin(slot, fileName, SAVE_DOLPHIN_FILE_NAME_MAX);
int32_t result = CARD_Open(
int32_t result;
do {
result = CARD_Open(
SAVE_DOLPHIN_CHANNEL, fileName, &SAVE.platform.cardFile
);
} while(result == CARD_ERROR_BUSY);
if(result == CARD_ERROR_NOFILE) {
file->exists = false;
errorOk();
}
if(result < 0) {
file->exists = false;
errorThrow("Failed to open memory card file for slot %u (error %d)",
(uint32_t)slot, result
errorThrow("Failed to open memory card file for slot %u: %s (%d)",
(uint32_t)slot, saveCardErrorStringDolphin(result), result
);
}
@@ -64,16 +92,18 @@ errorret_t saveLoadDolphin(const uint8_t slot, savefile_t *file) {
errorThrow("Failed to allocate memory card read buffer");
}
do {
result = CARD_Read(
&SAVE.platform.cardFile, buffer, SAVE_DOLPHIN_SECTOR_SIZE, 0
);
} while(result == CARD_ERROR_BUSY);
CARD_Close(&SAVE.platform.cardFile);
if(result < 0) {
memoryFree(buffer);
file->exists = false;
errorThrow("Failed to read memory card data for slot %u (error %d)",
(uint32_t)slot, result
errorThrow("Failed to read memory card data for slot %u: %s (%d)",
(uint32_t)slot, saveCardErrorStringDolphin(result), result
);
}
@@ -86,7 +116,7 @@ errorret_t saveLoadDolphin(const uint8_t slot, savefile_t *file) {
errorret_t saveWriteDolphin(const uint8_t slot, const savefile_t *file) {
char_t fileName[SAVE_DOLPHIN_FILE_NAME_MAX];
_saveGetFileName(slot, fileName, SAVE_DOLPHIN_FILE_NAME_MAX);
saveGetFileNameDolphin(slot, fileName, SAVE_DOLPHIN_FILE_NAME_MAX);
void *buffer = memoryAlign(32, SAVE_DOLPHIN_SECTOR_SIZE);
if(!buffer) {
@@ -96,34 +126,41 @@ errorret_t saveWriteDolphin(const uint8_t slot, const savefile_t *file) {
memoryCopy(buffer, file, sizeof(savefile_t));
// Try open existing file first; create if absent.
int32_t result = CARD_Open(
int32_t result;
do {
result = CARD_Open(
SAVE_DOLPHIN_CHANNEL, fileName, &SAVE.platform.cardFile
);
} while(result == CARD_ERROR_BUSY);
if(result == CARD_ERROR_NOFILE) {
do {
result = CARD_Create(
SAVE_DOLPHIN_CHANNEL,
fileName,
SAVE_DOLPHIN_SECTOR_SIZE,
&SAVE.platform.cardFile
);
} while(result == CARD_ERROR_BUSY);
}
if(result < 0) {
memoryFree(buffer);
errorThrow("Failed to open/create memory card file for slot %u (error %d)",
(uint32_t)slot, result
errorThrow("Failed to open/create memory card file for slot %u: %s (%d)",
(uint32_t)slot, saveCardErrorStringDolphin(result), result
);
}
do {
result = CARD_Write(
&SAVE.platform.cardFile, buffer, SAVE_DOLPHIN_SECTOR_SIZE, 0
);
} while(result == CARD_ERROR_BUSY);
CARD_Close(&SAVE.platform.cardFile);
memoryFree(buffer);
if(result < 0) {
errorThrow("Failed to write memory card data for slot %u (error %d)",
(uint32_t)slot, result
errorThrow("Failed to write memory card data for slot %u: %s (%d)",
(uint32_t)slot, saveCardErrorStringDolphin(result), result
);
}
@@ -132,14 +169,52 @@ errorret_t saveWriteDolphin(const uint8_t slot, const savefile_t *file) {
errorret_t saveDeleteDolphin(const uint8_t slot) {
char_t fileName[SAVE_DOLPHIN_FILE_NAME_MAX];
_saveGetFileName(slot, fileName, SAVE_DOLPHIN_FILE_NAME_MAX);
saveGetFileNameDolphin(slot, fileName, SAVE_DOLPHIN_FILE_NAME_MAX);
int32_t result = CARD_Delete(SAVE_DOLPHIN_CHANNEL, fileName);
int32_t result;
do {
result = CARD_Delete(SAVE_DOLPHIN_CHANNEL, fileName);
} while(result == CARD_ERROR_BUSY);
if(result < 0 && result != CARD_ERROR_NOFILE) {
errorThrow("Failed to delete memory card file for slot %u (error %d)",
(uint32_t)slot, result
errorThrow("Failed to delete memory card file for slot %u: %s (%d)",
(uint32_t)slot, saveCardErrorStringDolphin(result), result
);
}
errorOk();
}
void saveGetFileNameDolphin(
const uint8_t slot, char_t *out, const size_t max
) {
snprintf(out, max, "%s_%u", SAVE_DOLPHIN_GAME_CODE, (uint32_t)slot);
}
const char_t *saveCardErrorStringDolphin(const int32_t result) {
switch(result) {
case CARD_ERROR_READY: return "card is ready";
case CARD_ERROR_UNLOCKED:
return "card is being unlocked or already unlocked";
case CARD_ERROR_BUSY: return "card is busy";
case CARD_ERROR_WRONGDEVICE: return "wrong device connected in slot";
case CARD_ERROR_NOCARD: return "no memory card in slot";
case CARD_ERROR_NOFILE: return "specified file not found";
case CARD_ERROR_IOERROR: return "internal EXI I/O error";
case CARD_ERROR_BROKEN:
return "directory structure or file entry broken";
case CARD_ERROR_EXIST:
return "file already exists with the specified parameters";
case CARD_ERROR_NOENT:
return "no empty block available to create the file";
case CARD_ERROR_INSSPACE:
return "not enough space to write file to memory card";
case CARD_ERROR_NOPERM:
return "not enough permissions to operate on the file";
case CARD_ERROR_LIMIT: return "card size limit reached";
case CARD_ERROR_NAMETOOLONG: return "filename too long";
case CARD_ERROR_ENCODING: return "font encoding PAL/SJIS mismatch";
case CARD_ERROR_CANCELED: return "card operation canceled";
case CARD_ERROR_FATAL_ERROR: return "fatal error, non-recoverable";
default: return "unknown card error";
}
}
+23
View File
@@ -66,3 +66,26 @@ errorret_t saveWriteDolphin(const uint8_t slot, const savefile_t *file);
* @return An error code if the delete fails.
*/
errorret_t saveDeleteDolphin(const uint8_t slot);
/**
* Builds the memory card file name for a given save slot, from
* SAVE_DOLPHIN_GAME_CODE and the slot index.
*
* @param slot The save slot index.
* @param out Destination buffer for the file name.
* @param max Size of out, in bytes.
*/
void saveGetFileNameDolphin(
const uint8_t slot, char_t *out, const size_t max
);
/**
* Describes a libogc CARD_ERROR_* result code (see
* https://libogc.devkitpro.org/group__card__errors.html), for logging
* alongside the raw numeric code.
*
* @param result The result code returned by a CARD_* libogc call.
* @return A human-readable description of the result code, or
* "unknown card error" if result doesn't match a known CARD_ERROR_* code.
*/
const char_t *saveCardErrorStringDolphin(const int32_t result);
+27 -8
View File
@@ -19,12 +19,20 @@ static void _saveStreamGetFileName(
errorret_t saveStreamOpenReadDolphin(
savestreamdolphin_t *p, bool_t *found, const uint8_t slot
) {
if(!SAVE.platform.mounted) {
*found = false;
errorThrow("No memory card mounted");
}
char_t fileName[SAVE_DOLPHIN_FILE_NAME_MAX];
_saveStreamGetFileName(fileName, SAVE_DOLPHIN_FILE_NAME_MAX, slot);
int32_t result = CARD_Open(
int32_t result;
do {
result = CARD_Open(
SAVE_DOLPHIN_CHANNEL, fileName, &p->cardFile
);
} while(result == CARD_ERROR_BUSY);
if(result == CARD_ERROR_NOFILE) {
*found = false;
p->position = 0;
@@ -33,17 +41,19 @@ errorret_t saveStreamOpenReadDolphin(
}
if(result < 0) {
*found = false;
errorThrow("Failed to open memory card file for slot %u (error %d)",
(uint32_t)slot, result
errorThrow("Failed to open memory card file for slot %u: %s (%d)",
(uint32_t)slot, saveCardErrorStringDolphin(result), result
);
}
do {
result = CARD_Read(&p->cardFile, p->buffer, SAVE_DOLPHIN_SECTOR_SIZE, 0);
} while(result == CARD_ERROR_BUSY);
CARD_Close(&p->cardFile);
if(result < 0) {
*found = false;
errorThrow("Failed to read memory card data for slot %u (error %d)",
(uint32_t)slot, result
errorThrow("Failed to read memory card data for slot %u: %s (%d)",
(uint32_t)slot, saveCardErrorStringDolphin(result), result
);
}
@@ -57,6 +67,8 @@ errorret_t saveStreamOpenReadDolphin(
errorret_t saveStreamOpenWriteDolphin(
savestreamdolphin_t *p, const uint8_t slot
) {
if(!SAVE.platform.mounted) errorThrow("No memory card mounted");
memoryZero(p->buffer, SAVE_DOLPHIN_SECTOR_SIZE);
p->position = 0;
p->writing = true;
@@ -70,14 +82,21 @@ void saveStreamCloseDolphin(savestreamdolphin_t *p) {
char_t fileName[SAVE_DOLPHIN_FILE_NAME_MAX];
_saveStreamGetFileName(fileName, SAVE_DOLPHIN_FILE_NAME_MAX, p->slot);
int32_t result = CARD_Open(SAVE_DOLPHIN_CHANNEL, fileName, &p->cardFile);
int32_t result;
do {
result = CARD_Open(SAVE_DOLPHIN_CHANNEL, fileName, &p->cardFile);
} while(result == CARD_ERROR_BUSY);
if(result == CARD_ERROR_NOFILE) {
CARD_Create(
do {
result = CARD_Create(
SAVE_DOLPHIN_CHANNEL, fileName, SAVE_DOLPHIN_SECTOR_SIZE, &p->cardFile
);
} while(result == CARD_ERROR_BUSY);
}
CARD_Write(&p->cardFile, p->buffer, SAVE_DOLPHIN_SECTOR_SIZE, 0);
do {
result = CARD_Write(&p->cardFile, p->buffer, SAVE_DOLPHIN_SECTOR_SIZE, 0);
} while(result == CARD_ERROR_BUSY);
CARD_Close(&p->cardFile);
}
+2 -1
View File
@@ -6,6 +6,7 @@
*/
#include "input/input.h"
#include "save/save.h"
inputbuttondata_t INPUT_BUTTON_DATA[] = {
#ifdef DUSK_INPUT_GAMEPAD
@@ -547,5 +548,5 @@ errorret_t inputInitLinux(void) {
}
float_t inputGetDeadzoneSDL2(const inputbutton_t button) {
return 0.17f;
return saveGet(SAVE_ACTIVE_SLOT)->deadzone;
}
+2 -1
View File
@@ -6,6 +6,7 @@
*/
#include "input/input.h"
#include "save/save.h"
// #define INPUT_PSP_GAMEPAD_BUTTON_ACCEPT INPUT_SDL2_GAMEPAD_BUTTON_CUSTOM
// #define INPUT_PSP_GAMEPAD_BUTTON_CANCEL INPUT_SDL2_GAMEPAD_BUTTON_CUSTOM
@@ -94,5 +95,5 @@ errorret_t inputInitPSP(void) {
}
float_t inputGetDeadzoneSDL2(const inputbutton_t button) {
return 0.2f;
return saveGet(SAVE_ACTIVE_SLOT)->deadzone;
}
+13 -6
View File
@@ -16,15 +16,22 @@ typedef savestreampsp_t saveplatformstream_t;
#define saveDisposePlatform saveDisposePSP
#define saveDeletePlatform saveDeletePSP
#define saveStreamOpenReadPlatform(stream, slot) \
saveStreamOpenReadPSP(&(stream)->platform, &(stream)->found, slot)
#define saveStreamOpenWritePlatform(stream, slot) \
saveStreamOpenWritePSP(&(stream)->platform, slot)
#define saveStreamClosePlatform(stream) \
saveStreamClosePSP(&(stream)->platform)
#define saveStreamReadBytesPlatform(stream, buf, len) \
saveStreamReadBytesPSP(&(stream)->platform, buf, len)
#define saveStreamWriteBytesPlatform(stream, buf, len) \
saveStreamWriteBytesPSP(&(stream)->platform, buf, len)
#define saveStreamSeekPlatform(stream, pos) \
saveStreamSeekPSP(&(stream)->platform, pos)
// Save/load go entirely through the native sceUtilitySavedata dialog
// (savePSPBeginSave/Load), which spans multiple frames - these bypass
// save.c's normal synchronous open/write-fields/close flow above (that's
// still used internally, just against an in-memory buffer, from within
// savePSPBeginSave/Load themselves) and are what save.c's saveWrite()/
// saveLoad() actually call on this platform.
#define saveAsyncWritePlatform(slot, onComplete, user) \
savePSPBeginSave(slot, onComplete, user)
#define saveAsyncLoadPlatform(slot, onComplete, user) \
savePSPBeginLoad(slot, onComplete, user)
#define saveIsBusyPlatform() savePSPIsBusy()
#define savePlatformUpdate() savePSPUpdate()
+262 -53
View File
@@ -6,8 +6,38 @@
*/
#include "save/save.h"
#include "save/savepsp.h"
#include "save/savestream.h"
#include "system/systempsp.h"
#include "util/memory.h"
#include "util/string.h"
#include "assert/assert.h"
static void savePSPParamCommonInit(SceUtilitySavedataParam *param) {
memoryZero(param, sizeof(SceUtilitySavedataParam));
param->base.size = sizeof(SceUtilitySavedataParam);
param->base.language = systemPSPGetLanguage();
param->base.buttonSwap = systemPSPGetCrossButtonSetting();
param->base.graphicsThread = 17;
param->base.accessThread = 19;
param->base.fontThread = 18;
param->base.soundThread = 16;
stringCopy(param->gameName, SAVE_PSP_GAME_NAME, sizeof(param->gameName));
stringCopy(param->fileName, SAVE_PSP_FILE_NAME, sizeof(param->fileName));
}
static void savePSPSaveNameForSlot(
char_t *out, const size_t max, const uint8_t slot
) {
stringFormat(out, max, "%02u", (uint32_t)slot);
}
errorret_t saveInitPSP(void) {
SceIoStat stat;
if(sceIoGetstat(SAVE_PSP_ROOT, &stat) < 0) {
errorThrow("No memory stick detected");
}
errorOk();
}
@@ -15,61 +45,11 @@ errorret_t saveDisposePSP(void) {
errorOk();
}
errorret_t saveLoadPSP(const uint8_t slot, savefile_t *file) {
char_t path[SAVE_PSP_PATH_MAX];
snprintf(path, SAVE_PSP_PATH_MAX, SAVE_PSP_FILE_FORMAT,
SAVE_PSP_TITLE_ID, (uint32_t)slot
);
SceUID fd = sceIoOpen(path, PSP_O_RDONLY, 0);
if(fd < 0) {
file->exists = false;
errorOk();
}
int32_t read = sceIoRead(fd, file, sizeof(savefile_t));
sceIoClose(fd);
if(read != (int32_t)sizeof(savefile_t)) {
file->exists = false;
errorThrow("Failed to read save data for slot %u", (uint32_t)slot);
}
file->exists = true;
errorOk();
}
errorret_t saveWritePSP(const uint8_t slot, const savefile_t *file) {
char_t dir[SAVE_PSP_PATH_MAX];
snprintf(dir, SAVE_PSP_PATH_MAX, SAVE_PSP_DIR_FORMAT,
SAVE_PSP_TITLE_ID, (uint32_t)slot
);
sceIoMkdir(dir, 0777);
char_t path[SAVE_PSP_PATH_MAX];
snprintf(path, SAVE_PSP_PATH_MAX, SAVE_PSP_FILE_FORMAT,
SAVE_PSP_TITLE_ID, (uint32_t)slot
);
SceUID fd = sceIoOpen(path, PSP_O_WRONLY | PSP_O_CREAT | PSP_O_TRUNC, 0777);
if(fd < 0) {
errorThrow("Failed to open save file for writing: slot %u", (uint32_t)slot);
}
int32_t written = sceIoWrite(fd, file, sizeof(savefile_t));
sceIoClose(fd);
if(written != (int32_t)sizeof(savefile_t)) {
errorThrow("Failed to write save data for slot %u", (uint32_t)slot);
}
errorOk();
}
errorret_t saveDeletePSP(const uint8_t slot) {
char_t path[SAVE_PSP_PATH_MAX];
snprintf(path, SAVE_PSP_PATH_MAX, SAVE_PSP_FILE_FORMAT,
SAVE_PSP_TITLE_ID, (uint32_t)slot
stringFormat(
path, sizeof(path), SAVE_PSP_FILE_FORMAT, SAVE_PSP_GAME_NAME,
(uint32_t)slot
);
int32_t result = sceIoRemove(path);
@@ -77,5 +57,234 @@ errorret_t saveDeletePSP(const uint8_t slot) {
errorThrow("Failed to delete save file for slot %u", (uint32_t)slot);
}
char_t dir[SAVE_PSP_PATH_MAX];
stringFormat(
dir, sizeof(dir), "ms0:/PSP/SAVEDATA/%s%02u", SAVE_PSP_GAME_NAME,
(uint32_t)slot
);
char_t sfoPath[SAVE_PSP_PATH_MAX];
stringFormat(sfoPath, sizeof(sfoPath), "%s/PARAM.SFO", dir);
// Best-effort - PARAM.SFO/the directory itself may not exist (e.g. this
// slot was written by the old raw-file format, pre-dating this dialog-
// based rewrite) or the directory may still contain other entries.
sceIoRemove(sfoPath);
sceIoRmdir(dir);
errorOk();
}
void savePSPBeginSave(
const uint8_t slot, savecallback_t onComplete, void *user
) {
assertNotNull(onComplete, "onComplete cannot be NULL");
assertTrue(SAVE.platform.op == SAVE_PSP_OP_NONE, "Save already in progress");
savefile_t *file = &SAVE.files[slot];
// Serialize into the buffer synchronously (plain memory writes, same
// header/version/CRC framing as every other platform) before the dialog
// ever starts - only the actual commit-to-storage step needs to wait on
// the dialog.
savestream_t stream;
memoryZero(&stream, sizeof(savestream_t));
stream.platform.buffer = SAVE.platform.dataBuffer;
stream.platform.bufferSize = sizeof(SAVE.platform.dataBuffer);
errorret_t ret = saveFileWrite(&stream, file);
if(errorIsOk(ret)) ret = saveStreamFinalizeWriteImpl(&stream);
if(errorIsNotOk(ret)) {
onComplete(ret, user);
return;
}
SAVE.platform.dataLength = stream.platform.length;
SceUtilitySavedataParam *param = &SAVE.platform.param;
savePSPParamCommonInit(param);
// AUTOSAVE rather than SAVE - SAVE shows a "save to this data?" confirm
// screen even for a slot with no existing data, which isn't the UX we
// want for a menu-triggered "Save" action (that confirmation already
// happened when the player chose to save). AUTOSAVE writes silently
// (just a brief "saving" icon flash) while still generating the same
// PARAM.SFO/title/description as any other mode.
param->mode = PSP_UTILITY_SAVEDATA_AUTOSAVE;
param->overwrite = 1;
savePSPSaveNameForSlot(param->saveName, sizeof(param->saveName), slot);
param->dataBuf = SAVE.platform.dataBuffer;
param->dataBufSize = sizeof(SAVE.platform.dataBuffer);
param->dataSize = SAVE.platform.dataLength;
// No ICON0/PIC1/SND0 art exists in this project yet, so these are left
// zeroed (bufSize 0) - the utility treats that as "no icon/background/
// sound" rather than an error. title/savedataTitle/detail are still
// fully functional and are what actually populates PARAM.SFO and the
// save browser entry.
stringCopy(param->sfoParam.title, "Dusk", sizeof(param->sfoParam.title));
stringCopy(
param->sfoParam.savedataTitle, file->playerName,
sizeof(param->sfoParam.savedataTitle)
);
stringCopy(
param->sfoParam.detail, "Dusk save file.", sizeof(param->sfoParam.detail)
);
int32_t initRet = sceUtilitySavedataInitStart(param);
if(initRet < 0) {
onComplete(errorThrowImpl(
&SAVE.errorState, ERROR_NOT_OK, __FILE__, __func__, __LINE__,
"Failed to start save dialog: 0x%08X", initRet
), user);
return;
}
SAVE.platform.op = SAVE_PSP_OP_SAVE;
SAVE.platform.slot = slot;
SAVE.platform.onComplete = onComplete;
SAVE.platform.onCompleteUser = user;
}
void savePSPBeginLoad(
const uint8_t slot, savecallback_t onComplete, void *user
) {
assertNotNull(onComplete, "onComplete cannot be NULL");
assertTrue(SAVE.platform.op == SAVE_PSP_OP_NONE, "Save already in progress");
char_t path[SAVE_PSP_PATH_MAX];
stringFormat(
path, sizeof(path), SAVE_PSP_FILE_FORMAT, SAVE_PSP_GAME_NAME,
(uint32_t)slot
);
SceIoStat stat;
if(sceIoGetstat(path, &stat) < 0) {
// No save data for this slot yet - not an error (matches every other
// platform's "nothing to load yet" behavior), and deliberately skips
// showing the dialog at all rather than surfacing an empty "no data"
// native screen for a slot the player has never saved to.
onComplete(errorOkImpl(), user);
return;
}
SceUtilitySavedataParam *param = &SAVE.platform.param;
savePSPParamCommonInit(param);
param->mode = PSP_UTILITY_SAVEDATA_AUTOLOAD;// See savePSPBeginSave().
savePSPSaveNameForSlot(param->saveName, sizeof(param->saveName), slot);
param->dataBuf = SAVE.platform.dataBuffer;
param->dataBufSize = sizeof(SAVE.platform.dataBuffer);
int32_t initRet = sceUtilitySavedataInitStart(param);
if(initRet < 0) {
onComplete(errorThrowImpl(
&SAVE.errorState, ERROR_NOT_OK, __FILE__, __func__, __LINE__,
"Failed to start load dialog: 0x%08X", initRet
), user);
return;
}
SAVE.platform.op = SAVE_PSP_OP_LOAD;
SAVE.platform.slot = slot;
SAVE.platform.onComplete = onComplete;
SAVE.platform.onCompleteUser = user;
}
bool_t savePSPIsBusy(void) {
return SAVE.platform.op != SAVE_PSP_OP_NONE;
}
errorret_t savePSPUpdate(void) {
if(SAVE.platform.op == SAVE_PSP_OP_NONE) errorOk();
int32_t status = sceUtilitySavedataGetStatus();
switch(status) {
case PSP_UTILITY_DIALOG_INIT:
break;
// NOTE: unlike the netconf dialog, this does not replicate Dusk's own
// GL state (blend/cull/depth + texture/color) before calling Update().
// A prior fix for exactly that class of bug was documented for the
// network dialog, but no longer exists in the current codebase to
// copy from - if the save dialog's own text/icons don't render
// correctly on real hardware (PPSSPP won't reproduce this - it doesn't
// model pspGL's deferred state application), that state-priming
// pattern is the fix to reach for. See the network dialog's git
// history / the project's PSP dialog memory notes for the exact
// technique (state flags + a forced flush via a degenerate triangle
// draw).
case PSP_UTILITY_DIALOG_VISIBLE:
// sceUtilitySavedataUpdate() is void, unlike sceUtilityNetconfUpdate()
// - nothing to check here, GetStatus() next frame reflects any
// resulting state change.
sceUtilitySavedataUpdate(1);
break;
case PSP_UTILITY_DIALOG_QUIT:
// The save/load operation itself has already finished (successfully
// or not) - this just starts tearing the dialog down. The actual
// result is read once that teardown settles, below - don't call
// ShutdownStart more than once while waiting for it to.
if(!SAVE.platform.shuttingDown) {
SAVE.platform.shuttingDown = true;
sceUtilitySavedataShutdownStart();
}
break;
// Confirmed under PPSSPP: status settles straight from QUIT to NONE,
// without FINISHED ever being separately observed in between - so
// both are treated identically here as "torn down, read the result",
// and it's shuttingDown (not which of these two codes we saw) that
// distinguishes that from a genuine disappearance.
case PSP_UTILITY_DIALOG_FINISHED:
case PSP_UTILITY_DIALOG_NONE: {
savepspop_t op = SAVE.platform.op;
uint8_t slot = SAVE.platform.slot;
savecallback_t cb = SAVE.platform.onComplete;
void *user = SAVE.platform.onCompleteUser;
bool_t reachedQuit = SAVE.platform.shuttingDown;
SAVE.platform.op = SAVE_PSP_OP_NONE;
SAVE.platform.shuttingDown = false;
if(!reachedQuit) {
cb(errorThrowImpl(
&SAVE.errorState, ERROR_NOT_OK, __FILE__, __func__, __LINE__,
"Save dialog disappeared without a result"
), user);
break;
}
int32_t result = SAVE.platform.param.base.result;
if(result != 0) {
SAVE.available = false;
cb(errorThrowImpl(
&SAVE.errorState, ERROR_NOT_OK, __FILE__, __func__, __LINE__,
"Save dialog failed: 0x%08X", result
), user);
break;
}
SAVE.available = true;
if(op == SAVE_PSP_OP_LOAD) {
savefile_t *file = &SAVE.files[slot];
savestream_t stream;
memoryZero(&stream, sizeof(savestream_t));
stream.platform.buffer = SAVE.platform.dataBuffer;
stream.platform.bufferSize = sizeof(SAVE.platform.dataBuffer);
stream.platform.length = SAVE.platform.param.dataSize;
errorret_t ret = saveFileLoad(&stream, file);
if(errorIsOk(ret)) ret = saveStreamVerifyChecksumImpl(&stream, slot);
file->exists = errorIsOk(ret);
cb(ret, user);
} else {
SAVE.files[slot].exists = true;
cb(errorOkImpl(), user);
}
break;
}
default:
errorThrow("Unknown savedata dialog status: %d", status);
}
errorOk();
}
+90 -26
View File
@@ -9,23 +9,52 @@
#include "error/error.h"
#include "save/savefile.h"
#include <pspiofilemgr.h>
#include <psputility.h>
#define SAVE_PSP_PATH_MAX 256
#define SAVE_PSP_FILE_FORMAT "ms0:/PSP/SAVEDATA/%s%02u/save.dat"
#define SAVE_PSP_DIR_FORMAT "ms0:/PSP/SAVEDATA/%s%02u"
#define SAVE_PSP_ROOT "ms0:/"
#define SAVE_PSP_FILE_NAME "save.bin"
#define SAVE_PSP_FILE_FORMAT "ms0:/PSP/SAVEDATA/%s%02u/" SAVE_PSP_FILE_NAME
#define SAVE_PSP_DATA_BUFFER_SIZE 4096
#ifndef SAVE_PSP_TITLE_ID
#define SAVE_PSP_TITLE_ID "DUSK00001"
#ifndef SAVE_PSP_GAME_NAME
#define SAVE_PSP_GAME_NAME "DUSK00001"
#endif
typedef enum {
SAVE_PSP_OP_NONE,
SAVE_PSP_OP_SAVE,
SAVE_PSP_OP_LOAD
} savepspop_t;
typedef struct {
uint8_t unused;
SceUtilitySavedataParam param;
// Raw buffer sceUtilitySavedata reads/writes the whole save into/from -
// populated by our own savestream_t serialization (see savestreampsp.h)
// before a save starts, and deserialized from after a load finishes.
uint8_t dataBuffer[SAVE_PSP_DATA_BUFFER_SIZE] __attribute__((aligned(64)));
size_t dataLength;
savepspop_t op;
// True once sceUtilitySavedataShutdownStart() has been requested (dialog
// status PSP_UTILITY_DIALOG_QUIT seen) - distinguishes a normal "torn
// down after finishing" NONE/FINISHED from a genuinely unexpected one
// seen before ever reaching QUIT. Some implementations (confirmed on
// PPSSPP) settle straight to NONE after shutdown without a separately
// observable FINISHED step in between.
bool_t shuttingDown;
uint8_t slot;
savecallback_t onComplete;
void *onCompleteUser;
} savepsp_t;
/**
* Initializes the save system on PSP.
* Initializes the save system on PSP. Confirms the memory stick is
* actually reachable (sceIoGetstat on SAVE_PSP_ROOT) rather than assuming
* so, since the savedata dialog otherwise only reports failure once a
* save/load is actually attempted.
*
* @return An error code if initialization fails.
* @return An error code if no memory stick is reachable.
*/
errorret_t saveInitPSP(void);
@@ -37,27 +66,62 @@ errorret_t saveInitPSP(void);
errorret_t saveDisposePSP(void);
/**
* Loads a save file from PSP save data for the given slot.
*
* @param slot The save slot index.
* @param file Output save file data.
* @return An error code if the load fails.
*/
errorret_t saveLoadPSP(const uint8_t slot, savefile_t *file);
/**
* Writes a save file to PSP save data for the given slot.
*
* @param slot The save slot index.
* @param file Save file data to write.
* @return An error code if the write fails.
*/
errorret_t saveWritePSP(const uint8_t slot, const savefile_t *file);
/**
* Deletes the save file for the given slot from PSP save data.
* Deletes the save data folder for the given slot from the memory stick.
*
* @param slot The save slot index.
* @return An error code if the delete fails.
*/
errorret_t saveDeletePSP(const uint8_t slot);
/**
* Starts a save via the native sceUtilitySavedata dialog (mode AUTOSAVE -
* writes silently with just a brief icon flash, no confirm screen, since
* SAVE mode shows one even for a slot with no existing data - but
* PARAM.SFO/title/description are generated identically regardless of
* mode, and the OS handles the save browser entry either way) for the
* given slot. Serializes SAVE.files[slot] into SAVE.platform.dataBuffer
* first, synchronously, then kicks off the dialog and returns - completion
* is reported later via onComplete, driven by savePSPUpdate() each frame.
* If no save data exists yet for this slot, sceUtilitySavedataInitStart()
* creates it.
*
* @param slot The save slot index.
* @param onComplete Callback invoked once the dialog finishes.
* @param user User data passed through to onComplete.
*/
void savePSPBeginSave(
const uint8_t slot, savecallback_t onComplete, void *user
);
/**
* Starts a load via the native sceUtilitySavedata dialog (mode AUTOLOAD -
* see savePSPBeginSave() for why not the plain LOAD mode) for the given
* slot, unless a quick sceIoGetstat check finds no save data for this slot
* yet - in which case onComplete is invoked immediately with
* SAVE.files[slot].exists left false, matching the other platforms'
* "no file yet" semantics, and no dialog is shown at all.
*
* @param slot The save slot index.
* @param onComplete Callback invoked once the dialog (or immediate
* not-found short-circuit) finishes.
* @param user User data passed through to onComplete.
*/
void savePSPBeginLoad(
const uint8_t slot, savecallback_t onComplete, void *user
);
/**
* Pumps the in-progress save/load dialog one step, if any - must be called
* every engine frame (see saveUpdate()). No-op if no dialog is active.
*
* @return An error code indicating success or failure.
*/
errorret_t savePSPUpdate(void);
/**
* True while a save/load dialog is in progress (see savePSPBeginSave()/
* savePSPBeginLoad()).
*
* @return True if a save/load dialog is currently open.
*/
bool_t savePSPIsBusy(void);
+13 -49
View File
@@ -7,71 +7,35 @@
#include "save/save.h"
#include "save/savestreampsp.h"
errorret_t saveStreamOpenReadPSP(
savestreampsp_t *p, bool_t *found, const uint8_t slot
) {
char_t path[SAVE_PSP_PATH_MAX];
snprintf(path, SAVE_PSP_PATH_MAX, SAVE_PSP_FILE_FORMAT,
SAVE_PSP_TITLE_ID, (uint32_t)slot
);
p->fd = sceIoOpen(path, PSP_O_RDONLY, 0);
*found = (p->fd >= 0);
errorOk();
}
errorret_t saveStreamOpenWritePSP(savestreampsp_t *p, const uint8_t slot) {
char_t dir[SAVE_PSP_PATH_MAX];
snprintf(dir, SAVE_PSP_PATH_MAX, SAVE_PSP_DIR_FORMAT,
SAVE_PSP_TITLE_ID, (uint32_t)slot
);
sceIoMkdir(dir, 0777);
char_t path[SAVE_PSP_PATH_MAX];
snprintf(path, SAVE_PSP_PATH_MAX, SAVE_PSP_FILE_FORMAT,
SAVE_PSP_TITLE_ID, (uint32_t)slot
);
p->fd = sceIoOpen(path, PSP_O_WRONLY | PSP_O_CREAT | PSP_O_TRUNC, 0777);
if(p->fd < 0) {
errorThrow(
"Failed to open PSP save file for writing: slot %u", (uint32_t)slot
);
}
errorOk();
}
void saveStreamClosePSP(savestreampsp_t *p) {
if(p->fd >= 0) {
sceIoClose(p->fd);
p->fd = -1;
}
}
#include "util/memory.h"
errorret_t saveStreamReadBytesPSP(
savestreampsp_t *p, void *buf, const size_t len
) {
int32_t read = sceIoRead(p->fd, buf, (SceSize)len);
if(read != (int32_t)len) {
errorThrow("Unexpected end of PSP save file");
if(p->position + len > p->length) {
errorThrow("Save stream read exceeds buffer length");
}
memoryCopy(buf, p->buffer + p->position, len);
p->position += len;
errorOk();
}
errorret_t saveStreamWriteBytesPSP(
savestreampsp_t *p, const void *buf, const size_t len
) {
int32_t written = sceIoWrite(p->fd, buf, (SceSize)len);
if(written != (int32_t)len) {
errorThrow("Failed to write PSP save data");
if(p->position + len > p->bufferSize) {
errorThrow("Save stream write exceeds buffer size");
}
memoryCopy(p->buffer + p->position, buf, len);
p->position += len;
if(p->position > p->length) p->length = p->position;
errorOk();
}
errorret_t saveStreamSeekPSP(savestreampsp_t *p, const size_t pos) {
if(sceIoLseek(p->fd, (SceOff)pos, PSP_SEEK_SET) < 0) {
errorThrow("Failed to seek in PSP save file");
if(pos > p->bufferSize) {
errorThrow("Save stream seek out of range");
}
p->position = pos;
errorOk();
}
+16 -38
View File
@@ -7,71 +7,49 @@
#pragma once
#include "error/error.h"
#include <pspiofilemgr.h>
#include <stddef.h>
// Backed by SAVE.platform.dataBuffer (see savepsp.h) rather than owning its
// own memory - the buffer has to outlive a single saveFileWrite()/Load()
// call, since the actual save/load dialog it's handed to only completes
// several frames later.
typedef struct {
SceUID fd;
uint8_t *buffer;
size_t bufferSize;
size_t position;
size_t length;
} savestreampsp_t;
/**
* Opens a PSP save data file for reading.
*
* @param p Stream to initialize.
* @param found Set to true if the file exists, false if it does not.
* @param slot Save slot index.
* @return An error if the open fails for a reason other than missing file.
*/
errorret_t saveStreamOpenReadPSP(
savestreampsp_t *p, bool_t *found, const uint8_t slot
);
/**
* Opens a PSP save data file for writing, creating or truncating it.
* Creates the save data directory if it does not already exist.
*
* @param p Stream to initialize.
* @param slot Save slot index.
* @return An error if the file cannot be opened for writing.
*/
errorret_t saveStreamOpenWritePSP(savestreampsp_t *p, const uint8_t slot);
/**
* Closes the file descriptor held by the stream.
*
* @param p Stream to close.
*/
void saveStreamClosePSP(savestreampsp_t *p);
/**
* Reads len bytes from the stream into buf.
* Copies len bytes from the buffer at the current position into buf.
*
* @param p Active stream.
* @param buf Destination buffer.
* @param len Number of bytes to read.
* @return An error if fewer than len bytes are available.
* @return An error if the read would exceed the populated data length.
*/
errorret_t saveStreamReadBytesPSP(
savestreampsp_t *p, void *buf, const size_t len
);
/**
* Writes len bytes from buf into the stream.
* Copies len bytes from buf into the buffer at the current position,
* growing p->length if this write extends past it.
*
* @param p Active stream.
* @param buf Source buffer.
* @param len Number of bytes to write.
* @return An error if the write fails.
* @return An error if the write would exceed bufferSize.
*/
errorret_t saveStreamWriteBytesPSP(
savestreampsp_t *p, const void *buf, const size_t len
);
/**
* Seeks to an absolute byte position within the stream.
* Sets the current read/write position within the buffer.
*
* @param p Active stream.
* @param pos Target byte offset from the start of the file.
* @return An error if the seek fails.
* @param pos Target byte offset from the start of the buffer.
* @return An error if pos is out of range.
*/
errorret_t saveStreamSeekPSP(savestreampsp_t *p, const size_t pos);
+2 -1
View File
@@ -6,6 +6,7 @@
*/
#include "input/input.h"
#include "save/save.h"
inputbuttondata_t INPUT_BUTTON_DATA[] = {
{ .name = "triangle", {
@@ -83,5 +84,5 @@ inputbuttondata_t INPUT_BUTTON_DATA[] = {
};
float_t inputGetDeadzoneSDL2(const inputbutton_t button) {
return 0.17f;
return saveGet(SAVE_ACTIVE_SLOT)->deadzone;
}
+123 -5
View File
@@ -14,6 +14,16 @@ JSON input (assetsraw/chunks/chunk_X_Y_Z.json):
],
"meshes": [
{ "file": "house_5_3.dmf", "pos": [x, y, z] }
],
"entities": [
{ "type": "global", "globalId": <int>, "pos": [x, y, z] },
{ "type": "item", "itemId": <int>, "quantity": <int>, "pos": [x, y, z] }
],
"areas": [
{
"min": [x, y, z], "max": [x, y, z],
"callbackId": <int>, "notify": <int>, "trigger": <int>
}
]
}
@@ -25,10 +35,27 @@ JSON input (assetsraw/chunks/chunk_X_Y_Z.json):
Mesh files are located by searching under assets/meshes/ and referenced by
path from the assets root in the DCF.
"entities" spawns things into the world when this chunk loads. A "global"
entity is spawned via mapSpawnEntity() - globalId indexes
ENTITY_GLOBAL_LIST (src/dusk/rpg/entity/global/entitygloballist.h) and is
deduped automatically if already spawned, so it's safe to declare on a
chunk that streams in more than once. An "item" entity has no persistent
identity - it respawns fresh every time this chunk (re)loads, including
after being picked up, since nothing tracks "already collected" yet.
itemId is a raw ITEM_ID_* value (see src/dusk/rpg/item/item.json for the
name -> id mapping, same convention as the tile "type" ints above).
"areas" declares map trigger regions (see rpg/overworld/maparea.h) owned
by this chunk - they're removed when the chunk unloads and re-added if it
streams back in. callbackId indexes MAP_AREA_CALLBACK_LIST
(src/dusk/rpg/overworld/global/mapareagloballist.h; 0 is reserved and
invalid). notify is bitwise MAP_AREA_NOTIFY_PLAYER(1)|NOTIFY_NPC(2).
trigger is bitwise MAP_TRIGGER_STEP(1)|ENTER(2)|EXIT(4).
Output DCF is derived automatically:
assetsraw/chunks/chunk_X_Y_Z.json -> assets/chunks/X_Y_Z.dcf
Version 4 DCF format (after 8-byte header):
Version 5 DCF format (after 8-byte header):
tile_t tiles[CHUNK_WIDTH * CHUNK_HEIGHT] (one per x/y column)
each tile: uint32_t shape, uint8_t z, 3 padding bytes (8 bytes total,
matching the C tile_t struct's layout: { tileshape_t shape; uint8_t z; })
@@ -36,6 +63,19 @@ Version 4 DCF format (after 8-byte header):
for each model:
null-terminated string (relative asset path to .json model)
float32[3] (x, y, z offset)
uint8_t entitySpawnCount
for each entity spawn:
uint8_t kind (0 = global entity, 1 = item entity)
uint16_t a (globalId if kind 0, itemId if kind 1)
uint8_t b (unused if kind 0, quantity if kind 1)
int16_t x, y, z (world position, 3 fields)
uint8_t areaSpawnCount
for each area spawn:
int16_t minX, minY, minZ (3 fields)
int16_t maxX, maxY, maxZ (3 fields)
uint16_t callbackId
uint8_t notify
uint8_t trigger
DMF format:
Bytes 0-3: DMF\\x00
@@ -74,6 +114,11 @@ WORLD_LAYER_HEIGHT = 1.0 / math.sqrt(2)
CHUNK_MESH_COUNT_MAX = 10
CHUNK_MESH_NAME_MAX = 64
CHUNK_ENTITY_SPAWN_COUNT_MAX = 8
CHUNK_AREA_COUNT_MAX = 4
ENTITY_SPAWN_KIND_GLOBAL = 0
ENTITY_SPAWN_KIND_ITEM = 1
# Matches sizeof(tile_t) on the C side: uint32_t shape + uint8_t z, padded
# to 8 bytes ({ tileshape_t shape; uint8_t z; } with 4-byte enum alignment).
@@ -106,7 +151,7 @@ TILE_SHAPE_RAMP_SOUTHWEST_INNER = 13
FILE_MAGIC = b'DCF'
DMF_MAGIC = b'DMF\x00'
VERSION_OUT = 4
VERSION_OUT = 5
DMF_VERSION = 1
@@ -163,11 +208,29 @@ def write_dmf(path, vertex_bytes):
print(f' Wrote DMF {path}: {vert_count} vertices, {len(buf)} bytes')
def write_dcf(dcf_path, tiles, mesh_names, mesh_offsets=None):
def write_dcf(
dcf_path, tiles, mesh_names, mesh_offsets=None,
entity_spawns=None, area_spawns=None
):
"""Write a current-version DCF referencing the given DMF asset paths."""
mesh_count = len(mesh_names)
if mesh_offsets is None:
mesh_offsets = [(0.0, 0.0, 0.0)] * mesh_count
if entity_spawns is None:
entity_spawns = []
if area_spawns is None:
area_spawns = []
if len(entity_spawns) > CHUNK_ENTITY_SPAWN_COUNT_MAX:
raise ValueError(
f"Too many entity spawns ({len(entity_spawns)}) - max "
f"{CHUNK_ENTITY_SPAWN_COUNT_MAX}"
)
if len(area_spawns) > CHUNK_AREA_COUNT_MAX:
raise ValueError(
f"Too many area spawns ({len(area_spawns)}) - max "
f"{CHUNK_AREA_COUNT_MAX}"
)
buf = bytearray()
buf += FILE_MAGIC
@@ -183,11 +246,34 @@ def write_dcf(dcf_path, tiles, mesh_names, mesh_offsets=None):
)
buf += encoded + b'\x00'
buf += struct.pack('<3f', offset[0], offset[1], offset[2])
buf += struct.pack('<B', len(entity_spawns))
for spawn in entity_spawns:
kind = spawn['kind']
x, y, z = spawn['pos']
if kind == ENTITY_SPAWN_KIND_GLOBAL:
a, b = spawn['globalId'], 0
else:
a, b = spawn['itemId'], spawn['quantity']
buf += struct.pack('<BHB3h', kind, a, b, x, y, z)
buf += struct.pack('<B', len(area_spawns))
for area in area_spawns:
minX, minY, minZ = area['min']
maxX, maxY, maxZ = area['max']
buf += struct.pack(
'<6hHBB',
minX, minY, minZ, maxX, maxY, maxZ,
area['callbackId'], area['notify'], area['trigger']
)
with open(dcf_path, 'wb') as f:
f.write(buf)
print(
f' Wrote DCF {dcf_path}: '
f'version {VERSION_OUT}, {mesh_count} mesh(es), {len(buf)} bytes'
f'version {VERSION_OUT}, {mesh_count} mesh(es), '
f'{len(entity_spawns)} entity spawn(s), {len(area_spawns)} '
f'area(s), {len(buf)} bytes'
)
@@ -323,7 +409,39 @@ def from_json(json_path, dcf_path):
mesh_offsets.append((float(pos[0]), float(pos[1]), float(pos[2])))
print(f' Resolved {filename} -> {rel}')
write_dcf(dcf_path, bytes(tiles), model_names, mesh_offsets)
entity_spawns = []
for spawn in data.get('entities', []):
pos = tuple(int(v) for v in spawn['pos'])
if spawn['type'] == 'global':
entity_spawns.append({
'kind': ENTITY_SPAWN_KIND_GLOBAL,
'globalId': int(spawn['globalId']),
'pos': pos,
})
elif spawn['type'] == 'item':
entity_spawns.append({
'kind': ENTITY_SPAWN_KIND_ITEM,
'itemId': int(spawn['itemId']),
'quantity': int(spawn['quantity']),
'pos': pos,
})
else:
raise ValueError(f"Unknown entity spawn type: {spawn['type']}")
area_spawns = []
for area in data.get('areas', []):
area_spawns.append({
'min': tuple(int(v) for v in area['min']),
'max': tuple(int(v) for v in area['max']),
'callbackId': int(area['callbackId']),
'notify': int(area['notify']),
'trigger': int(area['trigger']),
})
write_dcf(
dcf_path, bytes(tiles), model_names, mesh_offsets,
entity_spawns, area_spawns
)
def process_json(json_path):
+5 -1
View File
@@ -38,7 +38,11 @@ out += [
" STORY_FLAG_COUNT",
"} storyflag_t;",
"",
"static storyflagvalue_t STORY_FLAG_VALUES[STORY_FLAG_COUNT] = {",
"// Stamped onto a save file's storyFlags the first time it's used (see",
"// storyFlagInitDefaults()) - not a live value array. Live flag state",
"// lives entirely in the save file (savefile_t.storyFlags), read/written",
"// via storyFlagGet()/storyFlagSet() - see storyflag.h.",
"static const storyflagvalue_t STORY_FLAG_DEFAULTS[STORY_FLAG_COUNT] = {",
]
for flag in flags:
out.append(f" [{flag_enum(flag['id'])}] = {flag['initial']},")