From a319517a5b0572d42216a99a6062b7e4a26071f9 Mon Sep 17 00:00:00 2001 From: shweet Date: Wed, 25 Nov 2026 19:34:24 -0500 Subject: [PATCH] Mod options on the overlay: Mod Config Menu and Dead Sea Scrolls settings as native widgets in Game Options' Mods tab; GPL-2 LICENSE; README trimmed to a short overview of the differences from Repentance+, its behaviour and libraries; REPENTOGON's reference checkout gitignored --- .gitignore | 2 + LICENSE | 117 +++++++++++ README.md | 146 +++++-------- src/overlay/game_options.cpp | 49 ++--- src/overlay/mod_options.cpp | 388 +++++++++++++++++++++++++++++++++++ src/overlay/overlay.cpp | 5 +- src/overlay/overlay.h | 61 ++++++ 7 files changed, 633 insertions(+), 135 deletions(-) create mode 100644 LICENSE create mode 100644 src/overlay/mod_options.cpp diff --git a/.gitignore b/.gitignore index 11854b2..0acb985 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ /resources/ # mods the game loads, linked beside the executable /mods/ +# REPENTOGON's source, a separate checkout read for reference +/repentogon/ # builds, editor index, local tools and test runs /build*/ /.cache/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..17cb286 --- /dev/null +++ b/LICENSE @@ -0,0 +1,117 @@ +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + + c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author + + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. + +signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice diff --git a/README.md b/README.md index 822f5ed..5c19def 100644 --- a/README.md +++ b/README.md @@ -1,106 +1,58 @@ -# Repentance+ rebuilt +# Isaac: Repentance+ port -A native 64-bit Linux build of The Binding of Isaac: Repentance+ (v1.9.7.17), reconstructed as C++ from the -original executable, with REPENTOGON's modding API built in. +A native 64-bit Linux build of The Binding of Isaac: Repentance+ (v1.9.7.17), reconstructed as C++ from the original executable. -**Private.** This repo holds decompiled game code. It is a local git repo with no remote: never push it, publish -it, or paste large parts of it anywhere public. Nothing from the game ships here: the game reads the player's own -install, which it never modifies. +## Differences from Repentance+ + +- Native Linux, no Proton or Wine. +- [REPENTOGON](https://repentogon.com/)'s modding API is built in. Without REPENTOGON mods, the game plays as vanilla. +- A developer overlay (` key) replaces the console, built on Dear ImGui. It has these windows: + - Console: the game's and REPENTOGON's commands, plus extra ones (`give`, `room`, `boss`, `character`, `nextstage`, `clearroom` and others). + - Game Options: every option in one place, REPENTOGON's included. Its Mods tab shows Mod Config Menu and Dead Sea Scrolls settings as native widgets. + - Mods: turns mods on and off. + - Debug and Log. +- Online features (Steam, online co-op, leaderboards, daily uploads) are offline stubs. +- Saves, mods and options live in a per-user folder, or wherever `SaveDirectory` in options.ini points. Steam Cloud is not used. +- A test harness: headless runs, input recording and replay, and state traces. + +### Behaviour + +By default the game behaves exactly like the original. REPENTOGON's changes to vanilla behaviour (its bug fixes, Vanilla Tweaks options and callback reordering) only apply once the `VanillaParity` switch is turned off, either in the overlay's REPENTOGON tab or in `Repentogon/options.ini`. + +### Libraries + +The original's Windows platform layer is replaced by: + +- SDL3: window, OpenGL context, input and audio. +- Lua 5.3: mods. It is POSIX-built, with no native modules. +- pugixml: the install's XML and `.anm2` files, and mods' XML. +- rapidjson: REPENTOGON's JSON save files. +- Ogg, Vorbis and Theora: cutscene videos, decoders only. +- Dear ImGui (docking branch): the overlay. +- stb: images and Vorbis sound. + +## Clarification + +This application was developed with the assistance of a large language model. + +No game files ship here. The game reads your own install's `resources/` folder as it is, and never modifies it. + +## Build + +After cloning and entering the repository's directory, make sure to initialize the submodules: + +```git submodule update --init --recursive``` + +Every library is built statically from the submodules. ``` -src/ the game (see Source layout) -assets/ files the repository ships itself: the overlay's fonts (git-lfs), with their licences, and REPENTOGON's Lua - scripts and the resources its menus load (assets/repentogon/, GPL-2, searched after every mount) -external/ static submodules: SDL3, Lua 5.3, pugixml, rapidjson, Ogg, Vorbis, Theora, stb, Dear ImGui (docking) -tools/ gitignored local tools: the resource importer and the test harness (tools/harness/) -``` - -## Building and running - -```sh -git submodule update --init --recursive -cmake -B build -G Ninja -DISAAC_RESOURCES="/resources" && cmake --build build +cmake -B build -G Ninja -DISAAC_RESOURCES="/resources" +cmake --build build build/linux/isaac ``` -The game builds into `build//`, which holds only the executable and links to the folders it reads beside -it: `resources` (`ISAAC_RESOURCES`, the import tool's `resources/` by default), `mods` (the repository's gitignored -`mods/`) and `assets`. It runs from any folder. `--resources DIR` and `--mods DIR` replace either one for a run. -Saves (save files, their backups, mod save data and REPENTOGON's per-save files) go to options.ini's `SaveDirectory`, -or SDL's per-user folder when it is empty, and `--saves DIR` replaces it for a run. `--options FILE` reads and writes -another options.ini, with REPENTOGON's options beside it. Logs and configs stay in the per-user folder. +`--resources DIR`, `--mods DIR`, `--saves DIR` and `--options FILE` override those locations for a run. -The build uses ccache and mold when they are installed and precompiles the standard headers and `classes.h`. -`-DISAAC_UNITY=ON` builds the game in unity batches, for faster clean builds and slower incremental ones. +## License -SDL3 (window, OpenGL context, input, audio) and Lua 5.3 (mods) are built statically, with pugixml for data, -rapidjson for REPENTOGON's own save files and Xiph's Ogg, Vorbis and Theora (decoders only) for the cutscene -videos. Online features (Steam, EOS, curl) are offline stubs. - -The game reads the player's own install as it is: its `resources/` folder 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. 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. Loaders read it through one node API -(`src/engine/data.h`) over pugixml's tree. The import tool in `tools/` (gitignored) still unpacks an install into -`resources/` and its mods into `mods/`, every file as it is. - -## Source layout - -`src/` is sorted by subsystem. A file drops its folder's prefix and includes others by path from `src/` -(`#include "entity/boss/mom.h"`); CMake builds every `.cpp` under it. - -``` -engine/ platform (SDL3 window, frame pacing, clock), gl, kage_* (graphics, input, sound), anm2, textures, - 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, - stage transition, Greed - grid/ grid entities (level/grid/rock, level/grid/door ...) -entity/ Entity and its list, factory, config, collision, combat - player/ Entity_Player split by concern (player/actives, player/cards, player/update ...), PlayerManager - npc/ Entity_NPC and every enemy AI (npc/gaper, npc/hopper ...) - boss/ every boss (boss/mom, boss/delirium ...) - familiar/ Entity_Familiar and familiar behaviour - effect/ Entity_Effect variants - pickup/ pickups, slots, item config, item pools, procedural items - weapon/ weapons, tears, lasers, knives, bombs, projectiles -ui/ HUDs, popups, pause screen, cutscenes, console - menu/ every menu screen (ui/menu/character, ui/menu/mods ...) -overlay/ the developer overlay (CMake option ISAAC_OVERLAY, on by default): ` shows it in place of the console, - with the Console, Game Options, Mods, Debug and Log windows on Dear ImGui -lua/ the Lua engine, API bindings and callbacks -online/ online-only code, kept as offline stubs -repentogon/ REPENTOGON's modding API built in (CMake option ISAAC_REPENTOGON, on by default, OFF builds the vanilla - game): its scripts' loading, its options store and the vanilla parity switch, inert without mods -generated/ frozen decompiler output: classes.h declares every original class, global and function, and - stubs.cpp stops the game at any original function src/ does not define -``` - -## Test harness - -Flags on the game binary (`src/engine/harness.cpp`), deterministic: the same input file always gives the same run. -The first three leave the developer overlay out, so the console behaves as the original's. - -``` ---headless no window, GL context or audio, no frame pacing (about 7,900 frames per second) ---record F / --replay F per-frame input from boot, so menu navigation is included ---frames N quit after N frames ---trace F [--trace-every N] [--trace-detail] hashes (or the fields) of the RNGs, players and entities ---mods DIR a private mods folder ---screenshot-every N a windowed run saves every Nth frame (as Isaac.GetFrameCount() counts) to screenshots/ -``` - -`tools/harness/run.sh SAVE WORK [flags]` runs on a fresh copy of a save folder with a private `XDG_DATA_HOME`; -`tools/harness/menu.py` writes the boot-to-run menu input; `tools/harness/compare.py A B` prints the first frame -and field where two traces differ; `tools/harness/bot/` is a Lua mod that plays through `MC_INPUT_ACTION`. -`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` points them at an install (the Steam install by default). -Traces follow the compiler's float code, so check with a clang build, as the goldens were recorded. +The code is under [GPL-2](LICENSE). The fonts in `assets/` and the libraries in `external/` are each under their own license. diff --git a/src/overlay/game_options.cpp b/src/overlay/game_options.cpp index 1031e3f..f7b8d53 100644 --- a/src/overlay/game_options.cpp +++ b/src/overlay/game_options.cpp @@ -17,42 +17,12 @@ constexpr float WIDGET_FONT_SIZES = 14; // A widget's width beside its label, in constexpr int KEY_COLUMNS = 3; constexpr ImVec4 UNBOUND_COLOR = {0.8f, 0.2f, 0.2f, 1}; // The key config menu's red for an action with no key. -// The window's tabs, Controls last. -enum OptionsTab -{ - OPTIONS_TAB_AUDIO, - OPTIONS_TAB_VIDEO, - OPTIONS_TAB_HUD, - OPTIONS_TAB_GAMEPLAY, - OPTIONS_TAB_CONSOLE, - OPTIONS_TAB_ONLINE, - OPTIONS_TAB_SYSTEM, -#ifdef ISAAC_REPENTOGON - OPTIONS_TAB_REPENTOGON, -#endif - OPTIONS_TAB_COUNT -}; - constexpr const char* OPTIONS_TAB_NAMES[OPTIONS_TAB_COUNT] = {"Audio", "Video", "HUD", "Gameplay", "Console", "Online", "System", #ifdef ISAAC_REPENTOGON - "REPENTOGON" + "REPENTOGON", #endif -}; - -// Where a setting sits: its tab, label and tooltip, the range of a number (a slider when it has one, else typed), and -// for a choice its labels, each standing for min plus its index. Each tab lists checkboxes, choices, sliders, then -// typed numbers. -struct OptionSpec -{ - std::string_view key; - const char* label; - const char* tooltip; - OptionsTab tab; - float min = 0; - float max = 0; - const char* choices = nullptr; -}; + "Mods"}; constexpr OptionSpec OPTION_SPECS[] = { {"AscentVoiceOver", "Ascent Voice Over", "**Plays the narration on each floor of the Ascent.", OPTIONS_TAB_AUDIO}, @@ -221,11 +191,12 @@ static void option_apply(std::string_view key) // A setting's widget by its type: a checkbox, a slider within its range, a choice's combo, or a typed number that // applies on Enter. Whether it changed. -template static bool is_option_edited(const OptionSpec& spec, T& value) +template bool is_option_edited(const OptionSpec& spec, T& value) { if constexpr (std::is_same_v) return ImGui::Checkbox(spec.label, &value); else if constexpr (std::is_same_v) - return ImGui::SliderFloat(spec.label, &value, spec.min, spec.max, "%.2f", ImGuiSliderFlags_AlwaysClamp); + return ImGui::SliderFloat(spec.label, &value, spec.min, spec.max, spec.format ? spec.format : "%.2f", + ImGuiSliderFlags_AlwaysClamp); else { int number = (int)value; @@ -238,14 +209,18 @@ template static bool is_option_edited(const OptionSpec& spec, T& va number = index + (int)spec.min; } else if (spec.max > spec.min) - isEdited = ImGui::SliderInt(spec.label, &number, (int)spec.min, (int)spec.max, "%d", - ImGuiSliderFlags_AlwaysClamp); + isEdited = ImGui::SliderInt(spec.label, &number, (int)spec.min, (int)spec.max, + spec.format ? spec.format : "%d", ImGuiSliderFlags_AlwaysClamp); else isEdited = ImGui::InputInt(spec.label, &number, 1, 1, ImGuiInputTextFlags_EnterReturnsTrue); if (isEdited) value = (T)number; return isEdited; } } +template bool is_option_edited(const OptionSpec& spec, bool& value); +template bool is_option_edited(const OptionSpec& spec, float& value); +template bool is_option_edited(const OptionSpec& spec, int& value); + // Every setting options.ini holds, a tab each by subject, REPENTOGON's own options in theirs, then the key bindings. // A change applies at once and is saved as the game saves it, once no widget is held. void Overlay::options_render() @@ -264,6 +239,7 @@ void Overlay::options_render() } if (tab == OPTIONS_TAB_CONSOLE) ImGui::TextDisabled("**The overlay's console works whatever these say. They drive the original's."); + if (tab == OPTIONS_TAB_MODS) mod_options_render(); for (const OptionSpec& spec : OPTION_SPECS) { @@ -300,6 +276,7 @@ void Overlay::options_render() ImGui::EndTabBar(); if (!isOptionsSavePending || ImGui::IsAnyItemActive()) return; + mod_options_save(); config.Save(); #ifdef ISAAC_REPENTOGON repentogonOptions.save(); diff --git a/src/overlay/mod_options.cpp b/src/overlay/mod_options.cpp new file mode 100644 index 0000000..65de303 --- /dev/null +++ b/src/overlay/mod_options.cpp @@ -0,0 +1,388 @@ +#include "overlay/overlay.h" +#include "engine/kage_input.h" +#include "lua/api.h" +#include "lua/engine.h" +#include +#include +#include + +constexpr const char* ADAPTER_NAME = "=mod options"; +constexpr const char* WAITING_LABELS[] = {"Press a key", "Press a button"}; +constexpr ImVec4 ERROR_COLOR = {0.8f, 0.2f, 0.2f, 1}; + +// Flattens Mod Config Menu's MenuData and Dead Sea Scrolls' Menus into rows of one shape, read live each frame. +// A row has a kind (ModOptionKind's order), label, tooltip and value, a range, a format or choices for some, and a +// setter that changes the setting as that menu would. A broken option becomes an error row. +constexpr char ADAPTER[] = R"lua( +local TEXT, TITLE, SPACE, BOOL, INT, FLOAT, CHOICE, KEY, BUTTON, TREE, TREE_END, ERROR = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 +local MCM_KINDS = {TEXT, SPACE, INT, BOOL, INT, KEY, BUTTON, TITLE} +local MCM_SCROLL = 3 +local MCM_NUMBER = 5 +local SCROLL_MAX = 10 +local DSS_CORE = "Menu" +local DSS_MAIN = "main" + +local adapter = {} +local dirty = {} +local keyNames = nil +local last = {} +local loaded = {} + +local function text(value) + if type(value) == "function" then value = value() end + if type(value) == "table" then value = table.concat(value.strset or (value.str and {value.str}) or value, " ") end + return value == nil and "" or tostring(value) +end + +local function escaped(label) + return (label:gsub("%%", "%%%%")) +end + +local function key_name(key) + if not keyNames then + keyNames = {} + for name, value in pairs(Keyboard or {}) do keyNames[value] = (name:gsub("^KEY_", ""):gsub("_", " ")) end + end + return keyNames[key] or "none" +end + +local function ranged(row, min, max, step) + local set = row.set + row.kind = step % 1 == 0 and INT or FLOAT + row.min, row.max = min, max + row.set = function(value) set(min + math.floor((value - min) / step + 0.5) * step) end +end + +local function row_add(rows, build, ...) + local isBuilt, row = pcall(build, ...) + if not isBuilt then row = {kind = ERROR, label = tostring(row)} end + rows[#rows + 1] = row +end + +local function mcm_row(option) + local value = option.CurrentSetting + if type(value) == "function" then value = value() end + + local label = (text(option.Display):gsub("%s*%$scroll%d*", "")) + local isScroll = option.Type == MCM_SCROLL + local row = {kind = MCM_KINDS[option.Type] or TEXT, label = label, tooltip = text(option.Info), value = value} + row.set = option.OnChange + + if isScroll or (option.Type == MCM_NUMBER and option.Minimum and option.Maximum) then + ranged(row, isScroll and 0 or option.Minimum, isScroll and SCROLL_MAX or option.Maximum, + isScroll and 1 or option.ModifyBy or 1) + row.label, row.format = "", escaped(label) + end + return row +end + +local function mcm_rows(menu, rows) + local isTree = #menu.Subcategories > 1 + for _, subcategory in ipairs(menu.Subcategories) do + if isTree then rows[#rows + 1] = {kind = TREE, label = text(subcategory.Name), tooltip = text(subcategory.Info)} end + for _, option in ipairs(subcategory.Options) do row_add(rows, mcm_row, option) end + if isTree then rows[#rows + 1] = {kind = TREE_END} end + end +end + +local function dss_row(menu, item, button) + if button.display == false or (button.displayif and not button.displayif(button, item, menu)) then return end + + local label = text(button.str or button.strset) + local row = {kind = TEXT, label = label, tooltip = text(button.tooltip), value = button.setting} + row.set = function(value) + button.setting = value + if button.variable then + menu.DirectoryKey.Settings[button.variable] = value + menu.DirectoryKey.SettingsChanged = true + end + if button.changefunc then button.changefunc(button, item) end + dirty[menu] = true + end + + if button.choices then + local choices = {} + for index, choice in ipairs(button.choices) do choices[index] = text(choice) end + row.kind, row.min, row.value, row.choices = CHOICE, 1, button.setting or 1, table.concat(choices, "\0") .. "\0" + elseif button.max then + ranged(row, button.min or 0, button.max, button.increment or 1) + row.value = button.setting or row.min + row.format = escaped(text(button.pref)) .. (row.kind == INT and "%d" or "%.2f") .. escaped(text(button.suffix)) + elseif button.keybind then + row.kind, row.label = KEY, label .. ": " .. key_name(button.setting) + elseif button.dest then + return {kind = TREE, label = label, tooltip = row.tooltip, dest = button.dest} + elseif button.func or button.action then + return nil + end + return row +end + +local function dss_page(menu, key, rows, visited) + local item = menu.Directory[key] + if type(item) ~= "table" or visited[key] then return end + + visited[key] = true + for _, button in ipairs(item.buttons or {}) do + local count = #rows + row_add(rows, dss_row, menu, item, button) + if #rows > count and rows[#rows].kind == TREE then + dss_page(menu, rows[#rows].dest, rows, visited) + if #rows == count + 1 then rows[#rows] = nil else rows[#rows + 1] = {kind = TREE_END} end + end + end +end + +local function dss_load(menu) + for _, item in pairs(menu.Directory) do + for _, button in ipairs(type(item) == "table" and item.buttons or {}) do + if button.load then + button.setting = button.load(button, item, menu) + if button.variable then menu.DirectoryKey.Settings[button.variable] = button.setting end + end + end + end +end + +function adapter.menus() + local names = {} + local seen = {} + for _, menu in ipairs(ModConfigMenu and ModConfigMenu.MenuData or {}) do + if not seen[menu.Name] then names[#names + 1], seen[menu.Name] = menu.Name, true end + end + for name in pairs(DeadSeaScrollsMenu and DeadSeaScrollsMenu.Menus or {}) do + if name ~= DSS_CORE and not seen[name] then names[#names + 1], seen[name] = name, true end + end + table.sort(names, function(a, b) return tostring(a):lower() < tostring(b):lower() end) + return names +end + +function adapter.rows(name) + local rows = {} + for _, menu in ipairs(ModConfigMenu and ModConfigMenu.MenuData or {}) do + if menu.Name == name then row_add(rows, mcm_rows, menu, rows) end + end + + local menu = name ~= DSS_CORE and DeadSeaScrollsMenu and DeadSeaScrollsMenu.Menus[name] + if menu then + if not loaded[menu] then + loaded[menu] = true + row_add(rows, dss_load, menu) + end + row_add(rows, dss_page, menu, DSS_MAIN, rows, {}) + end + last[name] = rows + return rows +end + +function adapter.set(name, index, value) + local row = last[name] and last[name][index] + if row and row.set then row.set(value) end +end + +function adapter.save() + local menus = dirty + dirty = {} + for menu in pairs(menus) do + if DeadSeaScrollsMenu.OpenedMenu ~= menu and menu.Close then menu.Close(menu) end + end +end + +return adapter +)lua"; + +static char adapterKey; // The registry key of a Lua state's adapter. + +// Calls a function of the adapter on the arguments atop the stack, compiling the adapter into the registry on a Lua +// state's first use. Whether it ran, leaving its results. A failure is logged. +static bool is_adapter_called(lua_State* state, const char* function, int arguments, int results) +{ + if (lua_rawgetp(state, LUA_REGISTRYINDEX, &adapterKey) == LUA_TNIL) + { + lua_pop(state, 1); + if (luaL_loadbuffer(state, ADAPTER, sizeof(ADAPTER) - 1, ADAPTER_NAME) != LUA_OK || + lua_pcall(state, 0, 1, 0) != LUA_OK) + { + lua_error_log(state, ADAPTER_NAME); + lua_pop(state, arguments); + return false; + } + lua_pushvalue(state, -1); + lua_rawsetp(state, LUA_REGISTRYINDEX, &adapterKey); + } + + lua_getfield(state, -1, function); + lua_replace(state, -2); + lua_insert(state, -1 - arguments); + if (lua_pcall(state, arguments, results, 0) == LUA_OK) return true; + lua_error_log(state, function); + return false; +} + +// The running Lua state, null while there is none. +static lua_State* state_get() +{ + return g_luaEngine ? lua_engine_get().state : nullptr; +} + +// A string field of the row atop the stack, null when absent. It lives as long as the row. +static const char* row_string_get(lua_State* state, const char* field) +{ + lua_getfield(state, -1, field); + const char* text = lua_type(state, -1) == LUA_TSTRING ? lua_tostring(state, -1) : nullptr; + lua_pop(state, 1); + return text; +} + +// A number field of the row atop the stack, 0 when absent. +static float row_number_get(lua_State* state, const char* field) +{ + lua_getfield(state, -1, field); + float number = (float)lua_tonumber(state, -1); + lua_pop(state, 1); + return number; +} + +// Sets a row of a mod's menu as that menu would. +template static void mod_option_set(lua_State* state, const char* menu, int index, T value) +{ + lua_pushstring(state, menu); + lua_pushinteger(state, index); + if constexpr (std::is_same_v) lua_pushboolean(state, value); + else if constexpr (std::is_integral_v) lua_pushinteger(state, value); + else lua_pushnumber(state, value); + is_adapter_called(state, "set", 3, 0); +} + +// The row atop the stack's widget for its value, setting the value it is changed to. Whether it changed. +template +static bool is_mod_option_edited(lua_State* state, const OptionSpec& spec, const char* menu, int index) +{ + T value; + lua_getfield(state, -1, "value"); + if constexpr (std::is_same_v) value = lua_toboolean(state, -1); + else value = (T)lua_tonumber(state, -1); + lua_pop(state, 1); + + if (!is_option_edited(spec, value)) return false; + mod_option_set(state, menu, index, value); + return true; +} + +// Saves the Dead Sea Scrolls menus a row changed, as closing them does. Mod Config Menu's settings save as they change. +void mod_options_save() +{ + if (lua_State* state = state_get()) is_adapter_called(state, "save", 0, 0); +} + +// Each mod's Mod Config Menu and Dead Sea Scrolls settings under a header of its own, read from those menus as they +// are now. +void Overlay::mod_options_render() +{ + lua_State* state = state_get(); + if (!state || !is_adapter_called(state, "menus", 0, 1)) return; + + int count = (int)luaL_len(state, -1); + if (!count) + ImGui::TextDisabled("**No mod has Mod Config Menu or Dead Sea Scrolls settings. Mods that use Mod Config Menu " + "need it on."); + for (int menu = 1; menu <= count; menu++) + { + lua_geti(state, -1, menu); + const char* name = lua_tostring(state, -1); + if (name && ImGui::CollapsingHeader(name)) mod_rows_render(state, name); + lua_pop(state, 1); + } + lua_pop(state, 1); +} + +// A mod's rows, each tree's rows hidden while it is closed. +void Overlay::mod_rows_render(lua_State* state, const char* menu) +{ + lua_pushstring(state, menu); + if (!is_adapter_called(state, "rows", 1, 1)) return; + + int closedDepth = 0; + int count = (int)luaL_len(state, -1); + ImGui::PushID(menu); + for (int index = 1; index <= count; index++) + { + lua_geti(state, -1, index); + ModOptionKind kind = (ModOptionKind)row_number_get(state, "kind"); + + if (closedDepth) closedDepth += (kind == MOD_OPTION_TREE) - (kind == MOD_OPTION_TREE_END); + else if (kind == MOD_OPTION_TREE) + closedDepth = !ImGui::TreeNode((void*)(intptr_t)index, "%s", row_string_get(state, "label")); + else if (kind == MOD_OPTION_TREE_END) ImGui::TreePop(); + else mod_row_render(state, menu, index, kind); + lua_pop(state, 1); + } + ImGui::PopID(); + lua_pop(state, 1); +} + +// The row atop the stack as its kind's widget: text, a checkbox, a slider, typed number or choice, or a button that +// waits for the key or gamepad button to bind. A change saves once no widget is held. +void Overlay::mod_row_render(lua_State* state, const char* menu, int index, ModOptionKind kind) +{ + const char* label = row_string_get(state, "label"); + const char* tooltip = row_string_get(state, "tooltip"); + OptionSpec spec = {"", + label ? label : "", + tooltip, + OPTIONS_TAB_MODS, + row_number_get(state, "min"), + row_number_get(state, "max"), + row_string_get(state, "choices"), + row_string_get(state, "format")}; + bool isEdited = false; + bool isWaiting = modBindingIndex == index && modBindingMenu == menu; + + ImGui::PushID(index); + switch (kind) + { + case MOD_OPTION_TITLE: ImGui::SeparatorText(spec.label); break; + case MOD_OPTION_SPACE: ImGui::Spacing(); break; + case MOD_OPTION_ERROR: ImGui::TextColored(ERROR_COLOR, "%s", spec.label); break; + case MOD_OPTION_BOOL: isEdited = is_mod_option_edited(state, spec, menu, index); break; + case MOD_OPTION_INT: + case MOD_OPTION_CHOICE: isEdited = is_mod_option_edited(state, spec, menu, index); break; + case MOD_OPTION_FLOAT: isEdited = is_mod_option_edited(state, spec, menu, index); break; + case MOD_OPTION_KEY: + case MOD_OPTION_BUTTON: + if (ImGui::Button(isWaiting ? WAITING_LABELS[kind == MOD_OPTION_BUTTON] : spec.label)) + { + modBindingIndex = index; + modBindingKind = kind; + modBindingMenu = menu; + } + break; + default: ImGui::TextWrapped("%s", spec.label); + } + if (tooltip && *tooltip) ImGui::SetItemTooltip("%s", tooltip); + ImGui::PopID(); + isOptionsSavePending |= isEdited; +} + +// A mod's keybind waiting for its key takes the next key press, or gamepad button press for a controller bind. +// Escape leaves it as it was. Whether the event went to it. +bool Overlay::is_mod_binding_taken(const SDL_Event& event) +{ + bool isButton = event.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN; + bool isKey = event.type == SDL_EVENT_KEY_DOWN; + lua_State* state = state_get(); + int button = KAGE::Input::BUTTON_NONE; + + if (isKey && modBindingKind == MOD_OPTION_KEY) button = KAGE::Input::key_from_scancode(event.key.scancode); + if (isButton && modBindingKind == MOD_OPTION_BUTTON) + button = KAGE::Input::button_from_gamepad((SDL_GamepadButton)event.gbutton.button); + + if (!state || (isKey && event.key.scancode == SDL_SCANCODE_ESCAPE)) modBindingIndex = -1; + else if (button != KAGE::Input::BUTTON_NONE) + { + mod_option_set(state, modBindingMenu.c_str(), modBindingIndex, button); + isOptionsSavePending = true; + modBindingIndex = -1; + } + return isKey || isButton; +} diff --git a/src/overlay/overlay.cpp b/src/overlay/overlay.cpp index 2aab49c..085bece 100644 --- a/src/overlay/overlay.cpp +++ b/src/overlay/overlay.cpp @@ -146,13 +146,14 @@ bool Overlay::is_event_captured(const SDL_Event& event) if (!isReady) return false; bool isToggle = event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_GRAVE && !event.key.repeat; - if (isToggle && bindingAction < 0) + if (isToggle && bindingAction < 0 && modBindingIndex < 0) { visible_set(!isVisible); return true; } if (!isVisible) return false; if (bindingAction >= 0 && is_binding_taken(event)) return true; + if (modBindingIndex >= 0 && is_mod_binding_taken(event)) return true; // The toggle key's own text never reaches the input. bool isToggleText = event.type == SDL_EVENT_TEXT_INPUT && std::string_view(event.text.text) == "`"; @@ -175,7 +176,7 @@ void Overlay::visible_set(bool isShown) } SDL_StopTextInput(platform.window); - bindingAction = -1; + bindingAction = modBindingIndex = -1; ImGui::GetIO().ClearEventsQueue(); ImGui::GetIO().ClearInputKeys(); } diff --git a/src/overlay/overlay.h b/src/overlay/overlay.h index 445142d..270104b 100644 --- a/src/overlay/overlay.h +++ b/src/overlay/overlay.h @@ -3,10 +3,12 @@ #include #include #include +#include #include struct ImGuiInputTextCallbackData; struct ModEntry; +struct lua_State; // The overlay's windows, docked together as tabs and each shown or hidden from the Tools menu. enum OverlayWindow @@ -26,6 +28,56 @@ enum ModsView : int MODS_VIEW_COMPACT }; +// The Game Options window's tabs, Controls last. +enum OptionsTab +{ + OPTIONS_TAB_AUDIO, + OPTIONS_TAB_VIDEO, + OPTIONS_TAB_HUD, + OPTIONS_TAB_GAMEPLAY, + OPTIONS_TAB_CONSOLE, + OPTIONS_TAB_ONLINE, + OPTIONS_TAB_SYSTEM, +#ifdef ISAAC_REPENTOGON + OPTIONS_TAB_REPENTOGON, +#endif + OPTIONS_TAB_MODS, + OPTIONS_TAB_COUNT +}; + +// The rows mod_options.cpp's adapter flattens Mod Config Menu's and Dead Sea Scrolls' settings into, in the adapter's +// order. KEY binds a keyboard key and BUTTON a gamepad button. +enum ModOptionKind +{ + MOD_OPTION_TEXT, + MOD_OPTION_TITLE, + MOD_OPTION_SPACE, + MOD_OPTION_BOOL, + MOD_OPTION_INT, + MOD_OPTION_FLOAT, + MOD_OPTION_CHOICE, + MOD_OPTION_KEY, + MOD_OPTION_BUTTON, + MOD_OPTION_TREE, + MOD_OPTION_TREE_END, + MOD_OPTION_ERROR +}; + +// Where a setting sits: its tab, label and tooltip, the range of a number (a slider when it has one, else typed), for a +// choice its labels, each standing for min plus its index, and the slider's text when not the plain number. Each tab +// lists checkboxes, choices, sliders, then typed numbers. +struct OptionSpec +{ + std::string_view key; + const char* label; + const char* tooltip; + OptionsTab tab; + float min = 0; + float max = 0; + const char* choices = nullptr; + const char* format = nullptr; +}; + // A completion the console offers: the whole line it makes, with a dim descriptor beside it. struct OverlaySuggestion { @@ -53,12 +105,15 @@ private: std::vector suggestions; std::string input; std::string layoutPath; + std::string modBindingMenu; std::string suggestedInput; + ModOptionKind modBindingKind = MOD_OPTION_KEY; ModsView modsView = MODS_VIEW_THUMBNAIL; float scale = 0; int bindingAction = -1; int bindingDevice = -1; int bindingSlot = 0; + int modBindingIndex = -1; int selected = -1; unsigned int listId = 0; bool isOpen[OVERLAY_WINDOW_COUNT] = {true, true, true, true, false}; @@ -87,6 +142,10 @@ private: void options_render(); void controls_render(); bool is_binding_taken(const SDL_Event& event); + void mod_options_render(); + void mod_rows_render(lua_State* state, const char* menu); + void mod_row_render(lua_State* state, const char* menu, int index, ModOptionKind kind); + bool is_mod_binding_taken(const SDL_Event& event); void mods_render(); void mod_render(ModEntry& mod, float width); unsigned int thumbnail_get(ModEntry& mod); @@ -100,3 +159,5 @@ private: extern Overlay overlay; void log_viewer_append(const std::string& text); +template bool is_option_edited(const OptionSpec& spec, T& value); +void mod_options_save();