diff --git a/Makefile b/Makefile index e4df61e..6906a76 100644 --- a/Makefile +++ b/Makefile @@ -196,14 +196,22 @@ export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) .PHONY: all clean -GENERATE_STAMP := $(BUILD)/.generate_data.$(BUILD_LANG).$(BUILD_TYPE).$(BUILD_XLSX).stamp -BUILD_STAMP := $(BUILD)/.build.$(BUILD_LANG).$(BUILD_TYPE).$(BUILD_XLSX).stamp +GENERATE_STAMP := $(BUILD)/.generate_data.$(BUILD_LANG).$(BUILD_TYPE).stamp +BUILD_STAMP := $(BUILD)/.build.$(BUILD_LANG).$(BUILD_TYPE).stamp PAYLOAD_GEN_INPUTS := $(shell find tools/payload-generator/src tools/payload-generator/include -type f \( -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \)) -TEXT_HELPER_INPUTS := tools/text_helper/main.py $(wildcard tools/text_helper/fonts/*.png) $(wildcard tools/text_helper/build/text.xlsx) +TEXT_HELPER_INPUTS := tools/text_helper/main.py $(wildcard tools/text_helper/fonts/*.png) $(wildcard tools/text_helper/text.xlsx) +TEXT_GENERATED_OUTPUTS := \ + $(GENERATED_DIR)/translated_text.h \ + $(GENERATED_DIR)/translated_text.cpp \ + $(GENERATED_DIR)/fonts.h all: - @before=$$(stat -c %Y $(BUILD_STAMP) 2>/dev/null || echo 0); \ + @set -e; \ + if [ "$(BUILD_XLSX)" = "remote" ]; then \ + $(MAKE) --no-print-directory text_generated BUILD_LANG=$(BUILD_LANG) BUILD_TYPE=$(BUILD_TYPE) BUILD_XLSX=$(BUILD_XLSX); \ + fi; \ + before=$$(stat -c %Y $(BUILD_STAMP) 2>/dev/null || echo 0); \ $(MAKE) --no-print-directory $(BUILD_STAMP) BUILD_LANG=$(BUILD_LANG) BUILD_TYPE=$(BUILD_TYPE) BUILD_XLSX=$(BUILD_XLSX); \ after=$$(stat -c %Y $(BUILD_STAMP) 2>/dev/null || echo 0); \ if [ "$$before" = "$$after" ] && [ "$$after" != "0" ]; then \ @@ -225,7 +233,9 @@ generated_dir: generate_data: $(GENERATE_STAMP) $(GENERATE_STAMP): $(TEXT_HELPER_INPUTS) $(PAYLOAD_GEN_INPUTS) compress_lz10.sh | data to_compress generated_dir - @$(MAKE) --no-print-directory text_generated BUILD_LANG=$(BUILD_LANG) BUILD_TYPE=$(BUILD_TYPE) BUILD_XLSX=$(BUILD_XLSX) + @if [ "$(BUILD_XLSX)" != "remote" ]; then \ + $(MAKE) --no-print-directory text_generated BUILD_LANG=$(BUILD_LANG) BUILD_TYPE=$(BUILD_TYPE) BUILD_XLSX=$(BUILD_XLSX); \ + fi @echo "----------------------------------------------------------------" @echo "Building v$(GIT_VERSION) with parameters: $(BUILD_LANG), $(BUILD_TYPE), $(BUILD_XLSX)" @echo "----------------------------------------------------------------" diff --git a/PCCS b/PCCS index 552fa4c..93a1e2e 160000 --- a/PCCS +++ b/PCCS @@ -1 +1 @@ -Subproject commit 552fa4c4e91ffa5f1cde850e6cfe7180c3d84886 +Subproject commit 93a1e2ea88e0b0dea3e963a8bce7e87bd989f5be diff --git a/include/background_engine.h b/include/background_engine.h index 6831edc..e6224ed 100644 --- a/include/background_engine.h +++ b/include/background_engine.h @@ -1,13 +1,20 @@ -#ifndef BACKGROUND_ENGINE_H -#define BACKGROUND_ENGINE_H +#ifndef BG_ENGINE_H +#define BG_ENGINE_H #include "sprite_data.h" #include "text_engine.h" #include "global_frame_controller.h" +// This order does matter, as if two backgrounds are on the same layer, +// the lowest number will be the one that is displayed +#define BG_BACKDROP REG_BG0CNT +#define BG_FLEX REG_BG1CNT +#define BG_TEXTBOX REG_BG2CNT +#define BG_TEXT REG_BG3CNT + void background_frame(int global_frame_count); +void create_textbox(int text_section, int text_key, bool eraseMainBox); void create_textbox(int startTileX, int startTileY, int text_space_width, int text_space_height, bool eraseMainBox); -void reset_textbox(); void show_textbox(); void hide_textbox(); #endif \ No newline at end of file diff --git a/include/dbg/debug_mode.h b/include/dbg/debug_mode.h index c812882..f2a59b9 100644 --- a/include/dbg/debug_mode.h +++ b/include/dbg/debug_mode.h @@ -120,4 +120,12 @@ extern debug_options g_debug_options; // needs to be a value divisible by 4 #define CUSTOM_MALLOC_POOL_SIZE 8192 +// This option enables PTGB_MGBA_XYZ() log messages. These get printed to the mgba log window. +// This option can only be enabled in debug builds because it relies on mgba_printf, +// which will only get included in debug builds for licensing reasons. +// Compiling with this option enabled in release builds will cause a static_assert failure. +// But the && DEBUG_MODE check will already prevent this from being enabled in release builds accidentally, +// so as long as no-one removes that, it should be fine. +#define DEBUG_USE_MGBA_PRINT (true && DEBUG_MODE) + #endif \ No newline at end of file diff --git a/include/dbg/ptgb_mgba_print.h b/include/dbg/ptgb_mgba_print.h new file mode 100644 index 0000000..bc13b24 --- /dev/null +++ b/include/dbg/ptgb_mgba_print.h @@ -0,0 +1,29 @@ +#ifndef _PTGB_MGBA_PRINT_H_ +#define _PTGB_MGBA_PRINT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#define PTGB_MGBA_LOG_FATAL 0 +#define PTGB_MGBA_LOG_ERROR 1 +#define PTGB_MGBA_LOG_WARN 2 +#define PTGB_MGBA_LOG_INFO 3 +#define PTGB_MGBA_LOG_DEBUG 4 + +#define PTGB_MGBA_FATAL(X, ...) ptgb_mgba_print(PTGB_MGBA_LOG_FATAL, X, ##__VA_ARGS__) +#define PTGB_MGBA_ERROR(X, ...) ptgb_mgba_print(PTGB_MGBA_LOG_ERROR, X, ##__VA_ARGS__) +#define PTGB_MGBA_WARN(X, ...) ptgb_mgba_print(PTGB_MGBA_LOG_WARN, X, ##__VA_ARGS__) +#define PTGB_MGBA_INFO(X, ...) ptgb_mgba_print(PTGB_MGBA_LOG_INFO, X, ##__VA_ARGS__) +#define PTGB_MGBA_DEBUG(X, ...) ptgb_mgba_print(PTGB_MGBA_LOG_DEBUG, X, ##__VA_ARGS__) + +void ptgb_mgba_init(void); +void ptgb_mgba_deinit(void); + +void ptgb_mgba_print(int level, const char *format_str, ...); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/include/libraries/libmgba/LICENSE b/include/libraries/libmgba/LICENSE new file mode 100644 index 0000000..f43f64b --- /dev/null +++ b/include/libraries/libmgba/LICENSE @@ -0,0 +1,402 @@ +There's a bit of ambiguity on the license, because the mgba.h header seems to show a BSD-2 license. + +But the mgba project -in which this lib is stored- shows an MPL-2 license. + +We have copied them both here below: + +From Header: + + Copyright (c) 2016 Jeffrey Pfau + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +MGBA project license: + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/include/libraries/libmgba/README.md b/include/libraries/libmgba/README.md new file mode 100644 index 0000000..2dd2a35 --- /dev/null +++ b/include/libraries/libmgba/README.md @@ -0,0 +1,10 @@ +# Usage of libmgba in Poke_Transporter_GB + +Libmgba has been copied from https://github.com/mgba-emu/mgba/tree/master/opt/libgba + +It offers a way to push debug logging to the MGBA emulator. This is useful during development. + +While we are using libmgba in Poke\_Transporter\_GB for debugging purposes, we have taken special care that the code doesn't end up in an actual release build. +(static assert) +Only debug builds _can_ include libmgba into Poke\_Transporter\_GB. However, these shouldn't end up in end-users hands. + diff --git a/include/libraries/libmgba/mgba.h b/include/libraries/libmgba/mgba.h new file mode 100644 index 0000000..53ba2b5 --- /dev/null +++ b/include/libraries/libmgba/mgba.h @@ -0,0 +1,47 @@ +/* + mgba.h + Copyright (c) 2016 Jeffrey Pfau + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef MGBA_H +#define MGBA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define MGBA_LOG_FATAL 0 +#define MGBA_LOG_ERROR 1 +#define MGBA_LOG_WARN 2 +#define MGBA_LOG_INFO 3 +#define MGBA_LOG_DEBUG 4 + +bool mgba_open(void); +void mgba_close(void); + +void mgba_printf(int level, const char* string, ...); +bool mgba_console_open(void); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/include/libraries/libugba/include/background.h b/include/libraries/libugba/include/background.h index 3375247..a1c3d2f 100644 --- a/include/libraries/libugba/include/background.h +++ b/include/libraries/libugba/include/background.h @@ -2,8 +2,8 @@ // // Copyright (c) 2020 Antonio Niño Díaz -#ifndef BACKGROUND_H__ -#define BACKGROUND_H__ +#ifndef BG_H__ +#define BG_H__ #include "bios.h" #include "hardware.h" @@ -87,4 +87,4 @@ EXPORT_API void BG_FramebufferSwap(void); // Set backdrop color (background palette 0 color). EXPORT_API void BG_BackdropColorSet(uint16_t color); -#endif // BACKGROUND_H__ +#endif // BG_H__ diff --git a/include/libraries/libugba/include/hardware.h b/include/libraries/libugba/include/hardware.h index 519bcb8..e9de4e9 100644 --- a/include/libraries/libugba/include/hardware.h +++ b/include/libraries/libugba/include/hardware.h @@ -367,10 +367,10 @@ static_assert(sizeof(oam_matrix_entry) == 32, "Wrong oam_matrix_entry size"); #define REG_GREENSWAP REG_16(OFFSET_GREENSWAP) #define REG_DISPSTAT REG_16(OFFSET_DISPSTAT) #define REG_VCOUNT REG_16(OFFSET_VCOUNT) -#define REG_BG0CNT REG_16(OFFSET_BG0CNT) -#define REG_BG1CNT REG_16(OFFSET_BG1CNT) -#define REG_BG2CNT REG_16(OFFSET_BG2CNT) -#define REG_BG3CNT REG_16(OFFSET_BG3CNT) +#define BG_BACKDROP REG_16(OFFSET_BG0CNT) +#define BG_FLEX REG_16(OFFSET_BG1CNT) +#define BG_TEXTBOX REG_16(OFFSET_BG2CNT) +#define BG_TEXT REG_16(OFFSET_BG3CNT) #define REG_BG0HOFS REG_16(OFFSET_BG0HOFS) #define REG_BG0VOFS REG_16(OFFSET_BG0VOFS) #define REG_BG1HOFS REG_16(OFFSET_BG1HOFS) diff --git a/include/sound.h b/include/sound.h index d94c2fd..cda4a93 100644 --- a/include/sound.h +++ b/include/sound.h @@ -9,7 +9,7 @@ extern "C" { #endif -typedef void* PTGBSFXHandle; +typedef unsigned short PTGBSFXHandle; /** * @brief The API's defined here are a thin abstraction layer over the sound engine functions. diff --git a/include/sprite_data.h b/include/sprite_data.h index 3b73d52..515b73a 100644 --- a/include/sprite_data.h +++ b/include/sprite_data.h @@ -106,11 +106,11 @@ extern OBJ_ATTR *grabbed_front_sprite; #define LINK_CABLE_PAL 13 #define PULLED_SPRITE_PAL 14 -#define BG_OPENING 0 -#define BG_FENNEL 1 -#define BG_DEX 2 -#define BG_MAIN_MENU 3 -#define BG_BOX 4 +#define FLEXBG_OPENING 0 +#define FLEXBG_FENNEL 1 +#define FLEXBG_DEX 2 +#define FLEXBG_MAIN_MENU 3 +#define FLEXBG_BOX 4 extern rom_data curr_GBA_rom; diff --git a/include/text_engine.h b/include/text_engine.h index cc55c42..21e339f 100644 --- a/include/text_engine.h +++ b/include/text_engine.h @@ -6,10 +6,6 @@ #define H_MAX 240 #define V_MAX 160 -#define LEFT 8 -#define RIGHT (H_MAX - LEFT) -#define TOP 120 -#define BOTTOM V_MAX #define INK_WHITE 15 #define INK_ROM_COLOR 14 @@ -22,14 +18,12 @@ void init_text_engine(); int text_loop(int script); int text_next_obj_id(script_obj current_line); -void show_text_box(); -void hide_text_box(); void set_text_exit(); -int ptgb_write(const char *text); -int ptgb_write(const byte *text, bool instant); -int ptgb_write(const byte *text, bool instant, int length); +int ptgb_write_textbox(const byte *text, bool instant, bool waitForUser, int text_section, int text_key, bool eraseMainBox); +int ptgb_write_simple(const byte *text, bool instant); +int ptgb_write(const byte *text, bool instant, int length, int box_type); int ptgb_write_debug(const u16* charset, const char *text, bool instant); -void wait_for_user_to_continue(bool clear_text); -void scroll_text(bool instant, TTC *tc); +void wait_for_user_to_continue(); +void scroll_text(bool instant, TTC *tc, int left, int top, int right, int bottom); #endif \ No newline at end of file diff --git a/source/background_engine.cpp b/source/background_engine.cpp index 93ad621..99e653f 100644 --- a/source/background_engine.cpp +++ b/source/background_engine.cpp @@ -1,6 +1,7 @@ #include #include "pokemon_data.h" #include "background_engine.h" +#include "translated_text.h" #define CBB 0 #define SBB 24 @@ -19,6 +20,17 @@ void background_frame(int global_frame_count) } // This could honestly be an object... might want to do that in the future, depending on how complex using this gets +void create_textbox(int text_section, int text_key, bool eraseMainBox) +{ + int box_type = text_box_type_tables[text_section][text_key]; + int startTileX = box_type_info[box_type][BOX_TYPE_VAL_START_TILE_X]; + int startTileY = box_type_info[box_type][BOX_TYPE_VAL_START_TILE_Y]; + int text_space_width = box_type_info[box_type][BOX_TYPE_VAL_PIXELS_PER_LINE]; + int text_space_height = box_type_info[box_type][BOX_TYPE_VAL_NUM_OF_LINES] * 16; + + create_textbox(startTileX, startTileY, text_space_width, text_space_height, eraseMainBox); +} + void create_textbox(int startTileX, int startTileY, int text_space_width, int text_space_height, bool eraseMainBox) { if (eraseMainBox) @@ -28,26 +40,17 @@ void create_textbox(int startTileX, int startTileY, int text_space_width, int te add_menu_box(startTileX, startTileY, text_space_width + 16, text_space_height + 16); tte_set_pos((startTileX + 1) * 8, (startTileY + 1) * 8); tte_set_margins((startTileX + 1) * 8, (startTileY + 1) * 8, - (startTileX + text_space_width) * 8, (startTileY + text_space_height) * 8); + ((startTileX + 1) * 8) + text_space_width, ((startTileY + 1) * 8) + text_space_height); tte_erase_rect(0, 0, H_MAX, V_MAX); -} - -void reset_textbox() -{ - tte_erase_rect(0, 0, H_MAX, V_MAX); - reload_textbox_background(); - tte_set_pos(LEFT, TOP); - tte_set_margins(LEFT, TOP, RIGHT, BOTTOM); + show_textbox(); } void show_textbox() { - REG_BG0CNT = (REG_BG0CNT & ~BG_PRIO_MASK) | BG_PRIO(3); - REG_BG2CNT = (REG_BG2CNT & ~BG_PRIO_MASK) | BG_PRIO(2); + BG_TEXTBOX = (BG_TEXTBOX & ~BG_PRIO_MASK) | BG_PRIO(1); } void hide_textbox() { - REG_BG0CNT = (REG_BG0CNT & ~BG_PRIO_MASK) | BG_PRIO(2); - REG_BG2CNT = (REG_BG2CNT & ~BG_PRIO_MASK) | BG_PRIO(3); + BG_TEXTBOX = (BG_TEXTBOX & ~BG_PRIO_MASK) | BG_PRIO(3); } \ No newline at end of file diff --git a/source/box_menu.cpp b/source/box_menu.cpp index f9ea386..9d39512 100644 --- a/source/box_menu.cpp +++ b/source/box_menu.cpp @@ -19,7 +19,7 @@ int Box_Menu::box_main(PokeBox* box) text_data_table PKMN_NAMES(names_decompression_buffer); tte_erase_screen(); - load_flex_background(BG_BOX, 2); + load_flex_background(FLEXBG_BOX, 2); REG_BG1VOFS = 0; REG_BG1HOFS = 0; load_temp_box_sprites(box); @@ -117,7 +117,7 @@ int Box_Menu::box_main(PokeBox* box) obj_hide(party_sprites[i]); } tte_erase_screen(); - load_flex_background(BG_FENNEL, 2); + load_flex_background(FLEXBG_FENNEL, 2); REG_BG2VOFS = BG2VOF_SMALL_TEXTBOX; global_next_frame(); return curr_button; @@ -135,23 +135,23 @@ int Box_Menu::box_main(PokeBox* box) byte val[11]; tte_set_pos(6, 88); curr_pkmn->externalConvertNickname(val); - ptgb_write(val, true); + ptgb_write_simple(val, true); if (curr_pkmn->getIsShiny()) { tte_set_pos(64, 16); val[0] = 0xF9; val[1] = 0xFF; - ptgb_write(val, true); + ptgb_write_simple(val, true); } tte_set_pos(14, 98); if (curr_pkmn->getSpeciesIndexNumber() == MISSINGNO) { - ptgb_write(PKMN_NAMES.get_text_entry(0), true); + ptgb_write_simple(PKMN_NAMES.get_text_entry(0), true); } else { - ptgb_write(PKMN_NAMES.get_text_entry(curr_pkmn->getSpeciesIndexNumber()), true); + ptgb_write_simple(PKMN_NAMES.get_text_entry(curr_pkmn->getSpeciesIndexNumber()), true); } tte_set_pos(6, 108); val[0] = 0xC6; // L @@ -159,9 +159,9 @@ int Box_Menu::box_main(PokeBox* box) val[2] = 0xF0; // : val[3] = 0x00; // " " val[4] = 0xFF; // endline - ptgb_write(val, true); + ptgb_write_simple(val, true); convert_int_to_ptgb_str(curr_pkmn->getLevel(), val); // Val should never go out of bounds - ptgb_write(val, true); + ptgb_write_simple(val, true); update_front_box_sprite(curr_pkmn); obj_unhide(grabbed_front_sprite, 0); diff --git a/source/button_menu.cpp b/source/button_menu.cpp index acead91..fffde84 100644 --- a/source/button_menu.cpp +++ b/source/button_menu.cpp @@ -30,7 +30,6 @@ void Button_Menu::set_xy_min_max(int nX_min, int nX_max, int nY_min, int nY_max) int Button_Menu::button_main() { - tte_set_pos(0, 0); organize_buttons(); show_buttons(); button_vector.at(curr_position).set_highlight(true); diff --git a/source/dbg/debug_menu.cpp b/source/dbg/debug_menu.cpp index 12d6f8d..3cfb535 100644 --- a/source/dbg/debug_menu.cpp +++ b/source/dbg/debug_menu.cpp @@ -22,7 +22,7 @@ void show_debug_menu() load_localized_charset(charset, 3, ENGLISH); tte_erase_rect(0, 0, H_MAX, V_MAX); erase_textbox_tiles(); - show_text_box(); + show_textbox(); tte_set_ink(INK_DARK_GREY); obj_unhide(toggle_arrow_left, 0); @@ -30,7 +30,7 @@ void show_debug_menu() const vertical_menu_settings menu_settings = { .x = 20, .y = 0, - .width = 200, + .width = 208, .height = 155, .margin_top = 8, .margin_bottom = 8, @@ -54,7 +54,7 @@ void show_debug_menu() obj_hide(toggle_arrow_left); obj_hide(toggle_arrow_right); - hide_text_box(); + hide_textbox(); tte_erase_rect(0, 0, H_MAX, V_MAX); // execute any callback that was delayed by pressing the A button on an executable row. diff --git a/source/dbg/debug_menu_functions.cpp b/source/dbg/debug_menu_functions.cpp index 19a2bcb..a030f4a 100644 --- a/source/dbg/debug_menu_functions.cpp +++ b/source/dbg/debug_menu_functions.cpp @@ -95,7 +95,7 @@ void show_text_debug_screen(void *context, unsigned user_param) (void)user_param; tte_set_ink(INK_DARK_GREY); - REG_BG1CNT = (REG_BG1CNT & ~BG_PRIO_MASK) | BG_PRIO(3); + BG_FLEX = (BG_FLEX & ~BG_PRIO_MASK) | BG_PRIO(3); text_loop(SCRIPT_DEBUG); } @@ -150,8 +150,8 @@ void show_debug_info_screen(void *context, unsigned user_param) n2hexstr(flags_hex_str, pkmn_flags); n2hexstr(def_lang_hex_str, def_lang); - create_textbox(4, 1, 160, 80, true); - show_text_box(); + //create_textbox(4, 1, 160, 80, true); + show_textbox(); npf_snprintf(text_buffer, sizeof(text_buffer), "Debug info:\n\nG: %d%s%d\nF: %d%d%d-%s\nS: %d-%s\n%s%s", @@ -174,8 +174,8 @@ void show_debug_info_screen(void *context, unsigned user_param) { if (key_hit(KEY_B)) { - hide_text_box(); - reset_textbox(); + hide_textbox(); + reload_textbox_background(); return; } global_next_frame(); diff --git a/source/dbg/debug_mode.cpp b/source/dbg/debug_mode.cpp index 4b6a95f..0ccaf30 100644 --- a/source/dbg/debug_mode.cpp +++ b/source/dbg/debug_mode.cpp @@ -8,7 +8,7 @@ debug_options g_debug_options = .ignore_game_pak_sprites = (false && DEBUG_MODE), .ignore_link_cable = (false && DEBUG_MODE), .ignore_mg_e4_flags = (true && DEBUG_MODE), - .ignore_unreceived_pkmn = (false && DEBUG_MODE), + .ignore_unreceived_pkmn = (true && DEBUG_MODE), .force_tutorial = (false && DEBUG_MODE), .dont_hide_invalid_pkmn = (false && DEBUG_MODE), .ignore_dex_completion = (false && DEBUG_MODE), diff --git a/source/dbg/ptgb_mgba_print.cpp b/source/dbg/ptgb_mgba_print.cpp new file mode 100644 index 0000000..b22cca2 --- /dev/null +++ b/source/dbg/ptgb_mgba_print.cpp @@ -0,0 +1,44 @@ +#include "dbg/ptgb_mgba_print.h" +#include "dbg/debug_mode.h" +#include + +#if DEBUG_USE_MGBA_PRINT +#include "libraries/libmgba/mgba.h" + +#if !DEBUG +static_assert(false, "DEBUG_USE_MGBA_PRINT is only allowed for debug builds!"); +#endif + +void ptgb_mgba_init(void) +{ + mgba_console_open(); +} + +void ptgb_mgba_deinit(void) +{ + mgba_close(); +} + +void ptgb_mgba_print(int level, const char *format_str, ...) +{ + va_list args; + va_start(args, format_str); + mgba_printf(level, format_str, args); + va_end(args); +} + +#else +void ptgb_mgba_init(void) +{ +} + +void ptgb_mgba_deinit(void) +{ +} + +void ptgb_mgba_print(int level, const char *format_str, ...) +{ + (void)level; + (void)format_str; +} +#endif \ No newline at end of file diff --git a/source/flash_mem.cpp b/source/flash_mem.cpp index 90ae725..94336e1 100644 --- a/source/flash_mem.cpp +++ b/source/flash_mem.cpp @@ -106,8 +106,8 @@ void print_mem_section() out[0] = get_char_from_charset(charset, mem_name); out[1] = get_char_from_charset(charset, '-'); out[2] = get_char_from_charset(charset, mem_id + 0xA1); // Kinda a dumb way to - tte_set_pos(0, 0); - ptgb_write(out, true); + //tte_set_pos(0, 0); + ptgb_write_simple(out, true); */ } @@ -153,7 +153,7 @@ bool read_flag(u16 flag_id) { if (false) { - tte_set_pos(0, 0); + //tte_set_pos(0, 0); tte_write("#{cx:0xD000}Attempting to read byte "); tte_write(ptgb::to_string((curr_GBA_rom.offset_flags + (flag_id / 8)) % 0xF80)); tte_write(" of memory section "); diff --git a/source/gameboy_colour.cpp b/source/gameboy_colour.cpp index 37dd135..b73931e 100644 --- a/source/gameboy_colour.cpp +++ b/source/gameboy_colour.cpp @@ -98,6 +98,7 @@ int link_cable_memory_section_index = 0; void print(const char *format, ...) { + // I don't think this function is called anymore... va_list args; va_start(args, format); @@ -122,12 +123,14 @@ void print(const char *format, ...) npf_vsnprintf(spi_text_out_array[0], SPI_TEXT_OUT_ARRAY_ELEMENT_SIZE, format, args); va_end(args); - tte_erase_rect(LEFT, TOP, RIGHT, BOTTOM); - tte_set_pos(LEFT, 0); + tte_erase_rect(0, 0, H_MAX, V_MAX); + for (int j = 0; j < 10; j++) { - ptgb_write("#{cx:0xE000}"); - ptgb_write(spi_text_out_array[j]); + tte_erase_rect(0, 0, H_MAX, V_MAX); + tte_set_pos(0, 0); + ptgb_write_simple(reinterpret_cast("#{cx:0xE000}"), true); + ptgb_write_simple((byte *)(spi_text_out_array[j]), true); } } @@ -162,15 +165,13 @@ void setup(const u16 *debug_charset) failed_packet = false; init_packet = true; end_of_data = false; - - create_textbox(5, 1, 128, 60, true); - { u8 general_text_table_buffer[2048]; text_data_table general_text(general_text_table_buffer); general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - ptgb_write(general_text.get_text_entry(GENERAL_connecting), true); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_connecting), true, false, + GENERAL_INDEX, GENERAL_connecting, false); } } @@ -222,14 +223,13 @@ byte handleIncomingByte(byte in, byte *box_data_storage, byte *curr_payload, GB_ { if (in == 0x60 || in == 0x61) { - tte_erase_rect(0, 0, H_MAX, V_MAX); - tte_set_pos(40, 24); { u8 general_text_table_buffer[2048]; text_data_table general_text(general_text_table_buffer); general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - ptgb_write(general_text.get_text_entry(curr_gb_rom->version != YELLOW_ID ? GENERAL_link_success : GENERAL_link_success_yellow), true); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_link_success), true, false, + GENERAL_INDEX, GENERAL_link_success, false); } link_animation_state(STATE_NO_ANIM); @@ -274,14 +274,13 @@ byte handleIncomingByte(byte in, byte *box_data_storage, byte *curr_payload, GB_ { if (in == 0xfd) { - tte_erase_rect(0, 0, H_MAX, V_MAX); - tte_set_pos(40, 24); { u8 general_text_table_buffer[2048]; text_data_table general_text(general_text_table_buffer); general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - ptgb_write(general_text.get_text_entry(GENERAL_transferring), true); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_transferring), true, false, + GENERAL_INDEX, GENERAL_transferring, false); } link_animation_state(STATE_TRANSFER); @@ -369,7 +368,6 @@ int loop(byte *box_data_storage, byte *curr_payload, GB_ROM *curr_gb_rom, PokeBo #define NUM_LINES 8 int counter = 0; char stuff[NUM_LINES][LINE_WIDTH]; - while (true) { if (g_debug_options.print_link_data && key_held(KEY_L)) @@ -385,11 +383,8 @@ int loop(byte *box_data_storage, byte *curr_payload, GB_ROM *curr_gb_rom, PokeBo if (g_debug_options.print_link_data && !key_held(KEY_DOWN)) { - // tte_set_margins(0, 0, H_MAX, V_MAX); - // print("%d: [%d][%d][%" PRIu8 "][%" PRIu8 "]\n\n", counter, data_counter, state, in_data, out_data); for (int i = 0; i < NUM_LINES; i++) { - // ptgb_write_debug(debug_charset, "\n", true); for (int j = 0; j < LINE_WIDTH; j++) { stuff[i][j] = stuff[i + 1][j]; @@ -407,7 +402,7 @@ int loop(byte *box_data_storage, byte *curr_payload, GB_ROM *curr_gb_rom, PokeBo n2hexstr(&stuff[NUM_LINES - 1][18], out_data & 0xFF, 2); stuff[NUM_LINES - 1][20] = '\0'; - create_textbox(0, 0, 125, 80, false); + create_textbox(0, 0, 125, 128, false); ptgb_write_debug(debug_charset, *stuff, true); } else if (g_debug_options.write_cable_data_to_save) @@ -616,7 +611,7 @@ byte exchange_boxes(byte curr_in, byte *box_data_storage, GB_ROM *curr_gb_rom, c n2hexstr(&outArr[currRow][14], init_packet, 2); outArr[currRow][16] = ' '; - create_textbox(0, 0, 125, 110, false); + // create_textbox(0, 0, 125, 110, false); link_animation_state(0); ptgb_write_debug(debug_charset, *outArr, true); diff --git a/source/global_frame_controller.cpp b/source/global_frame_controller.cpp index 081e63c..098fd9e 100644 --- a/source/global_frame_controller.cpp +++ b/source/global_frame_controller.cpp @@ -9,6 +9,7 @@ #include "string.h" #include "text_data_table.h" #include "translated_text.h" +#include "dbg/debug_mode.h" int global_frame_count = 0; bool rand_enabled = true; @@ -28,15 +29,14 @@ static void __attribute__((noinline)) show_pulled_cart_error() text_data_table general_text(general_text_table_buffer); general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - ptgb_write(general_text.get_text_entry(GENERAL_pulled_cart_error), true); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_pulled_cart_error), true, true, + GENERAL_INDEX, GENERAL_pulled_cart_error, true); } void global_next_frame() { key_poll(); rand_next_frame(); - // tte_set_pos(0, 0); - // tte_write(ptgb::to_string(get_rand_u32())); background_frame(global_frame_count); determine_fennel_blink(); if (missingno_enabled) @@ -50,10 +50,8 @@ void global_next_frame() set_menu_sprite_pal(0); if (!curr_GBA_rom.verify_rom()) { - REG_BG0CNT = (REG_BG0CNT & ~BG_PRIO_MASK) | BG_PRIO(2); - REG_BG2CNT = (REG_BG2CNT & ~BG_PRIO_MASK) | BG_PRIO(1); - tte_set_pos(40, 24); - create_textbox(4, 1, 160, 80, true); + BG_BACKDROP = (BG_BACKDROP & ~BG_PRIO_MASK) | BG_PRIO(2); + BG_TEXTBOX = (BG_TEXTBOX & ~BG_PRIO_MASK) | BG_PRIO(1); obj_hide_multi(ptgb_logo_l, num_sprites); show_pulled_cart_error(); @@ -211,11 +209,17 @@ void link_animation_state(int state) break; } curr_link_animation_state = state; + + if (g_debug_options.print_link_data) + { + obj_hide(cart_shell); + obj_hide(cart_label); + } } void determine_fennel_blink() { - if (get_curr_flex_background() == BG_FENNEL) + if (get_curr_flex_background() == FLEXBG_FENNEL) { if (fennel_blink_timer == 0) { @@ -324,7 +328,9 @@ void convert_int_to_ptgb_str(int val, byte str[], int min_length) { str[count] = 0xA1; // 0xA1 is 0 in the chart count++; - } else { + } + else + { first = false; } } diff --git a/source/libraries/libmgba/LICENSE b/source/libraries/libmgba/LICENSE new file mode 100644 index 0000000..f43f64b --- /dev/null +++ b/source/libraries/libmgba/LICENSE @@ -0,0 +1,402 @@ +There's a bit of ambiguity on the license, because the mgba.h header seems to show a BSD-2 license. + +But the mgba project -in which this lib is stored- shows an MPL-2 license. + +We have copied them both here below: + +From Header: + + Copyright (c) 2016 Jeffrey Pfau + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +MGBA project license: + +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/source/libraries/libmgba/mgba.c b/source/libraries/libmgba/mgba.c new file mode 100644 index 0000000..8540ccb --- /dev/null +++ b/source/libraries/libmgba/mgba.c @@ -0,0 +1,96 @@ +/* + mgba.h + Copyright (c) 2016 Jeffrey Pfau + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include "libraries/nanoprintf/nanoprintf.h" +#include "libraries/libmgba/mgba.h" + +#include +#include +#include + +#define REG_DEBUG_ENABLE (vu16*) 0x4FFF780 +#define REG_DEBUG_FLAGS (vu16*) 0x4FFF700 +#define REG_DEBUG_STRING (char*) 0x4FFF600 + +ssize_t mgba_stdout_write(struct _reent* r __attribute__((unused)), void* fd __attribute__((unused)), const char* ptr, size_t len) { + if (len > 0x100) { + len = 0x100; + } + strncpy(REG_DEBUG_STRING, ptr, len); + *REG_DEBUG_FLAGS = MGBA_LOG_INFO | 0x100; + return len; +} + +ssize_t mgba_stderr_write(struct _reent* r __attribute__((unused)), void* fd __attribute__((unused)), const char* ptr, size_t len) { + if (len > 0x100) { + len = 0x100; + } + strncpy(REG_DEBUG_STRING, ptr, len); + *REG_DEBUG_FLAGS = MGBA_LOG_ERROR | 0x100; + return len; +} + +void mgba_printf(int level, const char* ptr, ...) { + level &= 0x7; + va_list args; + va_start(args, ptr); + npf_vsnprintf(REG_DEBUG_STRING, 0x100, ptr, args); + va_end(args); + *REG_DEBUG_FLAGS = level | 0x100; +} + +static const devoptab_t dotab_mgba_stdout = { + "mgba_stdout", + 0, + NULL, + NULL, + mgba_stdout_write +}; + +static const devoptab_t dotab_mgba_stderr = { + "mgba_stderr", + 0, + NULL, + NULL, + mgba_stderr_write +}; + +bool mgba_console_open(void) { + if (!mgba_open()) { + return false; + } + devoptab_list[STD_OUT] = &dotab_mgba_stdout; + devoptab_list[STD_ERR] = &dotab_mgba_stderr; + return true; +} + +bool mgba_open(void) { + *REG_DEBUG_ENABLE = 0xC0DE; + return *REG_DEBUG_ENABLE == 0x1DEA; +} + +void mgba_close(void) { + *REG_DEBUG_ENABLE = 0; +} + diff --git a/source/main.cpp b/source/main.cpp index 9a7c14d..3259b80 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -16,6 +16,7 @@ #include "button_menu.h" #include "dbg/debug_mode.h" #include "dbg/debug_menu.h" +#include "dbg/ptgb_mgba_print.h" #include "dex_handler.h" #include "pokedex.h" #include "global_frame_controller.h" @@ -58,9 +59,8 @@ Button_Menu yes_no_menu(1, 2, 40, 24, false); void load_graphics() { - tte_erase_rect(0, 0, H_MAX, V_MAX); - // Load opening background first so it hides everything else - load_flex_background(BG_OPENING, 1); + // Load opening background first so it hides everything else + load_flex_background(FLEXBG_OPENING, 1); load_background(); load_textbox_background(); load_eternal_sprites(); @@ -84,7 +84,7 @@ void initialization_script(void) irq_init(NULL); irq_enable(II_VBLANK); // This currently crashes when you try to transfer a Pokemon: - //sound_init(); + // sound_init(); // Graphics init oam_init(obj_buffer, 128); @@ -92,29 +92,30 @@ void initialization_script(void) // Prepare text engine for dialogue init_text_engine(); + ptgb_mgba_init(); // Set the random seed rand_set_seed(0x1216); // Clean up the main screen quick - tte_erase_rect(0, 0, 240, 160); VBlankIntrWait(); REG_DISPCNT &= ~DCNT_BLANK; + + PTGB_MGBA_INFO("Hello from PTGB!"); }; void game_load_error(void) { - REG_BG2CNT = (REG_BG2CNT & ~BG_PRIO_MASK) | BG_PRIO(1); - - create_textbox(4, 1, 152, 100, true); + BG_TEXTBOX = (BG_TEXTBOX & ~BG_PRIO_MASK) | BG_PRIO(1); { u8 general_text_table_buffer[2048]; text_data_table general_text(general_text_table_buffer); general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - ptgb_write(general_text.get_text_entry(GENERAL_cart_load_error), true); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_cart_load_error), true, false, + GENERAL_INDEX, GENERAL_cart_load_error, false); } key_poll(); @@ -124,6 +125,7 @@ void game_load_error(void) } while (!key_hit(KEY_A) && !key_hit(KEY_SELECT)); tte_erase_rect(0, 0, H_MAX, V_MAX); + erase_textbox_tiles(); if (key_hit(KEY_SELECT)) { @@ -147,8 +149,6 @@ void game_load_error(void) void first_load_message(void) { - tte_set_margins(8, 8, H_MAX - 8, V_MAX); - tte_set_pos(8, 8); tte_set_ink(INK_ROM_COLOR); { @@ -156,14 +156,13 @@ void first_load_message(void) text_data_table general_text(general_text_table_buffer); general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - ptgb_write(general_text.get_text_entry(GENERAL_intro_first), true); + ptgb_write_simple(general_text.get_text_entry(GENERAL_intro_first), true); } while (!key_hit(KEY_A)) { global_next_frame(); } - tte_erase_rect(0, 0, H_MAX, V_MAX); } int credits() @@ -180,16 +179,16 @@ int credits() { if (update) { - create_textbox(1, 1, 200, 120, true); - show_text_box(); - ptgb_write(credits_text_table.get_text_entry(curr_credits_num), true); + ptgb_write_textbox(credits_text_table.get_text_entry(curr_credits_num), true, false, + CREDITS_INDEX, curr_credits_num, false); update = false; } if (key_hit(KEY_B)) { - hide_text_box(); - reset_textbox(); + tte_erase_rect(0, 0, H_MAX, V_MAX); + hide_textbox(); + erase_textbox_tiles(); return 0; } if (key_hit(KEY_LEFT) && curr_credits_num > 0) @@ -225,7 +224,6 @@ int main_menu_loop() { if (update) { - tte_erase_rect(0, 80, 240, 160); for (int i = 0; i < NUM_MENU_OPTIONS; i++) { text_entry = general_text.get_text_entry(menu_options[i]); @@ -240,7 +238,7 @@ int main_menu_loop() { tte_set_ink(INK_ROM_COLOR); } - ptgb_write(text_entry, true); + ptgb_write_simple(text_entry, true); test++; } } @@ -257,7 +255,6 @@ int main_menu_loop() else if (key_hit(KEY_A)) { tte_erase_rect(0, test, H_MAX, V_MAX); - ptgb_write("#{cx:0xF000}"); return return_values[curr_selection]; } else if ((key_held(KEY_L) && key_held(KEY_R))) @@ -273,28 +270,9 @@ int main_menu_loop() } } -// Legal stuff -static void show_legal_text(const u8 *intro_text) -{ - tte_set_margins(4, 0, H_MAX - 4, V_MAX); - tte_set_pos(4, 0); - tte_set_ink(INK_ROM_COLOR); - ptgb_write(intro_text, true); - bool wait = true; - while (wait) - { - global_next_frame(); - if (key_hit(KEY_A)) - { - wait = false; - } - } -} - // Gears of Progress static void show_gears_of_progress() { - tte_erase_rect(0, 0, 240, 160); REG_BG1VOFS = 0; delay_counter = 0; while (delay_counter < (15 * 60)) @@ -316,23 +294,20 @@ static void __attribute__((noinline)) show_intro() { bool start_pressed = false; u8 general_text_table_buffer[2048]; - u8 press_start_text[32]; - u8 press_start_text_length; text_data_table general_text(general_text_table_buffer); const u8 *text_entry; general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - - text_entry = general_text.get_text_entry(GENERAL_press_start); - press_start_text_length = get_string_char_count(text_entry); - memcpy(press_start_text, text_entry, press_start_text_length + 1); text_entry = general_text.get_text_entry(GENERAL_intro_legal); - show_legal_text(text_entry); + tte_set_ink(INK_ROM_COLOR); + ptgb_write_textbox(text_entry, true, true, + GENERAL_INDEX, GENERAL_intro_legal, true); + show_gears_of_progress(); - REG_BG1CNT = REG_BG1CNT | BG_PRIO(3); + BG_FLEX = BG_FLEX | BG_PRIO(3); key_poll(); // Reset the keys curr_GBA_rom.load_rom(false); @@ -343,22 +318,12 @@ static void __attribute__((noinline)) show_intro() REG_BLDCNT = BLD_BUILD(BLD_BG3, BLD_BG0, 1); -#ifndef PTGB_BUILD_LANGUAGE - -#error PTGB_NOT_DEFINED -#endif -#ifndef JPN_ID -#error JPN_ID_NOT_DEFINED -#endif -#pragma message "PTGB_BUILD_LANGUAGE=" PTGB_BUILD_LANGUAGE -#pragma message "JPN_ID=" JPN_ID - - int char_width = (PTGB_BUILD_LANGUAGE == JPN_ID ? 8 : 6); - int x = ((240 - (press_start_text_length * char_width)) / 2); - tte_set_pos(x, 12 * 8); + general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); + text_entry = general_text.get_text_entry(GENERAL_press_start); + tte_set_pos(0, 12 * 8); tte_set_ink(INK_DARK_GREY); - ptgb_write(press_start_text, true); + ptgb_write_simple(text_entry, true); int fade = 0; while (!start_pressed) @@ -383,7 +348,6 @@ int main(void) { first_load_message(); }*/ - show_intro(); key_poll(); @@ -408,8 +372,7 @@ int main(void) } // Initialize memory and save data after loading the game - reset_textbox(); - REG_BG2CNT = REG_BG2CNT | BG_PRIO(3); + BG_TEXTBOX = BG_TEXTBOX | BG_PRIO(3); init_bank(); initialize_memory_locations(); load_custom_save_data(); @@ -434,7 +397,7 @@ int main(void) print_mem_section(); curr_GBA_rom.print_rom_info(); } - load_flex_background(BG_MAIN_MENU, 2); + load_flex_background(FLEXBG_MAIN_MENU, 2); obj_unhide_multi(ptgb_logo_l, 1, 2); obj_set_pos(ptgb_logo_l, 56, 12); @@ -445,7 +408,7 @@ int main(void) case (BTN_TRANSFER): tte_set_ink(INK_DARK_GREY); obj_hide_multi(ptgb_logo_l, 2); - load_flex_background(BG_FENNEL, 3); + load_flex_background(FLEXBG_FENNEL, 3); text_loop(SCRIPT_TRANSFER); break; case (BTN_POKEDEX): @@ -453,20 +416,17 @@ int main(void) { obj_hide_multi(ptgb_logo_l, 2); global_next_frame(); - load_flex_background(BG_DEX, 2); + load_flex_background(FLEXBG_DEX, 2); set_background_pal(curr_GBA_rom.gamecode, true, false); pokedex_loop(); - load_flex_background(BG_DEX, 3); + load_flex_background(FLEXBG_DEX, 3); set_background_pal(curr_GBA_rom.gamecode, false, false); } break; case (BTN_CREDITS): tte_set_ink(INK_DARK_GREY); - // create_textbox(0, 0, 160, 80, true); - // show_text_box(); - REG_BG1CNT = (REG_BG1CNT & ~BG_PRIO_MASK) | BG_PRIO(3); - obj_set_pos(ptgb_logo_l, 56, 108); - obj_set_pos(ptgb_logo_r, 56 + 64, 108); + BG_FLEX = (BG_FLEX & ~BG_PRIO_MASK) | BG_PRIO(3); + obj_hide_multi(ptgb_logo_l, 2); credits(); break; case (BTN_EVENTS): diff --git a/source/multiboot_upload.cpp b/source/multiboot_upload.cpp index a4b5ab9..ef68e4c 100644 --- a/source/multiboot_upload.cpp +++ b/source/multiboot_upload.cpp @@ -7,12 +7,6 @@ #include "translated_text.h" #include "text_data_table.h" -static void multiboot_show_textbox() -{ - tte_erase_rect(0, 0, RIGHT, BOTTOM); - create_textbox(4, 1, 152, 100, true); -} - void multiboot_upload_screen() { u8 general_text_table_buffer[2048]; @@ -21,8 +15,9 @@ void multiboot_upload_screen() general_text.decompress(get_compressed_text_table(GENERAL_INDEX)); - multiboot_show_textbox(); - ptgb_write(general_text.get_text_entry(GENERAL_send_multiboot_instructions), true); + // multiboot_show_textbox(); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_send_multiboot_instructions), true, + false, GENERAL_INDEX, GENERAL_send_multiboot_instructions, false); // wait for key press do @@ -37,8 +32,9 @@ void multiboot_upload_screen() } // start upload - multiboot_show_textbox(); - ptgb_write(general_text.get_text_entry(GENERAL_send_multiboot_wait), true); + // multiboot_show_textbox(); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_send_multiboot_wait), true, + false, GENERAL_INDEX, GENERAL_send_multiboot_wait, false); global_next_frame(); const u32 romSize = 256 * 1024; // EWRAM = 256 KB @@ -52,15 +48,16 @@ void multiboot_upload_screen() // (when this returns true, the transfer will be canceled) }); // show result - // clear_textbox(); - multiboot_show_textbox(); + // multiboot_show_textbox(); if (multibootResult == LinkCableMultiboot::Result::SUCCESS) { - ptgb_write(general_text.get_text_entry(GENERAL_send_multiboot_success), true); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_send_multiboot_success), true, + false, GENERAL_INDEX, GENERAL_send_multiboot_success, false); } else { - ptgb_write(general_text.get_text_entry(GENERAL_send_multiboot_failure), true); + ptgb_write_textbox(general_text.get_text_entry(GENERAL_send_multiboot_failure), true, + false, GENERAL_INDEX, GENERAL_send_multiboot_failure, false); } // wait for keypress again. diff --git a/source/pokedex.cpp b/source/pokedex.cpp index 22a9709..51abeee 100644 --- a/source/pokedex.cpp +++ b/source/pokedex.cpp @@ -116,25 +116,26 @@ int pokedex_loop() // TODO: For some reason there is screen tearing here. Probably not noticable on console, // but it should be removed at some point + tte_set_ink(INK_DARK_GREY); tte_set_pos(8, 146); - ptgb_write(kanto_name, true); + ptgb_write_simple(kanto_name, true); convert_int_to_ptgb_str(kanto_dex_num, temp_string, 3); - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); temp_string[0] = 0xBA; // "/" temp_string[1] = 0xFF; - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); convert_int_to_ptgb_str(mew_caught ? 151 : 150, temp_string, 3); - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); tte_set_pos(128, 146); - ptgb_write(johto_name, true); + ptgb_write_simple(johto_name, true); convert_int_to_ptgb_str(johto_dex_num, temp_string, 3); - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); temp_string[0] = 0xBA; // "/" temp_string[1] = 0xFF; - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); convert_int_to_ptgb_str(celebi_caught ? 100 : 99, temp_string, 3); - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); while (true) { @@ -205,6 +206,7 @@ int pokedex_loop() } if (update) { + tte_set_ink(INK_ROM_COLOR); tte_erase_rect(0, 0, 240, 140); int mythic_skip = 0; for (int i = 0; i < DEX_MAX; i++) @@ -219,15 +221,15 @@ int pokedex_loop() tte_set_pos(dex_x_cord + (3 * 8 / 2), (i * 8 * 2) + 28); temp_string[0] = 0xF7; temp_string[1] = 0xFF; - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); } tte_set_pos(dex_x_cord + (3 * 8), (i * 8 * 2) + 28); convert_int_to_ptgb_str(dex_shift + i + 1 + mythic_skip, temp_string, 3); - ptgb_write(temp_string, true); + ptgb_write_simple(temp_string, true); tte_set_pos(dex_x_cord + (7 * 8), (i * 8 * 2) + 28); - ptgb_write(is_caught(dex_shift + i + 1 + mythic_skip) ? PKMN_NAMES.get_text_entry(dex_shift + i + 1 + mythic_skip) : undiscovered_text, true); + ptgb_write_simple(is_caught(dex_shift + i + 1 + mythic_skip) ? PKMN_NAMES.get_text_entry(dex_shift + i + 1 + mythic_skip) : undiscovered_text, true); } global_next_frame(); // This is a bit silly, but it works. Makes the types one frame off from the text, but that's 'fine' diff --git a/source/rom_data.cpp b/source/rom_data.cpp index 5beb35c..8d03cf6 100644 --- a/source/rom_data.cpp +++ b/source/rom_data.cpp @@ -180,8 +180,7 @@ void rom_data::print_rom_info() npf_snprintf(buffer, sizeof(buffer), "%c-%d-%c", gameTypeChar, version, language); - tte_set_pos(0, 8); - ptgb_write(buffer); + ptgb_write_simple(reinterpret_cast(buffer), true); } bool rom_data::verify_rom() diff --git a/source/script_array.cpp b/source/script_array.cpp index da01338..2776b76 100644 --- a/source/script_array.cpp +++ b/source/script_array.cpp @@ -813,11 +813,11 @@ bool run_conditional(int index) return false; case CMD_START_LINK: - load_flex_background(BG_FENNEL, 3); + load_flex_background(FLEXBG_FENNEL, 3); link_animation_state(STATE_CONNECTION); party_data.start_link(); - reset_textbox(); - load_flex_background(BG_FENNEL, 2); + reload_textbox_background(); + load_flex_background(FLEXBG_FENNEL, 2); link_animation_state(0); return true; @@ -828,15 +828,15 @@ bool run_conditional(int index) case CMD_BACK_TO_MENU: set_text_exit(); REG_BG1HOFS = 0; - load_flex_background(BG_FENNEL, 3); + load_flex_background(FLEXBG_FENNEL, 3); return true; case CMD_SHOW_PROF: - load_flex_background(BG_FENNEL, 2); + //load_flex_background(FLEXBG_FENNEL, 3); return true; case CMD_HIDE_PROF: - load_flex_background(BG_FENNEL, 3); + //load_flex_background(FLEXBG_FENNEL, 3); return true; case CMD_SET_TUTOR_TRUE: @@ -902,9 +902,9 @@ bool run_conditional(int index) return true; case CMD_BOX_MENU: - hide_text_box(); + hide_textbox(); ret = (box_viewer.box_main(&party_data.box) == CONFIRM_BUTTON); - show_text_box(); + show_textbox(); return ret; case CMD_MYTHIC_MENU: diff --git a/source/sprite_data.cpp b/source/sprite_data.cpp index 8a49e5d..2a01716 100644 --- a/source/sprite_data.cpp +++ b/source/sprite_data.cpp @@ -4,12 +4,13 @@ #include "dbg/debug_mode.h" #include "gba_rom_values/base_gba_rom_struct.h" #include "global_frame_controller.h" +#include "background_engine.h" #define SPRITE_CHAR_BLOCK 4 OBJ_ATTR obj_buffer[128]; OBJ_AFFINE *obj_aff_buffer = (OBJ_AFFINE *)obj_buffer; -int curr_flex_background; +int curr_flex_background = -1; int y_offset = 0; int y_offset_timer = 0; int y_offset_direction = 1; @@ -27,7 +28,7 @@ void load_background() LZ77UnCompVram(backgroundTiles, &tile_mem[CBB][0]); // Load map into SBB 0 LZ77UnCompVram(backgroundMap, &se_mem[SBB][0]); - REG_BG0CNT = BG_CBB(CBB) | BG_SBB(SBB) | BG_4BPP | BG_REG_32x32 | BG_PRIO(3); + BG_BACKDROP = BG_CBB(CBB) | BG_SBB(SBB) | BG_4BPP | BG_REG_32x32 | BG_PRIO(3); } void set_background_pal(int curr_rom_id, bool dark, bool fade) @@ -125,72 +126,76 @@ void set_background_pal(int curr_rom_id, bool dark, bool fade) void load_flex_background(int background_id, int layer) { - // This prevents screen tearing on this frame - global_next_frame(); - REG_BG1CNT = (REG_BG1CNT && !BG_PRIO_MASK) | BG_PRIO(3); - int CBB = 3; // CBB is the tiles that make up the sprite int SBB = 31; // SSB is the array of which tile goes where - switch (background_id) + + if (curr_flex_background != background_id) // Only load the background if it isn't already loaded { - case (BG_OPENING): - // Load palette - tonccpy(pal_bg_mem + 32, openingBGPal, openingBGPalLen); - // Load tiles into CBB 0 - LZ77UnCompVram(openingBGTiles, &tile_mem[CBB][0]); - // Give it a frame to uncompress the data + // This prevents screen tearing on this frame global_next_frame(); - // Load map into SBB 0 - LZ77UnCompVram(openingBGMap, &se_mem[SBB][0]); - REG_BG1VOFS = 96; - break; - case (BG_FENNEL): - // Load palette - tonccpy(pal_bg_mem + 32, fennelBGPal, fennelBGPalLen); - // Load tiles into CBB 0 - LZ77UnCompVram(fennelBGTiles, &tile_mem[CBB][0]); - // Give it a frame to uncompress the data - global_next_frame(); - // Load map into SBB 0 - LZ77UnCompVram(fennelBGMap, &se_mem[SBB][0]); - REG_BG1VOFS = FENNEL_SHIFT; - break; - case (BG_DEX): - // Load palette - tonccpy(pal_bg_mem + 32, dexBGPal, dexBGPalLen); - // Load tiles into CBB 0 - LZ77UnCompVram(dexBGTiles, &tile_mem[CBB][0]); - // Give it a frame to uncompress the data - global_next_frame(); - // Load map into SBB 0 - LZ77UnCompVram(dexBGMap, &se_mem[SBB][0]); - REG_BG1VOFS = 0; - break; - case (BG_MAIN_MENU): - // Load palette - tonccpy(pal_bg_mem + 32, pal_bg_mem, backgroundPalLen); - // Load tiles into CBB 0 - LZ77UnCompVram(menu_barsTiles, &tile_mem[CBB][0]); - // Give it a frame to uncompress the data - global_next_frame(); - // Load map into SBB 0 - LZ77UnCompVram(menu_barsMap, &se_mem[SBB][0]); - REG_BG1VOFS = 0; - break; - case (BG_BOX): - // Load palette - tonccpy(pal_bg_mem + 32, boxBGPal, boxBGPalLen); - // Load tiles into CBB 0 - LZ77UnCompVram(boxBGTiles, &tile_mem[CBB][0]); - // Give it a frame to uncompress the data - global_next_frame(); - // Load map into SBB 0 - LZ77UnCompVram(boxBGMap, &se_mem[SBB][0]); - REG_BG1VOFS = 0; - break; + BG_FLEX = (BG_FLEX && !BG_PRIO_MASK) | BG_PRIO(3); + + switch (background_id) + { + case (FLEXBG_OPENING): + // Load palette + tonccpy(pal_bg_mem + 32, openingBGPal, openingBGPalLen); + // Load tiles into CBB 0 + LZ77UnCompVram(openingBGTiles, &tile_mem[CBB][0]); + // Give it a frame to uncompress the data + global_next_frame(); + // Load map into SBB 0 + LZ77UnCompVram(openingBGMap, &se_mem[SBB][0]); + REG_BG1VOFS = 96; + break; + case (FLEXBG_FENNEL): + // Load palette + tonccpy(pal_bg_mem + 32, fennelBGPal, fennelBGPalLen); + // Load tiles into CBB 0 + LZ77UnCompVram(fennelBGTiles, &tile_mem[CBB][0]); + // Give it a frame to uncompress the data + global_next_frame(); + // Load map into SBB 0 + LZ77UnCompVram(fennelBGMap, &se_mem[SBB][0]); + REG_BG1VOFS = FENNEL_SHIFT; + break; + case (FLEXBG_DEX): + // Load palette + tonccpy(pal_bg_mem + 32, dexBGPal, dexBGPalLen); + // Load tiles into CBB 0 + LZ77UnCompVram(dexBGTiles, &tile_mem[CBB][0]); + // Give it a frame to uncompress the data + global_next_frame(); + // Load map into SBB 0 + LZ77UnCompVram(dexBGMap, &se_mem[SBB][0]); + REG_BG1VOFS = 0; + break; + case (FLEXBG_MAIN_MENU): + // Load palette + tonccpy(pal_bg_mem + 32, pal_bg_mem, backgroundPalLen); + // Load tiles into CBB 0 + LZ77UnCompVram(menu_barsTiles, &tile_mem[CBB][0]); + // Give it a frame to uncompress the data + global_next_frame(); + // Load map into SBB 0 + LZ77UnCompVram(menu_barsMap, &se_mem[SBB][0]); + REG_BG1VOFS = 0; + break; + case (FLEXBG_BOX): + // Load palette + tonccpy(pal_bg_mem + 32, boxBGPal, boxBGPalLen); + // Load tiles into CBB 0 + LZ77UnCompVram(boxBGTiles, &tile_mem[CBB][0]); + // Give it a frame to uncompress the data + global_next_frame(); + // Load map into SBB 0 + LZ77UnCompVram(boxBGMap, &se_mem[SBB][0]); + REG_BG1VOFS = 0; + break; + } } - REG_BG1CNT = BG_CBB(CBB) | BG_SBB(SBB) | BG_4BPP | BG_REG_32x32 | BG_PRIO(layer); + BG_FLEX = BG_CBB(CBB) | BG_SBB(SBB) | BG_4BPP | BG_REG_32x32 | BG_PRIO(layer); curr_flex_background = background_id; } #include "textBoxBG.h" @@ -206,7 +211,7 @@ void load_textbox_background() reload_textbox_background(); REG_BG2VOFS = 96; - REG_BG2CNT = BG_CBB(CBB) | BG_SBB(SBB) | BG_4BPP | BG_REG_32x32 | BG_PRIO(3); + BG_TEXTBOX = BG_CBB(CBB) | BG_SBB(SBB) | BG_4BPP | BG_REG_32x32 | BG_PRIO(3); } void reload_textbox_background() @@ -274,37 +279,37 @@ void add_menu_box(int startTileX, int startTileY, int full_width, int full_heigh int SBB = 20; int start = (32 * startTileY) + startTileX; - int tiles = (full_height / 8) - 2; // For the extra 2 tiles - int rem = full_height % 8; - full_width /= 8; + int tiles = (full_height / 8) - 1; // For the flex edge + int vert_rem = full_height % 8; + full_width = (full_width / 8) - 1; // For the right edge // Corners se_mem[SBB][start] = TILE_NW; se_mem[SBB][start + full_width] = TILE_NE; - se_mem[SBB][start + (32 * (tiles + 1))] = TILE_SW_U_ARR[rem / 2]; - se_mem[SBB][start + (32 * (tiles + 2))] = TILE_SW_L_ARR[rem / 2]; - se_mem[SBB][start + (32 * (tiles + 1)) + full_width] = TILE_SE_U_ARR[rem / 2]; - se_mem[SBB][start + (32 * (tiles + 2)) + full_width] = TILE_SE_L_ARR[rem / 2]; + se_mem[SBB][start + (32 * (tiles))] = TILE_SW_U_ARR[vert_rem / 2]; + se_mem[SBB][start + (32 * (tiles + 1))] = TILE_SW_L_ARR[vert_rem / 2]; + se_mem[SBB][start + (32 * (tiles)) + full_width] = TILE_SE_U_ARR[vert_rem / 2]; + se_mem[SBB][start + (32 * (tiles + 1)) + full_width] = TILE_SE_L_ARR[vert_rem / 2]; // Top and bottom edge for (int i = 1; i < full_width; i++) { se_mem[SBB][start + i] = TILE_N; - se_mem[SBB][start + ((32 * (tiles + 1))) + i] = TILE_S_U_ARR[rem / 2]; - se_mem[SBB][start + ((32 * (tiles + 2))) + i] = TILE_S_L_ARR[rem / 2]; + se_mem[SBB][start + ((32 * (tiles))) + i] = TILE_S_U_ARR[vert_rem / 2]; + se_mem[SBB][start + ((32 * (tiles + 1))) + i] = TILE_S_L_ARR[vert_rem / 2]; } // Sides - for (int i = 0; i < tiles; i++) + for (int i = 1; i < tiles; i++) { - se_mem[SBB][start + (32 * (i + 1)) + full_width] = TILE_E; - se_mem[SBB][start + (32 * (i + 1))] = TILE_W; + se_mem[SBB][start + (32 * i) + full_width] = TILE_E; + se_mem[SBB][start + (32 * i)] = TILE_W; } // Middle for (int x = 1; x < full_width; x++) { - for (int y = 1; y < tiles + 1; y++) + for (int y = 1; y < tiles; y++) { se_mem[SBB][start + (32 * y) + x] = TILE_MID; } diff --git a/source/text_engine.cpp b/source/text_engine.cpp index 856b07f..8334c80 100644 --- a/source/text_engine.cpp +++ b/source/text_engine.cpp @@ -87,9 +87,6 @@ void init_text_engine() ); tte_init_con(); - // tte_set_margins(LEFT, TOP, RIGHT, BOTTOM); - // tte_set_pos(LEFT, TOP); - pal_bg_bank[15][INK_WHITE] = CLR_WHITE; // White pal_bg_bank[15][INK_DARK_GREY] = 0b0000110001100010; // Dark Grey // 14 will be changed to game color @@ -125,18 +122,15 @@ int text_loop(int script) // tte_set_margins(LEFT, TOP, RIGHT, BOTTOM); if (script != SCRIPT_DEBUG) { - REG_BG1CNT = (REG_BG1CNT && !BG_PRIO_MASK) | BG_PRIO(2); // Show Fennel - show_text_box(); while (true) // This loops through all the connected script objects { if (curr_text != NULL && curr_text[char_index] != 0xFF && curr_text[char_index] != 0xFB) { - tte_set_pos(LEFT, TOP); - tte_erase_rect(LEFT, TOP, RIGHT, BOTTOM); - ptgb_write(curr_text, false); + ptgb_write_textbox(curr_text, false, true, + PTGB_INDEX, curr_line.get_text_entry_index(), false); } - wait_for_user_to_continue(false); + // wait_for_user_to_continue(); line_char_index = 0; switch (script) @@ -154,8 +148,9 @@ int text_loop(int script) if (text_exit) { - hide_text_box(); - tte_erase_rect(LEFT, TOP, RIGHT, BOTTOM); + hide_textbox(); + erase_textbox_tiles(); + tte_erase_screen(); text_exit = false; return 0; } @@ -167,7 +162,7 @@ int text_loop(int script) load_localized_charset(debug_charset, 3, ENGLISH); int text_section = 0; - int text_identifier = 0; + int text_key = 0; while (true) { bool exit = false; @@ -178,12 +173,12 @@ int text_loop(int script) { if (key_hit(KEY_LEFT)) { - text_identifier = (text_identifier + (text_section_lengths[text_section] - 1)) % text_section_lengths[text_section]; + text_key = (text_key + (text_section_lengths[text_section] - 1)) % text_section_lengths[text_section]; update_text = true; } else if (key_hit(KEY_RIGHT)) { - text_identifier = (text_identifier + 1) % text_section_lengths[text_section]; + text_key = (text_key + 1) % text_section_lengths[text_section]; update_text = true; } else if (key_hit(KEY_UP)) @@ -200,23 +195,24 @@ int text_loop(int script) { instant_text = key_hit(KEY_START); // instant with start, not with select exit = true; + tte_erase_line(); } if (update_text) { - if (text_identifier > text_section_lengths[text_section]) + if (text_key >= text_section_lengths[text_section]) { - text_identifier = text_section_lengths[text_section]; + text_key = text_section_lengths[text_section] - 1; } - if (text_section > NUM_TEXT_SECTIONS) + if (text_section >= NUM_TEXT_SECTIONS) { - text_section = NUM_TEXT_SECTIONS; + text_section = NUM_TEXT_SECTIONS - 1; } tte_set_pos(0, 0); tte_erase_rect(0, 0, 240, 160); ptgb_write_debug(debug_charset, "(", true); ptgb_write_debug(debug_charset, ptgb::to_string(text_section), true); ptgb_write_debug(debug_charset, ", ", true); - ptgb_write_debug(debug_charset, ptgb::to_string(text_identifier), true); + ptgb_write_debug(debug_charset, ptgb::to_string(text_key), true); ptgb_write_debug(debug_charset, ")", true); update_text = false; } @@ -224,27 +220,18 @@ int text_loop(int script) } line_char_index = 0; - curr_text = read_dialogue_text_entry(text_identifier, text_section, diag_entry_text_buffer); + curr_text = read_dialogue_text_entry(text_key, text_section, diag_entry_text_buffer); char_index = 0; if (curr_text != NULL && curr_text[char_index] != 0xFF && curr_text[char_index] != 0xFB) { - if (text_section == PTGB_INDEX) - { - reset_textbox(); - } - else - { - create_textbox(4, 1, 160, 80, true); - } - show_text_box(); - tte_erase_rect(0, 0, 240, 160); - ptgb_write(curr_text, instant_text); + ptgb_write_textbox(curr_text, instant_text, true, + text_section, text_key, true); } - wait_for_user_to_continue(false); update_text = true; - hide_text_box(); + hide_textbox(); + tte_erase_rect(0, 0, H_MAX, V_MAX); if (text_exit) { @@ -273,50 +260,74 @@ int text_next_obj_id(script_obj current_line) } } -void show_text_box() -{ - REG_BG2CNT = (REG_BG2CNT & ~BG_PRIO_MASK) | BG_PRIO(1); -} - -void hide_text_box() -{ - REG_BG2CNT = (REG_BG2CNT & ~BG_PRIO_MASK) | BG_PRIO(3); -} - void set_text_exit() { text_exit = true; key_poll(); // This removes the "A Hit" when exiting the text } -// Implement a version that just writes the whole string -int ptgb_write(const byte *text, bool instant) +// Implement a version that creates the textbox as well +int ptgb_write_textbox(const byte *text, bool instant, bool waitForUser, + int text_section, int text_key, bool eraseMainBox) { - return ptgb_write(text, instant, 9999); // This is kinda silly but it'll work. + tte_erase_rect(0, 0, H_MAX, V_MAX); + erase_textbox_tiles(); + create_textbox(text_section, text_key, eraseMainBox); + // Set up Fennel if we are in a PTGB dialogue box + if (get_curr_flex_background() == FLEXBG_FENNEL && text_section == PTGB_INDEX) + { + load_flex_background(FLEXBG_FENNEL, 2); + } + int out = ptgb_write(text, instant, 9999, text_box_type_tables[text_section][text_key]); // This is kinda silly but it'll work. + if (waitForUser) + { + wait_for_user_to_continue(); + } + if (eraseMainBox) + { + tte_erase_rect(0, 0, H_MAX, V_MAX); + hide_textbox(); + erase_textbox_tiles(); + } + return out; +} + +// Implement a version that just writes the whole string +int ptgb_write_simple(const byte *text, bool instant) +{ + return ptgb_write(text, instant, 9999, -1); // This is kinda silly but it'll work. } // Re-implementing TTE's "tte_write" to use the gen 3 character encoding chart -int ptgb_write(const byte *text, bool instant, int length) +int ptgb_write(const byte *text, bool instant, int length, int box_type) { + int left, top, right, bottom; + instant = instant || g_debug_options.instant_text_speed; if (text == NULL) return 0; + if (box_type == -1) + { + left = 0; + top = 0; + right = H_MAX; + bottom = V_MAX; + } + else + { + left = 8 * (box_type_info[box_type][BOX_TYPE_VAL_START_TILE_X] + 1); + top = 8 * (box_type_info[box_type][BOX_TYPE_VAL_START_TILE_Y] + 1); + right = left + box_type_info[box_type][BOX_TYPE_VAL_PIXELS_PER_LINE]; + bottom = top + box_type_info[box_type][BOX_TYPE_VAL_NUM_OF_LINES] * 16; + } + uint ch, gid; char *str = (char *)text; TTC *tc = tte_get_context(); TFont *font; int num = 0; - /* - if (curr_text[char_index] == 0xFB) // This will need to be moved - { - line_char_index += char_index; - line_char_index++; - // Low key kinda scuffed, but it works to split the string - curr_text = &curr_line.get_text()[line_char_index]; - } - */ while ((ch = *str) != 0xFF && num < length) { if (get_frame_count() % 2 == 0 || key_held(KEY_B) || key_held(KEY_A) || instant) @@ -329,17 +340,17 @@ int ptgb_write(const byte *text, bool instant, int length) { tc->drawgProc(0x79); } - wait_for_user_to_continue(false); - scroll_text(instant, tc); - tc->cursorY += tc->font->charH; - tc->cursorX = tc->marginLeft; + wait_for_user_to_continue(); + scroll_text(instant, tc, left, top, right, bottom); break; case 0xFB: if (g_debug_options.display_control_char) { tc->drawgProc(0xB9); } - wait_for_user_to_continue(true); + wait_for_user_to_continue(); + tte_erase_rect(left, top, right, bottom); + tte_set_pos(left, top); break; case 0xFC: ch = *str; @@ -347,7 +358,8 @@ int ptgb_write(const byte *text, bool instant, int length) num += 1; if (g_debug_options.display_control_char) { - for (uint i = 0; i < ch; i++){ + for (uint i = 0; i < ch; i++) + { tc->drawgProc(0xB9); } } @@ -375,20 +387,13 @@ int ptgb_write(const byte *text, bool instant, int length) // Character wrap int charW = font->widths ? font->widths[gid] : font->charW; - // We don't want this tbh- all of the newlines should deal with moving to the next line - /* if (tc->cursorX + charW > tc->marginRight) - { - tc->cursorY += 10; // font->charH; - tc->cursorX = tc->marginLeft; - } */ - // Draw and update position tc->drawgProc(gid); tc->cursorX += charW; } num += 1; } - if (get_curr_flex_background() == BG_FENNEL && !instant) + if (get_curr_flex_background() == FLEXBG_FENNEL && !instant) { fennel_speak(((num / 4) % 4) + 1); } @@ -429,18 +434,12 @@ int ptgb_write_debug(const u16 *charset, const char *text, bool instant) temp_holding[i] = get_char_from_charset(charset, utf16_char); } } - return ptgb_write(temp_holding, instant); + return ptgb_write_simple(temp_holding, instant); } -// Adding this to avoid compiler issues temporarilly -int ptgb_write(const char *text) +void wait_for_user_to_continue() { - return 0; -} - -void wait_for_user_to_continue(bool clear_text) -{ - if (get_curr_flex_background() == BG_FENNEL) + if (get_curr_flex_background() == FLEXBG_FENNEL) { if (get_missingno_enabled()) { @@ -453,23 +452,18 @@ void wait_for_user_to_continue(bool clear_text) } } key_poll(); - while (!(key_hit(KEY_A) || key_hit(KEY_B) || curr_text == NULL)) + while (!(key_hit(KEY_A) || key_hit(KEY_B))) { global_next_frame(); } - if (clear_text) - { - tte_erase_rect(LEFT, TOP, RIGHT, BOTTOM); - tte_set_pos(LEFT, TOP); - } } -void scroll_text(bool instant, TTC *tc) +void scroll_text(bool instant, TTC *tc, int left, int top, int right, int bottom) { for (int i = 1; i <= tc->font->charH; i++) { REG_BG3VOFS = i; - tte_erase_rect(LEFT, TOP - tc->font->charH, RIGHT, TOP + i); + tte_erase_rect(left, top - tc->font->charH, right, top + i); if (!instant) { global_next_frame(); @@ -480,10 +474,13 @@ void scroll_text(bool instant, TTC *tc) // The map starts at tile 0 in the top left, increases by 1 as you go down, and then loops back at the top. for (int i = 0; i < 30; i++) { - tonccpy(&tile_mem[TEXT_CBB][14 + (i * 20)], &tile_mem[TEXT_CBB][16 + (i * 20)], 2 * 2 * 32); + tonccpy(&tile_mem[TEXT_CBB][0 + (i * 20)], &tile_mem[TEXT_CBB][2 + (i * 20)], 20 * 32); } // Remove text that went outside of the box and set the position - tte_erase_rect(LEFT, TOP + tc->font->charH, RIGHT, BOTTOM); - tte_set_pos(LEFT, BOTTOM - (8 + (2 * tc->font->charH))); // The newline will trigger after this and move it down a line -} + tte_erase_rect(left, top - tc->font->charH, right, top); + tte_set_pos(left, bottom - (8 + (2 * tc->font->charH))); // The newline will trigger after this and move it down a line + + tc->cursorY = bottom - tc->font->charH; + tc->cursorX = left; +} \ No newline at end of file diff --git a/source/vertical_menu.cpp b/source/vertical_menu.cpp index a19073c..4903c3d 100644 --- a/source/vertical_menu.cpp +++ b/source/vertical_menu.cpp @@ -310,7 +310,7 @@ const simple_item_widget_data& simple_item_renderer::get_data() const void simple_item_renderer::render_item(text_data_table &text_table, unsigned x, unsigned y, bool is_focused) { tte_set_pos(x + data_.text.margin_left, y + data_.text.margin_top); - ptgb_write(text_table.get_text_entry(data_.text.text_table_index), true); + ptgb_write_simple(text_table.get_text_entry(data_.text.text_table_index), true); } MenuInputHandleState simple_item_renderer::handle_input() diff --git a/tools/text_helper/__pycache__/test_regression.cpython-312.pyc b/tools/text_helper/__pycache__/test_regression.cpython-312.pyc new file mode 100644 index 0000000..18cafc4 Binary files /dev/null and b/tools/text_helper/__pycache__/test_regression.cpython-312.pyc differ diff --git a/tools/text_helper/main.py b/tools/text_helper/main.py index 2a27e78..e6a56e6 100644 --- a/tools/text_helper/main.py +++ b/tools/text_helper/main.py @@ -9,6 +9,7 @@ import hashlib import math import png import debugpy +from dataclasses import dataclass class Languages(Enum): Japanese = 0 @@ -42,9 +43,47 @@ class Font: self.charWordTable = [0] * self.numWords self.charWidthTable = [0] * self.numBytes -FIRST_TRANSLATION_COL_INDEX = 10 +class LanguageConfig: + def __init__(self, language, column_aliases, char_array, token_indexes=None): + self.language = language + self.column_aliases = column_aliases + self.char_array = char_array + self.token_indexes = token_indexes + PURPOSEFUL_SPACE_CHAR = '|' -BACKGROUND_PAL_INDEX = 0 +BG_PAL_INDEX = 0 +TOKEN_NEWLINE = "\uE000" +TOKEN_BOX_BREAK = "\uE001" +TOKEN_SCROLL_BREAK = "\uE002" +TOKEN_CENTER_ON = "\uE003" +TOKEN_CENTER_OFF = "\uE004" +TOKEN_PRESERVED_BLANK_LINE = "\uE005" + +FORMAT_TOKEN_TO_BYTE_CHAR = { + TOKEN_NEWLINE: "Ň", + TOKEN_BOX_BREAK: "ȼ", + TOKEN_SCROLL_BREAK: "Ş", + TOKEN_CENTER_ON: "ɑ", + TOKEN_CENTER_OFF: "Ω", +} +BYTE_CHAR_TO_FORMAT_TOKEN = {value: key for key, value in FORMAT_TOKEN_TO_BYTE_CHAR.items()} + +def format_internal_tokens(text): + for token, byte_char in FORMAT_TOKEN_TO_BYTE_CHAR.items(): + text = text.replace(token, byte_char) + return text + +def normalize_control_glyphs_to_tokens(text): + for byte_char, token in BYTE_CHAR_TO_FORMAT_TOKEN.items(): + text = text.replace(byte_char, token) + return text + +def coerce_to_bool(value): + if pd.isna(value): + return False + if isinstance(value, str): + return value.strip().lower() in {"1", "true", "yes", "y"} + return bool(value) BASE_DIR = Path(__file__).resolve().parent BUILD_DIR = BASE_DIR / "build" @@ -61,22 +100,108 @@ XLSX_URL = 'https://docs.google.com/spreadsheets/d/14LLs5lLqWasFcssBmJdGXjjYxARA NEW_TEXT_XLSX_PATH = BASE_DIR / 'new_text.xlsx' TEXT_XLSX_PATH = BASE_DIR / 'text.xlsx' -LANGUAGE_TOKEN_INDEXES = { - Languages.English: (0x30, 0x60, 0x70), - Languages.French: (0x31, 0x60, 0x71), - Languages.German: (0x32, 0x61, 0x72), - Languages.Italian: (0x33, 0x60, 0x71), - Languages.SpanishEU: (0x34, 0x60, 0x72), - Languages.SpanishLA: (0x34, 0x60, 0x72), -} - def parse_build_args(argv): if len(argv) >= 4: return argv[1], argv[2], argv[3] return "", "debug", "local" # BUILD_LANG not implemented yet +def normalize_column_name(name): + return str(name).strip().lower() + +def normalize_box_type_header(name): + return "".join(ch for ch in str(name).lower() if ch.isalnum()) + +def find_required_box_type_column(columns_by_normalized, required_key): + matches = [] + for normalized, col in columns_by_normalized.items(): + if required_key == "numLines": + if "line" in normalized and ("num" in normalized or "number" in normalized) and "pixel" not in normalized: + matches.append(col) + elif required_key == "pixelsPerChar": + if "pixel" in normalized and "char" in normalized: + matches.append(col) + elif required_key == "pixelsInLine": + if "pixel" in normalized and "line" in normalized: + matches.append(col) + elif required_key == "includeBoxBreaks": + if "box" in normalized and "break" in normalized: + matches.append(col) + elif required_key == "includeScrolling": + if "scroll" in normalized: + matches.append(col) + elif required_key == "boxStyle": + if "style" in normalized: + matches.append(col) + elif required_key == "verticallyCenterText": + if "vertical" in normalized and "center" in normalized and "text" in normalized: + matches.append(col) + if len(matches) == 1: + return matches[0] + if len(matches) > 1: + raise KeyError(f"Multiple Box Types columns match '{required_key}': {matches}") + return None + +def find_column_by_aliases(columns, aliases): + normalized_columns = {normalize_column_name(col): col for col in columns} + for alias in aliases: + match = normalized_columns.get(normalize_column_name(alias)) + if match is not None: + return match + raise KeyError(f"Could not find column matching aliases: {aliases}") + +def find_optional_column_by_aliases(columns, aliases): + try: + return find_column_by_aliases(columns, aliases) + except KeyError: + return None + +def sanitize_macro_token(text): + out = "" + for char in str(text).upper(): + out += char if char.isalnum() else "_" + while "__" in out: + out = out.replace("__", "_") + return out.strip("_") + +def sanitize_c_identifier(text): + out = "" + for char in str(text).lower(): + out += char if char.isalnum() else "_" + while "__" in out: + out = out.replace("__", "_") + out = out.strip("_") + if not out: + out = "unnamed" + if out[0].isdigit(): + out = "n_" + out + return out + +@dataclass +class TextBuildContext: + storage: dict + + def initialize_storage(self, sections): + self.storage.clear() + for lang in Languages: + self.storage[lang.name] = {section: {} for section in sections} + self.storage[lang.name]["Warnings"] = {} + self.storage[lang.name]["Errors"] = {} + + def log(self, lang, level, text, entry_id=None): + bucket = level + "s" + prefix = f"[{entry_id}] " if entry_id is not None and str(entry_id).strip() != "" else "" + message = prefix + level + ": " + format_internal_tokens(text) + if message not in self.storage[lang.name][bucket].values(): + self.storage[lang.name][bucket][max(self.storage[lang.name][bucket].keys(), default=-1) + 1] = message + mainDict = {} +build_context = TextBuildContext(mainDict) textSections = [] +boxTypeDefinitions = {} +boxTypeNames = [] +boxTypeIdByName = {} +boxTypeValueKeys = [] +boxTypeValueMeta = [] fonts = { "International": Font("latin_normal", 1, 256, 16, 16, 16, 16, 16, 16), "Japanese": Font("japanese_normal", 1, 256, 16, 16, 16, 16, 16, 16), @@ -117,20 +242,23 @@ charArrays = { }, } -charArrayOfLanguage = { - Languages.Japanese: charArrays["Japanese"], - Languages.English: charArrays["International"], - Languages.French: charArrays["International"], - Languages.German: charArrays["International"], - Languages.Italian: charArrays["International"], - Languages.SpanishEU: charArrays["International"], - Languages.SpanishLA: charArrays["International"], - Languages.Korean: charArrays["International"], - Languages.ChineseSI: charArrays["International"], - Languages.ChineseTR: charArrays["International"], - Languages.PortugueseBR: charArrays["International"], +LANGUAGE_CONFIGS = { + Languages.Japanese: LanguageConfig(Languages.Japanese, ("Japanese",), charArrays["Japanese"]), + Languages.English: LanguageConfig(Languages.English, ("English",), charArrays["International"], (0x30, 0x60, 0x70)), + Languages.French: LanguageConfig(Languages.French, ("French",), charArrays["International"], (0x31, 0x60, 0x71)), + Languages.German: LanguageConfig(Languages.German, ("German",), charArrays["International"], (0x32, 0x61, 0x72)), + Languages.Italian: LanguageConfig(Languages.Italian, ("Italian",), charArrays["International"], (0x33, 0x60, 0x71)), + Languages.SpanishEU: LanguageConfig(Languages.SpanishEU, ("Spanish (EU)",), charArrays["International"], (0x34, 0x60, 0x72)), + Languages.SpanishLA: LanguageConfig(Languages.SpanishLA, ("Spanish (LA)",), charArrays["International"], (0x34, 0x60, 0x72)), + Languages.Korean: LanguageConfig(Languages.Korean, ("Korean",), charArrays["International"]), + Languages.ChineseSI: LanguageConfig(Languages.ChineseSI, ("Chinese (Simplified)",), charArrays["International"]), + Languages.ChineseTR: LanguageConfig(Languages.ChineseTR, ("Chinese (Traditional)",), charArrays["International"]), + Languages.PortugueseBR: LanguageConfig(Languages.PortugueseBR, ("Brazilian Portuguese",), charArrays["International"]), } +def get_language_config(lang): + return LANGUAGE_CONFIGS[lang] + charConversionList = [ # replaces the first char in the list with the latter ["'", "’"], @@ -188,18 +316,47 @@ def split_into_sentences(text: str) -> list[str]: text = text.replace("?","?") # Added for Japanese support text = text.replace("!","!") # Added for Japanese support text = text.replace("",".") - text = text.replace("Ň", "Ň") # Split newlines into their own sentences - text = text.replace("ȼ", "ȼ") # Split new boxes into their own sentences - text = text.replace("Ş", "Ş") # Split new boxes into their own sentences - text = text.replace("Ω", "Ω") # Split centering into their own sentences - text = text.replace("ɑ", "ɑ") # Split centering into their own sentences + for token in ( + TOKEN_NEWLINE, + TOKEN_BOX_BREAK, + TOKEN_SCROLL_BREAK, + TOKEN_CENTER_OFF, + TOKEN_CENTER_ON, + ): + text = text.replace(token, f"{token}") sentences = text.split("") sentences = [s.strip() for s in sentences] if sentences and not sentences[-1]: sentences = sentences[:-1] - return sentences + return remove_redundant_terminal_breaks(sentences) + +def remove_redundant_terminal_breaks(sentences: list[str]) -> list[str]: + cleaned_sentences = [] + for index, sentence in enumerate(sentences): + look_ahead_index = index + 1 + while look_ahead_index < len(sentences) and sentences[look_ahead_index] == TOKEN_CENTER_OFF: + look_ahead_index += 1 + + if sentence == TOKEN_CENTER_OFF and ( + look_ahead_index >= len(sentences) or sentences[look_ahead_index] in (TOKEN_BOX_BREAK, TOKEN_SCROLL_BREAK) + ): + continue + + if sentence not in (TOKEN_NEWLINE, TOKEN_SCROLL_BREAK): + cleaned_sentences.append(sentence) + continue + + if look_ahead_index >= len(sentences): + continue + + if sentences[look_ahead_index] in (TOKEN_BOX_BREAK, TOKEN_SCROLL_BREAK): + continue + + cleaned_sentences.append(sentence) + + return cleaned_sentences -def split_sentence_into_lines(sentence, offset, pixelsPerChar, pixelsInLine, centered, lang): +def split_sentence_into_lines(sentence, offset, pixelsPerChar, pixelsInLine, centered, lang, currLineCount, numLines, entry_id=None, context=None): outStr = "" currLine = "" lineCount = 0 @@ -207,101 +364,148 @@ def split_sentence_into_lines(sentence, offset, pixelsPerChar, pixelsInLine, cen lineLength = 0 spaceLength = 0 + language_config = get_language_config(lang) + language_char_array = language_config.char_array + + def format_output_line(line, line_pixel_length, trim_trailing_space=False): + if trim_trailing_space and line.endswith(" "): + line = line[:-1] + line_pixel_length -= spaceLength + + if centered and line: + count = ((pixelsInLine - line_pixel_length) // 2) + line = f'_[{count}]{line}' + line_pixel_length += count + return line, line_pixel_length + + # A centered block may get split into multiple sentences for wrapping, but each + # centered sentence still needs to begin at a real line start. + if centered and offset != 0 and sentence not in [ + TOKEN_CENTER_ON, + TOKEN_CENTER_OFF, + TOKEN_BOX_BREAK, + TOKEN_NEWLINE, + TOKEN_SCROLL_BREAK, + '', + ]: + outStr += TOKEN_NEWLINE + lineCount += 1 + offset = 0 + if sentence.startswith(PURPOSEFUL_SPACE_CHAR): + sentence = sentence[1:] + words = sentence.split() while(currWordIndex < len(words)): word = words[currWordIndex] - wordLength = 0 - # print(word) - - # Figure out the length of the word in pixels - for char in word: - if (char == PURPOSEFUL_SPACE_CHAR): - char = " " - if (pixelsPerChar == "Variable"): - wordLength += charArrayOfLanguage[lang]["font"].charWidthTable[convert_char_to_byte(ord(char), charArrayOfLanguage[lang]["array"], lang)] - spaceLength = charArrayOfLanguage[lang]["font"].charWidthTable[0] - elif (pixelsPerChar == "Default"): - if (lang == Languages.Japanese): - wordLength += 8 - spaceLength = 8 - - else: - wordLength += 6 - spaceLength = 6 - + # See if the whole sentence is a newline or scroll - if (sentence == "Ň" or sentence == "Ş"): - if (sentence == "Ň"): - outStr += "Ň" - elif (sentence == "Ş"): - outStr += "Ş" + if (sentence == TOKEN_NEWLINE or sentence == TOKEN_SCROLL_BREAK): + if (sentence == TOKEN_NEWLINE): + outStr += TOKEN_NEWLINE + elif (sentence == TOKEN_SCROLL_BREAK): + outStr += TOKEN_SCROLL_BREAK currLine = "" lineCount += 1 offset = 0 lineLength = 0 currWordIndex += 1 - # See if the whole sentence is a center character - elif (sentence == "ɑ" or sentence == "Ω"): - if (sentence == "ɑ"): + # See if the whole sentence is a center character + elif (sentence == TOKEN_CENTER_ON or sentence == TOKEN_CENTER_OFF): + if (sentence == TOKEN_CENTER_ON): centered = True - outStr += "Ň" + # Only advance when centering starts in the middle of an occupied line. + if offset != 0: + outStr += TOKEN_NEWLINE else: centered = False - outStr += "Ň" + # Only advance when centered text actually occupied the current line. + if offset != 0: + outStr += TOKEN_NEWLINE currLine = "" - lineCount += 1 offset = 0 lineLength = 0 currWordIndex += 1 - + # See if the sentence is a new box - elif(sentence == "ȼ"): + elif(sentence == TOKEN_BOX_BREAK): outStr += sentence currLine = "" offset = 0 lineLength = 0 currWordIndex += 1 - - # Test if the word is too long in general - elif (wordLength > pixelsInLine): - log_warning_error(lang, "Error", f"Word {word} exceeds alloted length ({pixelsInLine} pixels)") - currWordIndex += 1 - - # Test if adding the word will go over our alloted space - elif ((wordLength + lineLength + offset) <= pixelsInLine): - # If not, add the word and increase the index - if (currWordIndex == (len(words) - 1)): - # Don't add a space to the end of the sentence. - currLine += word - lineLength += wordLength - else: - currLine += (word + " ") - lineLength += (wordLength + spaceLength) - currWordIndex += 1 - - # We need to move to the next line + else: - # Every line should already have a space at the end of it. Remove it here - outStr += (currLine[:-1] + "Ň") - currLine = "" - lineCount += 1 - lineLength = 0 - offset = 0 - if (centered and (len(words) > 0) and words[0] not in ['ɑ', 'ȼ', 'Ň', 'Ş']): - count = ((pixelsInLine - lineLength) // 2) - currLine = f'_[{count}]{currLine}' - lineLength += count + wordLength = 0 + + # Figure out the length of the word in pixels + for char in word: + if (char == PURPOSEFUL_SPACE_CHAR): + char = " " + if (pixelsPerChar == -1): + wordLength += language_char_array["font"].charWidthTable[convert_char_to_byte(ord(char), language_char_array["array"], lang, entry_id)] + spaceLength = language_char_array["font"].charWidthTable[0] + else: + wordLength += pixelsPerChar + spaceLength = pixelsPerChar + + # Test if the word is too long in general + if (wordLength > pixelsInLine): + log_warning_error(lang, "Error", f"Word {word} exceeds alloted length ({pixelsInLine} pixels)", entry_id, context) + currWordIndex += 1 + + # Test if adding the word will go over our alloted space + elif ((wordLength + lineLength + offset) <= pixelsInLine): + # If not, add the word and increase the index + if (currWordIndex == (len(words) - 1)): + # Don't add a space to the end of the sentence. + currLine += word + lineLength += wordLength + else: + currLine += (word + " ") + lineLength += (wordLength + spaceLength) + currWordIndex += 1 + + # We need to move to the next line + else: + # Every wrapped line in a centered block needs its own horizontal offset. + formatted_line, _ = format_output_line(currLine, lineLength, trim_trailing_space=True) + outStr += (formatted_line + TOKEN_NEWLINE) + currLine = "" + lineCount += 1 + lineLength = 0 + offset = 0 + if (centered and (len(words) > 0) and words[0] not in [ + TOKEN_CENTER_ON, + TOKEN_BOX_BREAK, + TOKEN_NEWLINE, + TOKEN_SCROLL_BREAK, + ]): + currLine, lineLength = format_output_line(currLine, lineLength) outStr += currLine return lineLength + offset, lineCount, outStr, centered -def convert_char_to_byte(incoming, array, lang): +def get_text_pixel_length(text, pixelsPerChar, language_char_array, lang, entry_id=None, context=None): + if not text: + return 0 + + total = 0 + for char in text: + if char == PURPOSEFUL_SPACE_CHAR: + char = " " + if pixelsPerChar == -1: + total += language_char_array["font"].charWidthTable[convert_char_to_byte(ord(char), language_char_array["array"], lang, entry_id, context)] + else: + total += pixelsPerChar + return total + +def convert_char_to_byte(incoming, array, lang, entry_id=None, context=None): for pair in charConversionList: if incoming == ord(pair[0]): incoming = ord(pair[1]) - log_warning_error(lang, "Warning", f"Character {pair[0]} was used but is not in character table. Replaced with {pair[1]} .") + log_warning_error(lang, "Warning", f"Character {pair[0]} was used but is not in character table. Replaced with {pair[1]} .", entry_id, context) index = 0 #print(array) @@ -310,15 +514,11 @@ def convert_char_to_byte(incoming, array, lang): return index index += 1 if chr(incoming) != '_': - log_warning_error(lang, "Error", f"No match found for char [ {chr(incoming)} ]!") + log_warning_error(lang, "Error", f"No match found for char [ {chr(incoming)} ]!", entry_id, context) return 0 -def log_warning_error(lang, type, text): - nType = type + "s" - nText = type + ": " + text - if nText not in mainDict[lang.name][nType].values(): - mainDict[lang.name][nType][max(mainDict[lang.name][nType].keys(), default =- 1) + 1] = nText - #print(nText) +def log_warning_error(lang, type, text, entry_id=None, context=None): + (context or build_context).log(lang, type, text, entry_id) def hash_excel(path): sheets = pd.read_excel(path, sheet_name=None) @@ -330,19 +530,32 @@ def hash_excel(path): ).values) return h.digest() +def hash_file_bytes(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1024 * 1024), b""): + h.update(chunk) + return h.digest() + def apply_escape_sequences(line, arr, escape_list): + # Convert structural text controls to the formatter's internal sentinels + # before generic escape replacement so layout logic can see them reliably. + line = line.replace("{NEW}", TOKEN_NEWLINE) + for token, char_indexes in escape_list: if token in line: escape_string = "".join(arr[idx] for idx in char_indexes) line = line.replace(token, escape_string) # Special case for centering escape characters - line = line.replace("{CTR}", 'ɑ') - line = line.replace("{nCTR}", 'Ω') - return line + line = line.replace("{CTR}", TOKEN_CENTER_ON) + line = line.replace("{nCTR}", TOKEN_CENTER_OFF) + # Some control markers also arrive via the language escape table as visible + # glyphs. Normalize those too so layout treats them consistently. + return normalize_control_glyphs_to_tokens(line) def apply_language_tokens(line, arr, lang): - indexes = LANGUAGE_TOKEN_INDEXES.get(lang) + indexes = get_language_config(lang).token_indexes if indexes is None: return line @@ -354,86 +567,139 @@ def apply_language_tokens(line, arr, lang): .replace("{NO}", arr[no_index]) ) -def convert_item(ogDict, lang): - line = ogDict["bytes"] - numLines = ogDict["numLines"] - pixelsPerChar = ogDict["pixelsPerChar"] - pixelsInLine = ogDict["pixelsInLine"] - include_box_breaks = ogDict["includeBoxBreaks"] - include_scrolling = ogDict["includeScrolling"] +@dataclass +class FormatState: + out_text: str = "" + current_line_count: int = 0 + current_offset: int = 0 + escape_count: int = 0 + centered: bool = False - arr = charArrayOfLanguage[lang]["array"] - escape_list = charArrayOfLanguage[lang]["escape"] - - line = apply_escape_sequences(line, arr, escape_list) - line = apply_language_tokens(line, arr, lang) - - # Change all the punctuation marks followed by spaces into being followed by | temporarily +def preserve_punctuation_spacing(line): spaces = [' ', ' '] puncts = ['.', '?', '!', '。', '!', '?'] for space in spaces: for punct in puncts: line = line.replace(punct + space, punct + PURPOSEFUL_SPACE_CHAR) + return line - split_sents = split_into_sentences(line) - index = 0 - outStr = "" - currLine = 0 - offset = 0 - escapeCount = 0 - centered = False - while index < len(split_sents) and escapeCount < 100: - offset, recievedLine, out, centered = split_sentence_into_lines(split_sents[index], offset, pixelsPerChar, pixelsInLine, centered, lang) - currLine += recievedLine - - if (out == "ȼ"): - offset = 0 - currLine = 0 - # This tests if the character before the new box is a space, newline, or scroll - if outStr and (outStr[-1] in (" ", "Ň", "Ş")): - outStr = outStr[:-1] - outStr += "ȼ" - index += 1 - elif (currLine < (numLines + int(include_scrolling))): - #print(split_sents[index]) - index += 1 - # This tests if the character after the new box is a space, newline, or scroll - if outStr and out and outStr[-1] == 'ȼ' and out[0] in (" ", "Ň", "Ş"): - out = out[1:] - outStr += out +def force_newline_before_center_transition(state, sentence): + if sentence not in (TOKEN_CENTER_ON, TOKEN_CENTER_OFF): + return + if not state.out_text or state.out_text[-1] in (TOKEN_NEWLINE, TOKEN_SCROLL_BREAK, TOKEN_BOX_BREAK): + return + state.out_text += TOKEN_NEWLINE + state.current_line_count += 1 + state.current_offset = 0 + +def append_formatted_sentence(state, out, include_scrolling, numLines): + if out == TOKEN_BOX_BREAK: + state.current_offset = 0 + state.current_line_count = 0 + if state.out_text and (state.out_text[-1] in (" ", TOKEN_NEWLINE, TOKEN_SCROLL_BREAK)): + state.out_text = state.out_text[:-1] + state.out_text += TOKEN_BOX_BREAK + return True + + if state.current_line_count < (numLines + int(include_scrolling)): + if state.out_text and out and state.out_text[-1] == TOKEN_BOX_BREAK and out[0] in (" ", TOKEN_NEWLINE, TOKEN_SCROLL_BREAK): + out = out[1:] + state.out_text += out + return True + + return False + +def handle_box_overflow(state, out, numLines, include_scrolling, include_box_breaks, prev_offset, prev_curr_line, + pixelsInLine, pixelsPerChar, language_char_array, lang, entry_id, context=None): + if not include_box_breaks: + remaining_lines = max(0, (numLines + int(include_scrolling)) - prev_curr_line) + if remaining_lines > 0: + remaining_pixels = max(0, pixelsInLine - prev_offset) + ((remaining_lines - 1) * pixelsInLine) else: - if not include_box_breaks: - log_warning_error(lang, "Error", f"Attempted to make a new text box when disabled, sentence \"{outStr}\" is too long!") - # This tests if the character before the new box is a space, newline, or scroll(?) - elif outStr and (outStr[-1] in (" ", "Ň", "Ş")): - outStr = outStr[:-1] - outStr += "ȼ" # new textbox character - offset = 0 - currLine = 0 - escapeCount += 1 - #print(index) + remaining_pixels = 0 + required_pixels = get_text_pixel_length(out.replace(TOKEN_NEWLINE, '').replace(TOKEN_SCROLL_BREAK, ''), pixelsPerChar, language_char_array, lang, entry_id, context) + overflow_pixels = max(0, required_pixels - remaining_pixels) + if overflow_pixels > 0: + log_warning_error(lang, "Error", f"Attempted to make a new text box when disabled, sentence \"{format_internal_tokens(state.out_text)}\" is too long by at least {overflow_pixels} pixels!", entry_id, context) + else: + extra_lines = max(1, state.current_line_count - (numLines + int(include_scrolling)) + 1) + log_warning_error(lang, "Error", f"Attempted to make a new text box when disabled, sentence \"{format_internal_tokens(state.out_text)}\" requires at least {extra_lines} additional line(s)!", entry_id, context) + elif state.out_text and (state.out_text[-1] in (" ", TOKEN_NEWLINE, TOKEN_SCROLL_BREAK)): + state.out_text = state.out_text[:-1] - - if escapeCount == 100: - log_warning_error(lang, "Error", f"Sentence \"{out}\" is too long!") + state.out_text += TOKEN_BOX_BREAK + state.current_offset = 0 + state.current_line_count = 0 + state.escape_count += 1 - # It's safe to swap the purposeful spaces back - outStr = outStr.replace(PURPOSEFUL_SPACE_CHAR, " ") +def apply_vertical_centering_to_page(page_text, capacity, line_count_override=None): + trailing_newlines = len(page_text) - len(page_text.rstrip(TOKEN_NEWLINE)) + content_page = page_text.rstrip(TOKEN_NEWLINE) + if not content_page: + return page_text + + line_count = line_count_override if line_count_override is not None else (content_page.count(TOKEN_NEWLINE) + 1) + if line_count >= capacity: + return page_text + + top_padding = (capacity - line_count) // 2 + return (TOKEN_NEWLINE * top_padding) + content_page + (TOKEN_NEWLINE * trailing_newlines) + +def count_centering_lines(page_text): + content_page = page_text.rstrip(TOKEN_NEWLINE) + if not content_page: + return 0 + return content_page.count(TOKEN_NEWLINE) + 1 + +def apply_vertical_centering(out_text, numLines, reference_text=None): + centered_boxes = [] + reference_boxes = reference_text.split(TOKEN_BOX_BREAK) if reference_text is not None else None + for box_index, box in enumerate(out_text.split(TOKEN_BOX_BREAK)): + reference_box = None if reference_boxes is None or box_index >= len(reference_boxes) else reference_boxes[box_index] + reference_pages = reference_box.split(TOKEN_SCROLL_BREAK) if reference_box is not None else None + centered_pages = [] + for page_index, page_text in enumerate(box.split(TOKEN_SCROLL_BREAK)): + reference_page = None if reference_pages is None or page_index >= len(reference_pages) else reference_pages[page_index] + line_count_override = None + if reference_page is not None: + reference_line_count = count_centering_lines(reference_page) + if reference_line_count > 0: + line_count_override = reference_line_count + centered_pages.append(apply_vertical_centering_to_page(page_text, numLines, line_count_override)) + centered_boxes.append(TOKEN_SCROLL_BREAK.join(centered_pages)) + return TOKEN_BOX_BREAK.join(centered_boxes) + +def protect_explicit_blank_lines(text): + while TOKEN_NEWLINE + TOKEN_NEWLINE in text: + text = text.replace( + TOKEN_NEWLINE + TOKEN_NEWLINE, + TOKEN_NEWLINE + TOKEN_PRESERVED_BLANK_LINE + TOKEN_NEWLINE, + ) + return text + +def restore_explicit_blank_lines(text): + return text.replace(TOKEN_PRESERVED_BLANK_LINE, "") + +def normalize_formatted_text(out_text, numLines, include_scrolling, lang, entry_id, context=None, vertically_center_text=False): + original_out_text = out_text + out_text = protect_explicit_blank_lines(out_text) + out_text = out_text.replace(f"{TOKEN_NEWLINE}{PURPOSEFUL_SPACE_CHAR}", TOKEN_NEWLINE) + out_text = out_text.replace(f"{TOKEN_SCROLL_BREAK}{PURPOSEFUL_SPACE_CHAR}", TOKEN_SCROLL_BREAK) + out_text = out_text.replace(PURPOSEFUL_SPACE_CHAR, " ") - # Some cases that should be fixed exitLoop = False while(not exitLoop): newStr = "" - splitBoxes = outStr.split('ȼ') + splitBoxes = out_text.split(TOKEN_BOX_BREAK) outIndex = 0 for box in splitBoxes: if box and ((box[0] == " ")): box = box[1:] outIndex += 1 - # Make sure both kinds of newlines are being accounted for - box = box.replace('Ş', 'Ň') - splitLines = box.split('Ň') + box = box.replace(TOKEN_SCROLL_BREAK, TOKEN_NEWLINE) + leading_newlines = len(box) - len(box.lstrip(TOKEN_NEWLINE)) + splitLines = box.split(TOKEN_NEWLINE) outBox = "" i = 1 for split in splitLines: @@ -441,50 +707,140 @@ def convert_item(ogDict, lang): if split == splitLines[-1]: breakChar = "" elif ((i >= numLines) and include_scrolling): - breakChar = 'Ş' + breakChar = TOKEN_SCROLL_BREAK else: - breakChar = outStr[outIndex] + breakChar = out_text[outIndex] outBox += split + breakChar outIndex += 1 i += 1 - if (outBox and (outBox[:-1] == 'ȼ') or (outBox[:-1] == 'Ň')): - newStr += f'{outBox[:-1]}ȼ' + if leading_newlines: + existing_leading_newlines = len(outBox) - len(outBox.lstrip(TOKEN_NEWLINE)) + if existing_leading_newlines < leading_newlines: + outBox = (TOKEN_NEWLINE * (leading_newlines - existing_leading_newlines)) + outBox + if (outBox and (outBox[:-1] == TOKEN_BOX_BREAK) or (outBox[:-1] == TOKEN_NEWLINE)): + newStr += f'{outBox[:-1]}{TOKEN_BOX_BREAK}' elif (outBox): - newStr += f'{outBox}ȼ' - newStr = newStr[:-1] # remove the last ȼ + newStr += f'{outBox}{TOKEN_BOX_BREAK}' + newStr = newStr[:-1] if len(newStr) > 1023: newStr = newStr[:1023] - log_warning_error(lang, "Warning", f"String {newStr} exceeds character limit of 1023 and has been truncated.") + log_warning_error(lang, "Warning", f"String {newStr} exceeds character limit of 1023 and has been truncated.", entry_id, context) - exitLoop = (newStr == outStr) - outStr = newStr - + exitLoop = (newStr == out_text) + out_text = newStr + if vertically_center_text: + out_text = apply_vertical_centering(out_text, numLines, original_out_text) + return restore_explicit_blank_lines(out_text) + +def encode_formatted_text(out_text, arr, lang, entry_id, context=None): byteStr = "" - arr = charArrayOfLanguage[lang]["array"] i = 0 - while i < len(outStr[:-1]): - char = outStr[i] + while i < len(out_text[:-1]): + char = FORMAT_TOKEN_TO_BYTE_CHAR.get(out_text[i], out_text[i]) if (char == '['): val = '' i += 1 - while outStr[i] != ']': - val = val + outStr[i] + while out_text[i] != ']': + val = val + out_text[i] i += 1 num = int(val) byteStr += f"{num:02x} " else: - byteStr += f"{convert_char_to_byte(ord(char), arr, lang):02x} " + byteStr += f"{convert_char_to_byte(ord(char), arr, lang, entry_id, context):02x} " i += 1 - if (len(outStr) > 0 and outStr[-1] != ' '): # Check if the last char is a space - byteStr += f"{convert_char_to_byte(ord(outStr[-1]), arr, lang):02x} " - - byteStr += "ff" - - ogDict["bytes"] = byteStr + if (len(out_text) > 0 and out_text[-1] != ' '): + byteStr += f"{convert_char_to_byte(ord(FORMAT_TOKEN_TO_BYTE_CHAR.get(out_text[-1], out_text[-1])), arr, lang, entry_id, context):02x} " + + return byteStr + "ff" + +def render_debug_text(byte_string, arr): + byte_values = byte_string.split(" ") + outText = "" + index = 0 + while index < len(byte_values): + byte_value = int(byte_values[index], 16) + if byte_value == 0xFC and index + 1 < len(byte_values): + outText += f"_[{int(byte_values[index + 1], 16)}]" + index += 2 + continue + outText += str(arr[byte_value]) + index += 1 + return outText + +def format_text_entry(ogDict, lang, context=None): + line = ogDict["bytes"] + entry_id = ogDict.get("entryId") + numLines = ogDict["numLines"] + pixelsPerChar = ogDict["pixelsPerChar"] + pixelsInLine = ogDict["pixelsInLine"] + include_box_breaks = ogDict["includeBoxBreaks"] + include_scrolling = ogDict["includeScrolling"] + vertically_center_text = coerce_to_bool(ogDict["verticallyCenterText"]) + + language_char_array = get_language_config(lang).char_array + arr = language_char_array["array"] + escape_list = language_char_array["escape"] + + line = apply_escape_sequences(line, arr, escape_list) + line = apply_language_tokens(line, arr, lang) + line = preserve_punctuation_spacing(line) + + split_sents = split_into_sentences(line) + state = FormatState() + index = 0 + while index < len(split_sents) and state.escape_count < 100: + force_newline_before_center_transition(state, split_sents[index]) + prev_offset = state.current_offset + prev_curr_line = state.current_line_count + state.current_offset, recievedLine, out, state.centered = split_sentence_into_lines( + split_sents[index], state.current_offset, pixelsPerChar, pixelsInLine, + state.centered, lang, state.current_line_count, numLines, entry_id, context + ) + state.current_line_count += recievedLine + + if append_formatted_sentence(state, out, include_scrolling, numLines): + index += 1 + else: + handle_box_overflow( + state, out, numLines, include_scrolling, include_box_breaks, prev_offset, + prev_curr_line, pixelsInLine, pixelsPerChar, language_char_array, lang, entry_id, context + ) + + if state.escape_count == 100: + total_capacity = (numLines + int(include_scrolling)) * pixelsInLine + required_pixels = get_text_pixel_length( + out.replace(TOKEN_NEWLINE, '').replace(TOKEN_SCROLL_BREAK, ''), + pixelsPerChar, + language_char_array, + lang, + entry_id, + context, + ) + overflow_pixels = max(0, required_pixels - total_capacity) + if overflow_pixels > 0: + log_warning_error(lang, "Error", f"Sentence \"{out}\" is too long by at least {overflow_pixels} pixels!", entry_id, context) + else: + log_warning_error(lang, "Error", f"Sentence \"{out}\" requires additional line(s) beyond the available box height!", entry_id, context) + + return normalize_formatted_text( + state.out_text, + numLines, + include_scrolling, + lang, + entry_id, + context, + vertically_center_text, + ) + +def convert_item(ogDict, lang, context=None): + normalized_text = format_text_entry(ogDict, lang, context) + arr = get_language_config(lang).char_array["array"] + entry_id = ogDict.get("entryId") + ogDict["bytes"] = encode_formatted_text(normalized_text, arr, lang, entry_id, context) return ogDict -def write_text_bin_file(filename, dictionary, lang, section): +def write_text_bin_file(filename, dictionary, lang, section, context=None): MAX_BIN_SIZES = { "PTGB": 6144, "RSEFRLG": 3444, @@ -510,7 +866,7 @@ def write_text_bin_file(filename, dictionary, lang, section): # Append every line's binary data to bindata # keep an index of the binary offset within bindata at which each line starts for key, line in dictionary.items(): - dictionary[key] = convert_item(line, lang) + dictionary[key] = convert_item(line, lang, context) # store the offset of the line in the index as a 16 bit little endian value index[num * 2] = (current_offset & 0xFF) index[num * 2 + 1] = (current_offset >> 8) & 0xFF @@ -526,7 +882,7 @@ def write_text_bin_file(filename, dictionary, lang, section): binFile.write(bindata) binFile.seek(0, os.SEEK_END) if binFile.tell() > MAX_BIN_SIZES[section]: - log_warning_error(lang, "Error", f'Section {section} exceeds the max binary file size by {binFile.tell() - MAX_BIN_SIZES[section]} bytes!') + log_warning_error(lang, "Error", f'Section {section} exceeds the max binary file size by {binFile.tell() - MAX_BIN_SIZES[section]} bytes!', context=context) binFile.close() def write_enum_to_header_file(hFile, prefix, dictionary): @@ -567,7 +923,7 @@ def update_xlsx_file(build_xlsx_mode): # If cached file exists, compare hashes if TEXT_XLSX_PATH.exists(): - if hash_excel(NEW_TEXT_XLSX_PATH) == hash_excel(TEXT_XLSX_PATH): + if hash_file_bytes(NEW_TEXT_XLSX_PATH) == hash_file_bytes(TEXT_XLSX_PATH): print("\tDownloaded file is identical. Skipping parse.") NEW_TEXT_XLSX_PATH.unlink() return False @@ -603,13 +959,15 @@ def are_text_build_artifacts_newer(): return True def initialize_translation_storage(): - mainDict.clear() - for lang in Languages: - mainDict[lang.name] = {section: {} for section in textSections} - mainDict[lang.name]["Warnings"] = {} - mainDict[lang.name]["Errors"] = {} + build_context.initialize_storage(textSections) def transfer_xlsx_to_dict(): + global boxTypeDefinitions + global boxTypeNames + global boxTypeIdByName + global boxTypeValueKeys + global boxTypeValueMeta + print("\tGetting character arrays") currSheet = pd.read_excel(TEXT_XLSX_PATH, sheet_name="Character Arrays", header=None) offset = 0 @@ -627,10 +985,85 @@ def transfer_xlsx_to_dict(): print("\tGetting string data") currSheet = pd.read_excel(TEXT_XLSX_PATH, sheet_name="Translations") + sheet_columns = list(currSheet.columns) + + print("\tGetting box types") + boxTypeSheet = pd.read_excel(TEXT_XLSX_PATH, sheet_name="Box Types") + box_type_columns = list(boxTypeSheet.columns) + box_type_name_col = None + for col in box_type_columns: + if normalize_box_type_header(col) == "boxtype": + box_type_name_col = col + break + if box_type_name_col is None: + raise KeyError("Could not find 'Box Type' column in Box Types sheet.") + + boxTypeValueKeys = [] + boxTypeValueMeta = [] + box_type_columns_by_normalized = {} + for col in box_type_columns: + if col == box_type_name_col: + continue + normalized = normalize_box_type_header(col) + if normalized in box_type_columns_by_normalized: + raise KeyError(f"Duplicate normalized Box Types column '{normalized}' found.") + box_type_columns_by_normalized[normalized] = col + boxTypeValueKeys.append(col) + boxTypeValueMeta.append({"key": col, "macro_name": str(col)}) + + boxTypeDefinitions = {} + boxTypeNames = [] + boxTypeIdByName = {} + for _, box_type_row in boxTypeSheet.iterrows(): + box_type_name = box_type_row[box_type_name_col] + if pd.isna(box_type_name): + continue + box_type_name = str(box_type_name).strip() + if box_type_name in boxTypeDefinitions: + raise KeyError(f"Duplicate Box Type '{box_type_name}' found in Box Types sheet.") + boxTypeDefinitions[box_type_name] = {} + for col in boxTypeValueKeys: + value = box_type_row[col] + if normalize_box_type_header(col) == "pixelsperchar" and pd.isna(value): + value = "Default" + boxTypeDefinitions[box_type_name][col] = value + + required_keys = ( + "numLines", + "pixelsPerChar", + "pixelsInLine", + "includeBoxBreaks", + "includeScrolling", + "boxStyle", + ) + for internal_key in required_keys: + col = find_required_box_type_column(box_type_columns_by_normalized, internal_key) + if col is None: + raise KeyError(f"Missing required Box Types column matching '{internal_key}'.") + boxTypeDefinitions[box_type_name][internal_key] = boxTypeDefinitions[box_type_name][col] + vertical_center_col = find_required_box_type_column(box_type_columns_by_normalized, "verticallyCenterText") + if vertical_center_col is None: + raise KeyError("Missing required Box Types column matching 'verticallyCenterText'.") + boxTypeDefinitions[box_type_name]["verticallyCenterText"] = int( + coerce_to_bool(boxTypeDefinitions[box_type_name][vertical_center_col]) + ) + boxTypeIdByName[box_type_name] = len(boxTypeNames) + boxTypeNames.append(box_type_name) + + text_section_col = find_column_by_aliases(sheet_columns, ("Text Section",)) + text_key_col = find_column_by_aliases(sheet_columns, ("Text Key", "Text ID", "Key")) + box_type_col = find_column_by_aliases(sheet_columns, ("Box Type",)) + entry_id_col = sheet_columns[0] + + language_columns = { + lang: find_column_by_aliases(sheet_columns, get_language_config(lang).column_aliases) + for lang in Languages + } + english_col = language_columns[Languages.English] textSections.clear() for row in currSheet.iterrows(): - currRow = row[1]["Text Section"] + currRow = row[1][text_section_col] if (currRow not in textSections): textSections.append(currRow) @@ -640,17 +1073,23 @@ def transfer_xlsx_to_dict(): #print(row) for lang in Languages: currRow = row[1] - #print(currRow) - offset = lang.value - if (pd.isna(currRow.iloc[FIRST_TRANSLATION_COL_INDEX + lang.value])): - offset = Languages.English.value - mainDict[lang.name][currRow.iloc[1]][currRow.iloc[2]] = {"bytes": currRow.iloc[FIRST_TRANSLATION_COL_INDEX + offset], - "numLines": currRow.iloc[3], - "pixelsPerChar": currRow.iloc[4], - "pixelsInLine" : currRow.iloc[5], - "includeBoxBreaks": currRow.iloc[6], - "includeScrolling": currRow.iloc[7], - } + lang_col = language_columns[lang] + text_value = currRow[lang_col] + if pd.isna(text_value): + text_value = currRow[english_col] + box_type_name = currRow[box_type_col] + if pd.isna(box_type_name): + raise KeyError(f"Missing Box Type for row key '{currRow[text_key_col]}' in section '{currRow[text_section_col]}'.") + box_type_name = str(box_type_name).strip() + box_type_data = boxTypeDefinitions.get(box_type_name) + if box_type_data is None: + raise KeyError( + f"Unknown Box Type '{box_type_name}' for row key '{currRow[text_key_col]}' " + f"in section '{currRow[text_section_col]}'." + ) + entry = {"bytes": text_value, "boxType": box_type_name, "entryId": currRow[entry_id_col]} + entry.update(box_type_data) + mainDict[lang.name][currRow[text_section_col]][currRow[text_key_col]] = entry def generate_header_file(): print("\tGenerating header file") @@ -676,7 +1115,30 @@ def generate_header_file(): hFile.write("\t" + str(end) + ",\n") hFile.write("};\n\n") + hFile.write("#define BOX_TYPE_INVALID 0xFF\n") + for box_type_name in boxTypeNames: + box_type_id = boxTypeIdByName[box_type_name] + hFile.write(f"#define BOX_TYPE_{sanitize_macro_token(box_type_name)} {box_type_id}\n") + hFile.write(f"#define NUM_BOX_TYPES {len(boxTypeNames)}\n\n") + for index, meta in enumerate(boxTypeValueMeta): + hFile.write(f"#define BOX_TYPE_VAL_{sanitize_macro_token(meta['macro_name'])} {index}\n") + hFile.write(f"#define NUM_BOX_TYPE_VALS {len(boxTypeValueMeta)}\n\n") + hFile.write("const int box_type_info[NUM_BOX_TYPES][NUM_BOX_TYPE_VALS] = {\n") + for box_type_name in boxTypeNames: + boxType = boxTypeDefinitions[box_type_name] + values = [] + for meta in boxTypeValueMeta: + key = meta["key"] + value = boxType[key] + if key in ("includeBoxBreaks", "includeScrolling", "boxStyle"): + value = int(value) + values.append(str(value)) + hFile.write(f"\t{{{', '.join(values)}}},\n") + hFile.write("};\n\n") + hFile.write("const u8* get_compressed_text_table(int table_index);\n") + hFile.write("u8 get_text_box_type(int table_index, int text_index);\n") + hFile.write("extern const u8* const text_box_type_tables[NUM_TEXT_SECTIONS];\n") hFile.write("\n#endif") @@ -687,7 +1149,7 @@ def generate_text_tables(): for lang in Languages: for section in textSections: table_file = os.curdir + '/to_compress/' + section + '_' + lang.name.lower() + '.bin' - write_text_bin_file(table_file, mainDict[lang.name][section], lang, section) + write_text_bin_file(table_file, mainDict[lang.name][section], lang, section, build_context) def generate_cpp_file(): print("\tGenerating cpp file") @@ -698,6 +1160,22 @@ def generate_cpp_file(): for section in textSections: cppFile.write("#include \"" + section.upper() + "_" + lang.name.lower() + "_lz10_bin.h\"\n") + cppFile.write("\n") + for section in textSections: + section_var = sanitize_c_identifier(section) + box_type_macros = [] + for _, entry in mainDict[Languages.English.name][section].items(): + box_type_name = entry["boxType"] + box_type_macros.append(f"\n\tBOX_TYPE_{sanitize_macro_token(box_type_name)}") + cppFile.write(f"\nstatic const u8 {section_var}_box_types[] = {{") + cppFile.write(",".join(box_type_macros)) + cppFile.write("\n};\n") + + cppFile.write("\nextern const u8* const text_box_type_tables[NUM_TEXT_SECTIONS] = {") + for section in textSections: + section_var = sanitize_c_identifier(section) + cppFile.write(f"\n\t{section_var}_box_types,") + cppFile.write("\n};\n") cppFile.write("\nconst u8* get_compressed_text_table(int table_index)\n") @@ -706,7 +1184,7 @@ def generate_cpp_file(): cppFile.write("{\n") cppFile.write("\tswitch (table_index)\n\t{\n") for section in textSections: - cppFile.write("\tcase(" + section + "_INDEX):\n") + cppFile.write("\tcase (" + section + "_INDEX):\n") if(section == "PTGB"): cppFile.write("\tdefault:\n") cppFile.write("\t\treturn " + section + "_" + lang.name.lower() + "_lz10_bin;\n") @@ -715,21 +1193,35 @@ def generate_cpp_file(): cppFile.write("}\n") cppFile.write(f"#else\n#error \"Unsupported PTGB_BUILD_LANGUAGE\"\n#endif") + cppFile.write("\n\nu8 get_text_box_type(int table_index, int text_index)\n") + cppFile.write("{\n") + cppFile.write("\tif (text_index < 0)\n") + cppFile.write("\t\treturn BOX_TYPE_INVALID;\n") + cppFile.write("\tswitch (table_index)\n") + cppFile.write("\t{\n") + for section in textSections: + section_var = sanitize_c_identifier(section) + cppFile.write(f"\tcase({section}_INDEX):\n") + cppFile.write(f"\t\tif (text_index >= {section}_LENGTH)\n") + cppFile.write("\t\t\treturn BOX_TYPE_INVALID;\n") + cppFile.write(f"\t\treturn {section_var}_box_types[text_index];\n") + cppFile.write("\tdefault:\n") + cppFile.write("\t\treturn BOX_TYPE_INVALID;\n") + cppFile.write("\t}\n") + cppFile.write("}\n") + def output_json_file(): print("\tOutputting json file") for lang in Languages: for section in textSections: for item in mainDict[lang.name][section]: - string = mainDict[lang.name][section][item]["bytes"].split(" ") - outText = "" - arr = charArrayOfLanguage[lang]["array"] - for byte in string: - byte = arr[int(byte, 16)] - outText += str(byte) - mainDict[lang.name][section][item]["text"] = outText + arr = get_language_config(lang).char_array["array"] + mainDict[lang.name][section][item]["text"] = render_debug_text( + mainDict[lang.name][section][item]["bytes"], arr + ) - with open(OUTPUT_JSON_PATH, 'w') as jsonFile: - jsonFile.write(json.dumps(mainDict)) + with open(OUTPUT_JSON_PATH, 'w', encoding='utf-8') as jsonFile: + jsonFile.write(json.dumps(mainDict, ensure_ascii=False, indent=2)) def are_generated_files_stale(source_files, generated_files): source_paths = [Path(path) for path in source_files] @@ -871,7 +1363,7 @@ def generate_tables(): globalX = x + (charX * tilesPerCharX * pixelsPerTileX) globalY = 0 + (charY * tilesPerCharY * pixelsPerTileY) #print(f'x: {globalX}, y: {globalY}') - if (pixels[globalY][globalX] == BACKGROUND_PAL_INDEX): + if (pixels[globalY][globalX] == BG_PAL_INDEX): myFont.charWidthTable[(charY * charsPerChartX) + charX] = x break @@ -922,8 +1414,8 @@ def main(): _, _, build_xlsx_mode = parse_build_args(sys.argv) print("Running text_helper:") update_font_files() - xlsx_changed = update_xlsx_file(build_xlsx_mode) - if not xlsx_changed and are_text_build_artifacts_newer(): + update_xlsx_file(build_xlsx_mode) + if are_text_build_artifacts_newer(): print("text_helper finished!\n") return transfer_xlsx_to_dict() diff --git a/tools/text_helper/test_regression.py b/tools/text_helper/test_regression.py new file mode 100644 index 0000000..7b0a569 --- /dev/null +++ b/tools/text_helper/test_regression.py @@ -0,0 +1,178 @@ +import importlib.util +import sys +import types +import unittest +from pathlib import Path + + +sys.modules.setdefault("debugpy", types.SimpleNamespace()) +sys.modules.setdefault( + "pandas", + types.SimpleNamespace( + isna=lambda value: value is None, + util=types.SimpleNamespace(hash_pandas_object=lambda *args, **kwargs: types.SimpleNamespace(values=b"")) + ), +) + + +MODULE_PATH = Path(__file__).resolve().parent / "main.py" +SPEC = importlib.util.spec_from_file_location("text_helper_main", MODULE_PATH) +text_helper = importlib.util.module_from_spec(SPEC) +TEXT_HELPER_IMPORT_ERROR = None +try: + SPEC.loader.exec_module(text_helper) +except ModuleNotFoundError as exc: + TEXT_HELPER_IMPORT_ERROR = exc + + +def install_test_charset(): + arr = [" "] * 0x100 + for codepoint in range(32, 127): + arr[codepoint] = chr(codepoint) + arr[0x5F] = " " + arr[0x01] = "l" + arr[0x02] = "ρ" + arr[0x03] = "№" + arr[0xFC] = "_" + arr[0xFB] = "Ş" + arr[0xFD] = "ȼ" + arr[0xFE] = "Ň" + arr[0xFF] = "ƞ" + + widths = [8] * 0x100 + language_config = text_helper.get_language_config(text_helper.Languages.English) + language_config.token_indexes = (0x01, 0x02, 0x03) + language_config.char_array["array"] = arr + language_config.char_array["font"].charWidthTable = widths + language_config.char_array["escape"] = [ + ["{SCL}", [0xFA]], + ["{CLR}", [0xFB]], + ["{DEF}", [0xFC, 0x01, 0x02]], + ["{FEM}", [0xFC, 0x01, 0x04]], + ["{FPC}", [0xFC, 0x01, 0x06]], + ["{MLE}", [0xFC, 0x01, 0x08]], + ["{SPA}", [0xFC]], + ["{PLR}", [0xFD, 0x01]], + ["{NEW}", [0xFE]], + ["{END}", [0xFF]], + ] + + +def decode_text(byte_string, lang): + arr = text_helper.get_language_config(lang).char_array["array"] + text = text_helper.render_debug_text(byte_string, arr) + return text.removesuffix(str(arr[0xFF])) + + +@unittest.skipIf(TEXT_HELPER_IMPORT_ERROR is not None, f"text_helper dependencies missing: {TEXT_HELPER_IMPORT_ERROR}") +class TextHelperRegressionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + install_test_charset() + text_helper.build_context.initialize_storage([]) + + def make_entry(self, text, **overrides): + entry = { + "bytes": text, + "entryId": overrides.pop("entryId", "test::entry"), + "numLines": 2, + "pixelsPerChar": 8, + "pixelsInLine": 208, + "includeBoxBreaks": 1, + "includeScrolling": 0, + "verticallyCenterText": 0, + } + entry.update(overrides) + return entry + + def convert_text(self, text, **overrides): + entry = self.make_entry(text, **overrides) + return text_helper.convert_item(entry, text_helper.Languages.English, text_helper.build_context) + + def test_centered_text_renders_offsets_readably(self): + entry = self.convert_text("{CTR}Connecting to Game Boy.") + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertIn("_[", text) + self.assertIn("Connecting to Game Boy.", text) + + def test_centered_multi_sentence_text_keeps_second_sentence_at_line_start(self): + entry = self.convert_text("{CTR}Alpha. Beta.") + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertNotIn("._[", text) + self.assertRegex(text, r"Alpha\.Ň_\[\d+\]Beta\.") + + def test_center_tag_mid_text_forces_newline_before_centered_block(self): + entry = self.convert_text("Alpha {CTR}Beta.") + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertRegex(text, r"AlphaŇ_\[\d+\]Beta\.") + + def test_terminal_center_close_does_not_append_newline(self): + entry = self.convert_text("{CTR}PUSH THE START BUTTON!{nCTR}") + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertRegex(text, r"^_\[\d+\]PUSH THE START BUTTON!$") + + def test_terminal_newline_before_center_close_is_ignored(self): + entry = self.convert_text("{CTR}PUSH THE START BUTTON!{NEW}{nCTR}", numLines=1, includeBoxBreaks=0) + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertRegex(text, r"^_\[\d+\]PUSH THE START BUTTON!$") + + def test_newline_removes_leading_space_on_following_line(self): + entry = self.convert_text("Thanks.{NEW} Again.") + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertNotIn("Ň ", text) + + def test_level_token_resolves_before_encoding(self): + entry = self.convert_text("Reach {LVL} 5.") + text = decode_text(entry["bytes"], text_helper.Languages.English) + lvl_index, _, _ = text_helper.get_language_config(text_helper.Languages.English).token_indexes + expected_token = text_helper.get_language_config(text_helper.Languages.English).char_array["array"][lvl_index] + self.assertEqual(text, f"Reach {expected_token} 5.") + self.assertNotIn("{LVL}", text) + + def test_vertical_centering_uses_box_type_flag(self): + entry = self.convert_text( + "Line one.{NEW}Line two.", + numLines=5, + includeScrolling=0, + includeBoxBreaks=1, + verticallyCenterText=1, + ) + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertEqual(text, "ŇLine one.ŇLine two.") + + def test_vertical_centering_in_eight_line_box_uses_two_top_lines_for_four_line_block(self): + entry = self.convert_text( + "{CTR}Line one{NEW}{NEW}Line three{NEW}Line four{nCTR}", + numLines=8, + includeScrolling=0, + includeBoxBreaks=0, + verticallyCenterText=1, + ) + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertTrue(text.startswith("ŇŇ_[")) + + def test_explicit_blank_line_counts_toward_vertical_centering(self): + entry = self.convert_text( + "{CTR}Top{NEW}{NEW}Bottom{nCTR}", + numLines=8, + includeScrolling=0, + includeBoxBreaks=0, + verticallyCenterText=1, + ) + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertTrue(text.startswith("ŇŇ_[")) + + def test_explicit_blank_line_is_preserved_after_centering(self): + entry = self.convert_text( + "{CTR}Top{NEW}{NEW}Bottom{nCTR}", + numLines=8, + includeScrolling=0, + includeBoxBreaks=0, + verticallyCenterText=1, + ) + text = decode_text(entry["bytes"], text_helper.Languages.English) + self.assertRegex(text, r"_\[\d+\]TopŇŇ_\[\d+\]Bottom") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/text_helper/text.xlsx b/tools/text_helper/text.xlsx index 31a8f46..3d0ca48 100644 Binary files a/tools/text_helper/text.xlsx and b/tools/text_helper/text.xlsx differ