diff --git a/.gitmodules b/.gitmodules index 153f048..8697fb0 100644 --- a/.gitmodules +++ b/.gitmodules @@ -30,3 +30,7 @@ path = external/imgui url = https://github.com/ocornut/imgui.git shallow = true +[submodule "external/pugixml"] + path = external/pugixml + url = https://github.com/zeux/pugixml.git + shallow = true diff --git a/CMakeLists.txt b/CMakeLists.txt index 5555b73..4ba1308 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,11 +30,17 @@ add_library(lua STATIC ${LUA_SOURCES}) target_include_directories(lua SYSTEM PUBLIC external/lua) target_compile_definitions(lua PRIVATE LUA_USE_POSIX) -# simdjson: its single-file build, static, without exceptions, for the JSON the import tool writes into resources/. +# simdjson: its single-file build, static, without exceptions, for the JSON the import tool writes into resources/ +# and Anm2Ed's .anm2 documents. add_library(simdjson STATIC external/simdjson/singleheader/simdjson.cpp) target_include_directories(simdjson SYSTEM PUBLIC external/simdjson/singleheader) target_compile_definitions(simdjson PUBLIC SIMDJSON_EXCEPTIONS=0) +# pugixml for the game's own XML (the install's data and anm2 files, mods' XML): static, without XPath or exceptions. +add_library(pugixml STATIC external/pugixml/src/pugixml.cpp) +target_include_directories(pugixml SYSTEM PUBLIC external/pugixml/src) +target_compile_definitions(pugixml PUBLIC PUGIXML_NO_XPATH PUGIXML_NO_EXCEPTIONS) + # Xiph's Ogg, Vorbis and Theora for the cutscene videos (.ogv): static, decoders only. set(INCLUDE_INTTYPES_H 1) set(INCLUDE_STDINT_H 1) @@ -98,7 +104,7 @@ endif() add_executable(isaac ${SOURCES} generated-src/stubs.cpp) target_include_directories(isaac PRIVATE src) target_include_directories(isaac SYSTEM PRIVATE generated-src external/stb) -target_link_libraries(isaac PRIVATE SDL3::SDL3-static lua simdjson theora vorbis ogg) +target_link_libraries(isaac PRIVATE SDL3::SDL3-static lua simdjson pugixml theora vorbis ogg) if(ISAAC_OVERLAY) target_compile_definitions(isaac PRIVATE ISAAC_OVERLAY) target_link_libraries(isaac PRIVATE imgui) diff --git a/README.md b/README.md index bf2e0ac..3bd607d 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ scripts/ decompile.sh (print decompiled C for a function, by name regex or fields), build.sh (rebuild everything from the exe after a game update), and the Ghidra Java scripts and Python helpers they use tools/ gitignored local tools: the resource importer and the test harness (tools/harness/) -external/ static submodules: SDL3, Lua 5.3, simdjson, Ogg, Vorbis, Theora, stb, Dear ImGui (docking) +external/ static submodules: SDL3, Lua 5.3, pugixml, simdjson, Ogg, Vorbis, Theora, stb, Dear ImGui (docking) assets/ files the repository ships itself: the overlay's fonts (git-lfs), with their licences, and REPENTOGON's Lua scripts (assets/repentogon/, GPL-2), adapted where they reach API not ported yet repentogon/ shallow clone of TeamREPENTOGON/REPENTOGON (libzhl/functions/*.zhl = sigs, structs, enums) @@ -42,9 +42,25 @@ jdk/ ghidra_12.2_PUBLIC/ Temurin 21 (system java is 8, too old) and Ghidra The goal is a C++ source tree that builds a native 64-bit Linux game: `git submodule update --init --recursive`, then `cmake -B build && cmake --build build`. SDL3 (window, OpenGL context, input, audio) and Lua 5.3 (mods) are submodules -in `external/`, built statically, with simdjson for data and Xiph's Ogg, Vorbis and Theora (decoders only) for the cutscene videos. Online features (Steam, EOS, curl) are offline stubs. The game -reads JSON, not XML: an import tool in `tools/` converts the player's own install (XML, packed archives) and mods into -`resources/` (both gitignored). Nothing from the game ships here. +in `external/`, built statically, with pugixml and simdjson for data and Xiph's Ogg, Vorbis and Theora (decoders only) +for the cutscene videos. Online features (Steam, EOS, curl) are offline stubs. Nothing from the game ships here. + +The game reads the player's own install as it is: `--resources /resources` mounts its packed archives +(`src/engine/filesys.cpp`, a port of KAGE's file system: each archive indexed once at start-up, its files unpacked on +demand) in the original's order (loose files, then animations, config, fonts, graphics, music, rooms, sfx, videos, +afterbirth, afterbirthp, the repentance_ archives and secret.a, a later archive overriding an earlier one), +with the language's mount (`resources.`) searched first and mods in the install's `mods/`. Every resource +(documents, anm2, images, sounds, music, videos, shaders, fonts, rooms, string tables, the game's Lua scripts) is read +through that one file system, and nothing is ever written into the install. XML documents and `.anm2` files are read +as the original's XML, and mods' own XML loads as it ships. The import tool in `tools/` (gitignored) still converts an +install into `resources/` (XML to JSON, anm2 to Anm2Ed's JSON), which the game reads just the same: loaders see one +node API (`src/engine/data.h`) over pugixml's tree or simdjson's, with identical elements, attribute strings and text. +An `.anm2` is told apart by its first character. + +When both a document's XML (`items.xml`) and its JSON (`items.xml.json`) are mounted, options.ini's `DataFormat` +(the overlay's Game Options, System tab) picks one: `xml` (the default) reads the XML wherever it is mounted, `json` +the JSON, and `auto` whichever the first mount holding either has, XML first there. A missing one falls back to the +other. The string tables load before options.ini, so they always prefer the XML. `generated-src/` is the whole decompiled game as C++, regenerated every build and never edited. `src/` is the readable game, written by hand on top of it one function at a time: @@ -67,7 +83,8 @@ Regenerate `generated-src/` after adding or moving a function in `src/`: ``` engine/ platform (SDL3 window, frame pacing, clock), gl, kage_* (graphics, input, sound), anm2, textures, - fonts, video, renderers, data loading, log, seeds and RNG, the test harness + fonts, video, renderers, the file system (packed archives) and data loading, log, seeds and RNG, the + test harness game/ main, Manager, game_* (game/state, game/save, game/update ...), options, strings, save data, mods, sound and music managers, dailies, local versus level/ level_* (level/generator, level/stage ...), room*, backdrop, minimap, path finder, rails, @@ -111,6 +128,7 @@ and field where two traces differ; `tools/harness/bot/` is a Lua mod that plays `tools/harness/goldens/check.sh` replays about 70 recorded runs (every character, the main and alternate floors, every final boss, Greed and Greedier, challenges, typed seeds, saving and continuing) on three saves (nothing unlocked in Hard, everything unlocked in Normal and in Hard) and names each trace that changed; `--record` re-records them. +`RESOURCES=/resources` replays them on the install itself instead of `resources/`. Traces follow the compiler's float code, so check with a clang build, as the goldens were recorded. ## Quick use diff --git a/external/pugixml b/external/pugixml new file mode 160000 index 0000000..ee86beb --- /dev/null +++ b/external/pugixml @@ -0,0 +1 @@ +Subproject commit ee86beb30e4973f5feffe3ce63bfa4fbadf72f38 diff --git a/generated-src/classes.h b/generated-src/classes.h index a62e2ed..1d1fb24 100644 --- a/generated-src/classes.h +++ b/generated-src/classes.h @@ -211,6 +211,10 @@ struct DamageEvent; struct DamageHit; struct DamageInfo; struct Data; +struct DataAttr; +struct DataAttrs; +struct DataChildren; +struct DataNode; struct DateTime; struct DeathmatchManager; struct DeathmatchTypeBase; @@ -8447,7 +8451,6 @@ void FUN_009a8a40(); // 009a8a40 void _player_hud_set_heart_anim_state(int param_1); // 009a90b0 void move_directory_files(); // 009a90e0 uint8_t delete_directory_recursive(uint8_t *path); // 009a9250 -void resources_mount_language(); // 009ab970 void FUN_009abd50(); // 009abd50 void FUN_009ad470(); // 009ad470 void FUN_009ad500(char *param_1, char *param_2); // 009ad500 @@ -12312,7 +12315,6 @@ bool FUN_00a68630(); // 00a68630 void FUN_00a68640(); // 00a68640 uint32_t FUN_00a68730(uint8_t *param_1); // 00a68730 uint32_t FUN_00a68790(uint8_t *param_1); // 00a68790 -void FUN_00a68a50(int *param_1); // 00a68a50 void FUN_00a68b50(uint8_t param_1); // 00a68b50 uint32_t FUN_00a68c40(); // 00a68c40 void FUN_00a68c50(); // 00a68c50 diff --git a/generated-src/file_system.cpp b/generated-src/file_system.cpp index 0f2a0bb..3a8e4bf 100644 --- a/generated-src/file_system.cpp +++ b/generated-src/file_system.cpp @@ -312,92 +312,6 @@ LAB_00a16b36: } while( true ); } -// 00a16c60 -uint32_t FileSystem::find_mount(uint8_t *param_1, uint8_t *param_2) -{ - int iVar1; - uint64_t qVar2; - uint8_t bVar3; - uint8_t *normalizedPath; - uint8_t *archivePath; - int *entry; - int in_ECX; - uint64_t *allocatedBytes; - int mountIndex; - uint8_t hashIter [8]; - int hashNode; - int fileSystem; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - uint32_t blockSize; - - local_8 = 0xffffffff; - puStack_c = &LAB_00b10fa0; - local_10 = ExceptionList; - ExceptionList = &local_10; - fileSystem = in_ECX; - normalizedPath = path_join(param_1,GHIDRA_CAST(0x0),0,0); - mountIndex = (*GHIDRA_CAST((in_ECX + 0xc)) - *GHIDRA_CAST((in_ECX + 8)) >> 2) + -1; - if (-1 < mountIndex) { - while( true ) { - if (DAT_00c37b14 != 0) { - archivePath = path_join(normalizedPath, - *GHIDRA_CAST((*GHIDRA_CAST((*GHIDRA_CAST((in_ECX + 8)) + mountIndex * 4)) + 0xc)),0, - 0); - bVar3 = open_archive_file(&PTR_vftable_00c37a10,archivePath,(void **)0x0); - param_1 = GHIDRA_CAST(CONCAT13(bVar3,(*GHIDRA_CAST((GHIDRA_CAST(&(param_1)) + 0x0))))); - if (archivePath != GHIDRA_CAST(0x0)) { - operator_delete(archivePath,1); - bVar3 = (*GHIDRA_CAST((GHIDRA_CAST(&(param_1)) + 0x3))); - } - if (bVar3 != 0) { - iVar1 = *GHIDRA_CAST((fileSystem + 8)); - *param_2 = 1; - ExceptionList = local_10; - return *GHIDRA_CAST((iVar1 + mountIndex * 4)); - } - in_ECX = fileSystem; - } - iVar1 = *GHIDRA_CAST((*GHIDRA_CAST((in_ECX + 8)) + mountIndex * 4)); - param_1 = GHIDRA_CAST(KAGE_Filesys_FileManager)::GetPrimaryFilePathHash(normalizedPath); - _Find_lower_bound<>(hashIter,¶m_1); - if (((*GHIDRA_CAST((hashNode + 0xd)) == '\0') && (*GHIDRA_CAST((hashNode + 0x10)) <= param_1)) && - (hashNode != *GHIDRA_CAST((iVar1 + 4)))) { - entry = map_find_value((void *)(iVar1 + 4),GHIDRA_UINT(¶m_1)); - if (*entry != 0) { - if (normalizedPath != GHIDRA_CAST(0x0)) { - local_8 = 0; - tracked_alloc(1,normalizedPath,0); - } - *param_2 = 0; - ExceptionList = local_10; - return *GHIDRA_CAST((*GHIDRA_CAST((fileSystem + 8)) + mountIndex * 4)); - } - } - mountIndex = mountIndex + -1; - if (mountIndex < 0) break; - in_ECX = fileSystem; - } - } - if (normalizedPath != GHIDRA_CAST(0x0)) { - if (g_mainHeap == (void *)0x0) { - allocatedBytes = &g_allocatedBytesNoHeap; - } - else { - allocatedBytes = GHIDRA_CAST((GHIDRA_INT(g_mainHeap) + 0x30)); - } - blockSize = *GHIDRA_CAST((normalizedPath + -4)); - qVar2 = *allocatedBytes; - *GHIDRA_CAST(allocatedBytes) = GHIDRA_UINT(*allocatedBytes) - blockSize; - *GHIDRA_CAST((GHIDRA_CAST(allocatedBytes) + 4)) = - *GHIDRA_CAST((GHIDRA_CAST(allocatedBytes) + 4)) - GHIDRA_UINT((GHIDRA_UINT(qVar2) < blockSize)); - free(normalizedPath + -4); - } - ExceptionList = local_10; - return 0; -} - // 00a17180 uint8_t * FileSystem::ResolvePath(uint8_t *path) { @@ -456,53 +370,6 @@ uint8_t * FileSystem::ResolvePath(uint8_t *path) return pbVar1; } -// 00a178d0 -void * FileSystem::Open(uint8_t *path, int *outResolvedPath) -{ - uint8_t *resolvedPath; - void *this_00; - void *local_10; - uint8_t *puStack_c; - int *local_8; - - resolvedPath = path; - local_8 = GHIDRA_CAST(0xffffffff); - puStack_c = &LAB_00af0b60; - local_10 = ExceptionList; - if ((path == GHIDRA_CAST(0x0)) || (*path == 0)) { - return (void *)0x0; - } - path = GHIDRA_CAST(0x0); - ExceptionList = &local_10; - resolvedPath = ResolvePath(resolvedPath); - open_archive_file(this,resolvedPath,&path); - if (path == GHIDRA_CAST(0x0)) { - open_disk_file(this_00,resolvedPath,&path); - if (outResolvedPath == GHIDRA_CAST(0x0)) { - if (resolvedPath == GHIDRA_CAST(0x0)) { - ExceptionList = local_10; - return path; - } - local_8 = GHIDRA_CAST(0x1); -LAB_00a1795c: - tracked_alloc(1,resolvedPath,0); - ExceptionList = local_10; - return path; - } - } - else if (outResolvedPath == GHIDRA_CAST(0x0)) { - if (resolvedPath == GHIDRA_CAST(0x0)) { - ExceptionList = local_10; - return path; - } - local_8 = outResolvedPath; - goto LAB_00a1795c; - } - *outResolvedPath = GHIDRA_INT(resolvedPath); - ExceptionList = local_10; - return path; -} - // 00a17ea0 uint8_t FileSystem::open_disk_file(uint8_t *path, void **outFile) { diff --git a/generated-src/kage_filesys_file_manager.cpp b/generated-src/kage_filesys_file_manager.cpp index 24462b4..23cb5d5 100644 --- a/generated-src/kage_filesys_file_manager.cpp +++ b/generated-src/kage_filesys_file_manager.cpp @@ -58,207 +58,3 @@ uint32_t KAGE_Filesys_FileManager::GetSecondaryFilePathHash() } return uVar4; } - -// 00a179c0 -void KAGE_Filesys_FileManager::LoadArchiveFile(uint8_t *param_1, uint32_t *param_2, uint16_t param_3) -{ - uint8_t isExpectedChecksum; - uint32_t uVar1; - uint8_t *resolvedPath; - uint8_t *loadedPathChar; - uint32_t isExpectedChecksum; - uint32_t *fileEntry; - uint8_t *extraout_ECX; - uint8_t *resolvedPathChar; - int iVar3; - int *piVar4; - uint32_t uVar5; - int dwordCount; - bool isLess; - char *format; - uint32_t archiveIndex; - uint32_t fileCount; - uint8_t *archivePath; - int local_e58; - int *stream; - uint8_t archiveType; - uint32_t local_e4c; - int archivedFile [3]; - int archivedFileRecord; - int chunkBuffer [128]; - uint8_t headerMagic [7]; - uint8_t local_15; - uint32_t local_14; - void *local_10; - uint8_t *puStack_c; - uint32_t local_8; - uint8_t ch; - - local_8 = 0xffffffff; - puStack_c = &LAB_00b11020; - local_10 = ExceptionList; - uVar1 = __security_cookie ^ GHIDRA_UINT((headerMagic + 0x18)); - ExceptionList = &local_10; - archivePath = param_1; - local_14 = uVar1; - resolvedPath = FileSystem::ResolvePath(param_1); - if (resolvedPath == GHIDRA_CAST(0x0)) { - KAGE_LogMessage(8,GHIDRA_CAST("Failed to open archive file \'%s\'\n")); - } - else { - uVar5 = 0; - archiveIndex = 0; - resolvedPathChar = extraout_ECX; - if (DAT_00c37b14 != 0) { - do { - loadedPathChar = GHIDRA_CAST((&DAT_00c37a14)[uVar5 * 2]); - resolvedPathChar = resolvedPath; - do { - ch = *loadedPathChar; - isLess = ch < *resolvedPathChar; - if (ch != *resolvedPathChar) { -LAB_00a17a60: - isExpectedChecksum = -GHIDRA_UINT(isLess) | 1; - goto LAB_00a17a65; - } - if (ch == 0) break; - ch = loadedPathChar[1]; - isLess = ch < resolvedPathChar[1]; - if (ch != resolvedPathChar[1]) goto LAB_00a17a60; - loadedPathChar = loadedPathChar + 2; - resolvedPathChar = resolvedPathChar + 2; - } while (ch != 0); - isExpectedChecksum = 0; -LAB_00a17a65: - } while ((isExpectedChecksum != 0) && (uVar5 = uVar5 + 1, uVar5 < DAT_00c37b14)); - archiveIndex = uVar5; - if (0x1f < uVar5) { - KAGE_LogMessage(8,(uint8_t *) - "Cannot load archive file \'%s\', maximum number of archive files exceeded\n" - ); - local_8 = 0; - tracked_alloc(1,resolvedPath,0); - ExceptionList = local_10; - return; - } - } - (&DAT_00c37a14)[archiveIndex * 2] = resolvedPath; - stream = GHIDRA_CAST(0x0); - (GHIDRA_CAST((resolvedPathChar)))->FileSystem::open_disk_file(resolvedPath,&stream); - if ((stream == GHIDRA_CAST(0x0)) && - (FileSystem::open_archive_file - (&PTR_vftable_00c37a10,GHIDRA_CAST((&DAT_00c37a14)[archiveIndex * 2]),&stream), - stream == GHIDRA_CAST(0x0))) { - KAGE_LogMessage(8,GHIDRA_CAST("Failed to open archive file \'%s\'\n")); - if ((void *)(&DAT_00c37a14)[archiveIndex * 2] == (void *)0x0) { - ExceptionList = local_10; - return; - } - local_8 = 1; - tracked_alloc(1,(void *)(&DAT_00c37a14)[archiveIndex * 2],0); - (&DAT_00c37a14)[archiveIndex * 2] = 0; - ExceptionList = local_10; - return; - } - piVar4 = stream; - (**(code **)(*stream + 0x14))(headerMagic,1,7,uVar1); - local_15 = 0; - archiveType = 0; - (**(code **)(*piVar4 + 0x14))(&archiveType,1,1); - (&DAT_00c37a18)[archiveIndex * 8] = archiveType; - local_e58 = 0; - (**(code **)(*piVar4 + 0x14))(&local_e58,4,1); - fileCount = 0; - (**(code **)(*piVar4 + 0x14))(&fileCount,2,1); - (**(code **)(*piVar4 + 0xc))(local_e58,0); - local_e58 = 0; - if ((uint16_t)fileCount != 0) { - do { - fileEntry = operator_new(0x1c); - piVar4 = stream; - local_e4c = 0; - *fileEntry = archiveIndex; - (**(code **)(*stream + 0x14))(&local_e4c,4,1); - fileEntry[1] = local_e4c; - local_e4c = 0; - (**(code **)(*piVar4 + 0x14))(&local_e4c,4,1); - fileEntry[2] = local_e4c; - local_e4c = 0; - (**(code **)(*piVar4 + 0x14))(&local_e4c,4,1); - fileEntry[3] = local_e4c; - local_e4c = 0; - (**(code **)(*piVar4 + 0x14))(&local_e4c,4,1); - fileEntry[4] = local_e4c; - local_e4c = 0; - (**(code **)(*piVar4 + 0x14))(&local_e4c,4,1); - fileEntry[5] = local_e4c; - if (((uint16_t)local_e58 < param_3) && (*param_2 == local_e4c)) { - isExpectedChecksum = 1; - } - else { - isExpectedChecksum = 0; - } - *GHIDRA_CAST((fileEntry + 6)) = isExpectedChecksum; - FUN_00a68a50(fileEntry); - local_8 = 2; - uVar1 = 0xababeb98; - memset(chunkBuffer,0,0x200); - local_e4c = *GHIDRA_CAST((archivedFileRecord + 0x10)); - do { - uVar5 = local_e4c; - if (0x200 < GHIDRA_INT(local_e4c)) { - uVar5 = 0x200; - } - isExpectedChecksum = (**(code **)(archivedFile[0] + 0x14))(chunkBuffer,1,uVar5); - iVar3 = 0; - dwordCount = GHIDRA_INT(((GHIDRA_INT((isExpectedChecksum + 3)) >> 0x1f & 3U) + isExpectedChecksum + 3)) >> 2; - if (0 < dwordCount) { - do { - piVar4 = chunkBuffer + iVar3; - iVar3 = iVar3 + 1; - uVar1 = uVar1 * -0x80000000 + *piVar4 + (uVar1 >> 1); - } while (iVar3 < dwordCount); - } - local_e4c = local_e4c - uVar5; - } while ((0 < GHIDRA_INT(local_e4c)) && (isExpectedChecksum == uVar5)); - if (uVar1 == *GHIDRA_CAST((archivedFileRecord + 0x14))) { - uVar5 = fileEntry[1] & 0x7fff; - iVar3 = *GHIDRA_CAST((&DAT_00c37b18 + uVar5 * 4)); - uVar1 = 0; - if (iVar3 != 0) { - do { - if (((*GHIDRA_CAST((iVar3 + 4)) == fileEntry[1]) && - (isExpectedChecksum = uVar1, *GHIDRA_CAST((iVar3 + 8)) == fileEntry[2])) || - (isExpectedChecksum = uVar1 + 1, 0x7fff < uVar1)) break; - uVar5 = uVar5 + 1 & 0x7fff; - iVar3 = *GHIDRA_CAST((&DAT_00c37b18 + uVar5 * 4)); - uVar1 = isExpectedChecksum; - } while (iVar3 != 0); - if (0x7fff < isExpectedChecksum) { - format = "Failed to load file %x%x from \'%s\', hash table is full\n"; - goto LAB_00a17dad; - } - } - *GHIDRA_CAST((&DAT_00c37b18 + uVar5 * 4)) = fileEntry; - } - else { - format = "Failed to load file %x%x from \'%s\', checksum is invalid\n"; -LAB_00a17dad: - KAGE_LogMessage(8,GHIDRA_CAST(format)); - operator_delete(fileEntry,0x1c); - } - local_8 = 0xffffffff; - (GHIDRA_CAST((archivedFile)))->KAGE::Filesys::ArchivedFile::~ArchivedFile(); - param_2 = param_2 + 1; - local_e58 = local_e58 + 1; - } while ((uint16_t)local_e58 < (uint16_t)fileCount); - piVar4 = stream; - } - (**(code **)*piVar4)(1); - if (DAT_00c37b14 < archiveIndex + 1) { - DAT_00c37b14 = archiveIndex + 1; - } - } - ExceptionList = local_10; - return; -} diff --git a/generated-src/stubs.cpp b/generated-src/stubs.cpp index bc08d4c..3b57236 100644 --- a/generated-src/stubs.cpp +++ b/generated-src/stubs.cpp @@ -8284,9 +8284,7 @@ EntityList_Query::~EntityList_Query() { generated_stub("EntityList_Query::~Entit void EntitySaveStateRef::Set(void *state) { generated_stub("EntitySaveStateRef::Set 006eee10"); } void * FileSystem::GetMountPrefixes(void *outPrefixes) { generated_stub("FileSystem::GetMountPrefixes 00a16060"); } void FileSystem::load_mount_points() { generated_stub("FileSystem::load_mount_points 00a167d0"); } -uint32_t FileSystem::find_mount(uint8_t *param_1, uint8_t *param_2) { generated_stub("FileSystem::find_mount 00a16c60"); } uint8_t * FileSystem::ResolvePath(uint8_t *path) { generated_stub("FileSystem::ResolvePath 00a17180"); } -void * FileSystem::Open(uint8_t *path, int *outResolvedPath) { generated_stub("FileSystem::Open 00a178d0"); } uint8_t FileSystem::open_disk_file(uint8_t *path, void **outFile) { generated_stub("FileSystem::open_disk_file 00a17ea0"); } uint8_t FileSystem::open_archive_file(uint8_t *path, void **outFile) { generated_stub("FileSystem::open_archive_file 00a17f40"); } void FrameQueue::setSize(int count) { generated_stub("FrameQueue::setSize 00aaa500"); } @@ -9024,7 +9022,6 @@ void KAGE::Thread::vfunc_3() { generated_stub("KAGE::Thread::vfunc_3 00a5a700"); uint32_t KAGE::Util::String::CharacterIteratorUTF8::FUN_00a55aa0() { generated_stub("KAGE::Util::String::CharacterIteratorUTF8::FUN_00a55aa0 00a55aa0"); } uint32_t KAGE_Filesys_FileManager::GetPrimaryFilePathHash(uint8_t *filePath) { generated_stub("KAGE_Filesys_FileManager::GetPrimaryFilePathHash 00a159d0"); } uint32_t KAGE_Filesys_FileManager::GetSecondaryFilePathHash() { generated_stub("KAGE_Filesys_FileManager::GetSecondaryFilePathHash 00a15ab0"); } -void KAGE_Filesys_FileManager::LoadArchiveFile(uint8_t *param_1, uint32_t *param_2, uint16_t param_3) { generated_stub("KAGE_Filesys_FileManager::LoadArchiveFile 00a179c0"); } void KColor::FromRGBA255(int red, int green, int blue, int alpha) { generated_stub("KColor::FromRGBA255 00682f50"); } void KColor::SetFromARGB(uint32_t argb) { generated_stub("KColor::SetFromARGB 00a0f550"); } KColor * KColor::set_from_argb_signed(uint32_t argb) { generated_stub("KColor::set_from_argb_signed 00a0f610"); } @@ -12523,7 +12520,6 @@ void FUN_009a8a40() { generated_stub("FUN_009a8a40 009a8a40"); } void _player_hud_set_heart_anim_state(int param_1) { generated_stub("_player_hud_set_heart_anim_state 009a90b0"); } void move_directory_files() { generated_stub("move_directory_files 009a90e0"); } uint8_t delete_directory_recursive(uint8_t *path) { generated_stub("delete_directory_recursive 009a9250"); } -void resources_mount_language() { generated_stub("resources_mount_language 009ab970"); } void FUN_009abd50() { generated_stub("FUN_009abd50 009abd50"); } void FUN_009ad470() { generated_stub("FUN_009ad470 009ad470"); } void FUN_009ad500(char *param_1, char *param_2) { generated_stub("FUN_009ad500 009ad500"); } @@ -16393,7 +16389,6 @@ bool FUN_00a68630() { generated_stub("FUN_00a68630 00a68630"); } void FUN_00a68640() { generated_stub("FUN_00a68640 00a68640"); } uint32_t FUN_00a68730(uint8_t *param_1) { generated_stub("FUN_00a68730 00a68730"); } uint32_t FUN_00a68790(uint8_t *param_1) { generated_stub("FUN_00a68790 00a68790"); } -void FUN_00a68a50(int *param_1) { generated_stub("FUN_00a68a50 00a68a50"); } void FUN_00a68b50(uint8_t param_1) { generated_stub("FUN_00a68b50 00a68b50"); } uint32_t FUN_00a68c40() { generated_stub("FUN_00a68c40 00a68c40"); } void FUN_00a68c50() { generated_stub("FUN_00a68c50 00a68c50"); } diff --git a/src/engine/anm2.cpp b/src/engine/anm2.cpp index 5bb91aa..5f88fb4 100644 --- a/src/engine/anm2.cpp +++ b/src/engine/anm2.cpp @@ -8,6 +8,7 @@ #include "engine/render_passes.h" #include "level/room.h" #include "engine/texture_cache.h" +#include "simdjson.h" #include #include #include @@ -45,6 +46,8 @@ constexpr std::string_view IDLE_ANIMATION = "Idle"; constexpr std::string_view CHAMPION_COLOR_UNIFORM = "ChampionColor"; constexpr std::string_view COLOR_OFFSET_SHADER = "ColorOffset"; constexpr std::string_view COLOR_OFFSET_CHAMPION_SHADER = "ColorOffsetChampion"; +// What may come before an .anm2's first character: whitespace and a UTF-8 byte order mark. +constexpr std::string_view LEADING_SPACE = " \t\r\n\xef\xbb\xbf"; // Delirium's forms swap a boss's or monster's spritesheets for the ones under DELIRIUM_FORMS_FOLDER. constexpr int DELIRIUM_TYPE = 412; @@ -426,6 +429,16 @@ static void triggers_read(object source, const Anm2Parse& parse, AnimationData& } } +// Fills an animation's layerMap from its layer tracks. +static void layer_map_build(AnimationData& animation) +{ + for (size_t i = 0; i < animation.animLayers.size(); i++) + { + int layerId = animation.animLayers[i].layerId; + if (layerId >= 0 && layerId < ANM2_LAYER_LIMIT) animation.layerMap[layerId] = (int)i; + } +} + // Every animation of a list in file order, a group's among them in its place. static void animations_read(object list, const Anm2Parse& parse, AnmFileData& file) { @@ -450,11 +463,7 @@ static void animations_read(object list, const Anm2Parse& parse, AnmFileData& fi layer_tracks_read(fields, parse, animation, root); null_tracks_read(fields, parse, animation, root); triggers_read(fields, parse, animation); - for (size_t i = 0; i < animation.animLayers.size(); i++) - { - int layerId = animation.animLayers[i].layerId; - if (layerId >= 0 && layerId < ANM2_LAYER_LIMIT) animation.layerMap[layerId] = (int)i; - } + layer_map_build(animation); } } @@ -476,33 +485,30 @@ static std::vector names_read(object document, std::string_view key return names; } -// 0040ed50 Parses an .anm2, Anm2Ed's JSON document (its docs/json_format.md), into what the game plays. -// Ids are indices into their lists. Spritesheet paths become relative to resources/, from the .anm2's folder. -static std::shared_ptr file_parse(const std::string& path) +// A spritesheet's path from the .anm2's folder, relative to resources/. +static std::string sheet_path_resolve(const std::string& path, std::string_view sheet) +{ + std::string relative(sheet); + std::replace(relative.begin(), relative.end(), '\\', '/'); + return (std::filesystem::path(path).parent_path() / relative).lexically_normal().generic_string(); +} + +// Anm2Ed's JSON document (its docs/json_format.md). Ids are indices into their lists. +static bool json_file_read(Anm2Parse& parse, std::string& bytes, AnmFileData& file) { static simdjson::dom::parser parser; - auto file = std::make_shared(); - Anm2Parse parse = {path, {}, {}}; std::vector sheetPaths; + const std::string& path = parse.path; object document; array list; - std::string redirected = g_manager ? g_manager->modManager.TryRedirectPath(path) : path; - if (parser.load(resource_path(redirected)).get(document)) - { - log_print(LOG_INFO, "ERROR Could not open %s\n", path.c_str()); - return nullptr; - } - + if (parser.parse(bytes).get(document)) return false; if (!document["sheets"].get(list)) for (element entry : list) { object fields; if (entry.get(fields)) continue; - std::string relative(text_get(fields, "path")); - std::replace(relative.begin(), relative.end(), '\\', '/'); - auto resolved = std::filesystem::path(path).parent_path() / relative; - sheetPaths.push_back(resolved.lexically_normal().generic_string()); + sheetPaths.push_back(sheet_path_resolve(path, text_get(fields, "path"))); parse.regions.push_back(frames_read(fields, "regions", nullptr)); } @@ -510,9 +516,9 @@ static std::shared_ptr file_parse(const std::string& path) for (element entry : list) { object fields; - LayerData& layer = file->layers.emplace_back(); + LayerData& layer = file.layers.emplace_back(); bool isRead = !entry.get(fields); - layer.id = (int)file->layers.size() - 1; + layer.id = (int)file.layers.size() - 1; layer.name = isRead ? text_get(fields, "name") : ""; layer.spriteSheetId = isRead ? (int)number_get(fields, "sheet", 0) : 0; if (layer.id >= ANM2_LAYER_LIMIT) @@ -522,18 +528,217 @@ static std::shared_ptr file_parse(const std::string& path) else log_print(LOG_ASSERT, "%s: invalid spritesheet id %d\n", path.c_str(), layer.spriteSheetId); parse.layerSheets.push_back(layer.spriteSheetId); } - if (file->layers.empty()) log_print(LOG_ASSERT, "%s: no layers\n", path.c_str()); + if (file.layers.empty()) log_print(LOG_ASSERT, "%s: no layers\n", path.c_str()); - file->nullLayerNames = names_read(document, "nulls"); - if (file->nullLayerNames.size() > ANM2_LAYER_LIMIT) + file.nullLayerNames = names_read(document, "nulls"); + if (file.nullLayerNames.size() > ANM2_LAYER_LIMIT) log_print(LOG_ASSERT, "%s: invalid Null ID %d\n", path.c_str(), ANM2_LAYER_LIMIT); - file->eventNames = names_read(document, "events"); - if (file->eventNames.size() > ANM2_EVENT_LIMIT) + file.eventNames = names_read(document, "events"); + if (file.eventNames.size() > ANM2_EVENT_LIMIT) log_print(LOG_ASSERT, "%s: invalid Event ID %d\n", path.c_str(), ANM2_EVENT_LIMIT); - file->defaultAnimation = text_get(document, "default"); + file.defaultAnimation = text_get(document, "default"); object animations; - if (!document["animations"].get(animations)) animations_read(animations, parse, *file); + if (!document["animations"].get(animations)) animations_read(animations, parse, file); + return true; +} + +// A number attribute as atoi reads it, or fallback when the element lacks it. +static int xml_int(DataNode node, std::string_view name, int fallback) +{ + std::optional text = node_attr_find(node, name); + return text ? std::atoi(text->data()) : fallback; +} + +static float xml_float(DataNode node, std::string_view name, float fallback) +{ + std::optional text = node_attr_find(node, name); + return text ? (float)std::atof(text->data()) : fallback; +} + +// A bool attribute as the original reads it: "true", "True" or a nonzero number, false when empty. +static bool is_xml_true(DataNode node, std::string_view name, bool fallback) +{ + std::optional text = node_attr_find(node, name); + if (!text) return fallback; + return *text == "true" || *text == "True" || std::atoi(text->data()) != 0; +} + +// The first child with a tag, as rapidxml's first_node finds it. +static std::optional xml_child_find(DataNode node, std::string_view tag) +{ + for (DataNode child : node_children(node)) + if (node_tag(child) == tag) return child; + return std::nullopt; +} + +// The keyframes of a track of the original's XML, each read as frame_read reads Anm2Ed's: tints and offsets out of +// 255, scales out of 100. A missing attribute keeps Anm2Ed's default. +template static std::vector xml_frames_read(DataNode track) +{ + constexpr std::string_view TINTS[] = {"RedTint", "GreenTint", "BlueTint", "AlphaTint"}; + constexpr std::string_view OFFSETS[] = {"RedOffset", "GreenOffset", "BlueOffset"}; + std::vector frames; + + for (DataNode node : node_children(track)) + { + AnimationFrame frame; + frame.crop = vector_make(xml_float(node, "XCrop", 0), xml_float(node, "YCrop", 0)); + frame.pivot = vector_make(xml_float(node, "XPivot", 0), xml_float(node, "YPivot", 0)); + frame.width = xml_float(node, "Width", 0); + frame.height = xml_float(node, "Height", 0); + for (int i = 0; i < 4; i++) frame.color._tint[i] = xml_float(node, TINTS[i], CHANNEL) / CHANNEL; + for (int i = 0; i < 3; i++) frame.color._offset[i] = xml_float(node, OFFSETS[i], 0) / CHANNEL; + frame.pos = vector_make(xml_float(node, "XPosition", 0), xml_float(node, "YPosition", 0)); + float scaleX = xml_float(node, "XScale", PERCENT); + float scaleY = xml_float(node, "YScale", PERCENT); + frame.scale = vector_make(scaleX / PERCENT, scaleY / PERCENT); + frame.rotation = xml_float(node, "Rotation", 0); + frame.duration = xml_int(node, "Delay", 1); + frame.isVisible = is_xml_true(node, "Visible", true); + frame.isInterpolated = is_xml_true(node, "Interpolated", false); + frames.push_back(frame); + } + return frames; +} + +// The names a list gives by id, as many as it has children, each child's Name at its Id. An id outside the list's +// limit logs error and names nothing. +static std::vector xml_names_read(std::optional list, size_t limit, const char* error, + const std::string& path) +{ + std::vector names(limit); + size_t count = 0; + + for (DataNode node : list ? node_children(*list) : DataChildren()) + { + int id = xml_int(node, "Id", (int)limit); + count++; + if (id >= 0 && id < (int)limit) names[id] = node_attr(node, "Name"); + else log_print(LOG_ASSERT, error, path.c_str(), id); + } + names.resize(count); + return names; +} + +// The animations of the original's XML: every element from the first on, its root track applied to its +// layer and null tracks, and one trigger per event. +static void xml_animations_read(DataNode list, const Anm2Parse& parse, AnmFileData& file) +{ + bool isFound = false; + + for (DataNode node : node_children(list)) + { + isFound = isFound || node_tag(node) == "Animation"; + if (!isFound) continue; + + AnimationData& animation = file.animations.emplace_back(); + std::optional rootTrack = xml_child_find(node, "RootAnimation"); + std::optional layers = xml_child_find(node, "LayerAnimations"); + std::optional nulls = xml_child_find(node, "NullAnimations"); + std::optional triggers = xml_child_find(node, "Triggers"); + animation.name = node_attr(node, "Name"); + animation.index = (int)file.animations.size() - 1; + animation.length = xml_int(node, "FrameNum", 0); + animation.isLooping = is_xml_true(node, "Loop", false); + + std::vector root; + if (rootTrack) root = track_interpolate(xml_frames_read(*rootTrack)); + for (DataNode track : layers ? node_children(*layers) : DataChildren()) + { + if (animation.animLayers.size() >= ANM2_LAYER_LIMIT) + log_print(LOG_ASSERT, "%s: too many animation layers\n", parse.path.c_str()); + auto frames = track_interpolate(xml_frames_read(track)); + animation.animLayers.push_back({track_root_apply(frames, root, parse.path), xml_int(track, "LayerId", -1), + is_xml_true(track, "Visible", true)}); + } + for (DataNode track : nulls ? node_children(*nulls) : DataChildren()) + { + if (animation.nullLayers.size() >= ANM2_LAYER_LIMIT) + log_print(LOG_ASSERT, "%s: too many null layers\n", parse.path.c_str()); + auto frames = track_interpolate(xml_frames_read(track)); + animation.nullLayers.push_back({track_root_apply(frames, root, parse.path), xml_int(track, "NullId", -1), + is_xml_true(track, "Visible", true)}); + } + for (DataNode trigger : triggers ? node_children(*triggers) : DataChildren()) + { + if (animation.eventTriggers.size() >= ANM2_TRIGGER_LIMIT) + log_print(LOG_ASSERT, "%s: too many triggers\n", parse.path.c_str()); + auto eventId = (uint32_t)xml_int(trigger, "EventId", 0); + animation.eventTriggers.push_back({xml_int(trigger, "AtFrame", 0), eventId}); + } + layer_map_build(animation); + } +} + +// The original's XML (, read through rapidxml): spritesheets, layers, nulls and events by their Id, the +// layers in file order logging an Id out of place, then the animations. +static bool xml_file_read(Anm2Parse& parse, std::string& bytes, AnmFileData& file) +{ + Data data; + data_parse(data, bytes); + std::optional actor = xml_child_find(data.root, "AnimatedActor"); + if (data.isLoaded && node_tag(data.root) == "AnimatedActor") actor = data.root; + if (!data.isLoaded || !actor) return false; + + const std::string& path = parse.path; + std::optional content = xml_child_find(*actor, "Content"); + std::optional sheets = content ? xml_child_find(*content, "Spritesheets") : std::nullopt; + std::optional layers = content ? xml_child_find(*content, "Layers") : std::nullopt; + std::vector sheetPaths(ANM2_LAYER_LIMIT); + int sheetCount = 0; + + for (DataNode node : sheets ? node_children(*sheets) : DataChildren()) + { + int id = xml_int(node, "Id", ANM2_LAYER_LIMIT); + if (id != sheetCount++ || id >= ANM2_LAYER_LIMIT) + log_print(LOG_ASSERT, "%s: invalid spritesheet id %d\n", path.c_str(), id); + if (id >= 0 && id < ANM2_LAYER_LIMIT) sheetPaths[id] = sheet_path_resolve(path, node_attr(node, "Path")); + } + for (DataNode node : layers ? node_children(*layers) : DataChildren()) + { + LayerData& layer = file.layers.emplace_back(); + int id = xml_int(node, "Id", ANM2_LAYER_LIMIT); + layer.id = (int)file.layers.size() - 1; + layer.name = node_attr(node, "Name"); + layer.spriteSheetId = xml_int(node, "SpritesheetId", -1); + if (id != layer.id || id >= ANM2_LAYER_LIMIT) + log_print(LOG_ASSERT, "%s: invalid layer id %d\n", path.c_str(), id); + if (layer.spriteSheetId >= 0 && layer.spriteSheetId < sheetCount) + layer.spriteSheetPath = sheetPaths[layer.spriteSheetId]; + else log_print(LOG_ASSERT, "%s: invalid spritesheet id %d\n", path.c_str(), layer.spriteSheetId); + } + if (file.layers.empty()) log_print(LOG_ASSERT, "%s: no layers\n", path.c_str()); + + std::optional nulls = content ? xml_child_find(*content, "Nulls") : std::nullopt; + std::optional events = content ? xml_child_find(*content, "Events") : std::nullopt; + file.nullLayerNames = xml_names_read(nulls, ANM2_LAYER_LIMIT, "%s: invalid Null ID %d\n", path); + file.eventNames = xml_names_read(events, ANM2_EVENT_LIMIT, "%s: invalid Event ID %d\n", path); + + std::optional animations = xml_child_find(*actor, "Animations"); + if (!animations) return true; + file.defaultAnimation = node_attr(*animations, "DefaultAnimation"); + xml_animations_read(*animations, parse, file); + return true; +} + +// 0040ed50 Parses an .anm2 into what the game plays, by its first character: the original's XML ('<') or Anm2Ed's JSON +// document. Spritesheet paths become relative to resources/, from the .anm2's folder. +static std::shared_ptr file_parse(const std::string& path) +{ + auto file = std::make_shared(); + Anm2Parse parse = {path, {}, {}}; + std::string redirected = g_manager ? g_manager->modManager.TryRedirectPath(path) : path; + std::string bytes; + + bool isRead = resource_load(redirected, bytes); + size_t first = bytes.find_first_not_of(LEADING_SPACE); + bool isXml = first != std::string::npos && bytes[first] == '<'; + if (!isRead || !(isXml ? xml_file_read(parse, bytes, *file) : json_file_read(parse, bytes, *file))) + { + log_print(LOG_INFO, "ERROR Could not open %s\n", path.c_str()); + return nullptr; + } return file; } @@ -1386,7 +1591,7 @@ void ANM2::LoadDeliriumForm(ANM2& sprite, int type, int variant, bool isReloadAn if (!replaced) continue; path.replace(GFX_FOLDER.size(), replaced, DELIRIUM_FORMS_FOLDER); - if (std::filesystem::exists(resource_path(path))) sprite.ReplaceSpritesheet(i, path); + if (resource_exists(path)) sprite.ReplaceSpritesheet(i, path); } sprite.LoadGraphics(); diff --git a/src/engine/data.cpp b/src/engine/data.cpp index e56ea4d..a293277 100644 --- a/src/engine/data.cpp +++ b/src/engine/data.cpp @@ -1,122 +1,292 @@ #include "engine/data.h" #include "game/manager.h" -#include "engine/platform.h" -#include -#include +#include "pugixml.hpp" +#include "simdjson.h" +#include +#include +#include -constexpr std::string_view EMPTY_ARRAY = "[]"; -// What a missing tag, attribute or text reads as: empty, but C text that atoi can take. +// What a missing tag or attribute reads as: empty, but C text that atoi can take. constexpr std::string_view EMPTY_TEXT = ""; -constexpr std::string_view JSON_EXTENSION = ".json"; -// Where the import tool puts a language archive's files (the original's resources. mount). -constexpr std::string_view LANGUAGE_FOLDER = "lang/"; -// Mods reach their own files from resources/ through "../mods/", and here the mods live in resources/mods/. -constexpr std::string_view MODS_FROM_RESOURCES = "../mods/"; -constexpr std::string_view PARENT_FOLDER = "../"; -constexpr std::string_view MODS_FOLDER = "mods/"; -// The game's own folder name, which the exe writes in front of some paths ("resources/gfx/1000.034_Fart.anm2"). -constexpr std::string_view GAME_RESOURCES_FOLDER = "resources/"; -constexpr std::string_view ASSETS_FOLDER = "assets"; +// The whitespace Python's strip takes off, which decides whether the import tool keeps an element's text. +constexpr std::string_view TEXT_SPACE = " \t\n\r\v\f\x1c\x1d\x1e\x1f"; +// A run of text the import tool's fix-up leaves alone when it is only this whitespace, so expat turns its line ends +// into '\n'. It keeps every other run's carriage returns, as rapidxml does. +constexpr std::string_view PIECE_SPACE = " \t\n\r\v\f"; +constexpr std::string_view BYTE_ORDER_MARK = "\xef\xbb\xbf"; +constexpr std::string_view COMMENT_OPEN = ""; +// The parse keeps text as the XML holds it, whitespace and line ends included, as rapidxml and the import tool do. +constexpr unsigned int XML_PARSE_FLAGS = pugi::parse_cdata | pugi::parse_escapes | pugi::parse_ws_pcdata; -std::string dataDirectory = "resources/"; -std::string languageDirectory; - -// A game path lowercased with forward slashes, as the game normalizes every path before a lookup. A path already under -// the resources or the mods folder, which mods build from their script's path as the original's absolute ones, stays -// there. -static std::string path_normalize(std::string_view path) +// A simdjson element or iterator by its tape reference, which is all either holds. +struct JsonRef { - std::string_view mods = platform.modsDirectory; - bool isModsPath = !mods.empty() && path.starts_with(mods); - if (isModsPath) path.remove_prefix(mods.size()); - else if (path.starts_with(dataDirectory)) path.remove_prefix(dataDirectory.size()); + const void* document; + size_t index; +}; - std::string normalized(path); - for (char& letter : normalized) letter = letter == '\\' ? '/' : (char)std::tolower((unsigned char)letter); - if (isModsPath) normalized.insert(0, MODS_FOLDER); - else if (normalized.starts_with(MODS_FROM_RESOURCES)) normalized.erase(0, PARENT_FOLDER.size()); - else if (normalized.starts_with(GAME_RESOURCES_FOLDER)) normalized.erase(0, GAME_RESOURCES_FOLDER.size()); - return normalized; +static_assert(sizeof(JsonRef) == sizeof(simdjson::dom::element)); +static_assert(std::is_trivially_copyable_v); +static_assert(sizeof(JsonRef) == sizeof(simdjson::dom::array::iterator)); +static_assert(sizeof(JsonRef) == sizeof(simdjson::dom::object::iterator)); + +// A document's parsed form: pugixml's tree of its XML, or simdjson's tape of its JSON. +struct DataDocument +{ + pugi::xml_document xml; + simdjson::dom::parser parser; +}; + +Data::Data() = default; +Data::~Data() = default; + +template static Json json_get(DataNode node) +{ + return std::bit_cast(JsonRef{node.json, node.jsonIndex}); } -// A normalized path under the language's folder when that holds it, a mod's under the mods folder, under the data -// directory otherwise. -static std::string mount_resolve(const std::string& normalized) +template static DataNode json_node(Json json) { - std::error_code error; - std::string localized = languageDirectory + normalized; - - if (!languageDirectory.empty() && std::filesystem::exists(localized, error)) return localized; - if (normalized.starts_with(MODS_FOLDER) && !platform.modsDirectory.empty()) - return platform.modsDirectory + normalized.substr(MODS_FOLDER.size()); - return dataDirectory + normalized; + JsonRef ref = std::bit_cast(json); + return {ref.document, ref.index, nullptr}; } -// Where a game path lives once imported. -std::string resource_path(std::string_view path) +static pugi::xml_node xml_get(DataNode node) { - return mount_resolve(path_normalize(path)); + return pugi::xml_node((pugi::xml_node_struct*)node.xml); } -// Where a file the repository ships itself lives: in assets/, beside the resources folder. -std::string asset_path(std::string_view path) +static DataNode xml_node(pugi::xml_node node) { - return (std::filesystem::path(dataDirectory).parent_path().parent_path() / ASSETS_FOLDER / path).string(); + return {nullptr, 0, node.internal_object()}; } -// Where a converted XML document lives: its game path with ".json" appended. -std::string data_path(std::string_view path) +static DataNode xml_attr_node(pugi::xml_attribute attr) { - return mount_resolve(path_normalize(path) + std::string(JSON_EXTENSION)); + return {nullptr, 0, attr.internal_object()}; } -// 009abbd0 Remounts the resources, with the folder of the string table's language in front once there is a manager. -// The language folder is only mounted when the import tool wrote one, which finds the same files. -// The original also mounts the game folder behind the resources when its file system already knows it. Nothing on -// Linux reads from there. -void reload_resource_paths() +// The element itself, or the next element after it among its siblings. +static pugi::xml_node element_from(pugi::xml_node node) { - languageDirectory.clear(); - if (!g_manager) return; - - std::string localized = dataDirectory + std::string(LANGUAGE_FOLDER) + std::string(Manager::GetLanguage()) + '/'; - std::error_code error; - if (std::filesystem::is_directory(localized, error)) languageDirectory = localized; + while (node && node.type() != pugi::node_element) node = node.next_sibling(); + return node; } -// Loads a converted document, leaving isLoaded false when it is missing or unreadable. +// The attribute itself, or the next after it, that no later attribute of the same name repeats. +static pugi::xml_attribute attr_from(pugi::xml_attribute attr) +{ + for (; attr; attr = attr.next_attribute()) + { + pugi::xml_attribute later = attr.next_attribute(); + while (later && std::strcmp(later.name(), attr.name()) != 0) later = later.next_attribute(); + if (!later) break; + } + return attr; +} + +// What rapidxml does with closing tags the import tool's fix-up redoes for expat: each closes the element open +// there whatever its name, one with none open is dropped, and the end of the text closes the rest. +static std::string tags_balance(std::string_view text) +{ + std::vector open; + std::string balanced; + size_t last = 0; + + for (size_t start = text.find('<'); start != std::string_view::npos; start = text.find('<', start + 1)) + { + if (text.substr(start).starts_with(COMMENT_OPEN)) + { + start = text.find(COMMENT_CLOSE, start); + if (start == std::string_view::npos) break; + continue; + } + size_t end = start + 1; + for (char quote = 0; end < text.size() && (quote || text[end] != '>'); end++) + if (text[end] == '"' || text[end] == '\'') quote = quote == text[end] ? 0 : quote ? quote : text[end]; + if (end >= text.size()) break; + + std::string_view tag = text.substr(start, end + 1 - start); + if (tag[1] == '?' || tag[1] == '!' || tag.ends_with("/>")) + { + start = end; + continue; + } + if (tag[1] != '/') open.push_back(tag.substr(1, tag.find_first_of(" \t\r\n/>") - 1)); + else + { + balanced.append(text.substr(last, start - last)); + if (!open.empty()) balanced.append(""); + if (!open.empty()) open.pop_back(); + last = end + 1; + } + start = end; + } + balanced.append(text.substr(last)); + for (auto name = open.rbegin(); name != open.rend(); name++) balanced.append(""); + return balanced; +} + +// Parses an XML document as the game's rapidxml reads it, closing tags matched to the elements they close. Its root +// is its one top-level element, or the document over several. +static bool xml_parse(Data& data, std::string_view bytes) +{ + pugi::xml_document& xml = data.document->xml; + pugi::xml_parse_result result = xml.load_buffer(bytes.data(), bytes.size(), XML_PARSE_FLAGS); + if (result.status == pugi::status_end_element_mismatch) + { + std::string balanced = tags_balance(bytes); + result = xml.load_buffer(balanced.data(), balanced.size(), XML_PARSE_FLAGS); + } + if (!result) return false; + + pugi::xml_node root = element_from(xml.first_child()); + if (!root) return false; + data.root = xml_node(element_from(root.next_sibling()) ? xml : root); + return true; +} + +// Parses a document's bytes by their first character: '<' XML, '{' the import tool's JSON. isLoaded tells whether it +// parsed. A JSON document parses in place, so bytes may gain room for simdjson's padding. +void data_parse(Data& data, std::string& bytes) +{ + std::string_view text = bytes; + if (text.starts_with(BYTE_ORDER_MARK)) text.remove_prefix(BYTE_ORDER_MARK.size()); + size_t first = text.find_first_not_of(TEXT_SPACE); + + data.document = std::make_unique(); + data.isLoaded = false; + if (first != std::string_view::npos && text[first] == '<') data.isLoaded = xml_parse(data, bytes); + if (first == std::string_view::npos || text[first] != '{') return; + + simdjson::dom::element root; + bytes.reserve(bytes.size() + simdjson::SIMDJSON_PADDING); + data.isLoaded = data.document->parser.parse(bytes.data(), bytes.size(), false).get(root) == simdjson::SUCCESS; + data.root = json_node(root); +} + +// Loads a game document in the form the DataFormat option prefers, leaving isLoaded false when neither form is +// mounted or the one read does not parse. void data_load(Data& data, std::string_view path) { - data.isLoaded = data.parser.load(data_path(path)).get(data.root) == simdjson::SUCCESS; + DataFormat format = g_manager ? g_manager->optionsConfig.dataFormat : DATA_FORMAT_XML; + std::string json = std::string(path) + std::string(JSON_EXTENSION); + std::string bytes; + bool isRead = format == DATA_FORMAT_AUTO ? resource_load_first({path, json}, bytes) + : format == DATA_FORMAT_JSON ? resource_load(json, bytes) || resource_load(path, bytes) + : resource_load(path, bytes) || resource_load(json, bytes); + + data.isLoaded = false; + if (isRead) data_parse(data, bytes); } std::string_view node_tag(DataNode node) { std::string_view tag; - return node["tag"].get(tag) == simdjson::SUCCESS ? tag : EMPTY_TEXT; + if (node.xml) return xml_get(node).type() == pugi::node_document ? DOCUMENT_TAG : xml_get(node).name(); + return json_get(node)["tag"].get(tag) == simdjson::SUCCESS ? tag : EMPTY_TEXT; +} + +// An attribute's raw string, the last of a repeated one, or nothing when the element lacks it. +std::optional node_attr_find(DataNode node, std::string_view name) +{ + std::optional found; + std::string_view value; + + if (!node.xml) + { + if (json_get(node)["attrs"][name].get(value) == simdjson::SUCCESS) found = value; + return found; + } + for (pugi::xml_attribute attr = xml_get(node).last_attribute(); attr; attr = attr.previous_attribute()) + if (attr.name() == name) return attr.value(); + return found; } // An attribute's raw string, or an empty one when the element lacks it. std::string_view node_attr(DataNode node, std::string_view name) +{ + return node_attr_find(node, name).value_or(EMPTY_TEXT); +} + +// The element's text, all of it between its children joined, or empty when that is only whitespace. Line ends read as +// in the import tool's JSON. +std::string node_text(DataNode node) { std::string_view value; - return node["attrs"][name].get(value) == simdjson::SUCCESS ? value : EMPTY_TEXT; + std::string text; + + if (!node.xml) + { + if (json_get(node)["text"].get(value) == simdjson::SUCCESS) text = value; + return text; + } + for (pugi::xml_node child : xml_get(node).children()) + { + std::string_view piece = child.value(); + bool isKept = child.type() == pugi::node_pcdata && piece.find_first_not_of(PIECE_SPACE) != std::string::npos; + if (child.type() != pugi::node_pcdata && child.type() != pugi::node_cdata) continue; + + for (size_t i = 0; i < piece.size(); i++) + if (isKept || piece[i] != '\r') text += piece[i]; + else if (i + 1 == piece.size() || piece[i + 1] != '\n') text += '\n'; + } + if (text.find_first_not_of(TEXT_SPACE) == std::string::npos) text.clear(); + return text; } -std::string_view node_text(DataNode node) +DataChildren node_children(DataNode node) { - std::string_view text; - return node["text"].get(text) == simdjson::SUCCESS ? text : EMPTY_TEXT; + DataChildren children; + simdjson::dom::array list; + + if (node.xml) children.first.cursor = xml_node(element_from(xml_get(node).first_child())); + if (node.xml) children.last.cursor = xml_node(pugi::xml_node()); + if (node.xml || json_get(node)["children"].get(list) != simdjson::SUCCESS) return children; + children.first.cursor = json_node(list.begin()); + children.last.cursor = json_node(list.end()); + return children; } -// The element's children in document order, empty when it has none. -// A default-constructed array points at no document, so a parsed empty one stands in. -simdjson::dom::array node_children(DataNode node) +DataChildren::iterator& DataChildren::iterator::operator++() { - static simdjson::dom::parser emptyParser; - static simdjson::dom::array empty = - emptyParser.parse(EMPTY_ARRAY.data(), EMPTY_ARRAY.size()).get_array().value_unsafe(); - simdjson::dom::array children; - - return node["children"].get(children) == simdjson::SUCCESS ? children : empty; + if (cursor.xml) cursor = xml_node(element_from(xml_get(cursor).next_sibling())); + else cursor = json_node(++json_get(cursor)); + return *this; +} + +DataAttrs node_attrs(DataNode node) +{ + DataAttrs attrs; + simdjson::dom::object fields; + + if (node.xml) attrs.first.cursor = xml_attr_node(attr_from(xml_get(node).first_attribute())); + if (node.xml) attrs.last.cursor = xml_attr_node(pugi::xml_attribute()); + if (node.xml || json_get(node)["attrs"].get(fields) != simdjson::SUCCESS) return attrs; + attrs.first.cursor = json_node(fields.begin()); + attrs.last.cursor = json_node(fields.end()); + return attrs; +} + +DataAttr DataAttrs::iterator::operator*() const +{ + std::string_view value; + if (cursor.xml) + { + pugi::xml_attribute attr((pugi::xml_attribute_struct*)cursor.xml); + return {attr.name(), attr.value()}; + } + + auto field = json_get(cursor); + if (field.value().get(value) != simdjson::SUCCESS) value = EMPTY_TEXT; + return {field.key(), value}; +} + +DataAttrs::iterator& DataAttrs::iterator::operator++() +{ + pugi::xml_attribute attr((pugi::xml_attribute_struct*)cursor.xml); + if (cursor.xml) cursor = xml_attr_node(attr_from(attr.next_attribute())); + else cursor = json_node(++json_get(cursor)); + return *this; } diff --git a/src/engine/data.h b/src/engine/data.h index 1b29913..e875eff 100644 --- a/src/engine/data.h +++ b/src/engine/data.h @@ -1,36 +1,102 @@ #pragma once -#include "simdjson.h" +#include "engine/filesys.h" +#include +#include #include #include -// The root node a converted XML file opens with. +// The root a document with several top-level elements opens with, as the import tool names it. constexpr std::string_view DOCUMENT_TAG = "#document"; +// What the import tool appends to a document's path for its JSON. +constexpr std::string_view JSON_EXTENSION = ".json"; -// A game document the import tool converted from XML (items.xml, entities2.xml ...) into resources/.json. -// (.anm2 files are Anm2Ed's own JSON documents under their own names instead.) -// Each element is {"tag", "attrs", "children", "text"}, with every attribute value kept as the string the XML held, -// so loaders read it the way the game read its rapidxml nodes. -struct Data +// Which form of a game document data_load reads when there are both: the XML file, or the import tool's JSON beside +// it (.json). auto takes the first mount that holds either, XML first there. A missing one falls back to the +// other. +enum DataFormat : int { - simdjson::dom::parser parser; - simdjson::dom::element root; - bool isLoaded = false; + DATA_FORMAT_AUTO, + DATA_FORMAT_JSON, + DATA_FORMAT_XML }; -using DataNode = simdjson::dom::element; +constexpr std::string_view DATA_FORMAT_NAMES[] = {"auto", "json", "xml"}; + +// An element of a loaded document, the same to loaders in either form: a pugixml node of the XML, or a simdjson +// element of the JSON the import tool converts it to ({"tag", "attrs", "children", "text"}). Attribute values are the +// strings the XML held, NUL-terminated as atoi reads them. +struct DataNode +{ + const void* json = nullptr; + size_t jsonIndex = 0; + void* xml = nullptr; + + bool operator==(const DataNode& other) const = default; +}; + +struct DataAttr +{ + std::string_view name; + std::string_view value; +}; + +// A node's child elements in document order. +struct DataChildren +{ + struct iterator + { + DataNode cursor; + + DataNode operator*() const { return cursor; } + iterator& operator++(); + bool operator==(const iterator& other) const = default; + }; + iterator first; + iterator last; + + iterator begin() const { return first; } + iterator end() const { return last; } +}; + +// A node's attributes in document order. A repeated one counts once, with its last value where it last stands. +struct DataAttrs +{ + struct iterator + { + DataNode cursor; + + DataAttr operator*() const; + iterator& operator++(); + bool operator==(const iterator& other) const = default; + }; + iterator first; + iterator last; + + iterator begin() const { return first; } + iterator end() const { return last; } +}; + +struct DataDocument; + +// A loaded document: its parsed tree and its root, the one top-level element or DOCUMENT_TAG over several. isLoaded is +// false when the file is missing or does not parse. +struct Data +{ + std::unique_ptr document; + DataNode root; + bool isLoaded = false; + + Data(); + ~Data(); +}; void data_load(Data& data, std::string_view path); -std::string data_path(std::string_view path); -std::string resource_path(std::string_view path); -std::string asset_path(std::string_view path); -void reload_resource_paths(); +void data_parse(Data& data, std::string& bytes); std::string_view node_tag(DataNode node); std::string_view node_attr(DataNode node, std::string_view name); -std::string_view node_text(DataNode node); -simdjson::dom::array node_children(DataNode node); - -// The resources, and the language's own folder looked in first (empty while it has none). -extern std::string dataDirectory; -extern std::string languageDirectory; +std::optional node_attr_find(DataNode node, std::string_view name); +std::string node_text(DataNode node); +DataChildren node_children(DataNode node); +DataAttrs node_attrs(DataNode node); diff --git a/src/engine/filesys.cpp b/src/engine/filesys.cpp new file mode 100644 index 0000000..74b0c53 --- /dev/null +++ b/src/engine/filesys.cpp @@ -0,0 +1,658 @@ +#include "engine/filesys.h" +#include "engine/platform.h" +#include "game/manager.h" +#include "stb_image.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// The archives IsaacStartup (009aa040) mounts, in its order, later ones overriding earlier ones. secret.a is a file of +// afterbirthp.a. A language archive holds its files under resources./. +constexpr std::array ARCHIVE_NAMES = { + "packed/animations.a", "packed/config.a", "packed/fonts.a", "packed/graphics.a", + "packed/music.a", "packed/rooms.a", "packed/sfx.a", "packed/videos.a", + "packed/afterbirth.a", "packed/afterbirthp.a", "packed/repentance_de.a", "packed/repentance_es.a", + "packed/repentance_jp.a", "packed/repentance_kr.a", "packed/repentance_ru.a", "packed/repentance_zh.a", + "packed/repentance_fr.a", "secret.a"}; +constexpr std::string_view ARCHIVE_MAGIC = "ARCH000"; +constexpr char LANGUAGE_SEPARATOR = '_'; +constexpr size_t ARCHIVE_HEADER_SIZE = 14; +constexpr size_t ARCHIVE_TYPE_OFFSET = 7; +constexpr size_t ARCHIVE_INDEX_OFFSET = 8; +constexpr size_t ARCHIVE_COUNT_OFFSET = 12; +// An index row: primary hash, secondary hash, data offset, unpacked size, checksum. +constexpr size_t ARCHIVE_ROW_SIZE = 20; +constexpr size_t ROW_SECONDARY = 4; +constexpr size_t ROW_START = 8; +constexpr size_t ROW_SIZE = 12; + +constexpr std::string_view BASE_MOUNT = "resources/"; +constexpr std::string_view LANGUAGE_MOUNT = "resources."; +// Where the import tool puts a language archive's files. +constexpr std::string_view LANGUAGE_FOLDER = "lang/"; +// Mods reach their own files from resources/ through "../mods/". +constexpr std::string_view MODS_FROM_RESOURCES = "../mods/"; +constexpr std::string_view PARENT_FOLDER = "../"; +constexpr std::string_view MODS_FOLDER = "mods/"; +// The game's own folder name, which the exe writes in front of some paths ("resources/gfx/1000.034_Fart.anm2"). +constexpr std::string_view GAME_RESOURCES_FOLDER = "resources/"; +constexpr std::string_view ASSETS_FOLDER = "assets"; +// Room for simdjson's padding after a file's bytes, so a JSON document parses where it was read. +constexpr size_t READ_PADDING = 64; + +// The path hashes (GetPrimaryFilePathHash 00a159d0, FUN_00a15ab0): djb2, and FNV-1a from another seed. +constexpr uint32_t DJB_SEED = 5381; +constexpr uint32_t DJB_FACTOR = 33; +constexpr uint32_t FNV_SEED = 0x5bb2220e; +constexpr uint32_t FNV_PRIME = 0x1000193; + +// Type 0: dwords XORed with a xorshift32 key, then shuffled by the key's low nibble. +constexpr uint32_t XORSHIFT_KEY = 0xf9524287; +constexpr uint32_t NIBBLE_MASK = 15; +constexpr uint32_t NIBBLE_REVERSE = 2; +constexpr uint32_t NIBBLE_SWAP_BYTES = 9; +constexpr uint32_t NIBBLE_SWAP_HALVES = 13; +constexpr uint32_t LOW_BYTES_MASK = 0x00ff00ff; +constexpr int BYTE_BITS = 8; +constexpr int HALF_BITS = 16; +constexpr int XORSHIFT_FIRST = 8; +constexpr int XORSHIFT_SECOND = 9; +constexpr int XORSHIFT_THIRD = 23; + +// Type 1: LZW codes from 8 to 12 bits wide, the dictionary starting over at 0xfff entries. +constexpr int LZW_LITERALS = 256; +constexpr int LZW_RESET = 0xfff; +constexpr int LZW_TABLE_SIZE = 0x1000; +constexpr int LZW_NO_PREFIX = -1; +// The bytes a code can straddle: up to 12 bits from any bit of the first. +constexpr size_t LZW_WINDOW_BYTES = 3; + +// Type 2: raw deflate chunks until a full 1 KiB one that is not the last, stored and keyed by ISAAC from there on. +constexpr uint32_t LAST_CHUNK = 0x80000000; +constexpr uint32_t STORED_CHUNK_SIZE = 0x400; +// A last, empty stored block, which ends a stream the chunks leave open at a flush. +constexpr std::string_view DEFLATE_END = {"\x01\x00\x00\xff\xff", 5}; +constexpr int ISAAC_SIZE = 256; +constexpr int ISAAC_MIX_SIZE = 8; +constexpr int ISAAC_WARMUP_ROUNDS = 4; +constexpr uint32_t GOLDEN_RATIO = 0x9e3779b9; +constexpr uint64_t PCG_FACTOR = 0x5851f42d4c957f2d; +constexpr uint64_t PCG_INCREMENT = 0x7f; + +// Type 5 (secret.a only): bytes XORed with a fixed key. +constexpr std::array SECRET_KEY = { + 0xb0, 0x22, 0x5d, 0x47, 0xd3, 0x1b, 0x59, 0xd1, 0x97, 0x37, 0xfb, 0xd2, 0xc0, 0x31, 0x86, 0xfd, 0xb5, 0xdd, 0xac, + 0x4b, 0xb4, 0x01, 0x15, 0x52, 0x01, 0x0a, 0x75, 0x08, 0x5d, 0x50, 0xfe, 0x8c, 0xa8, 0xaf, 0xd5, 0xcb, 0x09, 0xee, + 0xdc, 0xca, 0x76, 0xc4, 0x3f, 0x67, 0xed, 0x09, 0x8f, 0x64, 0x43, 0x56, 0x30, 0x1a, 0x89, 0x2e, 0xdf, 0xf9, 0xe4, + 0xb8, 0x13, 0x1a, 0xbe, 0xaf, 0xa4, 0x02, 0xff, 0x60, 0x22, 0xe0, 0x0b, 0xff, 0xae, 0xc9, 0x7d, 0xa0, 0x27, 0xf9, + 0x11, 0x63, 0x2f, 0xe1, 0x20, 0x7e, 0x51, 0xd7, 0x0e, 0xcd, 0xc4, 0xd4, 0xcf, 0xcf, 0xa1, 0x88, 0x99, 0x42, 0x96, + 0xcf, 0xf0, 0xc1, 0x54, 0xc3, 0x36, 0x94, 0xc2, 0x92, 0xdc, 0xb8, 0x63, 0xca, 0xca, 0x32, 0x12, 0x7a, 0x3c, 0x88, + 0x5f, 0xd2, 0x4b, 0xc3, 0xe4, 0x69, 0x74, 0x32, 0xbd, 0x2c, 0x42, 0x28, 0xb2, 0x34}; + +// How an archive packs its files, from its header's type byte. +enum ArchiveType : uint8_t +{ + ARCHIVE_XORSHIFT = 0, + ARCHIVE_LZW = 1, + ARCHIVE_MINIZ = 2, + ARCHIVE_SECRET = 5 +}; + +// A mounted archive: its file on disk, or its bytes when it is itself a file of an earlier archive. +struct Archive +{ + std::string bytes; + std::FILE* file = nullptr; + ArchiveType type = ARCHIVE_XORSHIFT; +}; + +// A file of an archive by its index row: where its packed bytes start and how far they can run (to the next file's +// start), its unpacked size and the secondary hash its key derives from. +struct ArchiveEntry +{ + uint32_t length = 0; + uint32_t secondary = 0; + uint32_t size = 0; + uint32_t start = 0; + uint16_t archive = 0; +}; + +// Where a game path is: in an archive or on disk. +struct ResourceFile +{ + std::string path; + const ArchiveEntry* entry = nullptr; +}; + +// The keystream's words are used as their little-endian bytes. +static_assert(std::endian::native == std::endian::little); + +// Bob Jenkins' ISAAC seeded from 256 PCG32 outputs (FUN_00aa93e0, isaac_randinit 00aa9580, isaac FUN_00aa94a0), whose +// rounds key a miniz archive's stored chunks. +class IsaacStream +{ +public: + std::array memory = {}; + std::array results = {}; + uint32_t a = 0; + uint32_t b = 0; + uint32_t c = 0; + + explicit IsaacStream(uint32_t seed); + void round_run(); +}; + +std::string dataDirectory = "resources/"; +std::string languageDirectory; + +static std::vector archives; +static std::unordered_map archiveEntries; +static std::vector archiveLanguages; +// The language's mount prefix ("resources.de/") while languageDirectory is set. +static std::string languageMount; +// Each folder's entries by lowercased name, read once a lookup there misses with its exact case. +static std::unordered_map> folderListings; + +static void isaac_mix(std::array& v) +{ + v[0] ^= v[1] << 11; + v[3] += v[0]; + v[1] += v[2]; + v[1] ^= v[2] >> 2; + v[4] += v[1]; + v[2] += v[3]; + v[2] ^= v[3] << 8; + v[5] += v[2]; + v[3] += v[4]; + v[3] ^= v[4] >> 16; + v[6] += v[3]; + v[4] += v[5]; + v[4] ^= v[5] << 10; + v[7] += v[4]; + v[5] += v[6]; + v[5] ^= v[6] >> 4; + v[0] += v[5]; + v[6] += v[7]; + v[6] ^= v[7] << 8; + v[1] += v[6]; + v[7] += v[0]; + v[7] ^= v[0] >> 9; + v[2] += v[7]; + v[0] += v[1]; +} + +IsaacStream::IsaacStream(uint32_t seed) +{ + uint64_t state = (uint64_t)seed << 32 | (((seed << 15 ^ seed) << 8) ^ (seed >> 9) ^ seed); + for (uint32_t& result : results) + { + result = std::rotr((uint32_t)((state >> 18 ^ state) >> 27), (int)(state >> 59)); + state = state * PCG_FACTOR + PCG_INCREMENT; + } + + std::array v; + v.fill(GOLDEN_RATIO); + for (int i = 0; i < ISAAC_WARMUP_ROUNDS; i++) isaac_mix(v); + for (std::array* source : {&results, &memory}) + for (int i = 0; i < ISAAC_SIZE; i += ISAAC_MIX_SIZE) + { + for (int j = 0; j < ISAAC_MIX_SIZE; j++) v[j] += (*source)[i + j]; + isaac_mix(v); + std::copy(v.begin(), v.end(), memory.begin() + i); + } +} + +// Fills results with the next 256 words. +void IsaacStream::round_run() +{ + auto step = [&](int i, uint32_t mixed) + { + uint32_t x = memory[i]; + a = (a ^ mixed) + memory[(i + ISAAC_SIZE / 2) & (ISAAC_SIZE - 1)]; + uint32_t y = memory[i] = memory[(x >> 2) & (ISAAC_SIZE - 1)] + a + b; + b = results[i] = memory[(y >> 10) & (ISAAC_SIZE - 1)] + x; + }; + + b += ++c; + for (int i = 0; i < ISAAC_SIZE; i += 4) + { + step(i, a << 13); + step(i + 1, a >> 6); + step(i + 2, a << 2); + step(i + 3, a >> 16); + } +} + +// A path's primary and secondary hash under a mount, ASCII-lowercased with '\' as '/', as one key. +static uint64_t path_hash(std::string_view mount, std::string_view path) +{ + uint32_t primary = DJB_SEED; + uint32_t secondary = FNV_SEED; + + for (std::string_view text : {mount, path}) + for (unsigned char letter : text) + { + letter = letter == '\\' ? '/' : letter >= 'A' && letter <= 'Z' ? letter + ('a' - 'A') : letter; + primary = primary * DJB_FACTOR + letter; + secondary = (secondary ^ letter) * FNV_PRIME; + } + return (uint64_t)primary << 32 | secondary; +} + +// A little-endian dword, zero past the end. +static uint32_t word_get(std::string_view bytes, size_t offset) +{ + uint32_t word = 0; + std::memcpy(&word, bytes.data() + std::min(offset, bytes.size()), + std::min(sizeof(word), bytes.size() - std::min(offset, bytes.size()))); + return word; +} + +// Type 0 (ArchivedFile refill_buffer 00a68cf0). +static void xorshift_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes) +{ + uint32_t key = (entry.secondary ^ XORSHIFT_KEY) | 1; + + bytes.resize((entry.size + 3) & ~3u); + for (size_t offset = 0; offset < bytes.size(); offset += sizeof(key)) + { + uint32_t word = word_get(packed, offset) ^ key; + uint32_t swapped = (word & LOW_BYTES_MASK) << BYTE_BITS | (word >> BYTE_BITS & LOW_BYTES_MASK); + switch (key & NIBBLE_MASK) + { + case NIBBLE_REVERSE: word = std::rotl(swapped, HALF_BITS); break; + case NIBBLE_SWAP_BYTES: word = swapped; break; + case NIBBLE_SWAP_HALVES: word = std::rotl(word, HALF_BITS); break; + } + std::memcpy(bytes.data() + offset, &word, sizeof(word)); + key ^= key << XORSHIFT_FIRST; + key ^= key >> XORSHIFT_SECOND; + key ^= key << XORSHIFT_THIRD; + } +} + +// Type 1 (lzw_decompress 00a85320): chunks of [u32 length][MSB-first codes], the dictionary kept across chunks. The +// first code of a chunk adds no entry. +static void lzw_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes) +{ + struct Code + { + int length; + int prefix; + char first; + char last; + }; + std::vector table(LZW_TABLE_SIZE); + int count = LZW_LITERALS; + int width = BYTE_BITS; + size_t offset = 0; + + for (int i = 0; i < LZW_LITERALS; i++) table[i] = {1, LZW_NO_PREFIX, (char)i, (char)i}; + auto emit = [&](int code) + { + size_t end = bytes.size() + table[code].length; + bytes.resize(end); + for (int link = code; link != LZW_NO_PREFIX; link = table[link].prefix) bytes[--end] = table[link].last; + }; + + while (bytes.size() < entry.size && offset + sizeof(uint32_t) <= packed.size()) + { + size_t bitCount = word_get(packed, offset) * (size_t)BYTE_BITS; + const uint8_t* bits = (const uint8_t*)packed.data() + offset + sizeof(uint32_t); + size_t position = 0; + offset += sizeof(uint32_t) + bitCount / BYTE_BITS; + if (offset > packed.size()) return; + auto code_read = [&](int codeWidth) + { + size_t first = position / BYTE_BITS; + uint32_t window = 0; + for (size_t i = first; i < first + LZW_WINDOW_BYTES; i++) + window = window << BYTE_BITS | (i < bitCount / BYTE_BITS ? bits[i] : 0); + int shift = LZW_WINDOW_BYTES * BYTE_BITS - (int)(position % BYTE_BITS) - codeWidth; + position += codeWidth; + return (int)(window >> shift & ((1u << codeWidth) - 1)); + }; + + int previous = code_read(width); + emit(previous); + while (true) + { + if (count >= LZW_RESET) + { + count = LZW_LITERALS; + width = BYTE_BITS; + previous = code_read(width); + emit(previous); + } + if (bitCount - position < BYTE_BITS) break; + while (1 << width <= count) width++; + + int code = code_read(width); + if (code > count) return; + if (code == count || count < LZW_TABLE_SIZE) + { + char last = code == count ? table[previous].first : table[code].first; + table[count++] = {table[previous].length + 1, previous, table[previous].first, last}; + } + emit(code); + previous = code; + if (bitCount - position < BYTE_BITS) break; + } + } +} + +// Type 2 (FUN_00a89f80): one raw deflate stream over its chunks, then from the first full 1 KiB chunk that is not +// the last, stored chunks XORed with the ISAAC stream the secondary hash seeds, a round per chunk. +static void miniz_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes) +{ + std::string deflated; + std::unique_ptr keys; + size_t offset = 0; + auto inflate = [&] + { + deflated += DEFLATE_END; + bytes.resize(entry.size); + int size = deflated.empty() ? 0 + : stbi_zlib_decode_noheader_buffer(bytes.data(), (int)bytes.size(), + deflated.data(), (int)deflated.size()); + bytes.resize(std::max(size, 0)); + }; + + while (offset + sizeof(uint32_t) <= packed.size() && bytes.size() < entry.size) + { + uint32_t header = word_get(packed, offset); + uint32_t length = header & ~LAST_CHUNK; + std::string_view chunk = packed.substr(std::min(offset + sizeof(uint32_t), packed.size()), length); + offset += sizeof(uint32_t) + length; + + if (!keys && length == STORED_CHUNK_SIZE && !(header & LAST_CHUNK)) + { + keys = std::make_unique(entry.secondary); + inflate(); + if (bytes.size() >= entry.size) break; + } + if (!keys) + { + deflated += chunk; + if (header & LAST_CHUNK) break; + continue; + } + + size_t at = bytes.size(); + auto key = (const char*)keys->results.data(); + keys->round_run(); + bytes.append(chunk); + for (size_t i = 0; i < chunk.size(); i++) bytes[at + i] ^= key[i]; + } + if (!keys) inflate(); +} + +// Type 5: bytes XORed with the fixed key. +static void secret_unpack(std::string_view packed, const ArchiveEntry& entry, std::string& bytes) +{ + bytes.assign(packed.substr(0, entry.size)); + for (size_t i = 0; i < bytes.size(); i++) bytes[i] ^= (char)SECRET_KEY[i % SECRET_KEY.size()]; +} + +// Up to length of an archive's raw bytes from start on. +static bool archive_read(const Archive& archive, uint32_t start, uint32_t length, std::string& packed) +{ + if (!archive.file) + { + packed = std::string_view(archive.bytes).substr(std::min(start, archive.bytes.size()), length); + return true; + } + if (std::fseek(archive.file, start, SEEK_SET) != 0) return false; + packed.resize(length); + packed.resize(std::fread(packed.data(), 1, length, archive.file)); + return true; +} + +// 00a68a50 An archived file's bytes, unpacked by its archive's type, with room after them for a parser's padding. +static bool entry_read(const ArchiveEntry& entry, std::string& bytes) +{ + const Archive& archive = archives[entry.archive]; + std::string packed; + + bytes.clear(); + bytes.reserve(entry.size + READ_PADDING); + if (!archive_read(archive, entry.start, entry.length, packed)) return false; + switch (archive.type) + { + case ARCHIVE_XORSHIFT: xorshift_unpack(packed, entry, bytes); break; + case ARCHIVE_LZW: lzw_unpack(packed, entry, bytes); break; + case ARCHIVE_MINIZ: miniz_unpack(packed, entry, bytes); break; + case ARCHIVE_SECRET: secret_unpack(packed, entry, bytes); break; + default: return false; + } + bytes.resize(entry.size); + return true; +} + +// 00a179c0 (LoadArchiveFile) Indexes one archive, a file of an earlier one or on disk: its header, then a row per +// file. A file's packed bytes run to the next file's start, the index or the end. False when it is missing or not an +// archive. +static bool archive_index(std::string_view name) +{ + Archive& archive = archives.emplace_back(); + auto nested = archiveEntries.find(path_hash(BASE_MOUNT, name)); + std::string header; + std::string rows; + uint32_t end = 0; + + if (nested != archiveEntries.end()) entry_read(nested->second, archive.bytes); + else archive.file = std::fopen((dataDirectory + std::string(name)).c_str(), "rb"); + if (archive.file && std::fseek(archive.file, 0, SEEK_END) == 0) end = (uint32_t)std::ftell(archive.file); + if (!archive.file) end = (uint32_t)archive.bytes.size(); + if (end < ARCHIVE_HEADER_SIZE || !archive_read(archive, 0, ARCHIVE_HEADER_SIZE, header) || + !header.starts_with(ARCHIVE_MAGIC)) + { + if (archive.file) std::fclose(archive.file); + archives.pop_back(); + return false; + } + + archive.type = (ArchiveType)header[ARCHIVE_TYPE_OFFSET]; + uint32_t indexOffset = word_get(header, ARCHIVE_INDEX_OFFSET); + uint32_t count = word_get(header, ARCHIVE_COUNT_OFFSET) & UINT16_MAX; + archive_read(archive, indexOffset, count * ARCHIVE_ROW_SIZE, rows); + + std::vector bounds = {indexOffset, end}; + for (size_t row = 0; row + ARCHIVE_ROW_SIZE <= rows.size(); row += ARCHIVE_ROW_SIZE) + bounds.push_back(word_get(rows, row + ROW_START)); + std::ranges::sort(bounds); + + for (size_t row = 0; row + ARCHIVE_ROW_SIZE <= rows.size(); row += ARCHIVE_ROW_SIZE) + { + ArchiveEntry entry; + entry.secondary = word_get(rows, row + ROW_SECONDARY); + entry.start = word_get(rows, row + ROW_START); + entry.size = word_get(rows, row + ROW_SIZE); + entry.archive = (uint16_t)(archives.size() - 1); + auto next = std::ranges::upper_bound(bounds, entry.start); + entry.length = next == bounds.end() ? 0 : *next - entry.start; + archiveEntries[(uint64_t)word_get(rows, row) << 32 | entry.secondary] = entry; + } + return true; +} + +// 009aa040 (IsaacStartup) Mounts the archives of an install's resources folder, indexing every file once. A language +// archive (repentance_de.a) makes its language's mount. +void archives_load() +{ + for (std::string_view name : ARCHIVE_NAMES) + { + if (!archive_index(name)) continue; + size_t separator = name.rfind(LANGUAGE_SEPARATOR); + if (separator != std::string_view::npos) + archiveLanguages.emplace_back(name.substr(separator + 1, name.find('.', separator) - separator - 1)); + } +} + +// Whether the resources are an install's, read from its packed archives. Its folders are only read. +bool is_archive_mounted() +{ + return !archives.empty(); +} + +// A game path lowercased with forward slashes, as the game normalizes every path before a lookup. A path already under +// the language's folder, the resources or the mods folder, which mods build from their script's path as the original's +// absolute ones, stays there. +static std::string path_normalize(std::string_view path) +{ + std::string_view mods = platform.modsDirectory; + bool isModsPath = !mods.empty() && path.starts_with(mods); + if (isModsPath) path.remove_prefix(mods.size()); + else if (!languageDirectory.empty() && path.starts_with(languageDirectory)) + path.remove_prefix(languageDirectory.size()); + else if (path.starts_with(dataDirectory)) path.remove_prefix(dataDirectory.size()); + + std::string normalized(path); + for (char& letter : normalized) letter = letter == '\\' ? '/' : (char)std::tolower((unsigned char)letter); + if (isModsPath) normalized.insert(0, MODS_FOLDER); + else if (normalized.starts_with(MODS_FROM_RESOURCES)) normalized.erase(0, PARENT_FOLDER.size()); + else if (normalized.starts_with(GAME_RESOURCES_FOLDER)) normalized.erase(0, GAME_RESOURCES_FOLDER.size()); + return normalized; +} + +// A file or folder under a directory by its lowercased path, each name matched without case, as the original's +// FileMap (FileMap::scan_directory 00a687f0) matches them, when the exact one is missing. Empty when there is none. +static std::string disk_find(std::string directory, std::string_view normalized) +{ + std::error_code error; + std::string exact = directory + std::string(normalized); + + if (std::filesystem::exists(exact, error)) return exact; + for (size_t start = 0; start < normalized.size();) + { + size_t end = std::min(normalized.find('/', start), normalized.size()); + auto [listing, isNew] = folderListings.try_emplace(directory); + for (auto& entry : std::filesystem::directory_iterator(isNew ? directory : std::string(), error)) + { + std::string name = entry.path().filename().string(); + std::string lowered = name; + for (char& letter : lowered) letter = (char)std::tolower((unsigned char)letter); + listing->second.emplace(lowered, name); + } + + auto found = listing->second.find(std::string(normalized.substr(start, end - start))); + if (found == listing->second.end()) return ""; + directory += found->second + (end < normalized.size() ? "/" : ""); + start = end + 1; + } + return directory; +} + +// 00a16c60 (find_mount) The first of some game paths in the language's mount, then in the resources, each mount's +// archives before its folder. A mod's files are only in its folder. +static ResourceFile resource_find(std::initializer_list paths) +{ + ResourceFile file; + std::pair mounts[] = {{languageMount, languageDirectory}, + {BASE_MOUNT, dataDirectory}}; + std::vector normalized; + + for (std::string_view path : paths) normalized.push_back(path_normalize(path)); + for (auto [mount, directory] : mounts) + for (std::string_view path : normalized) + { + bool isModsPath = path.starts_with(MODS_FOLDER) && !platform.modsDirectory.empty(); + if (isModsPath && mount == BASE_MOUNT) + file.path = disk_find(platform.modsDirectory, path.substr(MODS_FOLDER.size())); + if (!file.path.empty()) return file; + if (isModsPath || directory.empty()) continue; + + auto found = archiveEntries.empty() ? archiveEntries.end() : archiveEntries.find(path_hash(mount, path)); + if (found != archiveEntries.end()) file.entry = &found->second; + else file.path = disk_find(std::string(directory), path); + if (file.entry || !file.path.empty()) return file; + } + return file; +} + +// Where a game path is mounted, the key the caches keep it under: under the language's folder when that mount has +// it, a mod's under the mods folder, under the resources otherwise. +std::string resource_path(std::string_view path) +{ + std::string normalized = path_normalize(path); + std::error_code error; + + if (normalized.starts_with(MODS_FOLDER) && !platform.modsDirectory.empty()) + return platform.modsDirectory + normalized.substr(MODS_FOLDER.size()); + if (!languageDirectory.empty() && (archiveEntries.contains(path_hash(languageMount, normalized)) || + std::filesystem::exists(languageDirectory + normalized, error))) + return languageDirectory + normalized; + return dataDirectory + normalized; +} + +// Whether a game path is mounted anywhere. +bool resource_exists(std::string_view path) +{ + ResourceFile file = resource_find({path}); + return file.entry || !file.path.empty(); +} + +// 00a178d0 (FileSystem::Open) The bytes of the first of some game paths that the first mount holding any has, from +// its archive or its file, with room after them for a parser's padding. False when none is mounted or it cannot be +// read. +bool resource_load_first(std::initializer_list paths, std::string& bytes) +{ + ResourceFile file = resource_find(paths); + if (file.entry) return entry_read(*file.entry, bytes); + + std::error_code error; + bool isFile = !file.path.empty() && std::filesystem::is_regular_file(file.path, error); + std::FILE* stream = isFile ? std::fopen(file.path.c_str(), "rb") : nullptr; + if (!stream) return false; + + std::fseek(stream, 0, SEEK_END); + long size = std::max(std::ftell(stream), 0L); + std::fseek(stream, 0, SEEK_SET); + bytes.clear(); + bytes.reserve(size + READ_PADDING); + bytes.resize(size); + bytes.resize(std::fread(bytes.data(), 1, bytes.size(), stream)); + std::fclose(stream); + return true; +} + +bool resource_load(std::string_view path, std::string& bytes) +{ + return resource_load_first({path}, bytes); +} + +// Where a file the repository ships itself lives: in assets/, beside the resources folder, or beside the folder the +// executable is built into when the resources are an install's. +std::string asset_path(std::string_view path) +{ + std::filesystem::path folder = is_archive_mounted() ? SDL_GetBasePath() : dataDirectory.c_str(); + return (folder.parent_path().parent_path() / ASSETS_FOLDER / path).string(); +} + +// 009abbd0 Remounts the resources, with the mount of the string table's language (009ab970) in front once there is a +// manager. That mount is only made when the language has an archive or the import tool wrote its folder. +// The original also mounts the game folder behind the resources when its file system already knows it. Nothing on +// Linux reads from there. +void reload_resource_paths() +{ + languageDirectory.clear(); + languageMount.clear(); + if (!g_manager) return; + + std::string code(Manager::GetLanguage()); + std::string localized = dataDirectory + std::string(LANGUAGE_FOLDER) + code + '/'; + std::error_code error; + if (std::ranges::find(archiveLanguages, code) == archiveLanguages.end() && + !std::filesystem::is_directory(localized, error)) + return; + + languageDirectory = localized; + languageMount = std::string(LANGUAGE_MOUNT) + code + '/'; +} diff --git a/src/engine/filesys.h b/src/engine/filesys.h new file mode 100644 index 0000000..d1ed9fa --- /dev/null +++ b/src/engine/filesys.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include + +// The resources, and the language's own folder looked in first (empty while it has none). +extern std::string dataDirectory; +extern std::string languageDirectory; + +void archives_load(); +bool is_archive_mounted(); +void reload_resource_paths(); +std::string resource_path(std::string_view path); +std::string asset_path(std::string_view path); +bool resource_exists(std::string_view path); +bool resource_load(std::string_view path, std::string& bytes); +bool resource_load_first(std::initializer_list paths, std::string& bytes); diff --git a/src/engine/font.cpp b/src/engine/font.cpp index 95c46b4..06a39b3 100644 --- a/src/engine/font.cpp +++ b/src/engine/font.cpp @@ -3,8 +3,6 @@ #include "engine/log.h" #include #include -#include -#include #include constexpr char FONT_MAGIC[] = "BMF"; @@ -193,10 +191,10 @@ bool Font::Load(std::string_view path) { Unload(); - std::ifstream stream(resource_path(path), std::ios::binary); - std::string file((std::istreambuf_iterator(stream)), std::istreambuf_iterator()); + std::string file; + if (!resource_load(path, file)) return false; FontReader reader = {file, std::size(FONT_MAGIC) - 1}; - if (!stream || file.compare(0, reader.offset, FONT_MAGIC) != 0) return false; + if (file.compare(0, reader.offset, FONT_MAGIC) != 0) return false; if (reader.read() != FONT_VERSION) return false; size_t slash = path.find_last_of(PATH_SEPARATORS); diff --git a/src/engine/fx_layers.cpp b/src/engine/fx_layers.cpp index 5f55bb0..1980340 100644 --- a/src/engine/fx_layers.cpp +++ b/src/engine/fx_layers.cpp @@ -122,14 +122,7 @@ static bool is_text_true(std::string_view text) // Calls visit with each attribute's name and text, in document order. template static void attrs_visit(DataNode node, Visit visit) { - simdjson::dom::object attrs; - if (node["attrs"].get(attrs) != simdjson::SUCCESS) return; - - for (simdjson::dom::key_value_pair attr : attrs) - { - std::string_view text; - if (attr.value.get(text) == simdjson::SUCCESS) visit(attr.key, text); - } + for (auto [name, text] : node_attrs(node)) visit(name, text); } // Calls visit with the children from the first one tagged tag on, as the game walks them: rapidxml's first_node(tag), diff --git a/src/engine/kage_graphics.cpp b/src/engine/kage_graphics.cpp index 2ed1020..825ef30 100644 --- a/src/engine/kage_graphics.cpp +++ b/src/engine/kage_graphics.cpp @@ -5,8 +5,6 @@ #include #include #include -#include -#include #include #define STB_IMAGE_IMPLEMENTATION @@ -147,6 +145,16 @@ std::string path_key(std::string_view path) return key; } +// A file's image as RGBA texels, which stbi_image_free frees, or null when it is missing or does not decode. +uint8_t* texels_load(std::string_view path, int& width, int& height) +{ + std::string file; + int channels = 0; + + if (!resource_load(path, file)) return nullptr; + return stbi_load_from_memory((stbi_uc*)file.data(), (int)file.size(), &width, &height, &channels, STBI_rgb_alpha); +} + // 00a114d0 Sets one of the three blend modes, the source color factor depending on premultiplied alpha. Another type // leaves the mode as it was. void BlendMode::SetMode(BlendType type) @@ -977,28 +985,18 @@ bool Manager::shader_create(std::string_view shaderName, std::span attributes, ShaderSource files) { std::string vertex; std::string fragment; - if (!file_read(resource_path(files.vertex), vertex)) + if (!resource_load(files.vertex, vertex)) { log_printf(LOG_ERROR, "Failed to load vertex shader '%s'\n", std::string(files.vertex).c_str()); return false; } - if (!file_read(resource_path(files.fragment), fragment)) + if (!resource_load(files.fragment, fragment)) { log_printf(LOG_ERROR, "Failed to load pixel shader '%s'\n", std::string(files.fragment).c_str()); return false; @@ -1200,14 +1198,12 @@ static bool extension_type_get(std::string_view path, ImageFileType& type) // file is missing or does not decode. ImagePtr Manager::image_load(std::string_view imagePath) { - std::string resolved = resource_path(imagePath); - std::error_code error; - if (!std::filesystem::is_regular_file(resolved, error)) return nullptr; + if (!resource_exists(imagePath)) return nullptr; if (ImagePtr cached = image_find(imagePath)) return cached; ImageFileType type = FILE_PLATFORM; std::string file; - if (!extension_type_get(imagePath, type) || !file_read(resolved, file)) return nullptr; + if (!extension_type_get(imagePath, type) || !resource_load(imagePath, file)) return nullptr; ImagePtr image = image_open({(const uint8_t*)file.data(), file.size()}, type, imagePath); if (!image) return nullptr; diff --git a/src/engine/kage_graphics.h b/src/engine/kage_graphics.h index 4f3a74c..8cd2027 100644 --- a/src/engine/kage_graphics.h +++ b/src/engine/kage_graphics.h @@ -388,6 +388,7 @@ public: extern Manager manager; std::string path_key(std::string_view path); +uint8_t* texels_load(std::string_view path, int& width, int& height); ColorQuad color_quad_rect(const Vector& position, const Vector& size, const KColor& color); SourceQuad source_quad_rect(const Vector& position, const Vector& size); bool is_quad_on_screen(const DestinationQuad& quad); diff --git a/src/engine/kage_sound.cpp b/src/engine/kage_sound.cpp index 0ada0b3..28516e7 100644 --- a/src/engine/kage_sound.cpp +++ b/src/engine/kage_sound.cpp @@ -3,6 +3,7 @@ #include "engine/harness.h" #include "engine/platform.h" #include +#include #include #include #include @@ -159,21 +160,26 @@ void Manager::Resume() if (output) SDL_ResumeAudioStreamDevice(output); } -// Opens a sound file into a source: a wav whole, an ogg whole or as a stream. -static bool source_open(SoundSource& source, const std::string& file, bool isOgg) +// Opens a sound file into a source: a wav whole, an ogg whole or as a stream over the file's bytes it keeps. +static bool source_open(SoundSource& source, std::string_view path, bool isOgg) { + if (!resource_load(path, source.file)) return false; if (!isOgg) { uint8_t* buffer = nullptr; uint32_t length = 0; - if (!SDL_LoadWAV(file.c_str(), &source.spec, &buffer, &length)) return false; + SDL_IOStream* stream = SDL_IOFromConstMem(source.file.data(), source.file.size()); + bool isLoaded = SDL_LoadWAV_IO(stream, true, &source.spec, &buffer, &length); + source.file = {}; + if (!isLoaded) return false; source.samples.assign(buffer, buffer + length); SDL_free(buffer); return true; } int error = 0; - source.stream = stb_vorbis_open_filename(file.c_str(), &error, nullptr); + auto bytes = (const unsigned char*)source.file.data(); + source.stream = stb_vorbis_open_memory(bytes, (int)source.file.size(), &error, nullptr); if (!source.stream) return false; stb_vorbis_info info = stb_vorbis_get_info(source.stream); source.spec = {SDL_AUDIO_S16, info.channels, (int)info.sample_rate}; @@ -185,6 +191,7 @@ static bool source_open(SoundSource& source, const std::string& file, bool isOgg source.samples.assign((uint8_t*)decoded.data(), (uint8_t*)(decoded.data() + (size_t)frames * info.channels)); stb_vorbis_close(source.stream); source.stream = nullptr; + source.file = {}; return true; } @@ -214,7 +221,7 @@ std::shared_ptr Manager::load_sound(std::string_view soundPath, Sou auto source = std::make_shared(); source->path = pathText; source->type = type; - if (!source_open(*source, resource_path(soundPath), isOgg)) + if (!source_open(*source, soundPath, isOgg)) { const char* kind = type == SOURCE_STREAM ? "stream" : "sample"; log_printf(LOG_ERROR, "Failed to open %s \"%s\"\n", kind, pathText.c_str()); diff --git a/src/engine/kage_sound.h b/src/engine/kage_sound.h index b05c07f..0dad4d5 100644 --- a/src/engine/kage_sound.h +++ b/src/engine/kage_sound.h @@ -29,6 +29,7 @@ class SoundSource { public: std::vector samples; + std::string file; std::string path; SDL_AudioSpec spec = {}; stb_vorbis* stream = nullptr; diff --git a/src/engine/platform.cpp b/src/engine/platform.cpp index d8d433e..586669f 100644 --- a/src/engine/platform.cpp +++ b/src/engine/platform.cpp @@ -178,8 +178,9 @@ static void folder_create(const std::string& path, const char* error) // 009a9510 Finds the save folder (SDL's per-user folder for the game) and the mods and mod data folders, removes the // mods folder older versions kept with the saves, moves loose online logs into online_logs/desyncs/ and notes the // folders in savedatapath.txt. -// The game's own folder, where it kept mods/, data/ and savedatapath.txt, is resources/ here. Mod data goes with saves. -// The harness's --mods replaces the mods folder. +// The game's own folder, where it kept mods/, data/ and savedatapath.txt, is resources/ here, or the install's own +// folder when the resources are an install's, which is only read: savedatapath.txt is left out there. Mod data goes +// with saves. The harness's --mods replaces the mods folder. void Platform::directories_load() { char* prefPath = SDL_GetPrefPath("", SAVE_FOLDER.data()); @@ -187,7 +188,8 @@ void Platform::directories_load() SDL_free(prefPath); if (userDataDirectory.empty()) SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error", SAVE_FOLDER_ERROR, nullptr); - modsDirectory = harness.modsDirectory.empty() ? dataDirectory + "mods/" : harness.modsDirectory; + std::string gameDirectory = is_archive_mounted() ? dataDirectory + "../" : dataDirectory; + modsDirectory = harness.modsDirectory.empty() ? gameDirectory + "mods/" : harness.modsDirectory; modsSaveDirectory = userDataDirectory + "data/"; folder_create(modsDirectory, "Modding data path %s is not a writable directory!"); folder_create(modsSaveDirectory, "Modding save data path %s is not a writable directory!"); @@ -204,7 +206,7 @@ void Platform::directories_load() std::filesystem::rename(entry.path(), std::filesystem::path(desyncs) / entry.path().filename(), result); } - FILE* info = std::fopen((dataDirectory + "savedatapath.txt").c_str(), "w"); + FILE* info = is_archive_mounted() ? nullptr : std::fopen((dataDirectory + "savedatapath.txt").c_str(), "w"); if (!info) return; std::fputs(SAVE_PATHS_NOTICE, info); std::fprintf(info, "Save Data Path: %s\n", userDataDirectory.c_str()); diff --git a/src/engine/video_player.cpp b/src/engine/video_player.cpp index 4442638..dbb6ab1 100644 --- a/src/engine/video_player.cpp +++ b/src/engine/video_player.cpp @@ -8,7 +8,7 @@ #include "engine/platform.h" #include #include -#include +#include #include #include #include @@ -43,7 +43,7 @@ constexpr int CB_TO_BLUE = 132201; // Its time is the sound the device took, run on by the clock between the device's reads, or the clock alone. struct VideoClip { - std::ifstream file; + std::istringstream file; std::vector samples; std::vector texels; ogg_sync_state sync = {}; @@ -340,8 +340,10 @@ bool VideoPlayer::load(const std::string& path) unload(); auto video = std::make_unique(); - video->file.open(resource_path(path), std::ios::binary); - if (!video->file || !video->headers_load()) + std::string bytes; + bool isRead = resource_load(path, bytes); + video->file.str(std::move(bytes)); + if (!isRead || !video->headers_load()) { log_printf(LOG_INFO, "ERROR: Failed creating video clip: %s\n", path.c_str()); return false; diff --git a/src/entity/boss/intro.cpp b/src/entity/boss/intro.cpp index 9ea99a0..95b4049 100644 --- a/src/entity/boss/intro.cpp +++ b/src/entity/boss/intro.cpp @@ -189,11 +189,8 @@ static void backdrop_tint(ANM2& versus, uint32_t bossId1) const KAGE::Graphics::ImagePtr& sheet = versus.GetLayer(LAYER_BOSS_SPOT)->spriteSheet; int width = 0; int height = 0; - int channels = 0; - stbi_uc* texels = nullptr; + uint8_t* texels = sheet && sheet->isLoaded ? KAGE::Graphics::texels_load(sheet->path, width, height) : nullptr; - if (sheet && sheet->isLoaded) - texels = stbi_load(resource_path(sheet->path).c_str(), &width, &height, &channels, STBI_rgb_alpha); if (!texels || width < 2) { layer_tint(versus, LAYER_BACKGROUND, 0, 0, 0); diff --git a/src/entity/boss/pool.cpp b/src/entity/boss/pool.cpp index a32ed2c..3c4fadb 100644 --- a/src/entity/boss/pool.cpp +++ b/src/entity/boss/pool.cpp @@ -86,10 +86,7 @@ constexpr std::array BOSS_POOL_STAGES = {{{"basement", 1}, // Calls visit with each attribute of an element, in document order. template static void attrs_walk(DataNode node, Visit visit) { - simdjson::dom::object attrs; - if (node["attrs"].get(attrs) != simdjson::SUCCESS) return; - - for (auto [name, value] : attrs) visit(name, value.get_string().value_unsafe()); + for (auto [name, value] : node_attrs(node)) visit(name, value); } // Whether a boss id is one the pools track, as only those have a bit in the removed and blacklisted sets. diff --git a/src/entity/config.cpp b/src/entity/config.cpp index e20d868..b63ab62 100644 --- a/src/entity/config.cpp +++ b/src/entity/config.cpp @@ -72,7 +72,7 @@ struct PlayerLoad std::string skinRoot; }; -// Attribute text as atoi and atof read it. Every attribute is NUL-terminated where simdjson keeps it. +// Attribute text as atoi and atof read it. Every attribute is NUL-terminated where the document keeps it. static int text_int(std::string_view text) { return text.empty() ? 0 : atoi(text.data()); @@ -124,20 +124,15 @@ template static uint32_t flags_parse(std::string_view text, const std // Calls visit with each attribute's name and text. template static void attrs_walk(DataNode node, Visit visit) { - simdjson::dom::object attrs; - if (node["attrs"].get(attrs) != simdjson::SUCCESS) return; - - for (auto [name, value] : attrs) visit(name, value.get_string().value_unsafe()); + for (auto [name, value] : node_attrs(node)) visit(name, value); } -// Calls visit with the children walk picks, in document order. A leaf has no children array to walk at all. +// Calls visit with the children walk picks, in document order. template static void children_walk(DataNode node, std::string_view tag, ChildWalk walk, Visit visit) { - simdjson::dom::array children; bool isFound = walk == CHILDREN_ALL; - if (node["children"].get(children) != simdjson::SUCCESS) return; - for (DataNode child : children) + for (DataNode child : node_children(node)) { bool isTagged = node_tag(child) == tag; isFound = isFound || isTagged; @@ -154,13 +149,6 @@ static std::optional child_find(DataNode node, std::string_view tag) return found; } -static std::optional attr_find(DataNode node, std::string_view name) -{ - std::string_view value; - if (node["attrs"][name].get(value) != simdjson::SUCCESS) return std::nullopt; - return value; -} - // The document's root element of a tag, logging its absence. The original goes on to read the missing root and crashes. static std::optional root_find(Data& data, std::string_view tag, std::string_view path) { @@ -441,7 +429,7 @@ bool EntityConfig::LoadEntities(std::string_view path, ModEntry* mod) path.data()); load.anm2Root = node_attr(*root, "anm2root"); - std::optional deathAnm2 = attr_find(*root, "deathanm2"); + std::optional deathAnm2 = node_attr_find(*root, "deathanm2"); if (mod && deathAnm2) { mod->load_content_anm2(MOD_SPRITE_DEATH_ENEMIES, *deathAnm2); diff --git a/src/entity/familiar/babies.cpp b/src/entity/familiar/babies.cpp index c1a5b83..5eb6f06 100644 --- a/src/entity/familiar/babies.cpp +++ b/src/entity/familiar/babies.cpp @@ -23,7 +23,6 @@ #include "level/room_descriptor.h" #include "level/room_grid.h" #include -#include #include // Lil Spewer's five kinds (its state): normal, white, red, black and yellow, each with its sheet, creep, charge tint and @@ -765,8 +764,7 @@ void minisaac_init(Entity_Familiar& minisaac) size_t dot = sheet.find_last_of('.'); if (dot == std::string::npos) continue; std::string path = g_manager->modManager.TryRedirectPath(sheet.substr(0, dot) + std::string(suffix) + sheet.substr(dot)); - std::error_code error; - if (std::filesystem::exists(resource_path(path), error)) minisaac.sprite.ReplaceSpritesheet(layer, path); + if (resource_exists(path)) minisaac.sprite.ReplaceSpritesheet(layer, path); } minisaac.sprite.LoadGraphics(); } diff --git a/src/entity/familiar/evaluate.cpp b/src/entity/familiar/evaluate.cpp index 9bbf53f..0bbd88c 100644 --- a/src/entity/familiar/evaluate.cpp +++ b/src/entity/familiar/evaluate.cpp @@ -11,7 +11,6 @@ #include "entity/weapon/weapon.h" #include #include -#include #include #include @@ -448,8 +447,7 @@ void Entity_Familiar::delirium_morph() continue; std::string sheet = g_manager->modManager.TryRedirectPath( std::string(data->spriteSheetPath).insert(DELIRIUM_SHEET_PREFIX, DELIRIUM_SHEET_FOLDER)); - std::error_code error; - if (!std::filesystem::exists(resource_path(sheet), error)) continue; + if (!resource_exists(sheet)) continue; sprite.ReplaceSpritesheet(layer, sheet); isRecolored = true; } diff --git a/src/entity/npc/npc.cpp b/src/entity/npc/npc.cpp index e570260..56eaae5 100644 --- a/src/entity/npc/npc.cpp +++ b/src/entity/npc/npc.cpp @@ -35,7 +35,6 @@ #include "entity/npc/alt.h" #include #include -#include #ifdef ISAAC_REPENTOGON #include "repentogon/callbacks.h" #include "repentogon/npc.h" @@ -868,7 +867,7 @@ std::string sheet_path_resolve(const std::string& path, std::string_view floorSu std::string stem = path.substr(0, path.size() - SHEET_EXTENSION_SIZE); std::string extension = path.substr(path.size() - SHEET_EXTENSION_SIZE); auto isFound = [&](const std::string& candidate) { - return std::filesystem::exists(resource_path(g_manager->modManager.TryRedirectPath(candidate))); + return resource_exists(g_manager->modManager.TryRedirectPath(candidate)); }; std::string both = stem + std::string(championSuffix) + std::string(floorSuffix) + extension; diff --git a/src/entity/npc/spider.cpp b/src/entity/npc/spider.cpp index c5d534e..fe6e681 100644 --- a/src/entity/npc/spider.cpp +++ b/src/entity/npc/spider.cpp @@ -9,7 +9,6 @@ #include "entity/config.h" #include "game/manager.h" #include "ui/menu/manager.h" -#include // A spider rests 14 frames, then runs at its target (leading it) when near and in sight, else somewhere at random // within 70 to 110, keeping out of the walls. The jumping kinds leap there one time in three. @@ -282,7 +281,7 @@ bool spider_load_graphics(Entity_NPC& npc, std::string_view suffix) if (path.empty() || dot == std::string::npos) return false; std::string redirected = g_manager->modManager.TryRedirectPath(path.substr(0, dot) + std::string(suffix) + path.substr(dot)); - if (!std::filesystem::exists(resource_path(redirected))) return false; + if (!resource_exists(redirected)) return false; std::string animation = npc.sprite.GetAnimation(); npc.sprite.Load(redirected, GRAPHICS_LOAD); diff --git a/src/entity/pickup/item_config.cpp b/src/entity/pickup/item_config.cpp index 67c7ce6..6a661fa 100644 --- a/src/entity/pickup/item_config.cpp +++ b/src/entity/pickup/item_config.cpp @@ -151,30 +151,15 @@ static std::optional document_open_warned(Data& data, std::string_view return root; } -// An attribute's text, null-terminated, or nothing when the element lacks it. -static std::optional attr_find(DataNode node, std::string_view name) -{ - std::string_view text; - if (node["attrs"][name].get(text) != simdjson::SUCCESS) return std::nullopt; - return text; -} - static std::string_view attr_get(DataNode node, std::string_view name) { - return attr_find(node, name).value_or(""); + return node_attr_find(node, name).value_or(""); } // Calls function with each attribute's name and text, in document order, as rapidxml's attribute walk visits them. template static void attrs_each(DataNode node, Function function) { - simdjson::dom::object attrs; - if (node["attrs"].get(attrs) != simdjson::SUCCESS) return; - - for (auto [name, value] : attrs) - { - std::string_view text; - if (value.get(text) == simdjson::SUCCESS) function(name, text); - } + for (auto [name, text] : node_attrs(node)) function(name, text); } // The game's bool attribute: "true", "True" or a nonzero number, so empty is false. @@ -211,7 +196,7 @@ static void value_parse(std::string_view text, std::string& value) // Reads an attribute into value, leaving value as it is when the element lacks it. template static void attr_read(DataNode node, std::string_view name, T& value) { - if (auto text = attr_find(node, name)) value_parse(*text, value); + if (auto text = node_attr_find(node, name)) value_parse(*text, value); } // Calls function on each word between single spaces, as getline splits: doubled spaces give an empty word, a trailing @@ -648,11 +633,11 @@ static std::unique_ptr item_parse(DataNode node, std::string_vi attr_read(node, "id", item->id); attr_read(node, "name", item->name); attr_read(node, "description", item->desc); - if (auto gfx = attr_find(node, "gfx")) + if (auto gfx = node_attr_find(node, "gfx")) item->gfxFilename = std::string(gfxRoot) + (item->IsTrinket() ? "trinkets/" : "collectibles/") += *gfx; attr_read(node, "achievement", item->achievementId); - if (auto cache = attr_find(node, "cache")) item->cacheFlags |= cache_flags_parse(*cache); - if (auto tags = attr_find(node, "tags")) item->tags = tags_parse(*tags); + if (auto cache = node_attr_find(node, "cache")) item->cacheFlags |= cache_flags_parse(*cache); + if (auto tags = node_attr_find(node, "tags")) item->tags = tags_parse(*tags); attr_read(node, "maxhearts", item->addMaxHearts); attr_read(node, "hearts", item->addHearts); @@ -676,7 +661,7 @@ static std::unique_ptr item_parse(DataNode node, std::string_vi attr_read(node, "hidden", item->isHidden); attr_read(node, "persistent", item->isPersistentEffect); - if (auto chargeType = attr_find(node, "chargetype")) + if (auto chargeType = node_attr_find(node, "chargetype")) { if (*chargeType == "normal") item->chargeType = CHARGE_NORMAL; @@ -715,7 +700,7 @@ bool ItemConfig::Load(std::string_view path, ModEntry* mod) std::string_view version = attr_get(*root, "version"); std::string_view gfxRoot = attr_get(*root, "gfxroot"); - std::optional deathAnm2 = attr_find(*root, "deathanm2"); + std::optional deathAnm2 = node_attr_find(*root, "deathanm2"); if (version != ITEMS_VERSION) log_print(LOG_ASSERT, "Invalid version %s for %s\n", version.data(), std::string(path).c_str()); if (mod && deathAnm2) mod->load_content_anm2(MOD_SPRITE_DEATH_ITEMS, *deathAnm2); @@ -750,7 +735,8 @@ static ItemConfig_Costume costume_parse(DataNode node, std::string_view anm2Root costume.id = 0; attr_read(node, "id", costume.id); - if (auto anm2Path = attr_find(node, "anm2path")) costume.anm2Path = std::string(anm2Root) + std::string(*anm2Path); + if (auto anm2Path = node_attr_find(node, "anm2path")) + costume.anm2Path = std::string(anm2Root) + std::string(*anm2Path); attr_read(node, "priority", costume.priority); attr_read(node, "skinColor", costume.skinColor); attr_read(node, "hasOverlay", costume.isHasOverlay); @@ -862,9 +848,9 @@ bool ItemConfig::LoadCraftingRecipes(std::string_view path, ModEntry* mod) if (!root) return data.isLoaded; for (DataNode node : node_children(*root)) { - std::optional input = attr_find(node, "input"); - std::optional output = attr_find(node, "output"); - std::optional outputName = attr_find(node, "outputName"); + std::optional input = node_attr_find(node, "input"); + std::optional output = node_attr_find(node, "output"); + std::optional outputName = node_attr_find(node, "outputName"); int outputId = 0; int pool = std::atoi(attr_get(node, "pool").data()); @@ -939,7 +925,7 @@ bool ItemConfig::LoadPocketItems(std::string_view path, ModEntry* mod) std::string_view tag = node_tag(node); CardType cardType = CARD_SPECIAL; - if (auto type = attr_find(node, "type")) cardType = card_type_parse(*type); + if (auto type = node_attr_find(node, "type")) cardType = card_type_parse(*type); if (tag == "card" || tag == "rune") { auto card = std::make_unique(); @@ -968,7 +954,7 @@ bool ItemConfig::LoadPocketItems(std::string_view path, ModEntry* mod) auto pill = std::make_unique(); pocket_item_parse(*pill, node, mod); attr_read(node, "announcer2", pill->announcerVoiceSuper); - if (auto effectClass = attr_find(node, "class")) pill_class_parse(*pill, *effectClass); + if (auto effectClass = node_attr_find(node, "class")) pill_class_parse(*pill, *effectClass); if (pill->id < 0) { log_print(LOG_INFO, "[warn] %s: Pill Effect ID %d out of range!\n", pathText.c_str(), pill->id); @@ -1003,8 +989,8 @@ bool ItemConfig::player_forms_load(std::string_view path) attr_read(node, "id", form->id); attr_read(node, "name", form->name); attr_read(node, "costume", form->costume); - if (auto tags = attr_find(node, "tags")) form->tags = tags_parse(*tags); - if (auto cache = attr_find(node, "cache")) form->cacheFlags = cache_flags_parse(*cache); + if (auto tags = node_attr_find(node, "tags")) form->tags = tags_parse(*tags); + if (auto cache = node_attr_find(node, "cache")) form->cacheFlags = cache_flags_parse(*cache); if (form->id >= 0 && form->id < (int)playerForms.size()) playerForms[form->id] = std::move(form); else @@ -1113,7 +1099,7 @@ bool ItemConfig::LoadWispConfig(std::string_view path, ModEntry* mod) for (DataNode node : node_children(*root)) { std::string_view tag = node_tag(node); - std::optional id = attr_find(node, "id"); + std::optional id = node_attr_find(node, "id"); std::unique_ptr* slot = nullptr; if (tag == "color") color_preset_load(presets, node); @@ -1239,7 +1225,7 @@ void ItemConfig::LoadLocustConfig(std::string_view path, ModEntry* mod) } if (tag != "locust") continue; - std::optional id = attr_find(node, "id"); + std::optional id = node_attr_find(node, "id"); if (!id) continue; int collectibleId = mod_id_get(mod ? &mod->collectibleIdMap : nullptr, std::atoi(id->data())); if (ItemConfig_Item* item = item_find(collectibles, collectibleId, COLLECTIBLE_OUT_OF_BOUNDS)) diff --git a/src/entity/pickup/item_pool.cpp b/src/entity/pickup/item_pool.cpp index b681be5..7eaefe3 100644 --- a/src/entity/pickup/item_pool.cpp +++ b/src/entity/pickup/item_pool.cpp @@ -152,14 +152,6 @@ static bool is_kind_allowed(ItemConfig_Item* item, uint32_t flags) return !((flags & POOL_FLAG_BAN_ACTIVES) && isActive) && !((flags & POOL_FLAG_BAN_PASSIVES) && !isActive); } -// An attribute's text, or nothing when the element lacks it. -static std::optional attr_find(DataNode node, std::string_view name) -{ - std::string_view text; - if (node["attrs"][name].get(text) != simdjson::SUCCESS) return std::nullopt; - return text; -} - // The children of node from the first with a tag on, as rapidxml's first_node(tag) then next_sibling() walks them. static std::vector elements_from(DataNode node, std::string_view tag) { @@ -174,21 +166,16 @@ static std::vector elements_from(DataNode node, std::string_view tag) static PoolItem pool_item_parse(DataNode node) { PoolItem item; - simdjson::dom::object attrs; + auto& names = g_manager->itemConfig.collectibleNameMap; - if (node["attrs"].get(attrs) == simdjson::SUCCESS) - for (auto [name, value] : attrs) - { - std::string_view text; - if (value.get(text) != simdjson::SUCCESS) continue; - - auto& names = g_manager->itemConfig.collectibleNameMap; - if (name == "Id") item.itemId = std::atoi(text.data()); - if (name == "Weight") item.initialWeight = item.weight = (float)std::atof(text.data()); - if (name == "DecreaseBy") item.decreaseBy = (float)std::atof(text.data()); - if (name == "RemoveOn") item.removeOn = (float)std::atof(text.data()); - if (name == "Name" && names.contains(text)) item.itemId = names.find(text)->second; - } + for (auto [name, text] : node_attrs(node)) + { + if (name == "Id") item.itemId = std::atoi(text.data()); + if (name == "Weight") item.initialWeight = item.weight = (float)std::atof(text.data()); + if (name == "DecreaseBy") item.decreaseBy = (float)std::atof(text.data()); + if (name == "RemoveOn") item.removeOn = (float)std::atof(text.data()); + if (name == "Name" && names.contains(text)) item.itemId = names.find(text)->second; + } ItemConfig_Item* config = collectible_get(item.itemId); item.isSpecial = config && config->isSpecial; @@ -305,7 +292,7 @@ void ItemPool::load_pools(std::string_view path, PoolsLoad load) for (DataNode node : elements_from(*root, "Pool")) { - std::optional name = attr_find(node, "Name"); + std::optional name = node_attr_find(node, "Name"); if (!name) continue; auto found = std::ranges::find(POOL_NAMES, *name); diff --git a/src/entity/player/hud.cpp b/src/entity/player/hud.cpp index 1281f97..97b1d6f 100644 --- a/src/entity/player/hud.cpp +++ b/src/entity/player/hud.cpp @@ -472,8 +472,7 @@ static void trinket_icon_load(PlayerHUDTrinket& trinket) int width = 0; int height = 0; - int channels = 0; - stbi_uc* pixels = stbi_load(resource_path(trinket.image->path).c_str(), &width, &height, &channels, STBI_rgb_alpha); + uint8_t* pixels = KAGE::Graphics::texels_load(trinket.image->path, width, height); std::array square{}; for (int row = 0; pixels && row < std::min(height, TRINKET_ICON_PIXELS); row++) std::copy_n(pixels + (size_t)row * width * RGBA, std::min(width, TRINKET_ICON_PIXELS) * RGBA, square.begin() + row * TRINKET_ICON_PIXELS * RGBA); diff --git a/src/entity/player/player.cpp b/src/entity/player/player.cpp index 6192cb2..67bae24 100644 --- a/src/entity/player/player.cpp +++ b/src/entity/player/player.cpp @@ -22,7 +22,6 @@ #include "level/room_grid.h" #include #include -#include #ifdef ISAAC_REPENTOGON #include "repentogon/player.h" #endif @@ -86,13 +85,6 @@ constexpr const char* CHARGE_BAR_PATHS[CHARGE_BAR_COUNT] = { "gfx/chargebar_poop.anm2", "gfx/chargebar_berserk.anm2", "gfx/chargebar_sumptorium.anm2"}; -// Whether a resource file exists, after the mods redirected it. -static bool is_file_found(const std::string& path) -{ - std::error_code error; - return std::filesystem::exists(resource_path(path), error); -} - // A color from bytes as ColorParams::set_from_bytes builds it: a tint and an offset over 255, no colorize. static ColorMod color_from_bytes(int tintRed, int tintGreen, int tintBlue, int tintAlpha, int offsetRed, int offsetGreen, int offsetBlue) @@ -1555,7 +1547,7 @@ std::string costume_path_apply_skin_color(const std::string& path, int skinColor { std::string candidate = path.substr(0, slash) + "_" + playerConfig->costumeSuffixName + path.substr(slash); std::string redirected = g_manager->modManager.TryRedirectPath(candidate); - if (is_file_found(redirected)) + if (resource_exists(redirected)) { result = redirected; isPlayerFound = true; @@ -1571,7 +1563,7 @@ std::string costume_path_apply_skin_color(const std::string& path, int skinColor std::string_view suffix = SKIN_COLOR_SUFFIXES[skinColor < (int)SKIN_COLOR_SUFFIXES.size() ? skinColor : 0]; std::string candidate = result.substr(0, dot) + std::string(suffix) + result.substr(dot); std::string redirected = g_manager->modManager.TryRedirectPath(candidate); - if (is_file_found(redirected)) + if (resource_exists(redirected)) { result = redirected; isSkinFound = true; diff --git a/src/entity/weapon/bomb.cpp b/src/entity/weapon/bomb.cpp index 22584bd..7732bbe 100644 --- a/src/entity/weapon/bomb.cpp +++ b/src/entity/weapon/bomb.cpp @@ -23,7 +23,6 @@ #include "game/sfx_manager.h" #include #include -#include #ifdef ISAAC_REPENTOGON #include "repentogon/callbacks.h" #endif @@ -1124,8 +1123,7 @@ static std::string suffixed_sheet_get(const std::string& path, const std::vector for (const std::string& suffix : suffixes) { std::string candidate = g_manager->modManager.TryRedirectPath(path.substr(0, stem) + suffix + path.substr(stem)); - std::error_code error; - if (std::filesystem::exists(resource_path(candidate), error)) return candidate; + if (resource_exists(candidate)) return candidate; } return path; } diff --git a/src/game/game.cpp b/src/game/game.cpp index a04e895..9e52075 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -211,14 +211,6 @@ void Game::LoadConfigXmls() game.console.reset(); } -// An attribute when the element has it, empty or not. -static std::optional attr_find(DataNode node, std::string_view name) -{ - std::string_view value; - if (node["attrs"][name].get(value) != simdjson::SUCCESS) return std::nullopt; - return value; -} - // An attribute as the game reads booleans: "true", "True" or a nonzero number. static bool attr_bool(std::string_view value) { @@ -257,10 +249,10 @@ bool Game::load_giantbook_xml(std::string_view path) if (node_tag(node) != "entry") continue; GiantbookEntry entry; - if (auto text = attr_find(node, "id")) id = std::atoi(text->data()); - if (auto text = attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text); - if (auto text = attr_find(node, "anim")) entry.animation = *text; - if (auto text = attr_find(node, "gfx")) entry.gfxPath = anm2Root + std::string(*text); + if (auto text = node_attr_find(node, "id")) id = std::atoi(text->data()); + if (auto text = node_attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text); + if (auto text = node_attr_find(node, "anim")) entry.animation = *text; + if (auto text = node_attr_find(node, "gfx")) entry.gfxPath = anm2Root + std::string(*text); for (DataNode layerNode : node_children(node)) { @@ -271,7 +263,7 @@ bool Game::load_giantbook_xml(std::string_view path) layer.name = node_attr(layerNode, "name"); for (size_t channel = 0; channel < TINT_ATTRIBUTES.size(); channel++) - if (auto text = attr_find(layerNode, TINT_ATTRIBUTES[channel])) + if (auto text = node_attr_find(layerNode, TINT_ATTRIBUTES[channel])) tint[channel] = (float)std::atoi(text->data()) / COLOR_CHANNEL_MAX; if (!layer.name.empty()) entry.layers.push_back(layer); } @@ -302,10 +294,10 @@ bool Game::load_bossoverlays_xml(std::string_view path) if (node_tag(node) != "entry") continue; BossOverlayEntry entry; - if (auto text = attr_find(node, "id")) entry.id = std::atoi(text->data()); - if (auto text = attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text); - if (auto text = attr_find(node, "anim")) entry.animation = *text; - if (auto text = attr_find(node, "persist")) entry.isPersistent = attr_bool(*text); + if (auto text = node_attr_find(node, "id")) entry.id = std::atoi(text->data()); + if (auto text = node_attr_find(node, "anm2")) entry.anm2Path = anm2Root + std::string(*text); + if (auto text = node_attr_find(node, "anim")) entry.animation = *text; + if (auto text = node_attr_find(node, "persist")) entry.isPersistent = attr_bool(*text); if ((unsigned)entry.id < BOSS_OVERLAY_COUNT) bossOverlay.entries[entry.id] = std::move(entry); } return true; @@ -345,8 +337,8 @@ void Game::LoadBossRushXml(std::string_view path) int count = 1; spawn.type = std::atoi(node_attr(enemyNode, "type").data()); spawn.variant = std::atoi(node_attr(enemyNode, "variant").data()); - if (auto text = attr_find(enemyNode, "chunks")) spawn.chunks = std::atoi(text->data()); - if (auto text = attr_find(enemyNode, "count")) count = std::atoi(text->data()); + if (auto text = node_attr_find(enemyNode, "chunks")) spawn.chunks = std::atoi(text->data()); + if (auto text = node_attr_find(enemyNode, "count")) count = std::atoi(text->data()); slot.insert(slot.end(), std::max(count, 0), spawn); } } diff --git a/src/game/main.cpp b/src/game/main.cpp index 1e3f17b..a0ae9e7 100644 --- a/src/game/main.cpp +++ b/src/game/main.cpp @@ -78,8 +78,9 @@ int IsaacMain(int argc, uint8_t** argv) return 0; } -// The Linux entry point: "--resources " says where the imported game files are, "--mute" plays nothing, the -// harness takes its flags, then the game's own main runs. +// The Linux entry point: "--resources " says where the game files are (the import tool's folder, or an install's +// resources folder with its packed archives, mounted here), "--mute" plays nothing, the harness takes its flags, then +// the game's own main runs. int main(int argc, char** argv) { harness.arguments_load(argc, argv); @@ -89,5 +90,6 @@ int main(int argc, char** argv) else if (std::strcmp(argv[i], RESOURCES_FLAG) == 0 && i + 1 < argc) dataDirectory = std::string(argv[i + 1]) + "/"; } + archives_load(); return IsaacMain(argc, (uint8_t**)argv); } diff --git a/src/game/manager.cpp b/src/game/manager.cpp index d8f355f..3f75962 100644 --- a/src/game/manager.cpp +++ b/src/game/manager.cpp @@ -758,20 +758,15 @@ bool Manager::LoadChallenges(std::string_view path, ChallengeSource source) if (!isFirstFound) continue; ChallengeParam param; - simdjson::dom::object attributes; param.isPathTypeSet = true; - if (node["attrs"].get(attributes) == simdjson::SUCCESS) + for (auto [name, text] : node_attrs(node)) { - for (auto [name, value] : attributes) - { - std::string_view text = value.get_string().value_unsafe(); - std::string nameText(name); - auto found = CHALLENGE_ATTRIBUTES.find(name); + std::string nameText(name); + auto found = CHALLENGE_ATTRIBUTES.find(name); - if (name == CHALLENGE_ID) challengeId = std::atoi(text.data()); - else if (found != CHALLENGE_ATTRIBUTES.end()) found->second(param, text); - else log_printf(LOG_ASSERT, "Got invald parameter %s when reading challenges!\n", nameText.c_str()); - } + if (name == CHALLENGE_ID) challengeId = std::atoi(text.data()); + else if (found != CHALLENGE_ATTRIBUTES.end()) found->second(param, text); + else log_printf(LOG_ASSERT, "Got invald parameter %s when reading challenges!\n", nameText.c_str()); } if (source == CHALLENGES_MOD) challengeParams.push_back(std::move(param)); diff --git a/src/game/mod_manager.cpp b/src/game/mod_manager.cpp index 69c969d..46b7be1 100644 --- a/src/game/mod_manager.cpp +++ b/src/game/mod_manager.cpp @@ -8,6 +8,7 @@ #include "ui/menu/manager.h" #include "ui/pause_screen.h" #include "engine/platform.h" +#include "pugixml.hpp" #include #include #include @@ -135,30 +136,10 @@ static std::string text_lower(std::string text) return text; } -// Text as a JSON string. -static std::string text_quote(std::string_view text) -{ - std::string quoted = "\""; - for (char letter : text) - { - char escaped[8]; - - if (letter == '"' || letter == '\\') quoted += '\\'; - if ((unsigned char)letter >= ' ') quoted += letter; - else - { - std::snprintf(escaped, sizeof(escaped), "\\u%04x", letter); - quoted += escaped; - } - } - return quoted + '"'; -} - -// Whether a game path exists under resources/, as itself or as a converted XML document. +// Whether a game path is mounted, as itself or as a converted XML document. static bool is_resource_found(std::string_view path) { - std::error_code error; - return std::filesystem::exists(resource_path(path), error) || std::filesystem::exists(data_path(path), error); + return resource_exists(path) || resource_exists(std::string(path) + std::string(JSON_EXTENSION)); } // A mod folder's twin, whose files win over the folder's own. @@ -168,14 +149,11 @@ static std::string dlc_folder_get(std::string_view folder) } // The child elements with this tag, in document order. -// The children are read here, since iterating node_children's empty array crashes on a leaf. static std::vector node_children_find(DataNode node, std::string_view tag) { std::vector found; - simdjson::dom::array children; - if (node["children"].get(children) != simdjson::SUCCESS) return found; - for (DataNode child : children) + for (DataNode child : node_children(node)) if (node_tag(child) == tag) found.push_back(child); return found; } @@ -229,10 +207,7 @@ static void metadata_load(ModEntry& mod, std::string& modPath) for (MetadataField field : METADATA_FIELDS) if (std::optional child = node_child_find(*metadata, field.tag)) mod.*field.field = node_text(*child); for (DataNode tag : node_children_find(*metadata, TAG_TAG)) - { - std::string_view id; - if (tag["attrs"][ID_ATTRIBUTE].get(id) == simdjson::SUCCESS) mod.tags.emplace_back(id); - } + if (std::optional id = node_attr_find(tag, ID_ATTRIBUTE)) mod.tags.emplace_back(*id); } // A mod read from its folder: its metadata (missing fields defaulted and written back), its folders, and whether it @@ -499,26 +474,20 @@ std::string ModEntry::GetContentPath(std::string_view fileName) return is_resource_found(dlcPath) ? dlcPath : contentDirectory + std::string(fileName); } -// 008f92b0 Writes the mod's metadata back as its converted metadata.xml, where the game reads it. -// The original writes XML with rapidxml. This writes the JSON the import tool makes of it, blank text left out. +// 008f92b0 Writes the mod's metadata back as its metadata.xml, tab-indented as rapidxml prints it. // The workshop id stays out of the file, as in the original. void ModEntry::WriteMetadata() { - std::string children; + pugi::xml_document document; + pugi::xml_node metadata = document.append_child(METADATA_TAG); for (MetadataField field : METADATA_FIELDS) - { - if (field.field == &ModEntry::metadataWorkshopID) continue; - std::string& text = this->*field.field; - bool isBlank = text.find_first_not_of(" \t\r\n") == std::string::npos; - std::string textField = isBlank ? "" : ",\"text\":" + text_quote(text); - children += "{\"tag\":\"" + std::string(field.tag) + '"' + textField + "},"; - } - for (std::string& tag : tags) children += "{\"tag\":\"tag\",\"attrs\":{\"id\":" + text_quote(tag) + "}},"; - children.pop_back(); + if (field.field != &ModEntry::metadataWorkshopID) + metadata.append_child(field.tag).text() = (this->*field.field).c_str(); + for (std::string& tag : tags) metadata.append_child(TAG_TAG).append_attribute(ID_ATTRIBUTE) = tag.c_str(); - std::ofstream file(data_path(MODS_FOLDER + directory + METADATA_FILE)); - file << "{\"tag\":\"metadata\",\"children\":[" << children << "]}"; + std::string path = resource_path(MODS_FOLDER + directory + METADATA_FILE); + document.save_file(path.c_str(), "\t", pugi::format_indent | pugi::format_no_declaration); } // Writes disable.it into the mod's folder while the mod is off, and removes it once it is on (inlined in diff --git a/src/game/music_manager.cpp b/src/game/music_manager.cpp index 196072d..b7c95f7 100644 --- a/src/game/music_manager.cpp +++ b/src/game/music_manager.cpp @@ -221,20 +221,6 @@ static std::optional root_find(Data& data, std::string_view tag) return std::nullopt; } -// An element's attributes in document order, none when it has none. -static simdjson::dom::object attrs_get(DataNode node) -{ - simdjson::dom::object attrs; - return node["attrs"].get(attrs) == simdjson::SUCCESS ? attrs : simdjson::dom::object(); -} - -// An attribute's text, NUL-terminated as atoi needs. -static std::string_view text_get(simdjson::dom::element value) -{ - std::string_view text; - return value.get(text) == simdjson::SUCCESS ? text : std::string_view(""); -} - // A file music.xml names, under its root, where the mods redirect it. static std::string path_redirect(std::string_view root, std::string_view path) { @@ -252,9 +238,8 @@ static MusicLayer layer_parse(DataNode node, std::string_view root) { MusicLayer layer; - for (auto [key, value] : attrs_get(node)) + for (auto [key, text] : node_attrs(node)) { - std::string_view text = text_get(value); if (key == "intro") layer.introPath = path_redirect(root, text); else if (key == "path") layer.path = path_redirect(root, text); else if (key == "mul") layer.volume = (float)std::atof(text.data()); @@ -269,9 +254,8 @@ static MusicTrack track_parse(DataNode node, std::string_view root) MusicTrack track; MusicLayer attrLayer; - for (auto [key, value] : attrs_get(node)) + for (auto [key, text] : node_attrs(node)) { - std::string_view text = text_get(value); if (key == "id") track.id = std::atoi(text.data()); else if (key == "name") track.name = text; else if (key == "intro") track.introPath = path_redirect(root, text); diff --git a/src/game/options_config.cpp b/src/game/options_config.cpp index 5c9d18d..1293613 100644 --- a/src/game/options_config.cpp +++ b/src/game/options_config.cpp @@ -112,6 +112,14 @@ static void option_read(KeyValueMap& map, const char* key, float& value) value = keyvalue_map_read_float(map, key, value); } +// The data format, by its name. +static void option_read(KeyValueMap& map, const char* key, DataFormat& value) +{ + std::string text = keyvalue_map_get(map, key); + auto found = std::ranges::find(DATA_FORMAT_NAMES, text); + if (found != std::end(DATA_FORMAT_NAMES)) value = (DataFormat)(found - std::begin(DATA_FORMAT_NAMES)); +} + // Ints and the enums options.ini stores as ints. template static void option_read(KeyValueMap& map, const char* key, T& value) { @@ -125,6 +133,11 @@ static void line_write(std::string& text, const char* key, float value) text.append(line, std::snprintf(line, sizeof(line), "%s=%.4f\r\n", key, value)); } +static void line_write(std::string& text, const char* key, DataFormat value) +{ + text.append(key).append("=").append(DATA_FORMAT_NAMES[value]).append("\r\n"); +} + // Ints, bools and enums, all written as numbers. static void line_write(std::string& text, const char* key, int value) { @@ -157,20 +170,22 @@ void OptionsConfig::defaults_reset() // 00924180 Reads config.ini's effect switches, each on unless the file turns it off. void OptionsConfig::config_ini_load() { + std::string text; render = {}; - std::optional map = ini_load(resource_path(CONFIG_INI).c_str()); - if (!map) return; + if (!resource_load(CONFIG_INI, text)) return; - option_read(*map, "EnableColorCorrection", render.isColorCorrectionEnabled); - option_read(*map, "EnableCaustics", render.isCausticsEnabled); - option_read(*map, "EnableShockwave", render.isShockwaveEnabled); - option_read(*map, "EnableLighting", render.isLightingEnabled); - option_read(*map, "EnableFilter", render.isFilterEnabled); - option_read(*map, "EnablePixelation", render.isPixelationEnabled); - option_read(*map, "EnableBloom", render.isBloomEnabled); - option_read(*map, "EnableWaterSurface", render.isWaterSurfaceEnabled); - option_read(*map, "EnableInterpolation", render.isInterpolationEnabled); - option_read(*map, "EnableColorModifier", render.isColorModifierEnabled); + KeyValueMap map = keyvalue_map_parse(text); + + option_read(map, "EnableColorCorrection", render.isColorCorrectionEnabled); + option_read(map, "EnableCaustics", render.isCausticsEnabled); + option_read(map, "EnableShockwave", render.isShockwaveEnabled); + option_read(map, "EnableLighting", render.isLightingEnabled); + option_read(map, "EnableFilter", render.isFilterEnabled); + option_read(map, "EnablePixelation", render.isPixelationEnabled); + option_read(map, "EnableBloom", render.isBloomEnabled); + option_read(map, "EnableWaterSurface", render.isWaterSurfaceEnabled); + option_read(map, "EnableInterpolation", render.isInterpolationEnabled); + option_read(map, "EnableColorModifier", render.isColorModifierEnabled); render.isWaterOverlayEnabled = render.isWaterSurfaceEnabled; } diff --git a/src/game/options_config.h b/src/game/options_config.h index 6d336bb..7c88160 100644 --- a/src/game/options_config.h +++ b/src/game/options_config.h @@ -1,5 +1,6 @@ #pragma once +#include "engine/data.h" #include #include #include @@ -94,6 +95,7 @@ struct OptionsConfig AnnouncerVoiceMode announcerVoiceMode = ANNOUNCER_VOICE_MODE_RANDOM; CameraStyle cameraStyle = CAMERA_STYLE_ACTIVE_CAM_ON; ConsoleFont consoleFont = CONSOLE_FONT_DEFAULT; + DataFormat dataFormat = DATA_FORMAT_XML; ExtraHudStyle historyHudMode = EXTRA_HUD_STYLE_OFF; int eosCrossplay = 0; int jacobEsauControls = 1; @@ -202,6 +204,7 @@ template void options_visit(OptionsConfig& options, Visit visit visit("UseExclusiveFullscreen", options.isExclusiveFullscreen); visit("EnableEpicOverlay", options.isEpicOverlayEnabled); visit("EosCrossplay", options.eosCrossplay); + visit("DataFormat", options.dataFormat); } std::string options_path(); diff --git a/src/game/preload_manager.cpp b/src/game/preload_manager.cpp index 1797b7b..91a1c39 100644 --- a/src/game/preload_manager.cpp +++ b/src/game/preload_manager.cpp @@ -8,14 +8,6 @@ constexpr std::string_view ROOT_TAG = "preloads"; constexpr std::string_view GROUP_TAG = "preload"; -// An attribute when the element has it, empty or not. -static std::optional attr_find(DataNode node, std::string_view name) -{ - std::string_view value; - if (node["attrs"][name].get(value) != simdjson::SUCCESS) return std::nullopt; - return value; -} - // The first element of a document with a tag, as rapidxml's first_node finds it. static std::optional root_find(const Data& data, std::string_view tag) { @@ -46,12 +38,13 @@ bool PreloadManager::xml_load(std::string_view path) for (DataNode node : node_children(*root)) { isStarted = isStarted || node_tag(node) == GROUP_TAG; - std::optional id = attr_find(node, "id"); + std::optional id = node_attr_find(node, "id"); if (!isStarted || !id) continue; PreloadGroup& group = groups[std::string(*id)]; for (DataNode child : node_children(node)) - if (auto imagePath = attr_find(child, "path")) group.entries.push_back({std::string(*imagePath), nullptr}); + if (auto imagePath = node_attr_find(child, "path")) + group.entries.push_back({std::string(*imagePath), nullptr}); } return true; } diff --git a/src/game/string_table.cpp b/src/game/string_table.cpp index f07e1c9..badb7cc 100644 --- a/src/game/string_table.cpp +++ b/src/game/string_table.cpp @@ -24,7 +24,9 @@ static std::string text_lower(std::string_view text) // An attribute's text, or false when the element lacks it. static bool attr_find(DataNode node, std::string_view name, std::string_view& value) { - return node["attrs"][name].get(value) == simdjson::SUCCESS; + std::optional found = node_attr_find(node, name); + value = found.value_or(value); + return found.has_value(); } // The first child named tag, as rapidxml's first_node finds it, or false. diff --git a/src/level/backdrop.cpp b/src/level/backdrop.cpp index b95c061..1aada39 100644 --- a/src/level/backdrop.cpp +++ b/src/level/backdrop.cpp @@ -289,13 +289,9 @@ static BackdropConfig config_load(DataNode node, const BackdropConfig& base, std std::string_view gridRoot) { BackdropConfig config = base; - simdjson::dom::object attrs; - if (node["attrs"].get(attrs) != simdjson::SUCCESS) return config; - for (auto field : attrs) + for (auto [name, value] : node_attrs(node)) { - std::string_view name = field.key; - std::string_view value = node_attr(node, name); std::string sheet = std::string(gfxRoot) + std::string(value); if (name == "id") config.backdropId = attr_int(node, name); diff --git a/src/level/room_config.cpp b/src/level/room_config.cpp index 8481e2d..a8b7fa5 100644 --- a/src/level/room_config.cpp +++ b/src/level/room_config.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -109,7 +108,7 @@ constexpr SplitRule SPLIT_RULES[] = { // the game never checks. struct StbReader { - std::vector bytes; + std::string bytes; size_t position = 0; void read(void* destination, size_t size) @@ -152,14 +151,6 @@ static std::string localized_get(std::string_view category, std::string_view tex return std::string(isMissing ? text : localized); } -// An attribute's text, or nothing when the element lacks it. -static std::optional attr_find(DataNode node, std::string_view name) -{ - std::string_view text; - if (node["attrs"][name].get(text) != simdjson::SUCCESS) return std::nullopt; - return text; -} - // A loaded document's root element, as rapidxml's first_node(tag) finds it, or nothing. static std::optional root_find(Data& data, std::string_view tag) { @@ -192,9 +183,9 @@ static std::string doors_text(uint32_t doors) // Reads a whole file of the game's resources, or nothing when it is missing. static std::optional file_read(std::string_view path) { - std::ifstream stream(resource_path(path), std::ios::binary); - if (!stream) return std::nullopt; - return StbReader{std::vector(std::istreambuf_iterator(stream), {})}; + StbReader reader; + if (!resource_load(path, reader.bytes)) return std::nullopt; + return reader; } static bool is_stb_header_read(StbReader& reader) @@ -384,27 +375,27 @@ bool RoomConfig::LoadStages(std::string_view path) std::optional root = root_find(data, "stages"); if (!root) return false; - std::string roomsRoot(attr_find(*root, "root").value_or("rooms/")); - std::string greedRoot(attr_find(*root, "greedroot").value_or("rooms/greed/")); - std::string bossRoot(attr_find(*root, "bossgfxroot").value_or("")); + std::string roomsRoot(node_attr_find(*root, "root").value_or("rooms/")); + std::string greedRoot(node_attr_find(*root, "greedroot").value_or("rooms/greed/")); + std::string bossRoot(node_attr_find(*root, "bossgfxroot").value_or("")); int id = 0; for (DataNode node : elements_from(data, "stages", "stage")) { RoomConfig_Stage stage; - if (auto text = attr_find(node, "id")) id = std::atoi(text->data()); - if (auto text = attr_find(node, "name")) stage.displayName = *text; - if (auto text = attr_find(node, "path")) + if (auto text = node_attr_find(node, "id")) id = std::atoi(text->data()); + if (auto text = node_attr_find(node, "name")) stage.displayName = *text; + if (auto text = node_attr_find(node, "path")) { stage.rooms[ROOM_MODE_NORMAL].filePath = roomsRoot + std::string(*text); stage.rooms[ROOM_MODE_GREED].filePath = greedRoot + std::string(*text); } - if (auto text = attr_find(node, "playerspot")) stage.playerSpot = bossRoot + std::string(*text); - if (auto text = attr_find(node, "bossspot")) stage.bossSpot = bossRoot + std::string(*text); - if (auto text = attr_find(node, "music")) stage.musicId = std::atoi(text->data()); - if (auto text = attr_find(node, "backdrop")) stage.backdrop = std::atoi(text->data()); - if (auto text = attr_find(node, "suffix")) stage.suffix = *text; + if (auto text = node_attr_find(node, "playerspot")) stage.playerSpot = bossRoot + std::string(*text); + if (auto text = node_attr_find(node, "bossspot")) stage.bossSpot = bossRoot + std::string(*text); + if (auto text = node_attr_find(node, "music")) stage.musicId = std::atoi(text->data()); + if (auto text = node_attr_find(node, "backdrop")) stage.backdrop = std::atoi(text->data()); + if (auto text = node_attr_find(node, "suffix")) stage.suffix = *text; stage.id = id; if (id >= 0 && id < STAGE_SLOTS) stages[id] = std::move(stage); @@ -426,9 +417,9 @@ bool RoomConfig::LoadCurses(std::string_view path, CursesLoad load) for (DataNode node : elements_from(data, "curses", "curse")) { - std::string name(attr_find(node, "name").value_or("")); + std::string name(node_attr_find(node, "name").value_or("")); - if (auto text = attr_find(node, "id")) id = std::atoi(text->data()); + if (auto text = node_attr_find(node, "id")) id = std::atoi(text->data()); if (load == CURSES_APPEND) id = (int)curses.size(); if (load == CURSES_APPEND) curses.push_back({name, id}); else if (id >= 0 && id < (int)curses.size()) curses[id] = {name, id}; @@ -447,9 +438,9 @@ bool RoomConfig::LoadMinibosses(std::string_view path) for (DataNode node : elements_from(data, "minibosses", "miniboss")) { - std::string name(attr_find(node, "name").value_or("")); + std::string name(node_attr_find(node, "name").value_or("")); - if (auto text = attr_find(node, "id")) id = (uint32_t)std::atoi(text->data()); + if (auto text = node_attr_find(node, "id")) id = (uint32_t)std::atoi(text->data()); if (id < MINIBOSS_SLOTS) minibosses[id] = {name, (int)id}; } return true; @@ -503,94 +494,16 @@ void RoomConfig::ResetRoomWeights(int stageId, RoomMode mode) for (RoomConfig_Room& room : set.configs) room.weight = room.initialWeight; } -// An XML attribute value or name as JSON string text: its entities decoded, quotes, backslashes and controls escaped. -static std::string xml_value_json(std::string_view text) -{ - constexpr std::array, 5> ENTITIES = { - {{"<", '<'}, {">", '>'}, {"&", '&'}, {""", '"'}, {"'", '\''}}}; - std::string json = "\""; - - for (size_t i = 0; i < text.size(); i++) - { - char letter = text[i]; - for (auto [entity, decoded] : ENTITIES) - { - if (!text.substr(i).starts_with(entity)) continue; - letter = decoded; - i += entity.size() - 1; - break; - } - if (letter == '"' || letter == '\\') json += '\\'; - if ((unsigned char)letter < ' ') json += std::format("\\u{:04x}", (int)letter); - else json += letter; - } - return json + '"'; -} - -// An XML document as the import tool's JSON (tag, attrs and children, under #document), for a file nothing converted. -// Text, comments and declarations are left out, as no room file holds text. -static std::string xml_json_get(std::string_view text) -{ - constexpr std::string_view NAME_END = " \t\r\n/>"; - std::string json = "{\"tag\":\"#document\",\"attrs\":{},\"children\":["; - std::vector childCounts = {0}; - size_t pos = 0; - - while ((pos = text.find('<', pos)) != std::string_view::npos && pos + 1 < text.size()) - { - std::string_view rest = text.substr(pos); - size_t end = rest.starts_with("", pos) : text.find('>', pos); - if (rest[1] == '?' || rest[1] == '!' || end == std::string_view::npos) - { - pos = end; - continue; - } - if (rest[1] == '/') - { - if (childCounts.size() > 1) json += "]}"; - if (childCounts.size() > 1) childCounts.pop_back(); - pos = end; - continue; - } - - size_t nameEnd = text.find_first_of(NAME_END, pos + 1); - json += childCounts.back()++ ? "," : ""; - json += "{\"tag\":" + xml_value_json(text.substr(pos + 1, nameEnd - pos - 1)) + ",\"attrs\":{"; - pos = nameEnd; - for (bool isFirst = true;; isFirst = false) - { - pos = text.find_first_not_of(" \t\r\n", pos); - if (pos == std::string_view::npos || text[pos] == '/' || text[pos] == '>') break; - size_t equals = text.find('=', pos); - size_t open = text.find_first_of("\"'", equals); - size_t close = open == std::string_view::npos ? open : text.find(text[open], open + 1); - if (close == std::string_view::npos) break; - - std::string_view name = text.substr(pos, text.find_last_not_of(" \t\r\n=", equals) + 1 - pos); - json += (isFirst ? "" : ",") + xml_value_json(name) + ":" + - xml_value_json(text.substr(open + 1, close - open - 1)); - pos = close + 1; - } - json += "},\"children\":["; - pos = text.find('>', pos); - if (pos == std::string_view::npos) break; - if (text[pos - 1] == '/') json += "]}"; - else childCounts.push_back(0); - } - for (size_t open = childCounts.size(); open > 1; open--) json += "]}"; - return json + "]}"; -} - // An attribute as rapidxml handed it to atoi: its text, or empty when the element lacks it. static int attr_int(DataNode node, std::string_view name) { - return std::atoi(std::string(attr_find(node, name).value_or("")).c_str()); + return std::atoi(std::string(node_attr_find(node, name).value_or("")).c_str()); } // An attribute as atof read it, 0 when the element lacks it. static float attr_float(DataNode node, std::string_view name) { - return (float)std::atof(std::string(attr_find(node, name).value_or("")).c_str()); + return (float)std::atof(std::string(node_attr_find(node, name).value_or("")).c_str()); } // 00829af0 (RoomConfigRoom::ParseXml) Reads a room element: its attributes, then for a typed room the doors that @@ -603,13 +516,13 @@ static void room_parse(DataNode node, RoomConfig_Room& room) room.type = attr_int(node, "type"); room.variant = room.originalVariant = attr_int(node, "variant"); room.subtype = attr_int(node, "subtype"); - room.name = attr_find(node, "name").value_or(""); + room.name = node_attr_find(node, "name").value_or(""); room.difficulty = attr_int(node, "difficulty"); room.weight = room.initialWeight = attr_float(node, "weight"); room.flags = (uint32_t)attr_int(node, "flags"); - if (attr_find(node, "width")) room.width = (uint8_t)attr_int(node, "width"); - if (attr_find(node, "height")) room.height = (uint8_t)attr_int(node, "height"); - if (attr_find(node, "shape")) room.shape = (RoomShape)attr_int(node, "shape"); + if (node_attr_find(node, "width")) room.width = (uint8_t)attr_int(node, "width"); + if (node_attr_find(node, "height")) room.height = (uint8_t)attr_int(node, "height"); + if (node_attr_find(node, "shape")) room.shape = (RoomShape)attr_int(node, "shape"); if (room.type == 0) return; short doorX = 0; @@ -622,9 +535,9 @@ static void room_parse(DataNode node, RoomConfig_Room& room) std::string_view tag = node_tag(child); if (tag == "door") { - if (attr_find(child, "x")) doorX = (short)attr_int(child, "x"); - if (attr_find(child, "y")) doorY = (short)attr_int(child, "y"); - if (auto text = attr_find(child, "exists")) + if (node_attr_find(child, "x")) doorX = (short)attr_int(child, "x"); + if (node_attr_find(child, "y")) doorY = (short)attr_int(child, "y"); + if (auto text = node_attr_find(child, "exists")) isDoorExisting = *text == "true" || *text == "True" || attr_int(child, "exists") != 0; int slot = isDoorExisting ? RoomConfig::get_door_from_position(doorX, doorY, room.shape) : DOOR_NONE; @@ -638,11 +551,11 @@ static void room_parse(DataNode node, RoomConfig_Room& room) for (DataNode entity : node_children(child)) { if (node_tag(entity) != "entity") continue; - if (attr_find(entity, "type")) entry.type = (uint32_t)attr_int(entity, "type"); - if (attr_find(entity, "variant")) entry.variant = (uint16_t)attr_int(entity, "variant"); - if (attr_find(entity, "subtype")) entry.subtype = (uint16_t)attr_int(entity, "subtype"); - if (attr_find(entity, "weight")) entry.weight = attr_float(entity, "weight"); - if (attr_find(entity, "weight")) spawn.sumWeights += entry.weight; + if (node_attr_find(entity, "type")) entry.type = (uint32_t)attr_int(entity, "type"); + if (node_attr_find(entity, "variant")) entry.variant = (uint16_t)attr_int(entity, "variant"); + if (node_attr_find(entity, "subtype")) entry.subtype = (uint16_t)attr_int(entity, "subtype"); + if (node_attr_find(entity, "weight")) entry.weight = attr_float(entity, "weight"); + if (node_attr_find(entity, "weight")) spawn.sumWeights += entry.weight; int slot = RoomConfig::get_door_from_position(spawn.x, spawn.y, room.shape); bool isQuestDoor = entry.type == ENTITY_ENVIRONMENT && entry.variant == QUEST_DOOR_VARIANT; @@ -656,9 +569,9 @@ static void room_parse(DataNode node, RoomConfig_Room& room) { return a.y < b.y || (a.y == b.y && a.x < b.x); }); } -// 00829710 Reads the room element of a room file, for the --load-room start option: its converted JSON through the -// resources when the import tool converted it, else the XML file itself. An unreadable file gives an empty room, as -// does a file without a room element, where the original crashes. +// 00829710 Reads the room element of a room file, for the --load-room start option: a game path through the resources, +// else the file itself. An unreadable file gives an empty room, as does a file without a room element, where the +// original crashes. RoomConfig_Room RoomConfig::LoadRoomFromXmlFile(std::string_view path) { RoomConfig_Room room; @@ -668,13 +581,13 @@ RoomConfig_Room RoomConfig::LoadRoomFromXmlFile(std::string_view path) if (!data.isLoaded) { std::ifstream file{std::string(path), std::ios::binary}; - if (!file) + std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; + if (!file.is_open()) { log_printf(LOG_INFO, "[error] Could not open %s\n", std::string(path).c_str()); return room; } - std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; - data.isLoaded = data.parser.parse(xml_json_get(text)).get(data.root) == simdjson::SUCCESS; + data_parse(data, text); } std::optional root = root_find(data, "room"); diff --git a/src/lua/api_isaac.cpp b/src/lua/api_isaac.cpp index 7f7eee0..9a55004 100644 --- a/src/lua/api_isaac.cpp +++ b/src/lua/api_isaac.cpp @@ -302,14 +302,15 @@ static std::string module_path_find(std::string_view name, std::string& tried) std::string scriptPath = lua_engine_get().scriptPath; std::string local = scriptPath.substr(0, scriptPath.find_last_of(PATH_SEPARATORS)) + "/" + module; + std::string resource = resource_path(SCRIPTS_FOLDER + module); for (const std::string& path : { #ifdef ISAAC_REPENTOGON repentogon_script_path(module), #endif - resource_path(SCRIPTS_FOLDER + module), local, platform.modsDirectory + local}) + resource, local, platform.modsDirectory + local}) { std::error_code error; - if (std::filesystem::exists(path, error)) return path; + if (path == resource ? resource_exists(path) : std::filesystem::exists(path, error)) return path; tried += "\n\tno file '" + path + "'"; } return ""; @@ -329,7 +330,7 @@ static int module_require(lua_State* state) std::string tried; std::string path = module_path_find(name, tried); if (path.empty()) return luaL_error(state, "module '%s' not found:%s", name, tried.c_str()); - if (luaL_loadfile(state, path.c_str()) != LUA_OK) + if (lua_script_load(state, path) != LUA_OK) return luaL_error(state, "error loading module '%s' from file '%s':\n\t%s", name, path.c_str(), lua_tostring(state, -1)); @@ -355,7 +356,7 @@ static int module_include(lua_State* state) if (path.empty()) return 1; int top = lua_gettop(state); - if (luaL_loadfile(state, path.c_str()) != LUA_OK) return luaL_error(state, "%s", lua_tostring(state, -1)); + if (lua_script_load(state, path) != LUA_OK) return luaL_error(state, "%s", lua_tostring(state, -1)); lua_call(state, 0, LUA_MULTRET); return lua_gettop(state) - top; } diff --git a/src/lua/engine.cpp b/src/lua/engine.cpp index fcd2c19..30aac36 100644 --- a/src/lua/engine.cpp +++ b/src/lua/engine.cpp @@ -24,6 +24,7 @@ constexpr const char* SCRIPT_MODULES = "scripts/?.lua"; constexpr const char* SCRIPT_FOLDER_MODULES = "/?.lua;"; constexpr const char* UPDATE_MARKER = "/update.it"; constexpr const char* PATH_SEPARATORS = "/\\"; +constexpr std::string_view BYTE_ORDER_MARK = "\xef\xbb\xbf"; constexpr const char* RUN_CALLBACK = "_RunCallback"; constexpr const char* UNLOAD_MOD = "_UnloadMod"; @@ -208,6 +209,17 @@ void LuaEngine::destroy() state = nullptr; } +// Loads a script as luaL_loadfile does: a file of the resources through them, archived or not, any other from disk. +int lua_script_load(lua_State* state, const std::string& path) +{ + std::string bytes; + if (!path.starts_with(dataDirectory) || !resource_load(path, bytes)) return luaL_loadfile(state, path.c_str()); + + std::string_view chunk = bytes; + if (chunk.starts_with(BYTE_ORDER_MARK)) chunk.remove_prefix(BYTE_ORDER_MARK.size()); + return luaL_loadbuffer(state, chunk.data(), chunk.size(), ("@" + path).c_str()); +} + // 0086e6c0 Runs a script file, after unloading the mods it registered when it last ran. In debug mode require searches // the script's folder first. An error is logged, and a mod registered with an API version other than 1 gets an // update.it in its folder. After a run Lua collects its garbage and logs its memory. Whether the script ran. @@ -233,7 +245,7 @@ bool LuaEngine::RunScript(std::string_view path) } scriptPath = file; scriptApiVersion = API_VERSION_NONE; - bool isFailed = luaL_loadfile(state, file.c_str()) != LUA_OK || lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK; + bool isFailed = lua_script_load(state, file) != LUA_OK || lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK; if (mode == LUA_MODE_DEBUG) package_field_set(state, "path", modulesPath); if (!isFailed) diff --git a/src/lua/engine.h b/src/lua/engine.h index 246e21b..c73914a 100644 --- a/src/lua/engine.h +++ b/src/lua/engine.h @@ -251,6 +251,7 @@ extern void* g_luaEngine; const void* lua_class_key(LuaClass luaClass); void lua_error_log(lua_State* state, const char* name); +int lua_script_load(lua_State* state, const std::string& path); bool is_input_hook_asked(); // The game's Lua engine, which Manager creates at startup. diff --git a/src/ui/cutscene.cpp b/src/ui/cutscene.cpp index 33f120d..54681ee 100644 --- a/src/ui/cutscene.cpp +++ b/src/ui/cutscene.cpp @@ -12,7 +12,6 @@ #include "engine/texture_cache.h" #include #include -#include #include constexpr std::string_view ANM2_PART_TAG = "anm2part"; @@ -152,16 +151,12 @@ static uint32_t subtitle_time_get(std::string_view stamp) // four lines of text. A line ending the file is left out, as the game's reader reports the end before it. void CutscenePart::load_subtitles() { - std::ifstream file(resource_path(subtitlesPath), std::ios::binary); - std::stringstream contents; LineReader reader; subtitles.clear(); subtitleFrame = 0; subtitleIndex = 0; - if (!file) return; - contents << file.rdbuf(); - reader.text = contents.str(); + if (!resource_load(subtitlesPath, reader.text)) return; while (!reader.is_end()) { diff --git a/src/ui/menu/special_seeds.cpp b/src/ui/menu/special_seeds.cpp index c76b9d4..866a497 100644 --- a/src/ui/menu/special_seeds.cpp +++ b/src/ui/menu/special_seeds.cpp @@ -123,13 +123,6 @@ void Menu_SpecialSeeds::LoadGraphics() specialSeedsSprite.Load(SEEDS_MENU_ANM2, GRAPHICS_LOAD); } -// Whether a node has an attribute at all, even an empty one. -static bool node_has_attr(DataNode node, std::string_view name) -{ - std::string_view value; - return node["attrs"][name].get(value) == simdjson::SUCCESS; -} - // The first child of a node with a tag, or the node itself when there is none. static DataNode node_child_find(DataNode node, std::string_view tag) { @@ -170,7 +163,7 @@ void Menu_SpecialSeeds::entries_load() std::string implemented(node_attr(node, IMPLEMENTED_ATTR)); int id = std::atoi(std::string(node_attr(node, "id")).c_str()); bool isKnown = id >= 0 && id < SPECIAL_SEED_COUNT; - bool isImplemented = !node_has_attr(node, IMPLEMENTED_ATTR) || + bool isImplemented = !node_attr_find(node, IMPLEMENTED_ATTR) || std::ranges::count(IMPLEMENTED_TRUE, implemented) || std::atoi(implemented.c_str()); if (isImplemented && isKnown && data.specialSeeds[id]) diff --git a/src/ui/nightmare_scene.cpp b/src/ui/nightmare_scene.cpp index a85b046..fdd24a7 100644 --- a/src/ui/nightmare_scene.cpp +++ b/src/ui/nightmare_scene.cpp @@ -51,11 +51,6 @@ constexpr int STAGE_ICONS_PER_ALT_CHAPTER = 2; // The stage whose icon the void's slot shows again. constexpr int STAGE_VOID_SLOT = 10; -static bool is_attr_present(DataNode node, std::string_view name) -{ - return node["attrs"][name].error() == simdjson::SUCCESS; -} - // 0091fe80 Reads nightmares.xml, adding its nightmares to those known and shuffling their order, and loads the // progress bar and background unless loaded. Paths are under the root. False when the file is missing. bool NightmareScene::load_nightmares_xml(std::string_view path) @@ -67,11 +62,10 @@ bool NightmareScene::load_nightmares_xml(std::string_view path) std::string root(node_attr(data.root, "root")); std::string progressPath = root + std::string(node_attr(data.root, "progressAnm2")); - std::string backgroundPath = - root + std::string(is_attr_present(data.root, "backgroundAnm2") ? node_attr(data.root, "backgroundAnm2") - : BACKGROUND_DEFAULT); + std::string background(node_attr_find(data.root, "backgroundAnm2").value_or(BACKGROUND_DEFAULT)); + std::string backgroundPath = root + background; for (DataNode node : node_children(data.root)) - if (node_tag(node) == "nightmare" && is_attr_present(node, "anm2")) + if (node_tag(node) == "nightmare" && node_attr_find(node, "anm2")) nightmarePaths.push_back(root + std::string(node_attr(node, "anm2"))); if (!progressBarSprite.isLoaded) progressBarSprite.Load(progressPath, GRAPHICS_LOAD); diff --git a/src/ui/overlay/game_options.cpp b/src/ui/overlay/game_options.cpp index a6aebaf..6cd21db 100644 --- a/src/ui/overlay/game_options.cpp +++ b/src/ui/overlay/game_options.cpp @@ -104,6 +104,7 @@ constexpr OptionSpec OPTION_SPECS[] = { {"TryImportSave", "Import save", OPTIONS_TAB_SYSTEM}, {"AcceptedPublicBeta_v1.9.7.17", "Public beta accepted", OPTIONS_TAB_SYSTEM}, {"AcceptedDataCollectionDisclaimer", "Data collection accepted", OPTIONS_TAB_SYSTEM}, + {"DataFormat", "Data format", OPTIONS_TAB_SYSTEM, 0, 2, "Auto\0JSON\0XML\0"}, #ifdef ISAAC_REPENTOGON {"VanillaParity", "Vanilla parity", OPTIONS_TAB_REPENTOGON}, {"SyncVanillaOptions", "Sync vanilla options", OPTIONS_TAB_REPENTOGON}, diff --git a/src/ui/overlay/mods.cpp b/src/ui/overlay/mods.cpp index f3d0a01..2a93b28 100644 --- a/src/ui/overlay/mods.cpp +++ b/src/ui/overlay/mods.cpp @@ -27,10 +27,9 @@ unsigned int Overlay::thumbnail_get(ModEntry& mod) unsigned int texture = 0; int bound = 0; - int channels = 0; int height = 0; int width = 0; - if (stbi_uc* pixels = stbi_load(path.c_str(), &width, &height, &channels, STBI_rgb_alpha)) + if (uint8_t* pixels = KAGE::Graphics::texels_load(path, width, height)) { gl.GetIntegerv(GL_TEXTURE_BINDING_2D, &bound); gl.GenTextures(1, &texture);