├── .gitattributes ├── FFTacticsFix ├── includes │ ├── logger.h │ ├── config.h │ ├── Memory.h │ ├── MinHook.h │ └── ini.h ├── framework.h ├── logger.cpp ├── FFTacticsFix.vcxproj.filters ├── FFTacticsFix.filters ├── Memory.cpp ├── FFTacticsFix.vcxproj └── dllmain.cpp ├── .gitmodules ├── README.md ├── FFTacticsFix.sln └── .gitignore /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /FFTacticsFix/includes/logger.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | bool InitializeLogger(HMODULE gameModule, std::filesystem::path sExePath); -------------------------------------------------------------------------------- /FFTacticsFix/framework.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers 4 | // Windows Header Files 5 | #include 6 | -------------------------------------------------------------------------------- /FFTacticsFix/includes/config.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct GameConfig 4 | { 5 | bool PreferMovies = false; 6 | bool DisableFilter = false; 7 | int RenderScale = 4; 8 | }; 9 | 10 | extern GameConfig Config; -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "external/minhook"] 2 | path = external/minhook 3 | url = https://github.com/TsudaKageyu/minhook.git 4 | [submodule "external/spdlog"] 5 | path = external/spdlog 6 | url = https://github.com/gabime/spdlog 7 | -------------------------------------------------------------------------------- /FFTacticsFix/includes/Memory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace Memory 7 | { 8 | void DetourFunction(uint64_t target, LPVOID detour, LPVOID* ppOriginal); 9 | uintptr_t PatternScanBasic(uintptr_t beg, uintptr_t end, uint8_t* str, uintptr_t len); 10 | uint8_t* PatternScan(void* module, const char* signature); 11 | }; -------------------------------------------------------------------------------- /FFTacticsFix/logger.cpp: -------------------------------------------------------------------------------- 1 | #include "spdlog/spdlog.h" 2 | #include "spdlog/sinks/basic_file_sink.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #define LOG_FORMAT_PREFIX "[%Y-%m-%d %H:%M:%S.%e] [FFTacticsFix] [%l]" 10 | 11 | std::shared_ptr logger; 12 | 13 | bool InitializeLogger(HMODULE gameModule, std::filesystem::path sExePath) 14 | { 15 | try 16 | { 17 | logger = spdlog::basic_logger_mt("FFTacticsFix", "scripts\\FFTacticsFix.log", true); 18 | logger->set_level(spdlog::level::debug); 19 | logger->flush_on(spdlog::level::debug); 20 | spdlog::set_default_logger(logger); 21 | spdlog::set_pattern(LOG_FORMAT_PREFIX ": %v"); 22 | spdlog::info("Plugin loaded."); 23 | } 24 | catch (const spdlog::spdlog_ex& ex) { 25 | return false; 26 | } 27 | 28 | return true; 29 | } -------------------------------------------------------------------------------- /FFTacticsFix/FFTacticsFix.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | includes 12 | 13 | 14 | includes 15 | 16 | 17 | includes 18 | 19 | 20 | includes 21 | 22 | 23 | 24 | 25 | 26 | {ee8f53eb-6716-4579-bb3d-9e59d754173a} 27 | 28 | 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FFTacticsFix 2 | A plugin that aims to provide additional options and fix issues with Final Fantasy Tactics: The Ivalice Chronicles on PC. 3 | 4 | ## Features 5 | - [x] Remove grain filter 6 | - [x] Play animated cutscene videos in place of the in-game cutscenes 7 | - [x] Increased rendering resolution 8 | - [x] Ultrawide support 9 | - [ ] Increase framerate 10 | 11 | ## Installation 12 | [Download](https://github.com/cipherxof/FFTacticsFix/releases) and extract the zip to the root of your game directory. 13 | 14 | image 15 | 16 | ## Configuration 17 | 18 | scripts/FFTacticsFix.ini 19 | 20 | ```ini 21 | [Settings] 22 | RenderScale = 4 # 4 is the default. 10 is 4k 23 | PreferMovies = 1 # Play movies instead of cutscenes 24 | DisableFilter = 1 # Disable the grain filter 25 | ``` 26 | 27 | *Ultrawide users must launch their game in borderless windowed mode with your preferred ultrawide resolution. Changing resolutions after launch will not work** 28 | 29 | ## Steam Deck / Linux 30 | 31 | Use the following launch options 32 | 33 | ```bash 34 | `WINEDLLOVERRIDES="wininet,winhttp=n,b" %command%` 35 | ``` 36 | 37 | ## Before/After (Filter Removed/Increased Resolution/Ultrawide) 38 | 39 | ![ultrawide](https://github.com/user-attachments/assets/4ff92e18-cf6e-4ef3-84ad-164fa4f05638) 40 | 41 | -------------------------------------------------------------------------------- /FFTacticsFix/FFTacticsFix.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | Header Files 26 | 27 | 28 | Header Files 29 | 30 | 31 | 32 | 33 | Source Files 34 | 35 | 36 | Source Files 37 | 38 | 39 | -------------------------------------------------------------------------------- /FFTacticsFix.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.7.34031.279 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FFTacticsFix", "FFTacticsFix\FFTacticsFix.vcxproj", "{FE4A0B03-4DC5-4685-8D43-05F8C481C981}" 7 | EndProject 8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libMinHook", "external\minhook\build\VC17\libMinHook.vcxproj", "{F142A341-5EE0-442D-A15F-98AE9B48DBAE}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|x64 = Debug|x64 13 | Debug|x86 = Debug|x86 14 | Release|x64 = Release|x64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Debug|x64.ActiveCfg = Debug|x64 19 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Debug|x64.Build.0 = Debug|x64 20 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Debug|x86.ActiveCfg = Debug|Win32 21 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Debug|x86.Build.0 = Debug|Win32 22 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Release|x64.ActiveCfg = Release|x64 23 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Release|x64.Build.0 = Release|x64 24 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Release|x86.ActiveCfg = Release|Win32 25 | {FE4A0B03-4DC5-4685-8D43-05F8C481C981}.Release|x86.Build.0 = Release|Win32 26 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x64.ActiveCfg = Debug|x64 27 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x64.Build.0 = Debug|x64 28 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x86.ActiveCfg = Debug|Win32 29 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Debug|x86.Build.0 = Debug|Win32 30 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x64.ActiveCfg = Release|x64 31 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x64.Build.0 = Release|x64 32 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x86.ActiveCfg = Release|Win32 33 | {F142A341-5EE0-442D-A15F-98AE9B48DBAE}.Release|x86.Build.0 = Release|Win32 34 | EndGlobalSection 35 | GlobalSection(SolutionProperties) = preSolution 36 | HideSolutionNode = FALSE 37 | EndGlobalSection 38 | GlobalSection(ExtensibilityGlobals) = postSolution 39 | SolutionGuid = {B125DC41-92C1-4083-A6F3-40781EC209D8} 40 | EndGlobalSection 41 | EndGlobal 42 | -------------------------------------------------------------------------------- /FFTacticsFix/Memory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "Memory.h" 7 | #include "MinHook.h" 8 | 9 | void Memory::DetourFunction(uint64_t target, LPVOID detour, LPVOID* ppOriginal) 10 | { 11 | int error = 0; 12 | if (error = MH_CreateHook((LPVOID)target, detour, ppOriginal) != 0) 13 | { 14 | return; 15 | } 16 | MH_EnableHook((LPVOID)target); 17 | } 18 | 19 | uintptr_t Memory::PatternScanBasic(uintptr_t beg, uintptr_t end, uint8_t* str, uintptr_t len) 20 | { 21 | for (uintptr_t ptr = beg; ptr < end - len; ++ptr) 22 | { 23 | if (0 == memcmp((const void*)ptr, str, len)) 24 | return ptr; 25 | ptr++; 26 | } 27 | 28 | return 0; 29 | } 30 | 31 | // CSGOSimple's pattern scan 32 | // https://github.com/OneshotGH/CSGOSimple-master/blob/master/CSGOSimple/helpers/utils.cpp 33 | uint8_t* Memory::PatternScan(void* module, const char* signature) 34 | { 35 | static auto pattern_to_byte = [](const char* pattern) { 36 | auto bytes = std::vector{}; 37 | auto start = const_cast(pattern); 38 | auto end = const_cast(pattern) + strlen(pattern); 39 | 40 | for (auto current = start; current < end; ++current) { 41 | if (*current == '?') { 42 | ++current; 43 | if (*current == '?') 44 | ++current; 45 | bytes.push_back(-1); 46 | } 47 | else { 48 | bytes.push_back(strtoul(current, ¤t, 16)); 49 | } 50 | } 51 | return bytes; 52 | }; 53 | 54 | auto dosHeader = (PIMAGE_DOS_HEADER)module; 55 | auto ntHeaders = (PIMAGE_NT_HEADERS)((std::uint8_t*)module + dosHeader->e_lfanew); 56 | 57 | auto sizeOfImage = ntHeaders->OptionalHeader.SizeOfImage; 58 | auto patternBytes = pattern_to_byte(signature); 59 | auto scanBytes = reinterpret_cast(module); 60 | 61 | auto s = patternBytes.size(); 62 | auto d = patternBytes.data(); 63 | 64 | for (auto i = 0ul; i < sizeOfImage - s; ++i) { 65 | bool found = true; 66 | for (auto j = 0ul; j < s; ++j) { 67 | if (scanBytes[i + j] != d[j] && d[j] != -1) { 68 | found = false; 69 | break; 70 | } 71 | } 72 | if (found) { 73 | return &scanBytes[i]; 74 | } 75 | } 76 | return nullptr; 77 | } -------------------------------------------------------------------------------- /FFTacticsFix/includes/MinHook.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MinHook - The Minimalistic API Hooking Library for x64/x86 3 | * Copyright (C) 2009-2017 Tsuda Kageyu. 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions 8 | * are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright 11 | * notice, this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 | * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 18 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 19 | * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 20 | * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 21 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 22 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 23 | * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | #pragma once 30 | 31 | #if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__) 32 | #error MinHook supports only x86 and x64 systems. 33 | #endif 34 | 35 | #include 36 | 37 | // MinHook Error Codes. 38 | typedef enum MH_STATUS 39 | { 40 | // Unknown error. Should not be returned. 41 | MH_UNKNOWN = -1, 42 | 43 | // Successful. 44 | MH_OK = 0, 45 | 46 | // MinHook is already initialized. 47 | MH_ERROR_ALREADY_INITIALIZED, 48 | 49 | // MinHook is not initialized yet, or already uninitialized. 50 | MH_ERROR_NOT_INITIALIZED, 51 | 52 | // The hook for the specified target function is already created. 53 | MH_ERROR_ALREADY_CREATED, 54 | 55 | // The hook for the specified target function is not created yet. 56 | MH_ERROR_NOT_CREATED, 57 | 58 | // The hook for the specified target function is already enabled. 59 | MH_ERROR_ENABLED, 60 | 61 | // The hook for the specified target function is not enabled yet, or already 62 | // disabled. 63 | MH_ERROR_DISABLED, 64 | 65 | // The specified pointer is invalid. It points the address of non-allocated 66 | // and/or non-executable region. 67 | MH_ERROR_NOT_EXECUTABLE, 68 | 69 | // The specified target function cannot be hooked. 70 | MH_ERROR_UNSUPPORTED_FUNCTION, 71 | 72 | // Failed to allocate memory. 73 | MH_ERROR_MEMORY_ALLOC, 74 | 75 | // Failed to change the memory protection. 76 | MH_ERROR_MEMORY_PROTECT, 77 | 78 | // The specified module is not loaded. 79 | MH_ERROR_MODULE_NOT_FOUND, 80 | 81 | // The specified function is not found. 82 | MH_ERROR_FUNCTION_NOT_FOUND 83 | } 84 | MH_STATUS; 85 | 86 | // Can be passed as a parameter to MH_EnableHook, MH_DisableHook, 87 | // MH_QueueEnableHook or MH_QueueDisableHook. 88 | #define MH_ALL_HOOKS NULL 89 | 90 | #ifdef __cplusplus 91 | extern "C" { 92 | #endif 93 | 94 | // Initialize the MinHook library. You must call this function EXACTLY ONCE 95 | // at the beginning of your program. 96 | MH_STATUS WINAPI MH_Initialize(VOID); 97 | 98 | // Uninitialize the MinHook library. You must call this function EXACTLY 99 | // ONCE at the end of your program. 100 | MH_STATUS WINAPI MH_Uninitialize(VOID); 101 | 102 | // Creates a Hook for the specified target function, in disabled state. 103 | // Parameters: 104 | // pTarget [in] A pointer to the target function, which will be 105 | // overridden by the detour function. 106 | // pDetour [in] A pointer to the detour function, which will override 107 | // the target function. 108 | // ppOriginal [out] A pointer to the trampoline function, which will be 109 | // used to call the original target function. 110 | // This parameter can be NULL. 111 | MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID* ppOriginal); 112 | 113 | // Creates a Hook for the specified API function, in disabled state. 114 | // Parameters: 115 | // pszModule [in] A pointer to the loaded module name which contains the 116 | // target function. 117 | // pszTarget [in] A pointer to the target function name, which will be 118 | // overridden by the detour function. 119 | // pDetour [in] A pointer to the detour function, which will override 120 | // the target function. 121 | // ppOriginal [out] A pointer to the trampoline function, which will be 122 | // used to call the original target function. 123 | // This parameter can be NULL. 124 | MH_STATUS WINAPI MH_CreateHookApi( 125 | LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID* ppOriginal); 126 | 127 | // Creates a Hook for the specified API function, in disabled state. 128 | // Parameters: 129 | // pszModule [in] A pointer to the loaded module name which contains the 130 | // target function. 131 | // pszTarget [in] A pointer to the target function name, which will be 132 | // overridden by the detour function. 133 | // pDetour [in] A pointer to the detour function, which will override 134 | // the target function. 135 | // ppOriginal [out] A pointer to the trampoline function, which will be 136 | // used to call the original target function. 137 | // This parameter can be NULL. 138 | // ppTarget [out] A pointer to the target function, which will be used 139 | // with other functions. 140 | // This parameter can be NULL. 141 | MH_STATUS WINAPI MH_CreateHookApiEx( 142 | LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID* ppOriginal, LPVOID* ppTarget); 143 | 144 | // Removes an already created hook. 145 | // Parameters: 146 | // pTarget [in] A pointer to the target function. 147 | MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget); 148 | 149 | // Enables an already created hook. 150 | // Parameters: 151 | // pTarget [in] A pointer to the target function. 152 | // If this parameter is MH_ALL_HOOKS, all created hooks are 153 | // enabled in one go. 154 | MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget); 155 | 156 | // Disables an already created hook. 157 | // Parameters: 158 | // pTarget [in] A pointer to the target function. 159 | // If this parameter is MH_ALL_HOOKS, all created hooks are 160 | // disabled in one go. 161 | MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget); 162 | 163 | // Queues to enable an already created hook. 164 | // Parameters: 165 | // pTarget [in] A pointer to the target function. 166 | // If this parameter is MH_ALL_HOOKS, all created hooks are 167 | // queued to be enabled. 168 | MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget); 169 | 170 | // Queues to disable an already created hook. 171 | // Parameters: 172 | // pTarget [in] A pointer to the target function. 173 | // If this parameter is MH_ALL_HOOKS, all created hooks are 174 | // queued to be disabled. 175 | MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget); 176 | 177 | // Applies all queued changes in one go. 178 | MH_STATUS WINAPI MH_ApplyQueued(VOID); 179 | 180 | // Translates the MH_STATUS to its name as a string. 181 | const char* WINAPI MH_StatusToString(MH_STATUS status); 182 | 183 | #ifdef __cplusplus 184 | } 185 | #endif 186 | 187 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /FFTacticsFix/FFTacticsFix.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 17.0 23 | Win32Proj 24 | {fe4a0b03-4dc5-4685-8d43-05f8c481c981} 25 | FFTacticsFix 26 | 10.0 27 | FFTacticsFix 28 | 29 | 30 | 31 | DynamicLibrary 32 | true 33 | v143 34 | Unicode 35 | 36 | 37 | DynamicLibrary 38 | false 39 | v143 40 | true 41 | Unicode 42 | 43 | 44 | DynamicLibrary 45 | true 46 | v143 47 | Unicode 48 | 49 | 50 | DynamicLibrary 51 | false 52 | v143 53 | true 54 | Unicode 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | .asi 76 | 77 | 78 | .asi 79 | 80 | 81 | 82 | Level3 83 | true 84 | WIN32;_DEBUG;FFTFIX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 85 | true 86 | Use 87 | pch.h 88 | 89 | 90 | Windows 91 | true 92 | false 93 | 94 | 95 | 96 | 97 | Level3 98 | true 99 | true 100 | true 101 | WIN32;NDEBUG;FFTFIX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 102 | true 103 | Use 104 | pch.h 105 | 106 | 107 | Windows 108 | true 109 | true 110 | true 111 | false 112 | 113 | 114 | 115 | 116 | Level3 117 | true 118 | _DEBUG;FFTFIX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 119 | true 120 | NotUsing 121 | pch.h 122 | stdcpplatest 123 | 124 | 125 | Windows 126 | true 127 | false 128 | $(CoreLibraryDependencies);%(AdditionalDependencies);$(SolutionDir)\libMinHook.lib; 129 | 130 | 131 | 132 | 133 | Level3 134 | true 135 | true 136 | true 137 | NDEBUG;FFTFIX_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 138 | true 139 | NotUsing 140 | pch.h 141 | MaxSpeed 142 | false 143 | stdcpplatest 144 | $(ProjectDir)\includes;..\external\spdlog\include; 145 | /utf-8 %(AdditionalOptions) 146 | 147 | 148 | Windows 149 | true 150 | true 151 | true 152 | false 153 | $(CoreLibraryDependencies);%(AdditionalDependencies);Shlwapi.lib;$(SolutionDir)lib\$(Configuration)\libMinHook.x64.lib 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /FFTacticsFix/dllmain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Memory.h" 5 | #include "MinHook.h" 6 | #include "ini.h" 7 | #include "logger.h" 8 | #include "config.h"; 9 | 10 | HMODULE GameModule = 0; 11 | uintptr_t GameBase = 0; 12 | 13 | mINI::INIStructure ConfigValues; 14 | GameConfig Config; 15 | 16 | const int BASE_WIDTH = 1920; 17 | const int BASE_HEIGHT = 1080; 18 | const float BASE_ASPECT = 16.0f / 9.0f; 19 | 20 | int* FBO_W = 0; 21 | int* FBO_H = 0; 22 | float* InternalRenderScale = 0; 23 | float* ClipScale = 0; 24 | uint8_t* MenuState = 0; 25 | uint8_t* MovieType = 0; 26 | int8_t* MovieCurrentId = 0; 27 | uint32_t* CurrentScript = 0; 28 | uint32_t* SkipScriptFlag = 0; 29 | int* m_iScreenW = 0; 30 | int* m_iScreenH = 0; 31 | int* gEventOrBattle = 0; 32 | uintptr_t GraphicsManager = 0; 33 | 34 | std::unordered_map ScriptVideoMap = 35 | { 36 | {6, 9}, // Ovelia's Abduction 37 | {60, 10}, // Blades of Grass 38 | {90, 11}, // Partings 39 | {138, 12}, // Reuinion with Delita 40 | {172, 13}, // Delita's Warning 41 | {255, 14}, // Ovelia and Delita 42 | {345, 15}, // Delita's Will 43 | }; 44 | 45 | inline float GetAspectRatio() 46 | { 47 | if (!m_iScreenW || !m_iScreenH) 48 | return BASE_ASPECT; 49 | 50 | return *m_iScreenW / *m_iScreenH; 51 | } 52 | 53 | inline int GetScaledFBOWidth(float renderScaleFactor) 54 | { 55 | int width = m_iScreenW ? *m_iScreenW : BASE_WIDTH; 56 | int height = m_iScreenH ? *m_iScreenH : BASE_HEIGHT; 57 | 58 | float targetAspect = (float)width / (float)height; 59 | float aspectCorrection = targetAspect <= BASE_ASPECT ? 1.0f : targetAspect / BASE_ASPECT; 60 | return (int)(BASE_WIDTH * aspectCorrection * renderScaleFactor); 61 | } 62 | 63 | inline int GetScaledFBOHeight(float renderScaleFactor) 64 | { 65 | return (int)(BASE_HEIGHT * renderScaleFactor); 66 | } 67 | 68 | typedef __int64 __fastcall InitMovie_t(); 69 | InitMovie_t* InitMovie = 0; 70 | 71 | typedef __int64 __fastcall InitScriptVM_t(); 72 | InitScriptVM_t* InitScriptVM; 73 | __int64 __fastcall InitScriptVM_Hook() 74 | { 75 | auto result = InitScriptVM(); 76 | int scriptId = *CurrentScript; 77 | if (Config.PreferMovies && *MenuState == 0 && ScriptVideoMap.find(scriptId) != ScriptVideoMap.end()) 78 | { 79 | *SkipScriptFlag = 1; 80 | *MovieCurrentId = ScriptVideoMap[scriptId]; 81 | *MovieType = 0; // otherwise black screen after movie 82 | InitMovie(); 83 | } 84 | return result; 85 | } 86 | 87 | typedef char __fastcall SetMovieId_t(); 88 | SetMovieId_t* SetMovieId; 89 | char __fastcall SetMovieId_Hook() 90 | { 91 | char movieId = SetMovieId(); 92 | 93 | if (FBO_W && FBO_H) 94 | { 95 | float factor = Config.RenderScale / 4.0f; 96 | 97 | if (movieId > 0) 98 | { 99 | *FBO_W = factor < 1.0f ? BASE_WIDTH * factor : BASE_WIDTH; 100 | *FBO_H = factor < 1.0f ? BASE_HEIGHT * factor : BASE_HEIGHT; 101 | } 102 | else 103 | { 104 | *FBO_W = GetScaledFBOWidth(factor); 105 | *FBO_H = GetScaledFBOHeight(factor); 106 | } 107 | } 108 | 109 | return movieId; 110 | } 111 | 112 | typedef void __fastcall CFFT_STATE__SetRenderSize_t(__int64 a1, int width, int height); 113 | CFFT_STATE__SetRenderSize_t* CFFT_STATE__SetRenderSize; 114 | void __fastcall CFFT_STATE__SetRenderSize_Hook(__int64 a1, int width, int height) 115 | { 116 | float factor = Config.RenderScale / 4.0f; 117 | *FBO_W = GetScaledFBOWidth(factor); 118 | *FBO_H = GetScaledFBOHeight(factor); 119 | 120 | *InternalRenderScale = (float)Config.RenderScale; 121 | 122 | CFFT_STATE__SetRenderSize(a1, width, height); 123 | 124 | *ClipScale = 1.0f * (*InternalRenderScale / 4.0); 125 | } 126 | 127 | typedef int* __fastcall CalculateViewportWithLetterboxing_t(int* a1, int a2, int a3, char a4); 128 | CalculateViewportWithLetterboxing_t* CalculateViewportWithLetterboxing; 129 | int* __fastcall CalculateViewportWithLetterboxing_Hook(int* outRect, int contentWidth, int contentHeight, char preserveWidth) 130 | { 131 | float currentAspect = GetAspectRatio(); 132 | if (currentAspect <= BASE_ASPECT) 133 | return CalculateViewportWithLetterboxing(outRect, contentWidth, contentHeight, preserveWidth); 134 | 135 | int letterboxOffsetX = 0; 136 | int letterboxOffsetY = 0; 137 | 138 | int screenWidth = *m_iScreenW; 139 | int screenHeight = *m_iScreenH; 140 | 141 | float scale = (float)screenHeight / (float)contentHeight; 142 | 143 | int scaledHeight = (int)((float)contentHeight * scale); 144 | int scaledWidth; 145 | 146 | if (!preserveWidth) 147 | scaledWidth = (int)((float)contentWidth * scale); 148 | else 149 | scaledWidth = screenWidth; 150 | 151 | int viewportX = (screenWidth - scaledWidth) / 2 + letterboxOffsetX; 152 | int viewportY = (screenHeight - scaledHeight) / 2 + letterboxOffsetY; 153 | 154 | outRect[0] = viewportX; // left 155 | outRect[1] = viewportY; // top 156 | outRect[2] = viewportX + scaledWidth; // right 157 | outRect[3] = viewportY + scaledHeight; // bottom 158 | 159 | return outRect; 160 | } 161 | 162 | typedef char __fastcall UILayerUpdate_t(__int64 layer); 163 | UILayerUpdate_t* UILayerUpdate; 164 | char __fastcall UILayerUpdate_Hook(__int64 layer) 165 | { 166 | float currentAspect = GetAspectRatio(); 167 | if (currentAspect <= BASE_ASPECT) 168 | return UILayerUpdate(layer); 169 | 170 | auto uiRenderer = *(__int64*)(*(uintptr_t*)GraphicsManager + 0x9430); 171 | auto firstLayer = *(__int64*)(uiRenderer + 0xD0); 172 | 173 | if (layer == firstLayer) 174 | return 0; // hide pillarbox 175 | 176 | return UILayerUpdate(layer); 177 | } 178 | 179 | typedef float* __fastcall SetupCameraCenter_t(__int64 a1, __int64 a2); 180 | SetupCameraCenter_t* SetupCameraCenter; 181 | float* __fastcall SetupCameraCenter_Hook(__int64 a1, __int64 a2) 182 | { 183 | float currentAspect = GetAspectRatio(); 184 | if (currentAspect <= BASE_ASPECT) 185 | return SetupCameraCenter(a1, a2);; 186 | 187 | float originalX = *(float*)(a2 + 120); 188 | float aspectDelta = currentAspect - BASE_ASPECT; 189 | 190 | float adjustment = aspectDelta * 105.0f; 191 | *(float*)(a2 + 120) = originalX + adjustment; 192 | float* result = SetupCameraCenter(a1, a2); 193 | *(float*)(a2 + 120) = originalX; 194 | 195 | return result; 196 | } 197 | 198 | typedef void __fastcall WorldToScreen_t(float* a1, float* a2, float* a3); 199 | WorldToScreen_t* WorldToScreen; 200 | void __fastcall WorldToScreen_Hook(float* a1, float* a2, float* a3) 201 | { 202 | WorldToScreen(a1, a2, a3); 203 | 204 | float currentAspect = GetAspectRatio(); 205 | if (currentAspect <= BASE_ASPECT) 206 | return; 207 | 208 | float factor = Config.RenderScale / 4.0f; 209 | float scaledBaseWidth = BASE_WIDTH * factor; 210 | float fboWidthDelta = (float)(*FBO_W) - scaledBaseWidth; 211 | float offset = (fboWidthDelta * -0.0975f) / factor; 212 | a2[0] = a2[0] + offset; 213 | } 214 | 215 | typedef __int64 __fastcall SetScreenSize_t(__int64 a1, int width, int height); 216 | SetScreenSize_t* SetScreenSize; 217 | __int64 __fastcall SetScreenSize_Hook(__int64 a1, int width, int height) 218 | { 219 | spdlog::info("SetScreenSize: {}x{}", width, height); 220 | 221 | auto result = SetScreenSize(a1, width, height); 222 | 223 | float factor = Config.RenderScale / 4.0f; 224 | *FBO_W = GetScaledFBOWidth(factor); 225 | *FBO_H = GetScaledFBOHeight(factor); 226 | 227 | return result; 228 | } 229 | 230 | void PatchResolution() 231 | { 232 | uintptr_t fboOffset = (uintptr_t)Memory::PatternScan(GameModule, "C7 05 ?? ?? ?? ?? 38 04 00 00"); 233 | uintptr_t resScaleOffset = (uintptr_t)Memory::PatternScan(GameModule, "0F 2F 05 ?? ?? ?? ?? 72 ?? 44 88 ?? 26"); 234 | uintptr_t setRenderSizeOffset = (uintptr_t)Memory::PatternScan(GameModule, "48 ?? ?? 48 89 58 08 48 89 ?? 10 ?? 48 83 EC ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 0F 29 78"); 235 | uintptr_t clipScaleOffset = (uintptr_t)Memory::PatternScan(GameModule, "83 3D ?? ?? ?? ?? 07 C7 05 ?? ?? ?? ?? 00 00 80 3F"); 236 | 237 | if (fboOffset && resScaleOffset && setRenderSizeOffset && clipScaleOffset) 238 | { 239 | int32_t fboRelative = *(int32_t*)(fboOffset + 2); 240 | uintptr_t fboHAddress = fboOffset + 10 + fboRelative; 241 | 242 | FBO_W = (int*)(fboHAddress - 4); 243 | FBO_H = (int*)(fboHAddress); 244 | 245 | int32_t resScale_Relative = *(int32_t*)(resScaleOffset + 3); 246 | InternalRenderScale = (float*)(resScaleOffset + 7 + resScale_Relative); 247 | 248 | int32_t clipScaleRelative = *(int32_t*)(clipScaleOffset + 9); 249 | ClipScale = (float*)(clipScaleOffset + 7 + 10 + clipScaleRelative); 250 | 251 | DWORD oldProtect; 252 | VirtualProtect((LPVOID)(fboOffset - 0xA), 6, PAGE_EXECUTE_READWRITE, &oldProtect); 253 | memset((void*)(fboOffset - 0xA), 0x90, 6); 254 | 255 | VirtualProtect((LPVOID)(fboOffset), 0xA, PAGE_EXECUTE_READWRITE, &oldProtect); 256 | memset((void*)(fboOffset), 0x90, 0xA); 257 | 258 | VirtualProtect((LPVOID)(InternalRenderScale), 4, PAGE_READWRITE, &oldProtect); 259 | 260 | float factor = Config.RenderScale / 4.0f; 261 | *FBO_W = (int)(BASE_WIDTH * factor); 262 | *FBO_H = (int)(BASE_HEIGHT * factor); 263 | 264 | spdlog::info("FBO: {}x{}", *FBO_W, *FBO_H); 265 | 266 | Memory::DetourFunction(setRenderSizeOffset, (LPVOID)CFFT_STATE__SetRenderSize_Hook, (LPVOID*)&CFFT_STATE__SetRenderSize); 267 | } 268 | 269 | spdlog::debug("fboOffset: {:#x}", fboOffset); 270 | spdlog::debug("resScaleOffset: {:#x}", resScaleOffset); 271 | spdlog::debug("setRenderSizeOffset: {:#x}", setRenderSizeOffset); 272 | spdlog::debug("clipScaleOffset: {:#x}", clipScaleOffset); 273 | } 274 | 275 | void PatchViewport() 276 | { 277 | uintptr_t m_iScreenWOffset = (uintptr_t)Memory::PatternScan(GameModule, "BE 80 07 00 00 89 ?? ?? ?? ?? ??"); 278 | 279 | if (!m_iScreenWOffset) 280 | { 281 | spdlog::error("Failed to find screen width offset"); 282 | return; 283 | } 284 | 285 | uintptr_t m_iScreenHOffset = (uintptr_t)Memory::PatternScan(GameModule, "B9 E0 04 00 00 89 ?? ?? ?? ?? ??"); 286 | if (!m_iScreenHOffset) 287 | { 288 | spdlog::error("Failed to find screen height offset"); 289 | return; 290 | } 291 | 292 | m_iScreenW = (int*)(m_iScreenWOffset + 11 + *(int32_t*)(m_iScreenWOffset + 7)); 293 | m_iScreenH = (int*)(m_iScreenHOffset + 11 + *(int32_t*)(m_iScreenHOffset + 7)); 294 | 295 | spdlog::info("Screen Dimensions: {}x{}", *m_iScreenW, *m_iScreenH); 296 | 297 | uintptr_t setupCamCenterOffset = (uintptr_t)Memory::PatternScan(GameModule, "48 8B C4 55 48 8D 68"); 298 | uintptr_t world2ScreenOffset = (uintptr_t)Memory::PatternScan(GameModule, "48 8B C4 48 89 58 18 48 89 78 20 55 48 8D 68 ?? 48 81 EC ?? ?? ?? ?? 0F 29 70 ?? 0F 29 78 ?? 44 0F 29 40 ?? 44 0F 29 48 ??"); 299 | uintptr_t calcViewportOffset = (uintptr_t)(Memory::PatternScan(GameModule, "89 78 20 41 56 41 57 48 8B 05") - 0x10); 300 | uintptr_t rightPlaneClipOffset = (uintptr_t)Memory::PatternScan(GameModule, "00 80 E2 43"); 301 | uintptr_t leftPlaneClipOffset = (uintptr_t)Memory::PatternScan(GameModule, "00 00 6C 42 00 00 70 42"); 302 | uintptr_t layerUpdateOffset = (uintptr_t)Memory::PatternScan(GameModule, "48 8B C4 55 53 56 57 48"); 303 | uintptr_t graphicsManagerOffset = (uintptr_t)Memory::PatternScan(GameModule, "48 8B 05 ?? ?? ?? ?? ?? 8B ?? 30 94 00 00"); 304 | 305 | if (setupCamCenterOffset && world2ScreenOffset && calcViewportOffset && rightPlaneClipOffset && 306 | leftPlaneClipOffset && layerUpdateOffset && graphicsManagerOffset) 307 | { 308 | DWORD oldProtect; 309 | VirtualProtect((LPVOID)(leftPlaneClipOffset), 4, PAGE_READWRITE, &oldProtect); 310 | VirtualProtect((LPVOID)(rightPlaneClipOffset), 4, PAGE_READWRITE, &oldProtect); 311 | 312 | *(float*)(leftPlaneClipOffset) = *(float*)(leftPlaneClipOffset) * -2; 313 | *(float*)(rightPlaneClipOffset) = *(float*)(rightPlaneClipOffset) * 2; 314 | 315 | GraphicsManager = (uintptr_t)(graphicsManagerOffset + *(int*)(graphicsManagerOffset + 3) + 7); 316 | 317 | Memory::DetourFunction(calcViewportOffset, (LPVOID)CalculateViewportWithLetterboxing_Hook, (LPVOID*)&CalculateViewportWithLetterboxing); 318 | Memory::DetourFunction(layerUpdateOffset, (LPVOID)UILayerUpdate_Hook, (LPVOID*)&UILayerUpdate); 319 | Memory::DetourFunction(setupCamCenterOffset, (LPVOID)SetupCameraCenter_Hook, (LPVOID*)&SetupCameraCenter); 320 | Memory::DetourFunction(world2ScreenOffset, (LPVOID)WorldToScreen_Hook, (LPVOID*)&WorldToScreen); 321 | } 322 | 323 | spdlog::debug("setupCamCenterOffset: {:#x}", setupCamCenterOffset); 324 | spdlog::debug("world2ScreenOffset: {:#x}", world2ScreenOffset); 325 | spdlog::debug("calcViewportOffset: {:#x}", calcViewportOffset); 326 | spdlog::debug("rightPlaneClipOffset: {:#x}", rightPlaneClipOffset); 327 | spdlog::debug("leftPlaneClipOffset: {:#x}", leftPlaneClipOffset); 328 | spdlog::debug("layerUpdateOffset: {:#x}", layerUpdateOffset); 329 | spdlog::debug("graphicsManagerOffset: {:#x}", GraphicsManager); 330 | } 331 | 332 | // pattern matching has gotten out of hand. 333 | // possibly better to hardcode offsets based on exe version 334 | void ApplyPatches() 335 | { 336 | uintptr_t movieCurrentOffset = (uintptr_t)Memory::PatternScan(GameModule, "0F B6 05 ?? ?? ?? ?? 3C FF 74 ??"); 337 | uint8_t* movieCurrentPtr = (uint8_t*)movieCurrentOffset + 3; 338 | int32_t movieCurrentOffsetRelative = *reinterpret_cast(movieCurrentPtr); 339 | MovieCurrentId = (int8_t*)(movieCurrentPtr + 4) + movieCurrentOffsetRelative; 340 | 341 | if (movieCurrentOffset) 342 | { 343 | Memory::DetourFunction(movieCurrentOffset, (LPVOID)SetMovieId_Hook, (LPVOID*)&SetMovieId); 344 | } 345 | 346 | spdlog::debug("movieCurrentOffset: {:#x}", movieCurrentOffset); 347 | 348 | if (Config.DisableFilter) 349 | { 350 | uintptr_t grainFilterOffset = (uintptr_t)Memory::PatternScan(GameModule, "38 ?? A0 55 02 00"); 351 | uintptr_t pauseMenuViewportResizeOffset = (uintptr_t)Memory::PatternScan(GameModule, "80 ?? B5 55 02 00 00"); 352 | 353 | if (grainFilterOffset) 354 | { 355 | DWORD oldProtect; 356 | VirtualProtect((LPVOID)(grainFilterOffset), 6, PAGE_EXECUTE_READWRITE, &oldProtect); 357 | memset((void*)grainFilterOffset, 0x90, 6); 358 | } 359 | 360 | if (pauseMenuViewportResizeOffset) 361 | { 362 | DWORD oldProtect; 363 | VirtualProtect((LPVOID)(pauseMenuViewportResizeOffset), 7, PAGE_EXECUTE_READWRITE, &oldProtect); 364 | memset((void*)pauseMenuViewportResizeOffset, 0x90, 7); 365 | } 366 | 367 | spdlog::debug("grainFilterOffset: {:#x}", grainFilterOffset); 368 | spdlog::debug("pauseMenuViewportResizeOffset: {:#x}", pauseMenuViewportResizeOffset); 369 | } 370 | 371 | if (Config.PreferMovies) 372 | { 373 | uintptr_t initScriptVMOffset = (uintptr_t)Memory::PatternScan(GameModule, "48 89 5C 24 10 48 89 6C 24 18 56 57 41 56 48 83 EC 20 E8"); 374 | uintptr_t menuStateOffset = (uintptr_t)Memory::PatternScan(GameModule, "F6 05 ?? ?? ?? ?? 08 0F 85 ?? ?? ?? ?? 8D 5D"); 375 | uintptr_t movieTypeOffset = (uintptr_t)Memory::PatternScan(GameModule, "C7 05 ?? ?? ?? ?? 01 00 00 00 C7 05 ?? ?? ?? ?? 01 00 00 00 83 ?? 10 01"); 376 | uintptr_t currentScriptOffset = (uintptr_t)Memory::PatternScan(GameModule, "81 3D ?? ?? ?? ?? 76 01 00 00"); 377 | uintptr_t scriptSkipFlag = (uintptr_t)Memory::PatternScan(GameModule, "B8 20 00 00 00 44 89 05 ?? ?? ?? ??"); 378 | InitMovie = (InitMovie_t*)(Memory::PatternScan(GameModule, "48 83 EC 30 31 F6 89 74 24 40 E8 ?? ?? ?? ?? 39 35 ?? ?? ?? ?? 74 07") - 0xB); 379 | 380 | if (initScriptVMOffset && menuStateOffset && movieTypeOffset && MovieCurrentId && currentScriptOffset && scriptSkipFlag && InitMovie) 381 | { 382 | int32_t menuStateOffsetRelative = *reinterpret_cast((uint8_t*)(menuStateOffset + 19)); 383 | MenuState = (uint8_t*)(menuStateOffset + 23) + menuStateOffsetRelative; 384 | 385 | uint8_t* movieTypeRelative = (uint8_t*)(movieTypeOffset + 12); 386 | int32_t movieTypeRelative32 = *reinterpret_cast(movieTypeRelative); 387 | MovieType = (uint8_t*)(movieTypeRelative + 8 + movieTypeRelative32); 388 | 389 | CurrentScript = (uint32_t*)(currentScriptOffset + 10 + *reinterpret_cast(currentScriptOffset + 2)); 390 | SkipScriptFlag = (uint32_t*)(scriptSkipFlag + 12 + *reinterpret_cast(scriptSkipFlag + 8)); 391 | 392 | Memory::DetourFunction(initScriptVMOffset, (LPVOID)InitScriptVM_Hook, (LPVOID*)&InitScriptVM); 393 | } 394 | 395 | spdlog::debug("initScriptVMOffset: {:#x}", initScriptVMOffset); 396 | spdlog::debug("menuStateOffset: {:#x}", menuStateOffset); 397 | spdlog::debug("movieTypeOffset: {:#x}", menuStateOffset); 398 | spdlog::debug("currentScriptOffset: {:#x}", menuStateOffset); 399 | spdlog::debug("scriptSkipFlag: {:#x}", menuStateOffset); 400 | } 401 | } 402 | 403 | typedef void GX_Init_t(); 404 | GX_Init_t* GX_Init; 405 | void GX_Init_Hook() 406 | { 407 | PatchResolution(); 408 | GX_Init(); 409 | PatchViewport(); 410 | ApplyPatches(); 411 | } 412 | 413 | void Init() 414 | { 415 | spdlog::info("Installing hooks and applying patches..."); 416 | 417 | MH_STATUS status = MH_Initialize(); 418 | if (status != MH_OK) 419 | { 420 | spdlog::error("Failed to initialize MinHook, status: {}", (int)status); 421 | return; 422 | } 423 | 424 | uintptr_t gxInitOffset = (uintptr_t)(Memory::PatternScan(GameModule, "ED B9 30 18 00 00") - 0x3A); 425 | uintptr_t setScreenSizeOffset = (uintptr_t)(Memory::PatternScan(GameModule, "48 39 ?? 58 75") - 0xB); 426 | 427 | if (!gxInitOffset) 428 | { 429 | spdlog::error("Unable to find GX_Init!"); 430 | return; 431 | } 432 | 433 | Memory::DetourFunction(gxInitOffset, (LPVOID)GX_Init_Hook, (LPVOID*)&GX_Init); 434 | 435 | if (!setScreenSizeOffset) 436 | { 437 | spdlog::error("Unable to find SetScreenSize!"); 438 | return; 439 | } 440 | 441 | Memory::DetourFunction(setScreenSizeOffset, (LPVOID)SetScreenSize_Hook, (LPVOID*)&SetScreenSize); 442 | } 443 | 444 | void ReadConfig() 445 | { 446 | std::string configPath = "scripts/FFTacticsFix.ini"; 447 | mINI::INIFile ini(configPath); 448 | if (!ini.read(ConfigValues)) 449 | { 450 | ConfigValues["Settings"]["PreferMovies"] = "0"; 451 | ConfigValues["Settings"]["DisableFilter"] = "0"; 452 | ConfigValues["Settings"]["RenderScale"] = "4"; 453 | ini.generate(ConfigValues); 454 | } 455 | 456 | auto readConfigInt = [](const std::string& str, int defaultValue) -> int { 457 | if (str.empty()) return defaultValue; 458 | try { return std::stoi(str); } 459 | catch (...) { return defaultValue; } 460 | }; 461 | 462 | Config.PreferMovies = readConfigInt(ConfigValues["Settings"]["PreferMovies"], 0); 463 | Config.DisableFilter = readConfigInt(ConfigValues["Settings"]["DisableFilter"], 0); 464 | Config.RenderScale = readConfigInt(ConfigValues["Settings"]["RenderScale"], 4); 465 | } 466 | 467 | DWORD WINAPI MainThread(LPVOID lpParam) 468 | { 469 | GameModule = GetModuleHandleA("FFT_enhanced.exe"); 470 | GameBase = (uintptr_t)GameModule; 471 | 472 | if (GameModule == 0) 473 | return true; 474 | 475 | WCHAR exePath[_MAX_PATH] = { 0 }; 476 | GetModuleFileNameW(GameModule, exePath, MAX_PATH); 477 | std::filesystem::path sExePath = exePath; 478 | WCHAR* filename = PathFindFileName(exePath); 479 | 480 | if (wcsncmp(filename, L"FFT_enhanced.exe", 16) != 0) 481 | return true; 482 | 483 | ReadConfig(); 484 | 485 | if (!InitializeLogger(GameModule, sExePath)) 486 | return true; 487 | 488 | Init(); 489 | 490 | return true; 491 | } 492 | 493 | BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) 494 | { 495 | switch (ul_reason_for_call) 496 | { 497 | case DLL_PROCESS_ATTACH: 498 | DisableThreadLibraryCalls(hModule); 499 | CreateThread(NULL, NULL, MainThread, NULL, NULL, NULL); 500 | break; 501 | case DLL_THREAD_ATTACH: 502 | case DLL_THREAD_DETACH: 503 | case DLL_PROCESS_DETACH: 504 | break; 505 | } 506 | return TRUE; 507 | } 508 | 509 | -------------------------------------------------------------------------------- /FFTacticsFix/includes/ini.h: -------------------------------------------------------------------------------- 1 | /* 2 | * The MIT License (MIT) 3 | * Copyright (c) 2018 Danijel Durakovic 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 9 | * of the Software, and to permit persons to whom the Software is furnished to do 10 | * so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | */ 23 | 24 | /////////////////////////////////////////////////////////////////////////////// 25 | // 26 | // /mINI/ v0.9.14 27 | // An INI file reader and writer for the modern age. 28 | // 29 | /////////////////////////////////////////////////////////////////////////////// 30 | // 31 | // A tiny utility library for manipulating INI files with a straightforward 32 | // API and a minimal footprint. It conforms to the (somewhat) standard INI 33 | // format - sections and keys are case insensitive and all leading and 34 | // trailing whitespace is ignored. Comments are lines that begin with a 35 | // semicolon. Trailing comments are allowed on section lines. 36 | // 37 | // Files are read on demand, upon which data is kept in memory and the file 38 | // is closed. This utility supports lazy writing, which only writes changes 39 | // and updates to a file and preserves custom formatting and comments. A lazy 40 | // write invoked by a write() call will read the output file, find what 41 | // changes have been made and update the file accordingly. If you only need to 42 | // generate files, use generate() instead. Section and key order is preserved 43 | // on read, write and insert. 44 | // 45 | /////////////////////////////////////////////////////////////////////////////// 46 | // 47 | // /* BASIC USAGE EXAMPLE: */ 48 | // 49 | // /* read from file */ 50 | // mINI::INIFile file("myfile.ini"); 51 | // mINI::INIStructure ini; 52 | // file.read(ini); 53 | // 54 | // /* read value; gets a reference to actual value in the structure. 55 | // if key or section don't exist, a new empty value will be created */ 56 | // std::string& value = ini["section"]["key"]; 57 | // 58 | // /* read value safely; gets a copy of value in the structure. 59 | // does not alter the structure */ 60 | // std::string value = ini.get("section").get("key"); 61 | // 62 | // /* set or update values */ 63 | // ini["section"]["key"] = "value"; 64 | // 65 | // /* set multiple values */ 66 | // ini["section2"].set({ 67 | // {"key1", "value1"}, 68 | // {"key2", "value2"} 69 | // }); 70 | // 71 | // /* write updates back to file, preserving comments and formatting */ 72 | // file.write(ini); 73 | // 74 | // /* or generate a file (overwrites the original) */ 75 | // file.generate(ini); 76 | // 77 | /////////////////////////////////////////////////////////////////////////////// 78 | // 79 | // Long live the INI file!!! 80 | // 81 | /////////////////////////////////////////////////////////////////////////////// 82 | 83 | #ifndef MINI_INI_H_ 84 | #define MINI_INI_H_ 85 | 86 | #include 87 | #include 88 | #include 89 | #include 90 | #include 91 | #include 92 | #include 93 | #include 94 | #include 95 | #include 96 | 97 | namespace mINI 98 | { 99 | namespace INIStringUtil 100 | { 101 | const char* const whitespaceDelimiters = " \t\n\r\f\v"; 102 | inline void trim(std::string& str) 103 | { 104 | str.erase(str.find_last_not_of(whitespaceDelimiters) + 1); 105 | str.erase(0, str.find_first_not_of(whitespaceDelimiters)); 106 | } 107 | #ifndef MINI_CASE_SENSITIVE 108 | inline void toLower(std::string& str) 109 | { 110 | std::transform(str.begin(), str.end(), str.begin(), [](const char c) { 111 | return static_cast(std::tolower(c)); 112 | }); 113 | } 114 | #endif 115 | inline void replace(std::string& str, std::string const& a, std::string const& b) 116 | { 117 | if (!a.empty()) 118 | { 119 | std::size_t pos = 0; 120 | while ((pos = str.find(a, pos)) != std::string::npos) 121 | { 122 | str.replace(pos, a.size(), b); 123 | pos += b.size(); 124 | } 125 | } 126 | } 127 | #ifdef _WIN32 128 | const char* const endl = "\r\n"; 129 | #else 130 | const char* const endl = "\n"; 131 | #endif 132 | } 133 | 134 | template 135 | class INIMap 136 | { 137 | private: 138 | using T_DataIndexMap = std::unordered_map; 139 | using T_DataItem = std::pair; 140 | using T_DataContainer = std::vector; 141 | using T_MultiArgs = typename std::vector>; 142 | 143 | T_DataIndexMap dataIndexMap; 144 | T_DataContainer data; 145 | 146 | inline std::size_t setEmpty(std::string& key) 147 | { 148 | std::size_t index = data.size(); 149 | dataIndexMap[key] = index; 150 | data.emplace_back(key, T()); 151 | return index; 152 | } 153 | 154 | public: 155 | using const_iterator = typename T_DataContainer::const_iterator; 156 | 157 | INIMap() { } 158 | 159 | INIMap(INIMap const& other) 160 | { 161 | std::size_t data_size = other.data.size(); 162 | for (std::size_t i = 0; i < data_size; ++i) 163 | { 164 | auto const& key = other.data[i].first; 165 | auto const& obj = other.data[i].second; 166 | data.emplace_back(key, obj); 167 | } 168 | dataIndexMap = T_DataIndexMap(other.dataIndexMap); 169 | } 170 | 171 | T& operator[](std::string key) 172 | { 173 | INIStringUtil::trim(key); 174 | #ifndef MINI_CASE_SENSITIVE 175 | INIStringUtil::toLower(key); 176 | #endif 177 | auto it = dataIndexMap.find(key); 178 | bool hasIt = (it != dataIndexMap.end()); 179 | std::size_t index = (hasIt) ? it->second : setEmpty(key); 180 | return data[index].second; 181 | } 182 | T get(std::string key) const 183 | { 184 | INIStringUtil::trim(key); 185 | #ifndef MINI_CASE_SENSITIVE 186 | INIStringUtil::toLower(key); 187 | #endif 188 | auto it = dataIndexMap.find(key); 189 | if (it == dataIndexMap.end()) 190 | { 191 | return T(); 192 | } 193 | return T(data[it->second].second); 194 | } 195 | bool has(std::string key) const 196 | { 197 | INIStringUtil::trim(key); 198 | #ifndef MINI_CASE_SENSITIVE 199 | INIStringUtil::toLower(key); 200 | #endif 201 | return (dataIndexMap.count(key) == 1); 202 | } 203 | void set(std::string key, T obj) 204 | { 205 | INIStringUtil::trim(key); 206 | #ifndef MINI_CASE_SENSITIVE 207 | INIStringUtil::toLower(key); 208 | #endif 209 | auto it = dataIndexMap.find(key); 210 | if (it != dataIndexMap.end()) 211 | { 212 | data[it->second].second = obj; 213 | } 214 | else 215 | { 216 | dataIndexMap[key] = data.size(); 217 | data.emplace_back(key, obj); 218 | } 219 | } 220 | void set(T_MultiArgs const& multiArgs) 221 | { 222 | for (auto const& it : multiArgs) 223 | { 224 | auto const& key = it.first; 225 | auto const& obj = it.second; 226 | set(key, obj); 227 | } 228 | } 229 | bool remove(std::string key) 230 | { 231 | INIStringUtil::trim(key); 232 | #ifndef MINI_CASE_SENSITIVE 233 | INIStringUtil::toLower(key); 234 | #endif 235 | auto it = dataIndexMap.find(key); 236 | if (it != dataIndexMap.end()) 237 | { 238 | std::size_t index = it->second; 239 | data.erase(data.begin() + index); 240 | dataIndexMap.erase(it); 241 | for (auto& it2 : dataIndexMap) 242 | { 243 | auto& vi = it2.second; 244 | if (vi > index) 245 | { 246 | vi--; 247 | } 248 | } 249 | return true; 250 | } 251 | return false; 252 | } 253 | void clear() 254 | { 255 | data.clear(); 256 | dataIndexMap.clear(); 257 | } 258 | std::size_t size() const 259 | { 260 | return data.size(); 261 | } 262 | const_iterator begin() const { return data.begin(); } 263 | const_iterator end() const { return data.end(); } 264 | }; 265 | 266 | using INIStructure = INIMap>; 267 | 268 | namespace INIParser 269 | { 270 | using T_ParseValues = std::pair; 271 | 272 | enum class PDataType : char 273 | { 274 | PDATA_NONE, 275 | PDATA_COMMENT, 276 | PDATA_SECTION, 277 | PDATA_KEYVALUE, 278 | PDATA_UNKNOWN 279 | }; 280 | 281 | inline PDataType parseLine(std::string line, T_ParseValues& parseData) 282 | { 283 | parseData.first.clear(); 284 | parseData.second.clear(); 285 | INIStringUtil::trim(line); 286 | if (line.empty()) 287 | { 288 | return PDataType::PDATA_NONE; 289 | } 290 | char firstCharacter = line[0]; 291 | if (firstCharacter == ';') 292 | { 293 | return PDataType::PDATA_COMMENT; 294 | } 295 | if (firstCharacter == '[') 296 | { 297 | auto commentAt = line.find_first_of(';'); 298 | if (commentAt != std::string::npos) 299 | { 300 | line = line.substr(0, commentAt); 301 | } 302 | auto closingBracketAt = line.find_last_of(']'); 303 | if (closingBracketAt != std::string::npos) 304 | { 305 | auto section = line.substr(1, closingBracketAt - 1); 306 | INIStringUtil::trim(section); 307 | parseData.first = section; 308 | return PDataType::PDATA_SECTION; 309 | } 310 | } 311 | auto lineNorm = line; 312 | INIStringUtil::replace(lineNorm, "\\=", " "); 313 | auto equalsAt = lineNorm.find_first_of('='); 314 | if (equalsAt != std::string::npos) 315 | { 316 | auto key = line.substr(0, equalsAt); 317 | INIStringUtil::trim(key); 318 | INIStringUtil::replace(key, "\\=", "="); 319 | auto value = line.substr(equalsAt + 1); 320 | INIStringUtil::trim(value); 321 | parseData.first = key; 322 | parseData.second = value; 323 | return PDataType::PDATA_KEYVALUE; 324 | } 325 | return PDataType::PDATA_UNKNOWN; 326 | } 327 | } 328 | 329 | class INIReader 330 | { 331 | public: 332 | using T_LineData = std::vector; 333 | using T_LineDataPtr = std::shared_ptr; 334 | 335 | bool isBOM = false; 336 | 337 | private: 338 | std::ifstream fileReadStream; 339 | T_LineDataPtr lineData; 340 | 341 | T_LineData readFile() 342 | { 343 | fileReadStream.seekg(0, std::ios::end); 344 | const std::size_t fileSize = static_cast(fileReadStream.tellg()); 345 | fileReadStream.seekg(0, std::ios::beg); 346 | if (fileSize >= 3) { 347 | const char header[3] = { 348 | static_cast(fileReadStream.get()), 349 | static_cast(fileReadStream.get()), 350 | static_cast(fileReadStream.get()) 351 | }; 352 | isBOM = ( 353 | header[0] == static_cast(0xEF) && 354 | header[1] == static_cast(0xBB) && 355 | header[2] == static_cast(0xBF) 356 | ); 357 | } 358 | else { 359 | isBOM = false; 360 | } 361 | std::string fileContents; 362 | fileContents.resize(fileSize); 363 | fileReadStream.seekg(isBOM ? 3 : 0, std::ios::beg); 364 | fileReadStream.read(&fileContents[0], fileSize); 365 | fileReadStream.close(); 366 | T_LineData output; 367 | if (fileSize == 0) 368 | { 369 | return output; 370 | } 371 | std::string buffer; 372 | buffer.reserve(50); 373 | for (std::size_t i = 0; i < fileSize; ++i) 374 | { 375 | char& c = fileContents[i]; 376 | if (c == '\n') 377 | { 378 | output.emplace_back(buffer); 379 | buffer.clear(); 380 | continue; 381 | } 382 | if (c != '\0' && c != '\r') 383 | { 384 | buffer += c; 385 | } 386 | } 387 | output.emplace_back(buffer); 388 | return output; 389 | } 390 | 391 | public: 392 | INIReader(std::string const& filename, bool keepLineData = false) 393 | { 394 | fileReadStream.open(filename, std::ios::in | std::ios::binary); 395 | if (keepLineData) 396 | { 397 | lineData = std::make_shared(); 398 | } 399 | } 400 | ~INIReader() { } 401 | 402 | bool operator>>(INIStructure& data) 403 | { 404 | if (!fileReadStream.is_open()) 405 | { 406 | return false; 407 | } 408 | T_LineData fileLines = readFile(); 409 | std::string section; 410 | bool inSection = false; 411 | INIParser::T_ParseValues parseData; 412 | for (auto const& line : fileLines) 413 | { 414 | auto parseResult = INIParser::parseLine(line, parseData); 415 | if (parseResult == INIParser::PDataType::PDATA_SECTION) 416 | { 417 | inSection = true; 418 | data[section = parseData.first]; 419 | } 420 | else if (inSection && parseResult == INIParser::PDataType::PDATA_KEYVALUE) 421 | { 422 | auto const& key = parseData.first; 423 | auto const& value = parseData.second; 424 | data[section][key] = value; 425 | } 426 | if (lineData && parseResult != INIParser::PDataType::PDATA_UNKNOWN) 427 | { 428 | if (parseResult == INIParser::PDataType::PDATA_KEYVALUE && !inSection) 429 | { 430 | continue; 431 | } 432 | lineData->emplace_back(line); 433 | } 434 | } 435 | return true; 436 | } 437 | T_LineDataPtr getLines() 438 | { 439 | return lineData; 440 | } 441 | }; 442 | 443 | class INIGenerator 444 | { 445 | private: 446 | std::ofstream fileWriteStream; 447 | 448 | public: 449 | bool prettyPrint = false; 450 | 451 | INIGenerator(std::string const& filename) 452 | { 453 | fileWriteStream.open(filename, std::ios::out | std::ios::binary); 454 | } 455 | ~INIGenerator() { } 456 | 457 | bool operator<<(INIStructure const& data) 458 | { 459 | if (!fileWriteStream.is_open()) 460 | { 461 | return false; 462 | } 463 | if (!data.size()) 464 | { 465 | return true; 466 | } 467 | auto it = data.begin(); 468 | for (;;) 469 | { 470 | auto const& section = it->first; 471 | auto const& collection = it->second; 472 | fileWriteStream 473 | << "[" 474 | << section 475 | << "]"; 476 | if (collection.size()) 477 | { 478 | fileWriteStream << INIStringUtil::endl; 479 | auto it2 = collection.begin(); 480 | for (;;) 481 | { 482 | auto key = it2->first; 483 | INIStringUtil::replace(key, "=", "\\="); 484 | auto value = it2->second; 485 | INIStringUtil::trim(value); 486 | fileWriteStream 487 | << key 488 | << ((prettyPrint) ? " = " : "=") 489 | << value; 490 | if (++it2 == collection.end()) 491 | { 492 | break; 493 | } 494 | fileWriteStream << INIStringUtil::endl; 495 | } 496 | } 497 | if (++it == data.end()) 498 | { 499 | break; 500 | } 501 | fileWriteStream << INIStringUtil::endl; 502 | if (prettyPrint) 503 | { 504 | fileWriteStream << INIStringUtil::endl; 505 | } 506 | } 507 | return true; 508 | } 509 | }; 510 | 511 | class INIWriter 512 | { 513 | private: 514 | using T_LineData = std::vector; 515 | using T_LineDataPtr = std::shared_ptr; 516 | 517 | std::string filename; 518 | 519 | T_LineData getLazyOutput(T_LineDataPtr const& lineData, INIStructure& data, INIStructure& original) 520 | { 521 | T_LineData output; 522 | INIParser::T_ParseValues parseData; 523 | std::string sectionCurrent; 524 | bool parsingSection = false; 525 | bool continueToNextSection = false; 526 | bool discardNextEmpty = false; 527 | bool writeNewKeys = false; 528 | std::size_t lastKeyLine = 0; 529 | for (auto line = lineData->begin(); line != lineData->end(); ++line) 530 | { 531 | if (!writeNewKeys) 532 | { 533 | auto parseResult = INIParser::parseLine(*line, parseData); 534 | if (parseResult == INIParser::PDataType::PDATA_SECTION) 535 | { 536 | if (parsingSection) 537 | { 538 | writeNewKeys = true; 539 | parsingSection = false; 540 | --line; 541 | continue; 542 | } 543 | sectionCurrent = parseData.first; 544 | if (data.has(sectionCurrent)) 545 | { 546 | parsingSection = true; 547 | continueToNextSection = false; 548 | discardNextEmpty = false; 549 | output.emplace_back(*line); 550 | lastKeyLine = output.size(); 551 | } 552 | else 553 | { 554 | continueToNextSection = true; 555 | discardNextEmpty = true; 556 | continue; 557 | } 558 | } 559 | else if (parseResult == INIParser::PDataType::PDATA_KEYVALUE) 560 | { 561 | if (continueToNextSection) 562 | { 563 | continue; 564 | } 565 | if (data.has(sectionCurrent)) 566 | { 567 | auto& collection = data[sectionCurrent]; 568 | auto const& key = parseData.first; 569 | auto const& value = parseData.second; 570 | if (collection.has(key)) 571 | { 572 | auto outputValue = collection[key]; 573 | if (value == outputValue) 574 | { 575 | output.emplace_back(*line); 576 | } 577 | else 578 | { 579 | INIStringUtil::trim(outputValue); 580 | auto lineNorm = *line; 581 | INIStringUtil::replace(lineNorm, "\\=", " "); 582 | auto equalsAt = lineNorm.find_first_of('='); 583 | auto valueAt = lineNorm.find_first_not_of( 584 | INIStringUtil::whitespaceDelimiters, 585 | equalsAt + 1 586 | ); 587 | std::string outputLine = line->substr(0, valueAt); 588 | if (prettyPrint && equalsAt + 1 == valueAt) 589 | { 590 | outputLine += " "; 591 | } 592 | outputLine += outputValue; 593 | output.emplace_back(outputLine); 594 | } 595 | lastKeyLine = output.size(); 596 | } 597 | } 598 | } 599 | else 600 | { 601 | if (discardNextEmpty && line->empty()) 602 | { 603 | discardNextEmpty = false; 604 | } 605 | else if (parseResult != INIParser::PDataType::PDATA_UNKNOWN) 606 | { 607 | output.emplace_back(*line); 608 | } 609 | } 610 | } 611 | if (writeNewKeys || std::next(line) == lineData->end()) 612 | { 613 | T_LineData linesToAdd; 614 | if (data.has(sectionCurrent) && original.has(sectionCurrent)) 615 | { 616 | auto const& collection = data[sectionCurrent]; 617 | auto const& collectionOriginal = original[sectionCurrent]; 618 | for (auto const& it : collection) 619 | { 620 | auto key = it.first; 621 | if (collectionOriginal.has(key)) 622 | { 623 | continue; 624 | } 625 | auto value = it.second; 626 | INIStringUtil::replace(key, "=", "\\="); 627 | INIStringUtil::trim(value); 628 | linesToAdd.emplace_back( 629 | key + ((prettyPrint) ? " = " : "=") + value 630 | ); 631 | } 632 | } 633 | if (!linesToAdd.empty()) 634 | { 635 | output.insert( 636 | output.begin() + lastKeyLine, 637 | linesToAdd.begin(), 638 | linesToAdd.end() 639 | ); 640 | } 641 | if (writeNewKeys) 642 | { 643 | writeNewKeys = false; 644 | --line; 645 | } 646 | } 647 | } 648 | for (auto const& it : data) 649 | { 650 | auto const& section = it.first; 651 | if (original.has(section)) 652 | { 653 | continue; 654 | } 655 | if (prettyPrint && output.size() > 0 && !output.back().empty()) 656 | { 657 | output.emplace_back(); 658 | } 659 | output.emplace_back("[" + section + "]"); 660 | auto const& collection = it.second; 661 | for (auto const& it2 : collection) 662 | { 663 | auto key = it2.first; 664 | auto value = it2.second; 665 | INIStringUtil::replace(key, "=", "\\="); 666 | INIStringUtil::trim(value); 667 | output.emplace_back( 668 | key + ((prettyPrint) ? " = " : "=") + value 669 | ); 670 | } 671 | } 672 | return output; 673 | } 674 | 675 | public: 676 | bool prettyPrint = false; 677 | 678 | INIWriter(std::string const& filename) 679 | : filename(filename) 680 | { 681 | } 682 | ~INIWriter() { } 683 | 684 | bool operator<<(INIStructure& data) 685 | { 686 | struct stat buf; 687 | bool fileExists = (stat(filename.c_str(), &buf) == 0); 688 | if (!fileExists) 689 | { 690 | INIGenerator generator(filename); 691 | generator.prettyPrint = prettyPrint; 692 | return generator << data; 693 | } 694 | INIStructure originalData; 695 | T_LineDataPtr lineData; 696 | bool readSuccess = false; 697 | bool fileIsBOM = false; 698 | { 699 | INIReader reader(filename, true); 700 | if ((readSuccess = reader >> originalData)) 701 | { 702 | lineData = reader.getLines(); 703 | fileIsBOM = reader.isBOM; 704 | } 705 | } 706 | if (!readSuccess) 707 | { 708 | return false; 709 | } 710 | T_LineData output = getLazyOutput(lineData, data, originalData); 711 | std::ofstream fileWriteStream(filename, std::ios::out | std::ios::binary); 712 | if (fileWriteStream.is_open()) 713 | { 714 | if (fileIsBOM) { 715 | const char utf8_BOM[3] = { 716 | static_cast(0xEF), 717 | static_cast(0xBB), 718 | static_cast(0xBF) 719 | }; 720 | fileWriteStream.write(utf8_BOM, 3); 721 | } 722 | if (output.size()) 723 | { 724 | auto line = output.begin(); 725 | for (;;) 726 | { 727 | fileWriteStream << *line; 728 | if (++line == output.end()) 729 | { 730 | break; 731 | } 732 | fileWriteStream << INIStringUtil::endl; 733 | } 734 | } 735 | return true; 736 | } 737 | return false; 738 | } 739 | }; 740 | 741 | class INIFile 742 | { 743 | private: 744 | std::string filename; 745 | 746 | public: 747 | INIFile(std::string const& filename) 748 | : filename(filename) 749 | { } 750 | 751 | ~INIFile() { } 752 | 753 | bool read(INIStructure& data) const 754 | { 755 | if (data.size()) 756 | { 757 | data.clear(); 758 | } 759 | if (filename.empty()) 760 | { 761 | return false; 762 | } 763 | INIReader reader(filename); 764 | return reader >> data; 765 | } 766 | bool generate(INIStructure const& data, bool pretty = false) const 767 | { 768 | if (filename.empty()) 769 | { 770 | return false; 771 | } 772 | INIGenerator generator(filename); 773 | generator.prettyPrint = pretty; 774 | return generator << data; 775 | } 776 | bool write(INIStructure& data, bool pretty = false) const 777 | { 778 | if (filename.empty()) 779 | { 780 | return false; 781 | } 782 | INIWriter writer(filename); 783 | writer.prettyPrint = pretty; 784 | return writer << data; 785 | } 786 | }; 787 | } 788 | 789 | #endif // MINI_INI_H_ 790 | --------------------------------------------------------------------------------