From 5c47bdb571090956a0ce7a2c3f14dc25e175cf11 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 12 Oct 2026 22:38:03 +0200 Subject: [PATCH 01/42] feat: rewrote dumping. added dump of ALL sprites and their sprite infos. added the launch pipe from 1.3 and other minor stuff. removed installer --- .github/workflows/installer.yml | 43 ------- PolyMod.csproj | 4 +- README.md | 4 +- installer/build.py | 19 ---- installer/icon.ico | Bin 116829 -> 0 bytes installer/main.py | 154 ------------------------- installer/requirements.txt | 4 - resources/localization.json | 34 +++--- src/Managers/AutoUpdate.cs | 182 ----------------------------- src/Managers/Compatibility.cs | 37 ++++++ src/Managers/Hub.cs | 196 +++++++++++++++++++++----------- src/Managers/Main.cs | 34 +++++- src/NullableFix.cs | 2 +- src/Plugin.cs | 68 +++++++++-- 14 files changed, 282 insertions(+), 499 deletions(-) delete mode 100644 .github/workflows/installer.yml delete mode 100644 installer/build.py delete mode 100644 installer/icon.ico delete mode 100644 installer/main.py delete mode 100644 installer/requirements.txt delete mode 100644 src/Managers/AutoUpdate.cs diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml deleted file mode 100644 index f75f773..0000000 --- a/.github/workflows/installer.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Installer -on: - push: - paths: - - 'installer/**' - pull_request: - paths: - - 'installer/**' -jobs: - job: - defaults: - run: - working-directory: ./installer - strategy: - fail-fast: false - matrix: - os: [windows-latest, ubuntu-22.04, macos-13] - name: Build on ${{ matrix.os }} - runs-on: ${{ matrix.os }} - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.11' - - name: Install requirements - run: pip install -r requirements.txt - - name: Build - run: python build.py - - uses: actions/upload-artifact@v4 - with: - name: ${{ matrix.os }} - path: installer/dist/ - merge: - name: Merge artifacts - runs-on: ubuntu-latest - needs: job - steps: - - uses: actions/upload-artifact/merge@v4 - with: - name: artifacts - delete-merged: true - separate-directories: true - diff --git a/PolyMod.csproj b/PolyMod.csproj index d17309e..4ace07a 100644 --- a/PolyMod.csproj +++ b/PolyMod.csproj @@ -11,7 +11,7 @@ IL2CPP PolyMod - 1.2.18 + 2.0.0-pre 2.17.3.16375 PolyModdingTeam The Battle of Polytopia's mod loader. @@ -23,7 +23,7 @@ - + all diff --git a/README.md b/README.md index 2772d50..408cd22 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ | | x86 | ARM | |:-------:|:---:|:---:| | Windows | ✅ | ❌ | -| Linux | ⏺️ | ❌ | -| MacOS | ⏺️ | ❌ | +| Linux | ✅ | ❌ | +| MacOS | ❌ | ❌ | | Android | ➖ | 🚧 | | IOS | ➖ | ❌ | diff --git a/installer/build.py b/installer/build.py deleted file mode 100644 index 8b802ae..0000000 --- a/installer/build.py +++ /dev/null @@ -1,19 +0,0 @@ -import os -import PyInstaller.__main__ - -ROOT = os.path.abspath(os.getcwd()) - -PyInstaller.__main__.run( - [ - "--noconfirm", - "--onefile", - "--windowed", - "--icon", - ROOT + "/icon.ico", - "--name", - "PolyMod", - "--add-data", - ROOT + "/icon.ico:.", - ROOT + "/main.py", - ] -) diff --git a/installer/icon.ico b/installer/icon.ico deleted file mode 100644 index f52643a3ebe810f2156f072e7a17e4d7c7bd2821..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 116829 zcmWifWl$W=7KUdRTijiOBzOq!vN$0?aCi6M5+sYe6Fj)P2VX2eaCZytE+3X$?o3Th zPjyvSb^n-i&ilLv06?$z|1S_g4ag3G0HW7%gtC$>CK?&q>k#v!oRsSSXaD~|kY8W= zE~S?L|N7#hqz;{%L_;b2Q7n zp=fij#$uPbU+5+^$A;vho`DL2;BTW~WG9t7Buu zid=e{x*|KnwlezOFVQSzR0+I0@^+!SYPv7UEM=6t_mOQJ3-x!671p{=MNMW(-}pxV zeVk3~vek+*ub z%IFk4YgX$mH|E~kOu+1tndk<2wRZjex!7f3Y$3+ZliS8SF~6z4^Z0J&ht^@sR{FTiEglvp;Q@mI znHm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!=^icltnNMAaekPJAiR)Kw_=Q z4akEu^_DOIa{x*4ymCuUf!YkngeLc0e~Xi zK1_H>XDSEa-E;T!WS=L7UM#{fSC!|z^uM+}h0Ou{IXGWq=oPsfoYkYn1kLYZI~CS& z06FfKGBzJR;}Jo?FJcy;WVyIWwed|X^_8>!2ASMF!vUfL*kWx!taZ)>{#TPN$N@B* zX73JwbvA~Xy_vC77mz!EVC-#T0N?zC1Nf~Rz-O{w`}>2s00PDZ+yVUOqV_W!;YDHV zQTy;k`290}`TLt+1uru#ae>^Brv)6 zH@~KL^m4{ry!p1L*p`rJJIRh&J78?Pf_UDRoX5b%!o=Ra_d0CTf3#hJygF}U+cf;u zItHWI(ya6fN2LL3{2Vnz!2-Y*yAyT*cpAY05Z8dCXbj?c4Ihi55j*V3mBN%#g-l{& z2t5(u0D3oHs=|z%i0=SO$(Y5kBrUeIzj2hUaqO|^<4i%qDL^E3|1B#ka}2^CNN3}D z)_R>`3-jR`@6L6N4svP-0MU(qZg}tR&GX;@zGHP7|30pg%jba)9&MZBcr)8^#d>>t zmM0H?x7r8Xb#>qX$mHA0?n|mCS*npnsq)zA{)aK<*rmeDTiCaclm+-Atub)tk?8^u z7yI)m<(K8+8QMD2)yG+Kf2{KQ&smfcM#{B^+&opge&d)&|Kwhdh+W4H`ufP6wd@BMr4?0biU?}2%^`+Lq0 zKjV&#ui$g7pv>xH9YTvuUo-f+`f$88}|UO$9Kg! zSPwXV71eOpd>%FDxCi098{s{l{QB>l`#$gWh3?In{S0%9^~W`X`*+LkHSbRt!~I?j z<12i>E3HFYYpY@G$#4FbYbLI#aGlUL_<1;bxL@J3ds<6)t*xoowk|n-VxM>C6@SOt zW}nJuKZJGr%GMpOFRa;Be12H-Sj$}BvO}yr*jJx+rE#8f8g0$&^^{e(vFln1|Lbau nc1Sy&CHsV}2K()>_6l00000NkvXXu0mjfcyCBQ diff --git a/installer/main.py b/installer/main.py deleted file mode 100644 index e1fad1b..0000000 --- a/installer/main.py +++ /dev/null @@ -1,154 +0,0 @@ -import os -import io -import sys -import shutil -import zipfile -import requests -import threading -import subprocess -import customtkinter -import CTkMessagebox as messagebox - -OS = { - "linux": "linux", - "linux2": "linux", - "win32": "win", - "darwin": "macos", -}[sys.platform] -BEPINEX = "https://polymod.dev/data/bepinex.txt" -POLYMOD = "https://api.github.com/repos/PolyModdingTeam/PolyMod/releases" - - -def resource_path(path): - try: - base_path = sys._MEIPASS - except Exception: - base_path = os.path.abspath(".") - return os.path.join(base_path, path) - - -def to_zip(request: requests.Response): - return zipfile.ZipFile(io.BytesIO(request.content)) - - -def browse(): - global path_entry - path_entry.delete(0, customtkinter.END) - path_entry.insert(0, customtkinter.filedialog.askdirectory()) - - -def prepare(target): - global progress_bar - path = path_entry.get() - try: - if "Polytopia_Data" not in os.listdir(path): - raise FileNotFoundError - except FileNotFoundError: - messagebox.CTkMessagebox( - title="Error", - message="The folder does not exist or is not valid!", - icon="cancel", - width=100, - height=50 - ) - return - path_entry.configure(state=customtkinter.DISABLED) - browse_button.configure(state=customtkinter.DISABLED) - prerelease_checkbox.destroy() - install_button.destroy() - uninstall_button.destroy() - progress_bar = customtkinter.CTkProgressBar(app, determinate_speed=50 / 2) - progress_bar.grid(column=0, row=1, columnspan=2, padx=5, pady=5) - progress_bar.set(0) - threading.Thread(target=target, daemon=True, args=(path, )).start() - - -def install(path): - to_zip( - requests.get( - requests.get(BEPINEX).text.strip().replace("{os}", OS) - ) - ).extractall(path) - progress_bar.step() - - for release in requests.get(POLYMOD).json(): - if release["prerelease"] and not prerelease_checkbox.get(): continue - latest = release - break - open(path + "/BepInEx/plugins/PolyMod.dll", "wb").write( - requests.get(latest["assets"][0]["browser_download_url"]).content - ) - progress_bar.step() - - customtkinter.CTkButton(app, text="Launch", command=lambda: launch(path)).grid( - column=0, row=2, columnspan=2, padx=5, pady=5 - ) - - -def uninstall(path): - dirs = [ - "BepInEx", - "dotnet", - ] - files = [ - ".doorstop_version", - "changelog.txt", - "doorstop_config.ini", - "winhttp.dll", # windows - "libdoorstop.so", # linux - "libdoorstop.dylib", # mac - "run_bepinex.sh", # linux + mac - ] - for dir in dirs: - shutil.rmtree(path + "/" + dir, True) - progress_bar.step() - for file in files: - try: - os.remove(path + "/" + file) - except FileNotFoundError: - ... - progress_bar.step() - customtkinter.CTkButton(app, text="Quit", command=quit).grid( - column=0, row=2, columnspan=2, padx=5, pady=5 - ) - - -def launch(path): - if sys.platform != "win32": - subprocess.check_call(f"chmod +x {path}/run_bepinex.sh", shell=True) - subprocess.check_call(f"{path}/run_bepinex.sh {path}/Polytopia.*", shell=True) - subprocess.check_call(f"xdg-open https://docs.bepinex.dev/articles/advanced/steam_interop.html", shell=True) - else: - subprocess.check_call(f"start steam://rungameid/874390", shell=True) - quit() - - -def quit(): - app.destroy() - sys.exit() - - -app = customtkinter.CTk() -app.title("PolyMod") -if OS != "linux": - app.iconbitmap(default=resource_path("icon.ico")) -app.resizable(False, False) - -path_entry = customtkinter.CTkEntry( - app, placeholder_text="Game path", width=228) -browse_button = customtkinter.CTkButton( - app, text="Browse", command=browse, width=1) -prerelease_checkbox = customtkinter.CTkCheckBox( - app, text="Prerelease", width=1) -install_button = customtkinter.CTkButton( - app, text="Install", command=lambda: prepare(install)) -uninstall_button = customtkinter.CTkButton( - app, text="Uninstall", command=lambda: prepare(uninstall)) - -path_entry.grid(column=0, row=0, padx=5, pady=5) -browse_button.grid(column=1, row=0, padx=(0, 5), pady=5) -prerelease_checkbox.grid(column=0, row=1, columnspan=2, padx=5, pady=5) -install_button.grid(column=0, row=2, columnspan=2, padx=5, pady=5) -uninstall_button.grid(column=0, row=3, columnspan=2, padx=5, pady=5) - -app.mainloop() diff --git a/installer/requirements.txt b/installer/requirements.txt deleted file mode 100644 index c396099..0000000 --- a/installer/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -requests -pyinstaller -customtkinter -CTkMessagebox \ No newline at end of file diff --git a/resources/localization.json b/resources/localization.json index 3b19f1e..b1219e2 100644 --- a/resources/localization.json +++ b/resources/localization.json @@ -218,18 +218,14 @@ "Russian": "{0} задан на {1}!", "Elyrion": "{0} iȓ ȓ∑Ŧ Ŧȱ {1}!" }, - "polymod_hub_spriteinfo_update": { - "English": "UPDATE SPRITES", - "Russian": "ОБНОВИТЬ СПРАЙТЫ", - "Elyrion": "₺πΔaŦ∑ ȓπriŦ∑ȓ" - }, - "polymod_spriteinfo_updated": { - "English": "Sprite info for mod {0} updated!", - "Russian": "Данные спрайтов обновлены для мода {0}!", - "Elyrion": "ȓπriŦ∑ iŋ₼ȱ ₼ȱr mȱΔ {0} ₺πΔaŦ∑Δ!" - }, - "polymod_spriteinfo_notupdated": { - "English": "No sprite infos were found!", + "polymod_hub_hotreload": { + "English": "HOT RELOAD" + }, + "polymod_hotreload_success": { + "English": "Hot reload completed for the mod {0}!" + }, + "polymod_hotreload_failure": { + "English": "No mods for hot reload!", "Russian": "Данные спрайтов не найдены!", "Elyrion": "ŋȱ ȓπriŦ∑ iŋ₼ȱȓ ~∑r∑ ₼ȱ₺ŋΔ!" }, @@ -242,5 +238,17 @@ "English": "PROCEED", "Russian": "ПРОДОЛЖИТЬ", "Elyrion": "πrȱ#∑∑Δ" + }, + "polymod_title_invalid": { + "English": "Invalid Launch", + "Russian": "Неверный Запуск" + }, + "polymod_description_invalid": { + "English": "PolyMod launch was invalid. Please, open the game via the PolyMod Launcher or proceed to our site to install it :)", + "Russian": "PolyMod запущен неккоректно. Пожалуйста, откройте игру через PolyMod Launcher или перейдите на наш сайт и установите его :)" + }, + "buttons_download_launcher": { + "English": "OUR SITE", + "Russian": "НАШ САЙТ" } -} +} \ No newline at end of file diff --git a/src/Managers/AutoUpdate.cs b/src/Managers/AutoUpdate.cs deleted file mode 100644 index 6384616..0000000 --- a/src/Managers/AutoUpdate.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Diagnostics; -using System.IO.Compression; -using System.Text.Json; -using HarmonyLib; -using UnityEngine; - -namespace PolyMod.Managers; - -/// -/// Manages the automatic update process for PolyMod. -/// -internal static class AutoUpdate -{ - /// - /// Checks for updates when the start screen is shown. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] - private static void StartScreen_UI2_OnShow() - { - if (!Plugin.config.autoUpdate) return; - if (Environment.GetEnvironmentVariable("WINEPREFIX") != null) - { - Plugin.logger.LogError("Autoupdate is not supported on Wine!"); - return; - } - HttpClient client = new(); - client.DefaultRequestHeaders.Add("User-Agent", "PolyMod"); - try - { - // Fetch release information from GitHub API - var json = JsonDocument.Parse( - client.GetAsync("https://api.github.com/repos/PolyModdingTeam/PolyMod/releases").UnwrapAsync() - .Content.ReadAsStringAsync().UnwrapAsync() - ); - JsonElement? latest = null; - for (int i = 0; i < json.RootElement.GetArrayLength(); i++) - { - var release = json.RootElement[i]; - if (release.GetProperty("prerelease").GetBoolean() && !Plugin.config.updatePrerelease) continue; - latest = release; - break; - } - string newVersion = latest?.GetProperty("tag_name").GetString()!.TrimStart('v')!; - if (newVersion.IsVersionOlderOrEqual(Plugin.VERSION)) return; - - // Determine the correct BepInEx URL for the current OS - string os = Application.platform switch - { - RuntimePlatform.WindowsPlayer => "win", - RuntimePlatform.LinuxPlayer => "linux", - RuntimePlatform.OSXPlayer => "macos", - _ => "unknown", - }; - if (os == "unknown") - { - Plugin.logger.LogError("Unsupported platform for autoupdate!"); - return; - } - string bepinex_url = client - .GetAsync("https://polymod.dev/data/bepinex.txt").UnwrapAsync() - .Content.ReadAsStringAsync().UnwrapAsync() - .Replace("{os}", os); - - // The actual update logic - void Update() - { - Time.timeScale = 0; - - // Download new PolyMod DLL and BepInEx files - File.WriteAllBytes( - Path.Combine(Plugin.BASE_PATH, "PolyMod.new.dll"), - client.GetAsync(latest?.GetProperty("assets")[0].GetProperty("browser_download_url").GetString()!).UnwrapAsync() - .Content.ReadAsByteArrayAsync().UnwrapAsync() - ); - using ZipArchive bepinex = new(client.GetAsync(bepinex_url).UnwrapAsync().Content.ReadAsStream()); - bepinex.ExtractToDirectory(Path.Combine(Plugin.BASE_PATH, "New"), overwriteFiles: true); - - // Create and run the appropriate update script for the OS - ProcessStartInfo info = new() - { - WorkingDirectory = Path.Combine(Plugin.BASE_PATH), - CreateNoWindow = true, - }; - if (Application.platform == RuntimePlatform.WindowsPlayer) - { - string batchPath = Path.Combine(Plugin.BASE_PATH, "update.bat"); - File.WriteAllText(batchPath, $@" - @echo off - echo Waiting for Polytopia.exe to exit... - :waitloop - tasklist | findstr /I ""Polytopia.exe"" >nul - if not errorlevel 1 ( - timeout /T 1 >nul - goto waitloop - ) - - echo Updating... - robocopy ""New"" . /E /MOVE /NFL /NDL /NJH /NJS /NP >nul - rmdir /S /Q ""New"" - del /F /Q ""BepInEx\plugins\PolyMod.dll"" - move /Y ""PolyMod.new.dll"" ""BepInEx\plugins\PolyMod.dll"" - - echo Launching game... - start steam://rungameid/874390 - timeout /T 3 /NOBREAK >nul - exit - "); - info.FileName = "cmd.exe"; - info.Arguments = $"/C start \"\" \"{batchPath}\""; - info.WorkingDirectory = Plugin.BASE_PATH; - info.CreateNoWindow = true; - info.UseShellExecute = false; - } - if (Application.platform == RuntimePlatform.LinuxPlayer || Application.platform == RuntimePlatform.OSXPlayer) - { - string bashPath = Path.Combine(Plugin.BASE_PATH, "update.sh"); - File.WriteAllText(bashPath, $@" - #!/bin/bash - - echo ""Waiting for Polytopia to exit..."" - while pgrep -x ""Polytopia"" > /dev/null; do - sleep 1 - done - - echo ""Updating..."" - mv New/* . && rm -rf New - rm -f BepInEx/plugins/PolyMod.dll - mv -f PolyMod.new.dll BepInEx/plugins/PolyMod.dll - - echo ""Launching game..."" - xdg-open steam://rungameid/874390 & - - sleep 3 - exit 0 - "); - - System.Diagnostics.Process chmod = new System.Diagnostics.Process(); - chmod.StartInfo.FileName = "chmod"; - chmod.StartInfo.Arguments = $"+x \"{bashPath}\""; - chmod.StartInfo.UseShellExecute = false; - chmod.StartInfo.CreateNoWindow = true; - chmod.Start(); - chmod.WaitForExit(); - - info.FileName = "/bin/bash"; - info.Arguments = $"\"{bashPath}\""; - info.WorkingDirectory = Plugin.BASE_PATH; - info.CreateNoWindow = true; - info.UseShellExecute = false; - } - Process.Start(info); - Application.Quit(); - } - - // Show a popup to the user asking if they want to update - PopupManager.GetBasicPopupWithData(new( - Localization.Get("polymod.autoupdate"), - Localization.Get("polymod.autoupdate.description"), - new(new PopupBase.PopupButtonData[] { - new( - "polymod.autoupdate.update", - PopupBase.PopupButtonData.States.None, - (Il2CppSystem.Action)Update - ) - })) - ).Show(); - } - catch (Exception e) - { - Plugin.logger.LogError($"Failed to check updates: {e.Message}"); - } - } - - /// - /// Initializes the AutoUpdate manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(AutoUpdate)); - } -} \ No newline at end of file diff --git a/src/Managers/Compatibility.cs b/src/Managers/Compatibility.cs index 1d55bb7..c2d2498 100644 --- a/src/Managers/Compatibility.cs +++ b/src/Managers/Compatibility.cs @@ -1,4 +1,5 @@ using HarmonyLib; +using Il2CppInterop.Runtime; using System.Text; using UnityEngine; using UnityEngine.EventSystems; @@ -20,6 +21,12 @@ internal static class Compatibility /// internal static bool shouldResetSettings = false; private static bool sawSignatureWarning; + private const string downloadLink = "https://polymod.dev/download/"; + + // TODO: rewrite all of this bullshit! each mod should have a checksum. and then using per mod checksum, we should calculate overall checksum + // why? launcher will let you install a mod if u dont have it. if u have a mod with this id, but it doesnt match any checksum of any ver of + // this mod on polymod.dev, then we just leave it as "install". if there is a new ver, we can simply put "update" + // also add a client mod check or whatever /// /// Hashes the signatures of all loaded mods to create a checksum. @@ -87,6 +94,36 @@ private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] private static void StartScreen_UI2_OnShow() { + if(!Plugin.ValidLaunch && Application.platform != RuntimePlatform.Android) + { + PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.title.invalid"), + Localization.Get("polymod.description.invalid"), + new PopupBase.PopupButtonData[] { + new( + "buttons.exitgame", + PopupBase.PopupButtonData.States.None, + callback: (Il2CppSystem.Action)Application.Quit, + closesPopup: false + ), + new( + "buttons.download.launcher", + PopupBase.PopupButtonData.States.None, + callback: DelegateSupport.ConvertDelegate(OpenSite), + closesPopup: false + ) + } + ) + ).Show(); + + void OpenSite() + { + NativeHelpers.OpenURL(downloadLink, false); + Application.Quit(); + } + return; + } string lastChecksum = checksum; try { diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 57da0b6..28d3601 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -12,6 +12,8 @@ using System.Text.Encodings.Web; using Il2CppSystem.Linq; using System.Text.RegularExpressions; +using Il2CppInterop.Runtime.InteropTypes.Arrays; +using UnityEngine.Experimental.U2D; namespace PolyMod.Managers; @@ -168,13 +170,13 @@ internal static void UpdateSpriteInfos() { Loader.UpdateSprite(kvp.Key); } - message += Localization.Get("polymod.spriteinfo.updated", new Il2CppSystem.Object[] { subnames[1] }); + message += Localization.Get("polymod.hotreload.success", new Il2CppSystem.Object[] { subnames[1] }); } } } if (message == string.Empty) { - message = Localization.Get("polymod.spriteinfo.notupdated"); + message = Localization.Get("polymod.hotreload.failure"); } NotificationManager.Notify(message); } @@ -185,16 +187,38 @@ internal static void UpdateSpriteInfos() internal static void DumpData() { Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); + DumpLogic(); + DumpLocalization(); + DumpSprites(); + DumpTribePreviewLegacy(); + DumpPrefabs(); + NotificationManager.Notify(Localization.Get("polymod.hub.dumped")); + } + + internal static void DumpLogic() + { Directory.CreateDirectory(Plugin.LOGIC_DUMP_PATH); + for (int version = 1; version <= VersionManager.GameLogicDataVersion; version++) + { + File.WriteAllTextAsync( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"GameLogicData{version}.json"), + PolytopiaDataManager.provider.LoadGameLogicData(version) + ); + } + for (int version = 1; version <= VersionManager.AvatarDataVersion; version++) + { + File.WriteAllTextAsync( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"AvatarData{version}.json"), + PolytopiaDataManager.provider.LoadAvatarData(version) + ); + } + } + + internal static void DumpLocalization() + { Directory.CreateDirectory(Plugin.LOCALIZATION_DUMP_PATH); - File.WriteAllTextAsync( - Path.Combine(Plugin.LOGIC_DUMP_PATH, "gameLogicData.json"), - PolytopiaDataManager.provider.LoadGameLogicData(VersionManager.GameLogicDataVersion) - ); - File.WriteAllTextAsync( - Path.Combine(Plugin.LOGIC_DUMP_PATH, "avatarData.json"), - PolytopiaDataManager.provider.LoadAvatarData(1337) - ); + + // Languages dump var source = LocalizationManager.Sources[0]; foreach (var language in source.GetLanguages()) { @@ -221,26 +245,102 @@ internal static void DumpData() json ); } + // Full loc dump foreach (var category in source.GetCategories()) File.WriteAllTextAsync( Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"localization_{category}.csv"), source.Export_CSV(category) ); - foreach (KeyValuePair entry in Registry.mods) + } + + private static void DumpSprites() + { + Directory.CreateDirectory(Plugin.SPRITES_DUMP_PATH); + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + + for (int i = 0; i < AtlasData.raw.Count; i++) { - foreach (Mod.File file in entry.Value.files) + if (spriteAtlasManager.loadedAtlases[i] == null) continue; // not loaded, skip + + string[] row = AtlasData.raw[i]; + string atlasName = row[0]; + string dir = Path.Combine(Plugin.SPRITES_DUMP_PATH, atlasName); + Directory.CreateDirectory(dir); + + Dictionary atlasSpriteInfo = new(); + for (int j = 1; j < row.Length; j++) { - Match spritesMatch = Regex.Match(Path.GetFileName(file.name), @"^sprites(?:_(.*))?\.json$"); - if (spritesMatch.Success) - File.WriteAllBytes( - Path.Combine( - Plugin.DUMPED_DATA_PATH, - $"{Path.GetFileNameWithoutExtension(file.name)}_{entry.Key}.json" - ), - file.bytes - ); + string spriteName = row[j]; + Sprite sprite = spriteAtlasManager.GetSprite(spriteName, atlasName); + if (sprite == null) continue; + + (byte[] bytes, Visual.SpriteInfo spriteInfo) = SpriteToPng(sprite); + File.WriteAllBytesAsync(Path.Combine(dir, spriteName + ".png"), bytes); + atlasSpriteInfo.Add(spriteName, spriteInfo); } + File.WriteAllTextAsync( + Path.Combine(dir, $"sprites_{atlasName}.json"), + JsonSerializer.Serialize(atlasSpriteInfo, new JsonSerializerOptions { WriteIndented = true, Converters = { new PolyMod.Json.Vector2Json() }}) + ); + } + } + + private static (byte[], Visual.SpriteInfo) SpriteToPng(Sprite sprite) + { + Texture2D atlasTexture = sprite.texture; + int spriteWidth = (int)sprite.rect.width; + int spriteHeight = (int)sprite.rect.height; + float pixelsPerUnit = sprite.pixelsPerUnit; + Vector2 spritePivot = sprite.pivot; + + var meshVertices = sprite.vertices; + var meshUvs = sprite.uv; + var meshTriangles = sprite.triangles; + + RenderTexture renderTexture = RenderTexture.GetTemporary( + spriteWidth, spriteHeight, 0, + RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); + RenderTexture previousActiveRenderTexture = RenderTexture.active; + RenderTexture.active = renderTexture; + GL.Clear(true, true, Color.clear); + + var spriteMaterial = new Material(Shader.Find("Sprites/Default")); + spriteMaterial.mainTexture = atlasTexture; + spriteMaterial.SetPass(0); + + GL.PushMatrix(); + GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); + GL.Begin(GL.TRIANGLES); + for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) + { + int vertexIndex = meshTriangles[triangleCornerIndex]; + Vector2 uv = meshUvs[vertexIndex]; + Vector2 vertex = meshVertices[vertexIndex]; + + GL.TexCoord(new Vector3(uv.x, uv.y, 0)); + GL.Vertex3(vertex.x * pixelsPerUnit + spritePivot.x, + vertex.y * pixelsPerUnit + spritePivot.y, 0); } + GL.End(); + GL.PopMatrix(); + + var croppedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); + croppedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); + croppedTexture.Apply(); + + RenderTexture.active = previousActiveRenderTexture; + RenderTexture.ReleaseTemporary(renderTexture); + + byte[] pngBytes = ImageConversion.EncodeToPNG(croppedTexture); + UnityEngine.Object.Destroy(croppedTexture); + UnityEngine.Object.Destroy(spriteMaterial); + UnityEngine.Object.Destroy(sprite); + return (pngBytes, new Visual.SpriteInfo(pixelsPerUnit, spritePivot)); + } + + internal static void DumpTribePreviewLegacy() + { + // TODO legacy tribe preview dump. i have to update that foreach (TribeType type in Enum.GetValues(typeof(TribeType))) { List previewTiles = new(); @@ -270,19 +370,21 @@ internal static void DumpData() JsonSerializer.Serialize(previewTiles, new JsonSerializerOptions { WriteIndented = true }) ); } - NotificationManager.Notify(Localization.Get("polymod.hub.dumped")); } + internal static void DumpPrefabs() // TODO + {} + /// /// Shows the configuration popup. /// internal static void ShowConfigPopup() { - BasicPopupLegacy polymodPopup = Visual.GetBasicPopupLegacy(); + BasicPopup polymodPopup = PopupManager.GetBasicPopup(); polymodPopup.Header = Localization.Get("polymod.hub.config"); polymodPopup.Description = ""; polymodPopup.buttonData = CreateConfigPopupButtonData(); - polymodPopup.ShowSetWidth(POPUP_WIDTH); + polymodPopup.Show(); } internal static void ShowPolyModHub() @@ -335,7 +437,7 @@ void OpenDiscord() closesPopup: false )); popupButtons.Add(new( - "polymod.hub.spriteinfo.update", + "polymod.hub.hotreload", callback: DelegateSupport.ConvertDelegate(UpdateSpriteInfos), closesPopup: false )); @@ -357,7 +459,7 @@ internal static PopupButtonData[] CreateConfigPopupButtonData() if (GameManager.Instance.isLevelLoaded) { - popupButtons.Add(new PopupButtonData(Localization.Get("polymod.hub.spriteinfo.update"), PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnUpdateSpritesButtonClicked), -1, true, null)); + popupButtons.Add(new PopupButtonData(Localization.Get("polymod.hub.hotreload"), PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnUpdateSpritesButtonClicked), -1, true, null)); } else { @@ -366,25 +468,13 @@ internal static PopupButtonData[] CreateConfigPopupButtonData() new Il2CppSystem.Object[] { Localization.Get("polymod.debug", new Il2CppSystem.Object[]{}).ToUpperInvariant() } ); - string autoUpdateButtonName = Localization.Get( - Plugin.config.autoUpdate ? "polymod.hub.config.disable" : "polymod.hub.config.enable", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate", - new Il2CppSystem.Object[]{}).ToUpperInvariant() } - ); - string includeAlphasButtonName = Localization.Get( - Plugin.config.updatePrerelease ? "polymod.hub.config.disable" : "polymod.hub.config.enable", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate.alpha", - new Il2CppSystem.Object[]{}).ToUpperInvariant() } - ); popupButtons.Add(new PopupButtonData(debugButtonName, PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnDebugButtonClicked), -1, true, null)); - popupButtons.Add(new PopupButtonData(autoUpdateButtonName, PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnAutoUpdateButtonClicked), -1, true, null)); - popupButtons.Add(new PopupButtonData(includeAlphasButtonName, Plugin.config.autoUpdate ? PopupButtonData.States.None : PopupButtonData.States.Disabled, DelegateSupport.ConvertDelegate(OnIncludeAlphasButtonClicked), -1, true, null)); } return popupButtons.ToArray(); void OnDebugButtonClicked() { - Plugin.config = new(debug: !Plugin.config.debug, autoUpdate: Plugin.config.autoUpdate, updatePrerelease: Plugin.config.updatePrerelease); + Plugin.config = new(debug: !Plugin.config.debug); Plugin.WriteConfig(); Plugin.UpdateConsole(); NotificationManager.Notify(Localization.Get( @@ -395,32 +485,6 @@ void OnDebugButtonClicked() isConfigPopupActive = false; } - void OnAutoUpdateButtonClicked() - { - Plugin.config = new(debug: Plugin.config.debug, autoUpdate: !Plugin.config.autoUpdate, updatePrerelease: Plugin.config.updatePrerelease); - Plugin.WriteConfig(); - Plugin.UpdateConsole(); - NotificationManager.Notify(Localization.Get( - "polymod.config.setto", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate", - new Il2CppSystem.Object[]{}), Plugin.config.autoUpdate } - )); - isConfigPopupActive = false; - } - - void OnIncludeAlphasButtonClicked() - { - Plugin.config = new(debug: Plugin.config.debug, autoUpdate: Plugin.config.autoUpdate, updatePrerelease: !Plugin.config.updatePrerelease); - Plugin.WriteConfig(); - Plugin.UpdateConsole(); - NotificationManager.Notify(Localization.Get( - "polymod.config.setto", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate.alpha", - new Il2CppSystem.Object[]{}), Plugin.config.updatePrerelease } - )); - isConfigPopupActive = false; - } - void OnUpdateSpritesButtonClicked() { UpdateSpriteInfos(); @@ -440,4 +504,4 @@ internal static void Init() { Harmony.CreateAndPatchAll(typeof(Hub)); } -} +} \ No newline at end of file diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 6bead52..bbc0b71 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -341,10 +341,42 @@ private static void StartTurnAction_Execute(StartTurnAction __instance, GameStat private static bool Unit_CreateUnit(Unit __instance, UnitData unitData, TribeType tribe, SkinType unitSkin) { Unit unit = PrefabManager.GetPrefab(unitData.type, tribe, unitSkin); - if (unit == null) Console.Write("THIS FUCKING SHIT IS NULL WHAT THE FUCK"); return true; } + + /// + /// Serialization fixes for custom (modded) content. + /// GamePlayerSummary stores the tribe as a single byte, which custom tribe ids (>= 1000) overflow into garbage. + /// Instead the tribe is clamped to None before the untouched native serializer runs and menu summaries show a generic icon for custom tribes, nothing more. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(GamePlayerSummary), nameof(GamePlayerSummary.Serialize))] + private static bool GamePlayerSummary_Serialize(GamePlayerSummary __instance) + { + if ((int)__instance.TribeType >= byte.MaxValue) + { + __instance.TribeType = TribeType.None; + } + + return true; + } + + /// + /// Serialization fixes for custom (modded) content. + /// PlayerState stores the play climate as a single byte, which custom climate ids (>= 1000) overflow into garbage. + /// Instead the climate is overriden by the tribe value, as those are effectively the same. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(PlayerState), nameof(PlayerState.Deserialize))] + private static void PlayerState_Deserialize(PlayerState __instance, Il2CppSystem.IO.BinaryReader reader, int version) + { + if ((int)__instance.tribe >= Plugin.AUTOIDX_STARTS_FROM) + { + __instance.climate = __instance.tribe; + } + } + /// /// Initializes the Main manager. /// diff --git a/src/NullableFix.cs b/src/NullableFix.cs index adc6cdf..1c7e549 100644 --- a/src/NullableFix.cs +++ b/src/NullableFix.cs @@ -1,5 +1,5 @@ #nullable disable - +// verify whether it is needed at all bruv, i tested one time quickly and it easily compiled namespace System.Runtime.CompilerServices { /// diff --git a/src/Plugin.cs b/src/Plugin.cs index 96ae942..5cc311d 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -1,10 +1,10 @@ -using System.Reflection; +using System.IO.Pipes; +using System.Reflection; using System.Text.Json; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using PolyMod.Managers; -using UnityEngine; namespace PolyMod; @@ -14,18 +14,22 @@ namespace PolyMod; [BepInPlugin("com.polymod", "PolyMod", VERSION)] public partial class Plugin : BepInEx.Unity.IL2CPP.BasePlugin { + internal static string? Token { get; set; } + internal static bool ValidLaunch { get; set; } = false; + internal static bool Disabled { get; set; } = false; + /// /// Represents the configuration for PolyMod. /// /// Whether to enable debug mode. - /// Whether to automatically update PolyMod. - /// Whether to include pre-release versions when updating. internal record PolyConfig( bool debug = false, - bool autoUpdate = true, - bool updatePrerelease = false, - bool allowUnsafeIndexes = false - ); + bool allowUnsafeIndexes = false, + string overrideDeviceId = "" + ) + { + public List disabledMods { get; init; } = new(); + }; /// /// The starting index for automatically assigned IDs. @@ -38,6 +42,8 @@ internal record PolyConfig( internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY = "INCOMPATIBILITY_WARNING_LAST_VERSION"; + internal const int LAUNCH_DATA_TIMEOUT = 2000; + /// /// The base path for PolyMod files. /// @@ -63,6 +69,16 @@ internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY /// public static readonly string LOCALIZATION_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Localization"); + /// + /// The path to the directory where sprites and sprite infos are dumped. + /// + public static readonly string SPRITES_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Sprites"); + + /// + /// The path to the directory where prefabs datas are dumped. + /// + public static readonly string PREFABS_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Prefabs"); + /// /// The path to the PolyMod configuration file. /// @@ -122,10 +138,12 @@ public override void Load() logger = Log; ConfigFile.CoreConfig[new("Logging.Disk", "WriteUnityLog")].BoxedValue = true; - AutoUpdate.Init(); + CaptureLaunchData(); - Compatibility.Init(); + if(Disabled) + return; + Compatibility.Init(); Audio.Init(); Loc.Init(); Visual.Init(); @@ -134,6 +152,31 @@ public override void Load() Main.Init(); } + internal static void CaptureLaunchData() + { + try + { + using var client = new NamedPipeClientStream( + ".", "PolyMod.Launcher", PipeDirection.In, PipeOptions.CurrentUserOnly); + client.Connect(LAUNCH_DATA_TIMEOUT); + + using var reader = new StreamReader(client); + var line = reader.ReadLine(); + if (string.IsNullOrEmpty(line)) return; + using var doc = JsonDocument.Parse(line); + var root = doc.RootElement; + + ValidLaunch = root.GetProperty("validLaunch").GetBoolean(); + Disabled = root.GetProperty("disabled").GetBoolean(); + Token = root.GetProperty("token").GetString() ?? ""; + } + catch + { + ValidLaunch = false; + } + ValidLaunch = true; + } + /// /// Gets a resource stream from the assembly. /// @@ -163,9 +206,10 @@ internal static void UpdateConsole() { ConsoleManager.CreateConsole(); } - else + else if (OperatingSystem.IsWindows()) { + // BepInEx's Unix console driver throws unsupported on detach. Off-Windows there is no separate console window, so there is nothing to detach. ConsoleManager.DetachConsole(); } } -} +} \ No newline at end of file From 4211f85ceb1d9b1b9e3623a2acec17ae919113d9 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Tue, 13 Oct 2026 22:33:21 +0200 Subject: [PATCH 02/42] removed a lot of stuff which is not needed anymore. removed WHOLE prefab system for now --- src/Loader.cs | 231 +------------------ src/Managers/Audio.cs | 7 +- src/Managers/Main.cs | 49 ++-- src/Managers/PrefabFix.cs | 141 ++++++++++++ src/Managers/Visual.cs | 461 +++++++------------------------------- src/Registry.cs | 76 ++++--- src/Util.cs | 72 ------ 7 files changed, 309 insertions(+), 728 deletions(-) create mode 100644 src/Managers/PrefabFix.cs diff --git a/src/Loader.cs b/src/Loader.cs index 69fe92b..bfbbb1a 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -135,19 +135,8 @@ out TribeAbility.Type tribeAbilityType [typeof(UnitData.Type)] = new List>() { new((token, duringEnumCacheCreation) => { - if(duringEnumCacheCreation) + if(!duringEnumCacheCreation) { - if (token["prefab"] == null) - { - Registry.prefabNames.Add((int)token["idx"], EnumCache.GetName(UnitData.Type.Scout).ToLowerInvariant()); - } - } - else - { - if (token["prefab"] != null) - { - Registry.prefabNames.Add((int)token["idx"], token["prefab"].ToString().ToLowerInvariant()); - } if (token["embarksTo"] != null) { string unitId = Util.GetJTokenName(token); @@ -169,19 +158,7 @@ out TribeAbility.Type tribeAbilityType [typeof(ImprovementData.Type)] = new List>() { new((token, duringEnumCacheCreation) => { - if (duringEnumCacheCreation) - { - ImprovementData.Type improvementPrefabType = ImprovementData.Type.CustomsHouse; - if (token["prefab"] != null) - { - string prefabId = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(token["prefab"]!.ToString()); - if (Enum.TryParse(prefabId, out ImprovementData.Type parsedType)) - improvementPrefabType = parsedType; - } - if(token["idx"] != null) - PrefabManager.improvements.TryAdd((ImprovementData.Type)(int)token["idx"], PrefabManager.improvements[improvementPrefabType]); - } - else + if (!duringEnumCacheCreation) { string improvementId = Util.GetJTokenName(token); if (token["attractsResource"] != null) @@ -204,20 +181,7 @@ out TribeAbility.Type tribeAbilityType [typeof(ResourceData.Type)] = new List>() { new((token, duringEnumCacheCreation) => - { - if (duringEnumCacheCreation) - { - ResourceData.Type resourcePrefabType = ResourceData.Type.Game; - if (token["prefab"] != null) - { - string prefabId = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(token["prefab"]!.ToString()); - if (Enum.TryParse(prefabId, out ResourceData.Type parsedType)) - resourcePrefabType = parsedType; - } - if(token["idx"] != null) - PrefabManager.resources.TryAdd((ResourceData.Type)(int)token["idx"], PrefabManager.resources[resourcePrefabType]); - } - }) + { }) }, [typeof(SkinData)] = new List>() { @@ -715,161 +679,17 @@ public static void LoadAudioFile(Mod mod, Mod.File file) // TODO: issue #71 } - /// - /// Loads a prefab info file from a mod and creates a new unit prefab. - /// - /// The mod the prefab info file belongs to. - /// The prefab info file to load. - public static void LoadPrefabInfoFile(Mod mod, Mod.File file) - { - try - { - var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (prefab == null || prefab.type != Visual.PrefabType.Unit || prefab.visualParts.Count == 0) - return; - - if (Registry.unitPrefabs.Keys.Any(pref => pref.name == prefab.name)) - { - Plugin.logger.LogInfo($"Prefab {prefab.name} already exists, skipping."); - } - var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); - if (baseUnit == null) - return; - - var unitInstance = GameObject.Instantiate(baseUnit); - if (unitInstance == null) - return; - - var spriteContainer = unitInstance.transform.GetChild(0); - var material = ClearExistingPartsAndExtractMaterial(spriteContainer); + public static void LoadPrefabsFile(Mod mod, Mod.File file) + {} - var visualParts = ApplyVisualParts(prefab, spriteContainer, material); + public static void LoadUnitPrefabFile(Mod mod, Mod.File file) + {} - Transform? headPositionMarker = null; - foreach (var vp in visualParts) - { - if (vp.visualPart.gameObject.name == prefab.headPositionMarker) - { - headPositionMarker = vp.visualPart.gameObject.transform; - break; - } - } - - unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; - - var svr = unitInstance.GetComponent(); - svr.visualParts = visualParts.ToArray(); + public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) + {} - GameObject.DontDestroyOnLoad(unitInstance.gameObject); - Registry.unitPrefabs.Add(prefab, unitInstance.GetComponent()); - - Plugin.logger.LogInfo($"Registered prefab {prefab.name} info from {mod.id} mod."); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading prefab {Path.GetFileNameWithoutExtension(file.name)} info from {mod.id} mod: {e.StackTrace}."); - } - } - - /// - /// Clears existing visual parts from a prefab and extracts the material. - /// - /// The transform containing the sprite parts. - /// The material of the original sprite parts. - private static Material? ClearExistingPartsAndExtractMaterial(Transform spriteContainer) - { - Material? material = null; - for (int i = 0; i < spriteContainer.childCount; i++) - { - var child = spriteContainer.GetChild(i); - if (child.gameObject.name == "Head") - { - var renderer = child.GetComponent(); - if (renderer != null) - material = renderer.material; - } - GameObject.Destroy(child.gameObject); - } - return material; - } - - /// - /// Applies new visual parts to a prefab. - /// - /// A list of visual part information. - /// The transform to add the parts to. - /// The material to use for the parts. - /// A list of the created visual parts. - private static List ApplyVisualParts( - Visual.PrefabInfo prefab, - Transform spriteContainer, - Material? material) - { - if (prefab.visualParts.Count == 0) - return new List(); - - List parts = new(); - - foreach (var info in prefab.visualParts) - { - parts.Add(CreateVisualPart(info, spriteContainer, material)); - } - - return parts; - } - - /// - /// Creates a single visual part for a prefab. - /// - /// The information for the visual part. - /// The parent transform for the part. - /// The material to use for the part. - /// The created visual part. - private static SkinVisualsReference.VisualPart CreateVisualPart( - Visual.VisualPartInfo info, - Transform parent, - Material? material) - { - var visualPartObj = new GameObject(info.gameObjectName); - visualPartObj.transform.SetParent(parent); - visualPartObj.transform.position = info.coordinates; - visualPartObj.transform.localScale = info.scale; - visualPartObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - var outlineObj = new GameObject("Outline"); - outlineObj.transform.SetParent(visualPartObj.transform); - outlineObj.transform.position = info.coordinates; - outlineObj.transform.localScale = info.scale; - outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - var visualPart = new SkinVisualsReference.VisualPart - { - DefaultSpriteName = info.baseName, - visualPart = visualPartObj, - outline = outlineObj, - tintable = info.tintable - }; - - var renderer = visualPartObj.AddComponent(); - renderer.material = material; - renderer.sortingLayerName = "Units"; - renderer.sortingOrder = info.tintable ? 0 : 1; - - visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; - - var outlineRenderer = outlineObj.AddComponent(); - outlineRenderer.material = material; - outlineRenderer.sortingLayerName = "Units"; - outlineRenderer.sortingOrder = -1; - - visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; - - return visualPart; - } + public static void LoadResourcePrefabFile(Mod mod, Mod.File file) + {} /// /// Loads and applies a game logic data patch from a mod. @@ -1030,35 +850,6 @@ internal static void CreateMappings(JObject rootObject) /// internal static void ProcessPrefabs() { - Plugin.logger.LogInfo($"Processing prefabs, count: {Registry.prefabNames.Count}."); - foreach (KeyValuePair item in Registry.prefabNames) - { - UnitData.Type unitPrefabType = UnitData.Type.Scout; - string prefabId = item.Value; - int hashKey = PrefabManager.GetSkinnedHashKey((UnitData.Type)item.Key, TribeType.None, SkinType.Default); - if (!Enum.TryParse(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(prefabId), out unitPrefabType)) // Existing unit prefabs - { - KeyValuePair prefabInfo = Registry.unitPrefabs.FirstOrDefault( - kv => kv.Key.name == prefabId - ); - if (!EqualityComparer.Default.Equals(prefabInfo.Key, default)) - { - Visual.UnitPrefabInfo unitPrefabInfo = new( - EnumCache.GetName((UnitData.Type)item.Key), - EnumCache.GetName(TribeType.None), - EnumCache.GetName(SkinType.Default) - ); - Visual.customPrefabs.Add(unitPrefabInfo, prefabInfo.Value); - Plugin.logger.LogInfo($"Using custom prefab {prefabId} for unit {item.Key}."); - continue; - } - } - Plugin.logger.LogInfo($"Using existing prefab {EnumCache.GetName(unitPrefabType)} for unit {item.Key}."); - PrefabManager.units.TryAdd( - hashKey, - PrefabManager.units[PrefabManager.GetSkinnedHashKey(unitPrefabType, TribeType.None, SkinType.Default)] - ); - } } /// diff --git a/src/Managers/Audio.cs b/src/Managers/Audio.cs index 100cec7..d6fb90e 100644 --- a/src/Managers/Audio.cs +++ b/src/Managers/Audio.cs @@ -1,5 +1,4 @@ using HarmonyLib; -using Polytopia.Data; using UnityEngine; using PolytopiaBackendBase.Common; @@ -17,7 +16,7 @@ public static class Audio [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetNatureAudioClip))] private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) { - AudioClip? audioClip = Registry.GetAudioClip("nature", Util.GetStyle(type, skinType)); + AudioClip? audioClip = Registry.GetAudioClip("nature", type, skinType); if (audioClip != null) { __result = audioClip; @@ -33,7 +32,7 @@ private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeTy [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetMusicAudioClip))] private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) { - AudioClip? audioClip = Registry.GetAudioClip("music", Util.GetStyle(type, skinType)); + AudioClip? audioClip = Registry.GetAudioClip("music", type, skinType); if (audioClip != null) { __result = audioClip; @@ -51,7 +50,7 @@ private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, Sk { AudioClip? audioClip = Registry.GetAudioClip( EnumCache.GetName(id), - EnumCache.GetName(skinType) + skin: skinType ); if (audioClip != null) { diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index bbc0b71..0e36936 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -333,18 +333,6 @@ private static void StartTurnAction_Execute(StartTurnAction __instance, GameStat } } - /// - /// Patches the unit creation method to handle custom unit prefabs. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(Unit), nameof(Unit.CreateUnit))] - private static bool Unit_CreateUnit(Unit __instance, UnitData unitData, TribeType tribe, SkinType unitSkin) - { - Unit unit = PrefabManager.GetPrefab(unitData.type, tribe, unitSkin); - return true; - } - - /// /// Serialization fixes for custom (modded) content. /// GamePlayerSummary stores the tribe as a single byte, which custom tribe ids (>= 1000) overflow into garbage. @@ -444,10 +432,41 @@ internal static void Load(GameLogicData gameLogicData, JObject json) ); continue; } - Match prefabMatch = Regex.Match(Path.GetFileName(file.name), @"^prefab(?:_(.*))?\.json$"); - if (prefabMatch.Success) + + Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); + if (prefabsMatch.Success) + { + Loader.LoadPrefabsFile( + mod, + file + ); + continue; + } + + Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); + if (unitPrefabMatch.Success) + { + Loader.LoadUnitPrefabFile( + mod, + file + ); + continue; + } + + Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); + if (improvementPrefabMatch.Success) + { + Loader.LoadImprovementPrefabFile( + mod, + file + ); + continue; + } + + Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); + if (resourcePrefabMatch.Success) { - Loader.LoadPrefabInfoFile( + Loader.LoadResourcePrefabFile( mod, file ); diff --git a/src/Managers/PrefabFix.cs b/src/Managers/PrefabFix.cs new file mode 100644 index 0000000..23dc092 --- /dev/null +++ b/src/Managers/PrefabFix.cs @@ -0,0 +1,141 @@ +using HarmonyLib; +using PolyMod; +using Polytopia.Data; +using PolytopiaBackendBase.Common; +using static PrefabManager; + +public static class PrefabFix +{ + public readonly struct SkinnedKey : IEquatable + { + private readonly UnitData.Type unitType; + private readonly TribeType tribeType; + private readonly SkinType skinType; + + public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + this.unitType = unitType; + this.tribeType = tribeType; + this.skinType = skinType; + } + + public bool Equals(SkinnedKey other) + { + return unitType == other.unitType + && tribeType == other.tribeType + && skinType == other.skinType; + } + + public override bool Equals(object? other) + { + return other is SkinnedKey otherKey && Equals(otherKey); + } + + public override int GetHashCode() + { + return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); + } + } + + private static readonly Dictionary unitsNew = new(); + private static readonly Dictionary> unitOverridesNew = new(); + private static readonly Dictionary unitUIOverridesNew = new(); + + [HarmonyPostfix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] + private static void PrefabManager_Awake_Postfix(PrefabManager __instance) + { + unitsNew.Clear(); + unitOverridesNew.Clear(); + unitUIOverridesNew.Clear(); + + foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) + { + unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; + } + + foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) + { + if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) + { + overridesForCondition = new Dictionary(); + unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; + } + overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; + } + + foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) + { + unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; + } + + Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] + public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] + public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) + { + __result = uiOverridePrefab; + } + else + { + __result = ResolveUnitPrefab(unitType, tribe, skin); + } + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] + public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) + { + __result = ResolveUnitPrefab(type, tribe, skin); + return false; + } + + private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + if (SeasonManager.IsChristmas() + && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) + && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) + && christmasPrefab != null) + { + return christmasPrefab; + } + + SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); + if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) + { + return exactPrefab; + } + + if (skinType != SkinType.Default || tribeType != TribeType.None) + { + SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); + SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); + SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); + + if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) + || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) + || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) + { + unitsNew[exactKey] = fallbackPrefab; + return fallbackPrefab; + } + } + + Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); + unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); + return lastResortPrefab!; + } +} \ No newline at end of file diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index bccc5fc..f048244 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -55,73 +55,21 @@ public record SkinInfo(int idx, string id, SkinData? skinData); /// A dictionary of custom widths for basic popups. public static Dictionary basicPopupWidths = new(); - /// Represents information about a unit prefab. - public struct UnitPrefabInfo - { - public UnitPrefabInfo(string type, string tribe, string skin) - { - this.type = type; - this.tribe = tribe; - this.skin = skin; - } - public string type; - public string tribe; - public string skin; - } + private const int BASIC_POPUP_LEGACY_ID = 29; - public static Dictionary customPrefabs = new(); - private static UnitData.Type currentUnitTypeUI = UnitData.Type.None; - private static TribeType attackerTribe = TribeType.None; /// /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. /// internal static Dictionary customFloodingSkins = new(); private static bool isTakingSnapshot = false; private static float? baseOrthographicCameraSize = null; - - /// The type of a custom prefab. - public enum PrefabType - { - Unit, - Improvement, - Resource - } - - /// Represents information about a custom prefab. - public record PrefabInfo - { - public PrefabType type { get; init; } - public string name { get; init; } - public List visualParts { get; init; } - public string headPositionMarker { get; init; } - - [JsonConstructor] - public PrefabInfo( - PrefabType type, - List visualParts, - string name = "", - string headPositionMarker = "") - { - this.type = type; - this.name = name.ToLowerInvariant(); - this.visualParts = visualParts; - this.headPositionMarker = headPositionMarker; - } - } - - /// Represents information about a visual part of a prefab. - public record VisualPartInfo( - string gameObjectName, - string baseName, - float rotation = 0f, - Vector2 coordinates = new Vector2(), - Vector2 scale = new Vector2(), - bool tintable = false - ); private static bool enableOutlines = false; private static bool seenWarningWCPopup = false; public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); + private static Dictionary? cachedSpriteDataReverse = null; + private static Dictionary cachedReversedNames = new(); + #region General /// A placeholder patch for the TechItem.SetupComplete method. @@ -131,9 +79,9 @@ private static void TechItem_SetupComplete() { } - /// Patches the sprite atlas manager to load custom sprites. - [HarmonyPrefix] - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), typeof(string), typeof(string), typeof(SpriteCallback))] + /// Patches the sprite atlas manager to load custom sprites. TODOOOO + // [HarmonyPrefix] + // [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), typeof(string), typeof(string), typeof(SpriteCallback))] private static bool SpriteAtlasManager_LoadSprite(SpriteAtlasManager __instance, string atlas, string sprite, SpriteCallback completion) { bool found = false; @@ -160,7 +108,7 @@ void GetAtlas(SpriteAtlas spriteAtlas) } } string name = string.Join("_", filteredNames); - Sprite? newSprite = Registry.GetSprite(name, style); + Sprite? newSprite = null; // Registry.GetSprite(name, style); if (newSprite != null) { completion?.Invoke(atlas, sprite, newSprite); @@ -171,13 +119,70 @@ void GetAtlas(SpriteAtlas spriteAtlas) } /// Patches the sprite atlas manager to look up custom sprites. + internal static void CacheSpriteNames() + { + cachedSpriteDataReverse = new(); + foreach (Polytopia.Data.TerrainData.Type terrainType in Enum.GetValues()) + { + string result = SpriteData.TerrainToString(terrainType); + if(terrainType == Polytopia.Data.TerrainData.Type.Wetland) + { + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(Polytopia.Data.TerrainData.Type.Field) + "_flooded"); + continue; + } + + if(result == SpriteData.TILE_UNKNOWN) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(terrainType)); + } + + foreach (ResourceData.Type resourceType in Enum.GetValues()) + { + string result = SpriteData.ResourceToString(resourceType); + if(result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(resourceType)); + } + + foreach (ImprovementData.Type improvementType in Enum.GetValues()) + { + string result = SpriteData.ImprovementToString(improvementType); + if(result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(improvementType)); + } + } + internal static string FormatSpriteName(string baseName) + { + if(cachedSpriteDataReverse == null) + CacheSpriteNames(); + + if(cachedReversedNames.ContainsKey(baseName)) + return cachedReversedNames[baseName]; + + string formattedName = baseName; + foreach (var valuePair in cachedSpriteDataReverse!) + { + formattedName = formattedName.Replace(valuePair.Key, valuePair.Value); + } + cachedReversedNames[baseName] = formattedName; + return baseName; + } + [HarmonyPostfix] [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] - private static void SpriteAtlasManager_DoSpriteLookup(ref SpriteAtlasManager.SpriteLookupResult __result, SpriteAtlasManager __instance, string baseName, TribeType tribe, SkinType skin, int level) + private static void SpriteAtlasManager_DoSpriteLookup(ref SpriteAtlasManager.SpriteLookupResult __result, SpriteAtlasManager __instance, + string baseName, TribeType tribe, SkinType skin, int level) { - baseName = Util.FormatSpriteName(baseName); + Sprite? sprite = Registry.GetSprite(baseName, tribe, skin, level); + if (sprite != null) + __result.sprite = sprite; - Sprite? sprite = Registry.GetSprite(baseName, Util.GetStyle(tribe, skin), level); + string formattedName = FormatSpriteName(baseName); + sprite = Registry.GetSprite(formattedName, tribe, skin, level); if (sprite != null) __result.sprite = sprite; } @@ -190,7 +195,7 @@ private static void SpriteAtlasManager_DoSpriteLookup(ref SpriteAtlasManager.Spr [HarmonyPatch(typeof(InteractionBar), nameof(InteractionBar.Show))] private static bool InteractionBar_Show(InteractionBar __instance, bool instant, bool force) { - enableOutlines = true; + enableOutlines = true; // bro return true; } @@ -199,7 +204,7 @@ private static bool InteractionBar_Show(InteractionBar __instance, bool instant, [HarmonyPatch(typeof(UISpriteDuplicator), nameof(UISpriteDuplicator.CreateImage), typeof(SpriteRenderer), typeof(Transform), typeof(Transform), typeof(float), typeof(Vector2), typeof(bool))] private static bool UISpriteDuplicator_CreateImage(SpriteRenderer spriteRenderer, Transform source, Transform destination, float scale, Vector2 offset, bool forceFullAlpha) { - return !(spriteRenderer.sortingOrder == -1 && !enableOutlines); + return !(spriteRenderer.sortingOrder == -1 && !enableOutlines); // uhhh tf is this hack } /// Disables outlines after the interaction bar is shown. @@ -210,111 +215,12 @@ private static void InteractionBar_Show_Postfix(InteractionBar __instance, bool enableOutlines = false; } - /// Sets the current unit type being rendered in the UI. - [HarmonyPrefix] - [HarmonyPatch(typeof(UIUnitRenderer), nameof(UIUnitRenderer.CreateUnit))] - private static bool UIUnitRenderer_CreateUnit_Prefix(UIUnitRenderer __instance) - { - currentUnitTypeUI = __instance.unitType; - return true; - } - - /// Resets the current unit type being rendered in the UI. - [HarmonyPostfix] - [HarmonyPatch(typeof(UIUnitRenderer), nameof(UIUnitRenderer.CreateUnit))] - private static void UIUnitRenderer_CreateUnit_Postfix(UIUnitRenderer __instance) - { - currentUnitTypeUI = UnitData.Type.None; - } - - /// Skins the visual parts of a unit with custom sprites. - [HarmonyPostfix] - [HarmonyPatch(typeof(SkinVisualsRenderer), nameof(SkinVisualsRenderer.SkinWorldObject))] - private static void SkinVisualsRenderer_SkinWorldObject( - SkinVisualsRenderer.SkinWorldType type, - SkinVisualsReference skinVisuals, - SkinVisualsTransientData transientSkinData, - bool checkOutlines, - int level) - { - if (type != SkinVisualsRenderer.SkinWorldType.Unit || skinVisuals == null || - skinVisuals.visualParts == null || transientSkinData == null) - return; - - Unit unit = skinVisuals.gameObject.GetComponent(); - - string unitTypeName = EnumCache.GetName(UnitData.Type.Warrior); - - if(unit != null && unit.UnitData != null) - unitTypeName = EnumCache.GetName(unit.unitData.type); - if (currentUnitTypeUI != UnitData.Type.None) - unitTypeName = EnumCache.GetName(currentUnitTypeUI); - - string style = Util.GetStyle(transientSkinData.unitSettings.tribe, transientSkinData.unitSettings.skin); - - foreach (var visualPart in skinVisuals.visualParts) - { - if(visualPart.visualPart != null) - UpdateVisualPart(visualPart, $"{visualPart.visualPart.name}_{unitTypeName}", style); - } - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), - typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) - )] - private static void PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) - { - UnitPrefabInfo unitPrefabInfo = new( - EnumCache.GetName(type), - EnumCache.GetName(TribeType.None), - EnumCache.GetName(SkinType.Default) - ); - if(customPrefabs.ContainsKey( - unitPrefabInfo - )) - { - __result = customPrefabs[unitPrefabInfo]; - } - } - #endregion #region Level - /// Updates the visual parts of a resource with custom sprites. - [HarmonyPostfix] - [HarmonyPatch(typeof(Resource), nameof(Resource.UpdateObject), typeof(MapRenderContext), typeof(SkinVisualsTransientData))] - private static void Resource_UpdateObject(Resource __instance, MapRenderContext ctx, SkinVisualsTransientData transientSkinData) - { - if (__instance.data != null) - { - string style = Util.GetStyle(__instance.tile.data.climate, __instance.tile.data.Skin); - string name = EnumCache.GetName(__instance.tile.data.resource.type); - - foreach (SkinVisualsReference.VisualPart visualPart in __instance.GetSkinVisualsReference().visualParts) - { - UpdateVisualPart(visualPart, name, style); - } - } - } - - /// Updates a building with a custom sprite. - [HarmonyPostfix] - [HarmonyPatch(typeof(Building), nameof(Building.UpdateObject), typeof(MapRenderContext), typeof(SkinVisualsTransientData))] - private static void Building_UpdateObject(Building __instance, MapRenderContext ctx, SkinVisualsTransientData transientSkinData) - { - string style = Util.GetStyle(transientSkinData.foundingTribeSettings.tribe, transientSkinData.foundingTribeSettings.skin); - string name = EnumCache.GetName(__instance.tile.data.improvement.type); - Sprite? sprite = Registry.GetSprite(name, style, __instance.Level); - if (sprite != null) - { - __instance.Sprite = sprite; - } - } - /// Updates the terrain graphics with custom sprites. [HarmonyPostfix] - [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] + [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] // recheck that private static void TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile) { string terrain = EnumCache.GetName(tile.data.terrain) ?? string.Empty; @@ -351,7 +257,7 @@ private static void TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, T PolytopiaSpriteRenderer? renderer = (PolytopiaSpriteRenderer?)rendererProperty.GetValue(tile); if (renderer != null) { - Sprite? additionalSprite = Registry.GetSprite(propertyName + flood, Util.GetStyle(tribe, skinType)); + Sprite? additionalSprite = Registry.GetSprite(propertyName + flood, tribe, skinType); if (additionalSprite != null) { renderer.Sprite = additionalSprite; @@ -361,7 +267,7 @@ private static void TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, T } } - Sprite? sprite = Registry.GetSprite(terrain + flood, Util.GetStyle(tribe, skinType)); + Sprite? sprite = Registry.GetSprite(terrain + flood, tribe, skinType); if (sprite != null) { __instance.spriteRenderer.Sprite = sprite; @@ -410,19 +316,6 @@ private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRende } } - [HarmonyPostfix] - [HarmonyPatch(typeof(Tile), nameof(Tile.Render), typeof(MapRenderContext), typeof(SkinVisualsTransientData))] - private static void Tile_Render(Tile __instance, MapRenderContext ctx, SkinVisualsTransientData transientSkinningData) - { - Sprite? sprite = Registry.GetSprite("hidden"); - if(sprite != null) - { - __instance.fogOfWarRenderer.atlasName = ""; - __instance.fogOfWarRenderer.sprite = sprite; - __instance.fogOfWarRenderer.spriteRenderer.sprite = sprite; - } - } - #endregion #region Tribe Preview @@ -604,13 +497,16 @@ public static void Tile_RenderDebug(Tile __instance) #endregion #region UI + // check if still needed /// Provides custom sprites for improvements in the UI. [HarmonyPostfix] [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetImprovementSprite), typeof(ImprovementData.Type), typeof(TribeType), typeof(SkinType), typeof(SpriteAtlasManager))] private static void UIUtils_GetImprovementSprite(ref Sprite __result, ImprovementData.Type improvement, TribeType tribe, SkinType skin, SpriteAtlasManager atlasManager) { - Sprite? sprite = Registry.GetSprite(EnumCache.GetName(improvement), Util.GetStyle(tribe, skin)); + Sprite? sprite = Registry.GetSprite(EnumCache.GetName(improvement), tribe, skin); + Console.Write(EnumCache.GetName(improvement)); + Console.Write(sprite == null); if (sprite != null) { __result = sprite; @@ -630,139 +526,14 @@ private static void UIUtils_GetImprovementSprite_2(ref Sprite __result, SkinVisu [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetResourceSprite))] private static void UIUtils_GetResourceSprite(ref Sprite __result, SkinVisualsTransientData data, ResourceData.Type resource, SpriteAtlasManager atlasManager) { - Sprite? sprite = Registry.GetSprite(EnumCache.GetName(resource), Util.GetStyle(data.tileClimateSettings.tribe, data.tileClimateSettings.skin)); + TribeAndSkin tileClimateSettings = data.tileClimateSettings; + Sprite? sprite = Registry.GetSprite(EnumCache.GetName(resource), tileClimateSettings.tribe, tileClimateSettings.skin); if (sprite != null) { __result = sprite; } } - #endregion - #region Houses - - /// Provides custom sprites for houses in the city view. - [HarmonyPostfix] - [HarmonyPatch(typeof(CityRenderer), nameof(CityRenderer.GetHouse))] - private static void CityRenderer_GetHouse(ref PolytopiaSpriteRenderer __result, CityRenderer __instance, TribeType tribe, int type, SkinType skinType) - { - PolytopiaSpriteRenderer polytopiaSpriteRenderer = __result; - - if (type != __instance.HOUSE_WORKSHOP && type != __instance.HOUSE_PARK) - { - Sprite? sprite = Registry.GetSprite("house", Util.GetStyle(tribe, skinType), type); - if (sprite != null) - { - polytopiaSpriteRenderer.Sprite = sprite; - TerrainMaterialHelper.SetSpriteSaturated(polytopiaSpriteRenderer, __instance.IsEnemyCity); - __result = polytopiaSpriteRenderer; - } - } - } - - /// Provides custom sprites for houses in the UI city renderer. - [HarmonyPostfix] - [HarmonyPatch(typeof(UICityRenderer), nameof(UICityRenderer.GetResource))] - private static void UICityRenderer_GetResource(ref GameObject __result, string baseName, TribeType tribe, SkinType skin) - { - Image imageComponent = __result.GetComponent(); - string[] tokens = baseName.Split('_'); - if (tokens.Length > 0) - { - if (tokens[0] == "House") - { - int level = 0; - if (tokens.Length > 1) - { - _ = int.TryParse(tokens[1], out level); - } - - Sprite? sprite = Registry.GetSprite("house", Util.GetStyle(tribe, skin), level); - if (sprite == null) - { - return; - } - imageComponent.sprite = sprite; - imageComponent.SetNativeSize(); - } - } - } - - #endregion - #region Icons - - /// Provides custom sprites for UI icons. - [HarmonyPostfix] - [HarmonyPatch(typeof(UIIconData), nameof(UIIconData.GetImage))] - private static void UIIconData_GetImage(ref Image __result, string id) - { - Sprite? sprite; - if (GameManager.LocalPlayer != null) - { - sprite = Registry.GetSprite(id, Util.GetStyle(GameManager.LocalPlayer.tribe, GameManager.LocalPlayer.skinType)); - } - else - { - sprite = Registry.GetSprite(id); - } - if (sprite != null) - { - __result.sprite = sprite; - __result.useSpriteMesh = true; - __result.SetNativeSize(); - } - } - - /// Provides custom sprites for face icons in the game info row. - [HarmonyPostfix] - [HarmonyPatch(typeof(GameInfoRow), nameof(GameInfoRow.LoadFaceIcon), typeof(TribeType), typeof(SkinType))] - private static void GameInfoRow_LoadFaceIcon(GameInfoRow __instance, TribeType type, SkinType skinType) - { - string style = EnumCache.GetName(type); - - if (style == "None") - { - for (int i = 0; i < 20; i++) - { - type += byte.MaxValue + 1; - style = EnumCache.GetName(type); - - if (style != "None") - { - break; - } - } - } - - Sprite? sprite = Registry.GetSprite("head", Util.GetStyle(type, skinType)); - - if (sprite != null) - { - __instance.SetFaceIcon(sprite); - } - - if (__instance.icon.sprite == null) - { - __instance.LoadFaceIcon(SpriteData.SpecialFaceIcon.neutral); - } - } - - /// Provides custom sprites for player info icons. - [HarmonyPostfix] - [HarmonyPatch(typeof(PlayerInfoIcon), nameof(PlayerInfoIcon.SetData), typeof(TribeType), typeof(SkinType), typeof(SpriteData.SpecialFaceIcon), typeof(Color), typeof(DiplomacyRelationState), typeof(PlayerInfoIcon.Mood))] - private static void PlayerInfoIcon_SetData(PlayerInfoIcon __instance, TribeType tribe, SkinType skin, SpriteData.SpecialFaceIcon face, Color color, DiplomacyRelationState diplomacyState, PlayerInfoIcon.Mood mood) - { - if (face == SpriteData.SpecialFaceIcon.tribe) - { - Sprite? sprite = Registry.GetSprite("head", Util.GetStyle(tribe, skin)); - if (sprite != null) - { - __instance.HeadImage.sprite = sprite; - Vector2 size = sprite.rect.size; - __instance.HeadImage.rectTransform.sizeDelta = size * __instance.rectTransform.GetHeight() / 512f; - } - } - } - #endregion #region Popups @@ -781,34 +552,6 @@ private static void UpdateWidth(PopupBase __instance) __instance.rectTransform.SetWidth(basicPopupWidths[id]); } - /// Sets the attacker's tribe before a unit attacks. - [HarmonyPrefix] - [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] - private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Il2CppSystem.Action onComplete) - { - if (__instance.Owner != null) - { - attackerTribe = __instance.Owner.tribe; - } - return true; - } - - /// Sets the skin of a weapon's graphics, using custom sprites if available. - [HarmonyPostfix] - [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.SetSkin))] - private static void WeaponGFX_SetSkin(WeaponGFX __instance, SkinType skinType) - { - if (attackerTribe != TribeType.None) - { - Sprite? sprite = Registry.GetSprite(__instance.defaultSprite.name, Util.GetStyle(attackerTribe, skinType)); - if (sprite != null) - { - __instance.spriteRenderer.sprite = sprite; - } - attackerTribe = TribeType.None; - } - } - /// Removes a popup's custom width when it is hidden. [HarmonyPostfix] [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] @@ -855,24 +598,6 @@ public static void ShowSetWidth(this BasicPopupLegacy self, int width) self.Show(); } - // [HarmonyPrefix] - // [HarmonyPatch(typeof(BasicPopup), nameof(BasicPopup.SetButtonData))] - // public static bool SetButtonData(BasicPopup __instance, PopupBase.PopupButtonData[] buttonDatas, bool updateOmniCursor) - // { - // if (buttonDatas == null) - // { - // __instance.SetDefaultOkbutton(); - // return false; - // } - // foreach (var buttonData in buttonDatas) - // { - // var MainButton = __instance.createButton(buttonData.text, buttonData.callback, UIButtonBase_UI2.ButtonStyle.Suggested); - // MainButton.OnClickedSignal.Add(DelegateSupport.ConvertDelegate(__instance.Hide)); - // } - // __instance.RunLayout(); - // return false; - // } - #endregion internal static BasicPopupLegacy GetBasicPopupLegacy() @@ -889,33 +614,6 @@ internal static BasicPopupLegacy GetBasicPopupLegacy() return basicPopupLegacy; } - /// Updates a visual part with a custom sprite. - private static void UpdateVisualPart(SkinVisualsReference.VisualPart? visualPart, string name, string style) - { - if(visualPart == null || visualPart.visualPart == null) - return; - - Sprite? sprite = Registry.GetSprite(name, style) ?? Registry.GetSprite(visualPart.visualPart.name, style); - - if (sprite != null && visualPart.renderer != null) - { - if (visualPart.renderer.spriteRenderer != null) - visualPart.renderer.spriteRenderer.sprite = sprite; - else if (visualPart.renderer.polytopiaSpriteRenderer != null) - visualPart.renderer.polytopiaSpriteRenderer.sprite = sprite; - } - - Sprite? outlineSprite = Registry.GetSprite($"{name}_outline", style) ?? Registry.GetSprite($"{visualPart.visualPart.name}_outline", style); - - if (outlineSprite != null && visualPart.outlineRenderer != null) - { - if (visualPart.outlineRenderer.spriteRenderer != null) - visualPart.outlineRenderer.spriteRenderer.sprite = outlineSprite; - else if (visualPart.outlineRenderer.polytopiaSpriteRenderer != null) - visualPart.outlineRenderer.polytopiaSpriteRenderer.sprite = outlineSprite; - } - } - /// Builds a sprite from raw byte data. /// The raw byte data of the image. /// The pivot point of the sprite. @@ -955,5 +653,6 @@ public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = internal static void Init() { Harmony.CreateAndPatchAll(typeof(Visual)); + Harmony.CreateAndPatchAll(typeof(PrefabFix)); } } diff --git a/src/Registry.cs b/src/Registry.cs index 3a3d36a..5bfd5f1 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -41,26 +41,6 @@ public static class Registry /// public static Dictionary spriteInfos = new(); - /// - /// A dictionary of prefab names, keyed by their enum value. - /// - public static Dictionary prefabNames = new(); - - /// - /// A dictionary of custom unit prefabs, keyed by their prefab info. - /// - public static Dictionary unitPrefabs = new(); - - /// - /// A dictionary of custom resource prefabs, keyed by their prefab info. - /// - public static Dictionary resourcePrefabs = new(); - - /// - /// A dictionary of custom improvement prefabs, keyed by their prefab info. - /// - public static Dictionary improvementsPrefabs = new(); - /// /// A dictionary of loaded asset bundles, keyed by their name. /// @@ -86,24 +66,45 @@ public static class Registry /// public static int gameModesAutoidx = Enum.GetValues(typeof(GameMode)).Length; + public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1) + { + string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); + string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); + return GetSpriteByText(baseName, tribeText, skinText, level); + } /// /// Gets a sprite from the registry, trying to find the best match. /// - /// The name of the sprite. - /// The style of the sprite (e.g., tribe or skin). - /// The level of the sprite (e.g., for cities). - /// The requested sprite, or null if not found. The lookup priority is: name_style_level, name__level, name_style_, name__. - public static Sprite? GetSprite(string name, string style = "", int level = 0) + public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", int level = -1) { Sprite? sprite = null; - name = name.ToLower(); - style = style.ToLower(); - // This looks backwards, but GetOrDefault returns the provided default value if the key isn't found. - // This means `sprite` is updated sequentially, and the last, most-specific match is the one that is kept. - sprite = sprites.GetOrDefault($"{name}__", sprite); - sprite = sprites.GetOrDefault($"{name}_{style}_", sprite); - sprite = sprites.GetOrDefault($"{name}__{level}", sprite); - sprite = sprites.GetOrDefault($"{name}_{style}_{level}", sprite); + baseName = baseName.ToLower(); + tribeText = tribeText.ToLower(); + skinText = skinText.ToLower(); + + List spriteNameVariants = new(); + + if (level >= 0) + { + string levelText = level.ToString(); + spriteNameVariants.Add(baseName + "_" + levelText); + spriteNameVariants.Add(baseName + "_" + levelText + "_" + tribeText); + spriteNameVariants.Add(baseName + "_" + levelText + "_" + skinText); + spriteNameVariants.Add(baseName + "_" + levelText + "_" + tribeText + "_" + skinText); + } + else + { + spriteNameVariants.Add(baseName); + spriteNameVariants.Add(baseName + "_" + tribeText); + spriteNameVariants.Add(baseName + "_" + skinText); + spriteNameVariants.Add(baseName + "_" + tribeText + "_" + skinText); + } + + foreach(string spriteName in spriteNameVariants) + { + sprite = sprites.GetOrDefault(spriteName, sprite); + } + return sprite; } @@ -113,12 +114,15 @@ public static class Registry /// The name of the audio clip. /// The style of the audio clip. /// The requested audio clip, or null if not found. - public static AudioClip? GetAudioClip(string name, string style) + public static AudioClip? GetAudioClip(string name, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default) { AudioSource? audioSource = null; name = name.ToLower(); - style = style.ToLower(); - audioSource = audioClips.GetOrDefault($"{name}_{style}", audioSource); + string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); + string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); + tribeText = tribeText.ToLower(); + skinText = skinText.ToLower(); + audioSource = audioClips.GetOrDefault($"{name}_{tribeText}_{skinText}", audioSource); if (audioSource == null) return null; return audioSource.clip; } diff --git a/src/Util.cs b/src/Util.cs index 3396965..d1fd591 100644 --- a/src/Util.cs +++ b/src/Util.cs @@ -3,8 +3,6 @@ using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Newtonsoft.Json.Linq; -using Polytopia.Data; -using PolytopiaBackendBase.Common; namespace PolyMod; @@ -100,74 +98,4 @@ internal static bool IsVersionOlderOrEqual(this string version1, string version2 return string.Compare(pre1, pre2, StringComparison.Ordinal) <= 0; } - - /// - /// Gets the style name for a tribe and skin combination. - /// - /// The tribe. - /// The skin. - /// The style name. - internal static string GetStyle(TribeType tribe, SkinType skin) - { - return skin != SkinType.Default ? EnumCache.GetName(skin) : EnumCache.GetName(tribe); - } - - /// - /// Formats a sprite name to match the enum naming convention. - /// This is a workaround for inconsistencies in the game's sprite naming. - /// - /// The original sprite name. - /// The formatted sprite name. - internal static string FormatSpriteName(string baseName) // I cant believe i had to do this shit #MIDJIWANFIXYOURSHITCODE - { - // This method is necessary because the sprite names in the game's data do not always - // match the names in the corresponding enums. This method replaces the hardcoded sprite - // names with the enum names to ensure consistency. - baseName = baseName.Replace(SpriteData.IMPROVEMENT_AQUA_FARM, EnumCache.GetName(ImprovementData.Type.Aquafarm)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ATOLL, EnumCache.GetName(ImprovementData.Type.Atoll)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_BURN_FOREST, EnumCache.GetName(ImprovementData.Type.BurnForest)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_CLEAR_FOREST, EnumCache.GetName(ImprovementData.Type.ClearForest)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_CUSTOMS_HOUSE, EnumCache.GetName(ImprovementData.Type.CustomsHouse)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_FARM, EnumCache.GetName(ImprovementData.Type.Farm)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_FOREST_TEMPLE, EnumCache.GetName(ImprovementData.Type.ForestTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_FORGE, EnumCache.GetName(ImprovementData.Type.Forge)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_GROW_FOREST, EnumCache.GetName(ImprovementData.Type.GrowForest)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ICE_BANK, EnumCache.GetName(ImprovementData.Type.IceBank)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ICE_PORT, EnumCache.GetName(ImprovementData.Type.Outpost)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ICE_TEMPLE, EnumCache.GetName(ImprovementData.Type.IceTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_LUMBER_HUT, EnumCache.GetName(ImprovementData.Type.LumberHut)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_MARKET, EnumCache.GetName(ImprovementData.Type.Market)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_MINE, EnumCache.GetName(ImprovementData.Type.Mine)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_MOUNTAIN_TEMPLE, EnumCache.GetName(ImprovementData.Type.MountainTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_PORT, EnumCache.GetName(ImprovementData.Type.Port)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ROAD, EnumCache.GetName(ImprovementData.Type.Road)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_RUIN, EnumCache.GetName(ImprovementData.Type.Ruin)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_SANCTUARY, EnumCache.GetName(ImprovementData.Type.Sanctuary)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_SAWMILL, EnumCache.GetName(ImprovementData.Type.Sawmill)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_TEMPLE, EnumCache.GetName(ImprovementData.Type.Temple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_WATER_TEMPLE, EnumCache.GetName(ImprovementData.Type.WaterTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_WINDMILL, EnumCache.GetName(ImprovementData.Type.Windmill)); - - baseName = baseName.Replace(SpriteData.RESOURCE_AQUACROP, EnumCache.GetName(ResourceData.Type.AquaCrop)); - baseName = baseName.Replace(SpriteData.RESOURCE_CROP, EnumCache.GetName(ResourceData.Type.Crop)); - baseName = baseName.Replace(SpriteData.RESOURCE_FISH, EnumCache.GetName(ResourceData.Type.Fish)); - baseName = baseName.Replace(SpriteData.RESOURCE_FRUIT, EnumCache.GetName(ResourceData.Type.Fruit)); - baseName = baseName.Replace(SpriteData.RESOURCE_GAME, EnumCache.GetName(ResourceData.Type.Game)); - baseName = baseName.Replace(SpriteData.RESOURCE_METAL, EnumCache.GetName(ResourceData.Type.Metal)); - baseName = baseName.Replace(SpriteData.RESOURCE_SPORES, EnumCache.GetName(ResourceData.Type.Spores)); - baseName = baseName.Replace(SpriteData.RESOURCE_STARFISH, EnumCache.GetName(ResourceData.Type.Starfish)); - baseName = baseName.Replace(SpriteData.RESOURCE_WHALE, EnumCache.GetName(ResourceData.Type.Whale)); - - baseName = baseName.Replace(SpriteData.TILE_FIELD, EnumCache.GetName(TerrainData.Type.Field)); - baseName = baseName.Replace(SpriteData.TILE_FOREST, EnumCache.GetName(TerrainData.Type.Forest)); - baseName = baseName.Replace(SpriteData.TILE_ICE, EnumCache.GetName(TerrainData.Type.Ice)); - baseName = baseName.Replace(SpriteData.TILE_MOUNTAIN, EnumCache.GetName(TerrainData.Type.Mountain)); - baseName = baseName.Replace(SpriteData.TILE_OCEAN, EnumCache.GetName(TerrainData.Type.Ocean)); - baseName = baseName.Replace(SpriteData.TILE_UNKNOWN, EnumCache.GetName(TerrainData.Type.Field)); - baseName = baseName.Replace(SpriteData.TILE_WATER, EnumCache.GetName(TerrainData.Type.Water)); - baseName = baseName.Replace(SpriteData.TILE_WETLAND, EnumCache.GetName(TerrainData.Type.Field) + "_flooded"); - - baseName = baseName.Replace("UI_", ""); - return baseName; - } } From 5b12ab229b8c382b2e2eeb8409237377e33d688a Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Wed, 14 Oct 2026 23:02:48 +0200 Subject: [PATCH 03/42] Rewrote whole prefabs system! (almost) --- src/Json/EnumNameJson.cs | 29 ++ src/Loader.cs | 110 ++++++- src/Managers/Hub.cs | 4 +- src/Managers/Visual.cs | 211 +------------ src/Managers/Visual/PrefabCreator.cs | 289 ++++++++++++++++++ .../PrefabRegistry.cs} | 44 +-- src/Managers/Visual/SkinnedKey.cs | 46 +++ src/Managers/Visual/TribePreviewManager.cs | 223 ++++++++++++++ src/Registry.cs | 2 +- 9 files changed, 705 insertions(+), 253 deletions(-) create mode 100644 src/Json/EnumNameJson.cs create mode 100644 src/Managers/Visual/PrefabCreator.cs rename src/Managers/{PrefabFix.cs => Visual/PrefabRegistry.cs} (78%) create mode 100644 src/Managers/Visual/SkinnedKey.cs create mode 100644 src/Managers/Visual/TribePreviewManager.cs diff --git a/src/Json/EnumNameJson.cs b/src/Json/EnumNameJson.cs new file mode 100644 index 0000000..953ec68 --- /dev/null +++ b/src/Json/EnumNameJson.cs @@ -0,0 +1,29 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace PolyMod.Json; + +/// +/// Converts fixed (non-extensible) enums to and from their plain string names. +/// Use this for enums that are not registered in EnumCache. +/// +public class EnumNameJson : JsonConverter where EnumType : struct, Enum +{ + public override EnumType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? enumName = reader.GetString(); + + if (enumName != null && Enum.TryParse(enumName, true, out EnumType parsedValue)) + { + return parsedValue; + } + + string validNames = string.Join(", ", Enum.GetNames(typeof(EnumType))); + throw new JsonException($"Unknown {typeof(EnumType).Name} value '{enumName}'. Valid values: {validNames}"); + } + + public override void Write(Utf8JsonWriter writer, EnumType value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } +} \ No newline at end of file diff --git a/src/Loader.cs b/src/Loader.cs index bfbbb1a..9e91445 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -126,7 +126,7 @@ out TribeAbility.Type tribeAbilityType } if (token["preview"] != null) { - Visual.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; + TribePreviewManager.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; Registry.tribePreviews[Util.GetJTokenName(token)] = preview; } } @@ -680,16 +680,114 @@ public static void LoadAudioFile(Mod mod, Mod.File file) } public static void LoadPrefabsFile(Mod mod, Mod.File file) - {} + { + try + { + if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("all") || PrefabCreator.prefabsFilesToProcess["all"] == null) + PrefabCreator.prefabsFilesToProcess["all"] = new(); + + PrefabCreator.prefabsFilesToProcess["all"].Add(file.bytes); + + // var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // { + // Converters = { new Vector2Json() }, + // PropertyNameCaseInsensitive = true, + // }); + // if (prefab == null) + // return; + + // PrefabCreator.unitInfos.AddRange(prefab.units); + // PrefabCreator.improvementInfos.AddRange(prefab.improvements); + // PrefabCreator.resourceInfos.AddRange(prefab.resources); + + Plugin.logger.LogInfo($"Registered prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } public static void LoadUnitPrefabFile(Mod mod, Mod.File file) - {} + { + try + { + if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("units") || PrefabCreator.prefabsFilesToProcess["units"] == null) + PrefabCreator.prefabsFilesToProcess["units"] = new(); + + PrefabCreator.prefabsFilesToProcess["units"].Add(file.bytes); + + // var unitPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // { + // Converters = { new Vector2Json() }, + // PropertyNameCaseInsensitive = true, + // }); + // if (unitPrefab == null) + // return; + + // PrefabCreator.unitInfos.Add(unitPrefab); + + Plugin.logger.LogInfo($"Registered unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) - {} + { + try + { + if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("improvements") || PrefabCreator.prefabsFilesToProcess["improvements"] == null) + PrefabCreator.prefabsFilesToProcess["improvements"] = new(); + + PrefabCreator.prefabsFilesToProcess["improvements"].Add(file.bytes); + + // var improvementPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // { + // Converters = { new Vector2Json() }, + // PropertyNameCaseInsensitive = true, + // }); + // if (improvementPrefab == null) + // return; + + // PrefabCreator.improvementInfos.Add(improvementPrefab); + + Plugin.logger.LogInfo($"Registered improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } public static void LoadResourcePrefabFile(Mod mod, Mod.File file) - {} + { + try + { + if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("resources") || PrefabCreator.prefabsFilesToProcess["resources"] == null) + PrefabCreator.prefabsFilesToProcess["resources"] = new(); + + PrefabCreator.prefabsFilesToProcess["resources"].Add(file.bytes); + + // var resourcePrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // { + // Converters = { new Vector2Json() }, + // PropertyNameCaseInsensitive = true, + // }); + // if (resourcePrefab == null) + // return; + + // PrefabCreator.resourceInfos.Add(resourcePrefab); + + Plugin.logger.LogInfo($"Registered resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } /// /// Loads and applies a game logic data patch from a mod. @@ -736,6 +834,7 @@ internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject r { CreateMappings(rootObject); ProcessCustomTribes(); + // OKAY BASICALLY I need to find a way to load certain files at this stage (?) ProcessPrefabs(); ProcessEmbarkOverrides(); ProcessAttractOverrides(); @@ -850,6 +949,7 @@ internal static void CreateMappings(JObject rootObject) /// internal static void ProcessPrefabs() { + PrefabCreator.ProcessPrefabs(); } /// diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 28d3601..553652c 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -343,7 +343,7 @@ internal static void DumpTribePreviewLegacy() // TODO legacy tribe preview dump. i have to update that foreach (TribeType type in Enum.GetValues(typeof(TribeType))) { - List previewTiles = new(); + List previewTiles = new(); SelectTribePopup popup = PopupManager.GetSelectTribePopup(); for (int x = -3; x <= 3; x++) { @@ -352,7 +352,7 @@ internal static void DumpTribePreviewLegacy() Vector2Int pos = new Vector2Int(x, y); if (popup.UIWorldPreview.worldPreviewData.TryGetData(pos, type, out UITileData tileData)) { - Visual.PreviewTile previewTile = new Visual.PreviewTile + TribePreviewManager.PreviewTile previewTile = new TribePreviewManager.PreviewTile { x = tileData.Position.x, y = tileData.Position.y, diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index f048244..82999a9 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -18,35 +18,6 @@ namespace PolyMod.Managers; /// public static class Visual { - /// - /// Represents a tile in a tribe preview. - /// - public class PreviewTile - { - /// The x-coordinate of the tile. - [JsonInclude] - public int? x = null; - /// The y-coordinate of the tile. - [JsonInclude] - public int? y = null; - /// The terrain type of the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public Polytopia.Data.TerrainData.Type terrainType = Polytopia.Data.TerrainData.Type.None; - /// The resource type on the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ResourceData.Type? resourceType = null; - /// The unit type on the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public UnitData.Type? unitType = null; - /// The improvement type on the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ImprovementData.Type? improvementType = null; - } - /// Represents information about a sprite, such as its pivot and pixels per unit. public record SpriteInfo(float? pixelsPerUnit, Vector2? pivot); @@ -61,11 +32,8 @@ public record SkinInfo(int idx, string id, SkinData? skinData); /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. /// internal static Dictionary customFloodingSkins = new(); - private static bool isTakingSnapshot = false; - private static float? baseOrthographicCameraSize = null; private static bool enableOutlines = false; private static bool seenWarningWCPopup = false; - public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); private static Dictionary? cachedSpriteDataReverse = null; private static Dictionary cachedReversedNames = new(); @@ -319,182 +287,6 @@ private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRende #endregion #region Tribe Preview - [HarmonyPostfix] - [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] - public static void PreloadTribePreviews() - { - Dictionary previewSaveStateDatas = new(); - - SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; - foreach(string tribe in Registry.tribePreviews.Keys) - { - string previewId = GetTribePreviewName(tribe); - PreviewTile[] customPreview = Registry.tribePreviews[tribe]; - previewSaveStateDatas[previewId] = new(TribePreviewRegistry.fallbackStateIndex, fallbackSaveStateData, customPreview); - } - - for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) - { - SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; - if(previewSaveStateDatas.ContainsKey(saveStateData.name)) - { - previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, previewSaveStateDatas[saveStateData.name].customPreview); - } - } - - foreach (string previewId in previewSaveStateDatas.Keys) - { - var data = previewSaveStateDatas[previewId]; - SaveStateData? customSaveStateData = ApplyCustomPreview(previewId, data.saveStateData, data.customPreview); - if(customSaveStateData == null) - continue; - - if(data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) - { - List saveStateDatas = TribePreviewRegistry.saveStateDatas.ToList(); - saveStateDatas.Add(customSaveStateData); - TribePreviewRegistry.saveStateDatas = saveStateDatas.ToArray(); - } - else - { - TribePreviewRegistry.saveStateDatas[data.arrayIdx] = customSaveStateData; - } - } - } - - private static string GetTribePreviewName(string tribeType) - { - return "worldpreview_" + tribeType; - } - - private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) - { - SaveStateData? saveStateData = null; - if (DiskSerializationHelpers.FromLZ4CompressedByteArray( - originalPreview.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) - { - GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); - foreach (var previewTile in preview) - { - if(previewTile.x == null || previewTile.y == null) - continue; - - WorldCoordinates coordinates = new((int)previewTile.x, (int)previewTile.y); - TileData? tileData = currentGameState.Map.GetTile(coordinates); - if(tileData == null) - continue; - - if(previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) - tileData.terrain = previewTile.terrainType; - - if(previewTile.resourceType != null) - { - ResourceState? resourceState = null; - ResourceData.Type resourceType = (ResourceData.Type)previewTile.resourceType; - if(resourceType != ResourceData.Type.None) - { - resourceState = new ResourceState { type = resourceType }; - } - tileData.resource = resourceState; - } - - if(previewTile.unitType != null) - { - tileData.unit = null; - if(previewTile.unitType != Polytopia.Data.UnitData.Type.None && - currentGameState.TryGetPlayer(currentGameState.CurrentPlayer, out PlayerState playerState) && - currentGameState.GameLogicData.TryGetData((UnitData.Type)previewTile.unitType, out UnitData unitData)) - { - UnitState unitState = ActionUtils.TrainUnit(currentGameState, playerState, tileData, unitData); - unitState.moved = false; - unitState.attacked = false; - } - } - - - if(previewTile.improvementType != null) - { - tileData.improvement = null; - ImprovementData.Type improvementType = (ImprovementData.Type)previewTile.improvementType; - if( - previewTile.improvementType != ImprovementData.Type.None && - currentGameState.GameLogicData.TryGetData( - improvementType, - out ImprovementData improvementData) - ) - { - tileData.improvement = new ImprovementState - { - type = improvementData.type, - borderSize = (ushort)improvementData.borderSize, - level = 0, - xp = 0, - production = 1, - founded = (ushort)currentGameState.CurrentTurn, - baseScore = (ushort)improvementData.GetScoreReward(), - founder = currentGameState.CurrentPlayer - }; - } - } - } - - saveStateData = ScriptableObject.CreateInstance(); - saveStateData.name = previewId; - saveStateData.byteArray = DiskSerializationHelpers.ToLZ4CompressedByteArray(clientSerializationWrapper, version); - } - - return saveStateData; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] - private static bool SpriteCamera_TakeSnapshotOfMapState(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, - float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) - { - if(!Plugin.config.debug) - return true; - - var instance = SpriteCamera.instance; - if(baseOrthographicCameraSize == null) - baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; - - instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; - isTakingSnapshot = true; - - return true; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] - private static void SpriteCamera_TakeSnapshotOfMapState_Postfix(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, - float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) - { - if(isTakingSnapshot) - isTakingSnapshot = false; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] - public static void Tile_RenderDebug(Tile __instance) - { - if(!isTakingSnapshot) - return; - - GameObject textObj = new GameObject("CoordinateText"); - textObj.transform.SetParent(__instance.transform); - textObj.transform.localPosition = new Vector3(0, 0.0f, 0); - - TextMeshPro textMesh = textObj.AddComponent(); - textMesh.text = __instance.Data.coordinates.ToString(); - textMesh.fontSize = 3; - textMesh.alignment = TextAlignmentOptions.Center; - textMesh.color = Color.white; - - MeshRenderer renderer = textObj.GetComponent(); - renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; - renderer.sortingOrder = __instance.Depth + 10; - } - #endregion #region UI // check if still needed @@ -653,6 +445,7 @@ public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = internal static void Init() { Harmony.CreateAndPatchAll(typeof(Visual)); - Harmony.CreateAndPatchAll(typeof(PrefabFix)); + Harmony.CreateAndPatchAll(typeof(PrefabRegistry)); + Harmony.CreateAndPatchAll(typeof(TribePreviewManager)); } } diff --git a/src/Managers/Visual/PrefabCreator.cs b/src/Managers/Visual/PrefabCreator.cs new file mode 100644 index 0000000..46a186e --- /dev/null +++ b/src/Managers/Visual/PrefabCreator.cs @@ -0,0 +1,289 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using PolyMod.Json; +using Polytopia.Data; +using PolytopiaBackendBase.Common; +using UnityEngine; +using static PolyMod.Managers.PrefabRegistry; + +namespace PolyMod.Managers; + +public static class PrefabCreator +{ + + internal static Dictionary> prefabsFilesToProcess = new(); + + public static List unitInfos = new(); + + public static List improvementInfos = new(); + + public static List resourceInfos = new(); + + public class VisualPartInfo + { + [JsonInclude] + public string? defaultSpriteName; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific + + [JsonInclude] + public Vector2 coordinates = new Vector2(); + + [JsonInclude] + public float rotation = 0f; + + [JsonInclude] + public bool tintable = false; + + [JsonInclude] + public bool levels = false; // improvement specific + } + + public class BasePrefabInfo + { + [JsonInclude] + public List visualParts = new(); + } + public class UnitPrefabInfo : BasePrefabInfo + { + [JsonInclude] + public SkinnedKey skinnedKey; + + [JsonInclude] + public string headPositionMarker = ""; + } + + public class ImprovementPrefabInfo : BasePrefabInfo + { + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; + } + + public class ResourcePrefabInfo : BasePrefabInfo + { + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; + } + + public class PrefabsInfo + { + [JsonInclude] + public List units = new(); + + [JsonInclude] + public List improvements = new(); + + [JsonInclude] + public List resources = new(); + } + + internal static void ProcessPrefabs() + { + foreach (var keyValuePair in prefabsFilesToProcess) + { + if(keyValuePair.Key == "all") + { + foreach (var bytes in keyValuePair.Value) + { + var prefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (prefab == null) + return; + + unitInfos.AddRange(prefab.units); + improvementInfos.AddRange(prefab.improvements); + resourceInfos.AddRange(prefab.resources); + } + } + else if(keyValuePair.Key == "units") + { + foreach (var bytes in keyValuePair.Value) + { + var unitPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (unitPrefab == null) + return; + + unitInfos.Add(unitPrefab); + } + } + else if(keyValuePair.Key == "improvements") + { + foreach (var bytes in keyValuePair.Value) + { + var improvementPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (improvementPrefab == null) + return; + + improvementInfos.Add(improvementPrefab); + } + } + else if(keyValuePair.Key == "resources") + { + foreach (var bytes in keyValuePair.Value) + { + var resourcePrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (resourcePrefab == null) + return; + + PrefabCreator.resourceInfos.Add(resourcePrefab); + } + } + } + foreach (var unitPrefabInfo in unitInfos) + { + ProcessUnitPrefabInfo(unitPrefabInfo); + } + + foreach (var improvementPrefabInfo in improvementInfos) + { + ProcessImprovementPrefabInfo(improvementPrefabInfo); + } + + foreach (var resourcePrefabInfo in resourceInfos) + { + ProcessResourcePrefabInfo(resourcePrefabInfo); + } + } + + /// The material of the original sprite parts. + private static Material? ClearExistingPartsAndExtractMaterial(Transform spriteContainer) + { + Material? material = null; + for (int i = 0; i < spriteContainer.childCount; i++) + { + var child = spriteContainer.GetChild(i); + if (child.gameObject.name == "Head") + { + var renderer = child.GetComponent(); + if (renderer != null) + material = renderer.material; + } + GameObject.Destroy(child.gameObject); + } + return material; + } + + private static List ApplyVisualParts( + UnitPrefabInfo prefab, + Transform spriteContainer, + Material? material) + { + if (prefab.visualParts.Count == 0) + return new List(); + + List parts = new(); + + foreach (var info in prefab.visualParts) + { + parts.Add(CreateVisualPart(info, spriteContainer, material)); + } + + return parts; + } + + private static SkinVisualsReference.VisualPart CreateVisualPart( + VisualPartInfo info, + Transform parent, + Material? material) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + visualPartObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + var outlineObj = new GameObject("Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + outlineObj.transform.position = info.coordinates; + outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + var visualPart = new SkinVisualsReference.VisualPart + { + DefaultSpriteName = info.defaultSpriteName, + visualPart = visualPartObj, + outline = outlineObj, + tintable = info.tintable + }; + + var renderer = visualPartObj.AddComponent(); + renderer.material = material; + renderer.sortingLayerName = "Units"; + renderer.sortingOrder = info.tintable ? 0 : 1; + + visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; + + var outlineRenderer = outlineObj.AddComponent(); + outlineRenderer.material = material; + outlineRenderer.sortingLayerName = "Units"; + outlineRenderer.sortingOrder = -1; + + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; + + return visualPart; + } + + internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) + { + var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); + if (baseUnit == null) + return; + + var unitInstance = GameObject.Instantiate(baseUnit); + if (unitInstance == null) + return; + + var spriteContainer = unitInstance.transform.GetChild(0); + var material = ClearExistingPartsAndExtractMaterial(spriteContainer); + + var visualParts = ApplyVisualParts(unitPrefabInfo, spriteContainer, material); + + Transform? headPositionMarker = null; + foreach (var vp in visualParts) + { + if (vp.visualPart.gameObject.name == unitPrefabInfo.headPositionMarker) + { + headPositionMarker = vp.visualPart.gameObject.transform; + break; + } + } + + unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; + + var svr = unitInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(unitInstance.gameObject); + + PrefabRegistry.unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; + } + + internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo unitPrefabInfo) + { + } + + internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo unitPrefabInfo) + { + } +} \ No newline at end of file diff --git a/src/Managers/PrefabFix.cs b/src/Managers/Visual/PrefabRegistry.cs similarity index 78% rename from src/Managers/PrefabFix.cs rename to src/Managers/Visual/PrefabRegistry.cs index 23dc092..6b3f50e 100644 --- a/src/Managers/PrefabFix.cs +++ b/src/Managers/Visual/PrefabRegistry.cs @@ -1,45 +1,17 @@ +using System.Text.Json.Serialization; using HarmonyLib; -using PolyMod; +using PolyMod.Json; using Polytopia.Data; using PolytopiaBackendBase.Common; using static PrefabManager; -public static class PrefabFix -{ - public readonly struct SkinnedKey : IEquatable - { - private readonly UnitData.Type unitType; - private readonly TribeType tribeType; - private readonly SkinType skinType; - - public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) - { - this.unitType = unitType; - this.tribeType = tribeType; - this.skinType = skinType; - } - - public bool Equals(SkinnedKey other) - { - return unitType == other.unitType - && tribeType == other.tribeType - && skinType == other.skinType; - } +namespace PolyMod.Managers; - public override bool Equals(object? other) - { - return other is SkinnedKey otherKey && Equals(otherKey); - } - - public override int GetHashCode() - { - return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); - } - } - - private static readonly Dictionary unitsNew = new(); - private static readonly Dictionary> unitOverridesNew = new(); - private static readonly Dictionary unitUIOverridesNew = new(); +public static class PrefabRegistry +{ + internal static Dictionary unitsNew = new(); + internal static Dictionary> unitOverridesNew = new(); + internal static Dictionary unitUIOverridesNew = new(); [HarmonyPostfix] [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] diff --git a/src/Managers/Visual/SkinnedKey.cs b/src/Managers/Visual/SkinnedKey.cs new file mode 100644 index 0000000..0f42c9c --- /dev/null +++ b/src/Managers/Visual/SkinnedKey.cs @@ -0,0 +1,46 @@ +using System.Text.Json.Serialization; +using PolyMod.Json; +using Polytopia.Data; +using PolytopiaBackendBase.Common; + +namespace PolyMod.Managers; + +public readonly struct SkinnedKey : IEquatable +{ + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.Type unitType { get; } + + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public TribeType tribeType { get; } + + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public SkinType skinType { get; } + + [JsonConstructor] + public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + this.unitType = unitType; + this.tribeType = tribeType; + this.skinType = skinType; + } + + public bool Equals(SkinnedKey other) + { + return unitType == other.unitType + && tribeType == other.tribeType + && skinType == other.skinType; + } + + public override bool Equals(object? other) + { + return other is SkinnedKey otherKey && Equals(otherKey); + } + + public override int GetHashCode() + { + return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); + } +} \ No newline at end of file diff --git a/src/Managers/Visual/TribePreviewManager.cs b/src/Managers/Visual/TribePreviewManager.cs new file mode 100644 index 0000000..5c12e7b --- /dev/null +++ b/src/Managers/Visual/TribePreviewManager.cs @@ -0,0 +1,223 @@ +using HarmonyLib; +using Polytopia.Data; +using UnityEngine; +using Il2CppSystem.Linq; +using PolyMod.Json; +using System.Text.Json.Serialization; +using PolytopiaBackendBase.Common; +using TMPro; + +namespace PolyMod.Managers; + +public static class TribePreviewManager +{ + /// + /// Represents a tile in a tribe preview. + /// + public class PreviewTile + { + /// The x-coordinate of the tile. + [JsonInclude] + public int? x = null; + /// The y-coordinate of the tile. + [JsonInclude] + public int? y = null; + /// The terrain type of the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public Polytopia.Data.TerrainData.Type terrainType = Polytopia.Data.TerrainData.Type.None; + /// The resource type on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; + /// The unit type on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.Type? unitType = null; + /// The improvement type on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; + } + + public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); + + private static bool isTakingSnapshot = false; + private static float? baseOrthographicCameraSize = null; + + [HarmonyPostfix] + [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] + public static void PreloadTribePreviews() + { + Dictionary previewSaveStateDatas = new(); + + SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; + foreach(string tribe in Registry.tribePreviews.Keys) + { + string previewId = GetTribePreviewName(tribe); + PreviewTile[] customPreview = Registry.tribePreviews[tribe]; + previewSaveStateDatas[previewId] = new(TribePreviewRegistry.fallbackStateIndex, fallbackSaveStateData, customPreview); + } + + for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) + { + SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; + if(previewSaveStateDatas.ContainsKey(saveStateData.name)) + { + previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, previewSaveStateDatas[saveStateData.name].customPreview); + } + } + + foreach (string previewId in previewSaveStateDatas.Keys) + { + var data = previewSaveStateDatas[previewId]; + SaveStateData? customSaveStateData = ApplyCustomPreview(previewId, data.saveStateData, data.customPreview); + if(customSaveStateData == null) + continue; + + if(data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) + { + List saveStateDatas = TribePreviewRegistry.saveStateDatas.ToList(); + saveStateDatas.Add(customSaveStateData); + TribePreviewRegistry.saveStateDatas = saveStateDatas.ToArray(); + } + else + { + TribePreviewRegistry.saveStateDatas[data.arrayIdx] = customSaveStateData; + } + } + } + + private static string GetTribePreviewName(string tribeType) + { + return "worldpreview_" + tribeType; + } + + private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) + { + SaveStateData? saveStateData = null; + if (DiskSerializationHelpers.FromLZ4CompressedByteArray( + originalPreview.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) + { + GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); + foreach (var previewTile in preview) + { + if(previewTile.x == null || previewTile.y == null) + continue; + + WorldCoordinates coordinates = new((int)previewTile.x, (int)previewTile.y); + TileData? tileData = currentGameState.Map.GetTile(coordinates); + if(tileData == null) + continue; + + if(previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) + tileData.terrain = previewTile.terrainType; + + if(previewTile.resourceType != null) + { + ResourceState? resourceState = null; + ResourceData.Type resourceType = (ResourceData.Type)previewTile.resourceType; + if(resourceType != ResourceData.Type.None) + { + resourceState = new ResourceState { type = resourceType }; + } + tileData.resource = resourceState; + } + + if(previewTile.unitType != null) + { + tileData.unit = null; + if(previewTile.unitType != Polytopia.Data.UnitData.Type.None && + currentGameState.TryGetPlayer(currentGameState.CurrentPlayer, out PlayerState playerState) && + currentGameState.GameLogicData.TryGetData((UnitData.Type)previewTile.unitType, out UnitData unitData)) + { + UnitState unitState = ActionUtils.TrainUnit(currentGameState, playerState, tileData, unitData); + unitState.moved = false; + unitState.attacked = false; + } + } + + + if(previewTile.improvementType != null) + { + tileData.improvement = null; + ImprovementData.Type improvementType = (ImprovementData.Type)previewTile.improvementType; + if( + previewTile.improvementType != ImprovementData.Type.None && + currentGameState.GameLogicData.TryGetData( + improvementType, + out ImprovementData improvementData) + ) + { + tileData.improvement = new ImprovementState + { + type = improvementData.type, + borderSize = (ushort)improvementData.borderSize, + level = 0, + xp = 0, + production = 1, + founded = (ushort)currentGameState.CurrentTurn, + baseScore = (ushort)improvementData.GetScoreReward(), + founder = currentGameState.CurrentPlayer + }; + } + } + } + + saveStateData = ScriptableObject.CreateInstance(); + saveStateData.name = previewId; + saveStateData.byteArray = DiskSerializationHelpers.ToLZ4CompressedByteArray(clientSerializationWrapper, version); + } + + return saveStateData; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] + private static bool SpriteCamera_TakeSnapshotOfMapState(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, + float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) + { + if(!Plugin.config.debug) + return true; + + var instance = SpriteCamera.instance; + if(baseOrthographicCameraSize == null) + baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; + + instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; + isTakingSnapshot = true; + + return true; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] + private static void SpriteCamera_TakeSnapshotOfMapState_Postfix(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, + float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) + { + if(isTakingSnapshot) + isTakingSnapshot = false; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] + public static void Tile_RenderDebug(Tile __instance) + { + if(!isTakingSnapshot) + return; + + GameObject textObj = new GameObject("CoordinateText"); + textObj.transform.SetParent(__instance.transform); + textObj.transform.localPosition = new Vector3(0, 0.0f, 0); + + TextMeshPro textMesh = textObj.AddComponent(); + textMesh.text = __instance.Data.coordinates.ToString(); + textMesh.fontSize = 3; + textMesh.alignment = TextAlignmentOptions.Center; + textMesh.color = Color.white; + + MeshRenderer renderer = textObj.GetComponent(); + renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; + renderer.sortingOrder = __instance.Depth + 10; + } +} \ No newline at end of file diff --git a/src/Registry.cs b/src/Registry.cs index 5bfd5f1..a3d075f 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -34,7 +34,7 @@ public static class Registry /// /// A dictionary of tribe previews, keyed by tribe name. /// - public static Dictionary tribePreviews = new(); + public static Dictionary tribePreviews = new(); /// /// A dictionary of sprite information, keyed by sprite name. From b3546ef122e51fc7c35d8fc761efb1cb6cd3e62f Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sat, 17 Oct 2026 13:16:41 +0200 Subject: [PATCH 04/42] Finished new unit prefabs --- src/Loader.cs | 5 +- src/Managers/Visual.cs | 36 ++----- src/Managers/Visual/PrefabCreator.cs | 133 +++++++++++++++++++------- src/Managers/Visual/PrefabRegistry.cs | 48 +++++++++- 4 files changed, 154 insertions(+), 68 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index 9e91445..d373cf3 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -8,7 +8,6 @@ using Polytopia.Data; using PolytopiaBackendBase.Game; using System.Diagnostics; -using System.Globalization; using System.IO.Compression; using System.Reflection; using System.Text; @@ -606,8 +605,8 @@ public static void LoadSpriteFile(Mod mod, Mod.File file) } Sprite sprite = Visual.BuildSprite(file.bytes, pivot, pixelsPerUnit); GameManager.GetSpriteAtlasManager().cachedSprites.TryAdd("Heads", new()); - GameManager.GetSpriteAtlasManager().cachedSprites["Heads"].Add(name, sprite); - Registry.sprites.Add(name, sprite); + GameManager.GetSpriteAtlasManager().cachedSprites["Heads"][name] = sprite; + Registry.sprites[name] = sprite; } /// diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 82999a9..64cb294 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -10,6 +10,7 @@ using PolytopiaBackendBase.Common; using Il2CppInterop.Runtime; using TMPro; +using SevenZip.Compression.LZMA; namespace PolyMod.Managers; @@ -32,7 +33,6 @@ public record SkinInfo(int idx, string id, SkinData? skinData); /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. /// internal static Dictionary customFloodingSkins = new(); - private static bool enableOutlines = false; private static bool seenWarningWCPopup = false; private static Dictionary? cachedSpriteDataReverse = null; @@ -149,38 +149,18 @@ private static void SpriteAtlasManager_DoSpriteLookup(ref SpriteAtlasManager.Spr if (sprite != null) __result.sprite = sprite; + Sprite? outlineSprite = Registry.GetSprite(baseName + "_outline", tribe, skin, level); + if (outlineSprite != null) + __result.outlineSprite = outlineSprite; + string formattedName = FormatSpriteName(baseName); sprite = Registry.GetSprite(formattedName, tribe, skin, level); if (sprite != null) __result.sprite = sprite; - } - - #endregion - #region Units - - /// Enables outlines when the interaction bar is shown. - [HarmonyPrefix] - [HarmonyPatch(typeof(InteractionBar), nameof(InteractionBar.Show))] - private static bool InteractionBar_Show(InteractionBar __instance, bool instant, bool force) - { - enableOutlines = true; // bro - return true; - } - /// Prevents outlines from being created when they are disabled. - [HarmonyPrefix] - [HarmonyPatch(typeof(UISpriteDuplicator), nameof(UISpriteDuplicator.CreateImage), typeof(SpriteRenderer), typeof(Transform), typeof(Transform), typeof(float), typeof(Vector2), typeof(bool))] - private static bool UISpriteDuplicator_CreateImage(SpriteRenderer spriteRenderer, Transform source, Transform destination, float scale, Vector2 offset, bool forceFullAlpha) - { - return !(spriteRenderer.sortingOrder == -1 && !enableOutlines); // uhhh tf is this hack - } - - /// Disables outlines after the interaction bar is shown. - [HarmonyPostfix] - [HarmonyPatch(typeof(InteractionBar), nameof(InteractionBar.Show))] - private static void InteractionBar_Show_Postfix(InteractionBar __instance, bool instant, bool force) - { - enableOutlines = false; + outlineSprite = Registry.GetSprite(formattedName + "_outline", tribe, skin, level); + if (outlineSprite != null) + __result.outlineSprite = outlineSprite; } #endregion diff --git a/src/Managers/Visual/PrefabCreator.cs b/src/Managers/Visual/PrefabCreator.cs index 46a186e..6ff3bec 100644 --- a/src/Managers/Visual/PrefabCreator.cs +++ b/src/Managers/Visual/PrefabCreator.cs @@ -5,12 +5,13 @@ using PolytopiaBackendBase.Common; using UnityEngine; using static PolyMod.Managers.PrefabRegistry; +using static SkinVisualsReference; namespace PolyMod.Managers; public static class PrefabCreator { - + internal static Material? cachedUnitMaterial; internal static Dictionary> prefabsFilesToProcess = new(); public static List unitInfos = new(); @@ -166,58 +167,100 @@ internal static void ProcessPrefabs() { ProcessResourcePrefabInfo(resourcePrefabInfo); } - } - /// The material of the original sprite parts. - private static Material? ClearExistingPartsAndExtractMaterial(Transform spriteContainer) - { - Material? material = null; - for (int i = 0; i < spriteContainer.childCount; i++) + foreach (var item in unitsNew) { - var child = spriteContainer.GetChild(i); - if (child.gameObject.name == "Head") + var skinnedKey = item.Key; + var unit = item.Value; + SkinVisualsReference skinVisualsReference = unit.GetComponent(); + if (skinVisualsReference == null) + { + skinVisualsReference = unit.GetComponentInChildren(true); + } + if (skinVisualsReference == null || skinVisualsReference.visualParts == null) + { + Plugin.logger.LogWarning($"{skinnedKey.unitType} {skinnedKey.tribeType} {skinnedKey.skinType}: no SkinVisualsReference"); + continue; + } + + for (int partIndex = 0; partIndex < skinVisualsReference.visualParts.Length; partIndex++) { - var renderer = child.GetComponent(); - if (renderer != null) - material = renderer.material; + VisualPart currentPart = skinVisualsReference.visualParts[partIndex]; + Plugin.logger.LogInfo($"{skinnedKey.unitType} {skinnedKey.tribeType} {skinnedKey.skinType} part {partIndex}"); + Plugin.logger.LogInfo($" visualPart: {DescribeVisualObject(currentPart.visualPart)}"); + Plugin.logger.LogInfo($" outline: {DescribeVisualObject(currentPart.outline)}"); } - GameObject.Destroy(child.gameObject); } - return material; } + private static string DescribeVisualObject(GameObject targetObject) + { + if (targetObject == null) + { + return "null"; + } + + string layerName = LayerMask.LayerToName(targetObject.layer); + string description = $"name={targetObject.name}, layer={targetObject.layer} ({layerName}), activeSelf={targetObject.activeSelf}"; + + SpriteRenderer spriteRenderer = targetObject.GetComponent(); + if (spriteRenderer != null) + { + description += $", SpriteRenderer(enabled={spriteRenderer.enabled}, sortingLayer={SortingLayer.IDToName(spriteRenderer.sortingLayerID)}, sortingOrder={spriteRenderer.sortingOrder}, hasSprite={spriteRenderer.sprite != null})"; + } + + PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetObject.GetComponent(); + if (polytopiaSpriteRenderer != null) + { + description += $", PolytopiaSpriteRenderer(enabled={polytopiaSpriteRenderer.enabled}, sortingLayer={SortingLayer.IDToName(polytopiaSpriteRenderer.SortingLayer)}, sortingOrder={polytopiaSpriteRenderer.SortingOrder}, hasSprite={polytopiaSpriteRenderer.HasSprite()})"; + } + + return description; + } + private static List ApplyVisualParts( UnitPrefabInfo prefab, - Transform spriteContainer, - Material? material) + Transform spriteContainer) { - if (prefab.visualParts.Count == 0) - return new List(); List parts = new(); + if (prefab.visualParts.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -prefab.visualParts.Count; foreach (var info in prefab.visualParts) { - parts.Add(CreateVisualPart(info, spriteContainer, material)); + parts.Add(CreateUnitVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); + if(nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + Console.Write($"{prefab.visualParts.Count} New orders {nextPartSortingOrder} {nextOutlineSortingOrder}"); } return parts; } - private static SkinVisualsReference.VisualPart CreateVisualPart( + private static SkinVisualsReference.VisualPart CreateUnitVisualPart( VisualPartInfo info, Transform parent, - Material? material) + int visualPartSortingOrder, + int outlineSortingOrder) { var visualPartObj = new GameObject(info.defaultSpriteName); visualPartObj.transform.SetParent(parent); - visualPartObj.transform.position = info.coordinates; - visualPartObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - var outlineObj = new GameObject("Outline"); + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); outlineObj.transform.SetParent(visualPartObj.transform); - outlineObj.transform.position = info.coordinates; - outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + // this bs was hunting me for so long. that is the thing which makes outline hidden in ui + outlineObj.SetActive(false); var visualPart = new SkinVisualsReference.VisualPart { @@ -228,22 +271,38 @@ private static SkinVisualsReference.VisualPart CreateVisualPart( }; var renderer = visualPartObj.AddComponent(); - renderer.material = material; + renderer.material = cachedUnitMaterial; + renderer.sortingOrder = visualPartSortingOrder; renderer.sortingLayerName = "Units"; - renderer.sortingOrder = info.tintable ? 0 : 1; - visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; var outlineRenderer = outlineObj.AddComponent(); - outlineRenderer.material = material; + outlineRenderer.material = cachedUnitMaterial; + outlineRenderer.sortingOrder = outlineSortingOrder; outlineRenderer.sortingLayerName = "Units"; - outlineRenderer.sortingOrder = -1; - visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; return visualPart; } + private static SkinVisualsReference.VisualPart CreateImprovementVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + return null; + } + + private static SkinVisualsReference.VisualPart CreateResourceVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + return null; + } + internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) { var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); @@ -254,10 +313,14 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) if (unitInstance == null) return; - var spriteContainer = unitInstance.transform.GetChild(0); - var material = ClearExistingPartsAndExtractMaterial(spriteContainer); + GameObject.Destroy(unitInstance.spriteContainer.gameObject); + + var spriteContainerObj = new GameObject("SpriteContainer"); + spriteContainerObj.transform.SetParent(unitInstance.transform, false); + var spriteContainer = spriteContainerObj.transform; + unitInstance.spriteContainer = spriteContainer; - var visualParts = ApplyVisualParts(unitPrefabInfo, spriteContainer, material); + var visualParts = ApplyVisualParts(unitPrefabInfo, spriteContainer); Transform? headPositionMarker = null; foreach (var vp in visualParts) diff --git a/src/Managers/Visual/PrefabRegistry.cs b/src/Managers/Visual/PrefabRegistry.cs index 6b3f50e..4c14ec6 100644 --- a/src/Managers/Visual/PrefabRegistry.cs +++ b/src/Managers/Visual/PrefabRegistry.cs @@ -1,9 +1,9 @@ -using System.Text.Json.Serialization; using HarmonyLib; -using PolyMod.Json; using Polytopia.Data; using PolytopiaBackendBase.Common; +using UnityEngine; using static PrefabManager; +using static SkinVisualsReference; namespace PolyMod.Managers; @@ -23,6 +23,27 @@ private static void PrefabManager_Awake_Postfix(PrefabManager __instance) foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) { + if(PrefabCreator.cachedUnitMaterial == null) + { + SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); + if (skinVisualsReference != null && skinVisualsReference.visualParts != null) + { + foreach (VisualPart currentPart in skinVisualsReference.visualParts) + { + if (currentPart.visualPart == null) + { + continue; + } + + SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); + if (headSpriteRenderer != null) + { + PrefabCreator.cachedUnitMaterial = headSpriteRenderer.sharedMaterial; + break; + } + } + } + } unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; } @@ -75,6 +96,29 @@ public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type return false; } + [HarmonyPostfix] // prolly remove later + [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] + public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) + { + bool flag = false; + flag = visualSetting.outline != null && visualSetting.outline.transform.parent == visualSetting.visualPart.transform; + if (!flag && visualSetting.visualPart.transform.childCount > 0) + { + visualSetting.outline = visualSetting.visualPart.transform.GetChild(0).gameObject; + flag = true; + } + bool flag2 = false; + if (flag) + { + string defaultSpriteName = visualSetting.DefaultSpriteName; + if (visualSetting.outline != null && visualSetting.outline.name == defaultSpriteName + "_Outline") + { + flag2 = true; + } + } + visualSetting.hasValidOutline = flag2; + } + private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) { if (SeasonManager.IsChristmas() From caf61e3cad052641d337ff345c201ef184bfd1bc Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sat, 17 Oct 2026 21:09:04 +0200 Subject: [PATCH 05/42] Implemented resources prefabs. Added unit prefabs dumping. Patched the last sprite getting method. Bunch of other stuff like splitting Visual manager into multiple small ones --- src/Loader.cs | 48 +- src/Managers/Hub.cs | 56 +- src/Managers/Prefabs.cs | 518 ++++++++++++++++++ ...ribePreviewManager.cs => TribePreviews.cs} | 2 +- src/Managers/Visual.cs | 68 +-- src/Managers/Visual/PrefabCreator.cs | 352 ------------ src/Managers/Visual/PrefabRegistry.cs | 157 ------ src/Prefabs/OtherPrefabInfo.cs | 34 ++ src/Prefabs/PrefabsInfo.cs | 16 + .../Visual => Prefabs}/SkinnedKey.cs | 2 +- src/Prefabs/VisualPartInfo.cs | 37 ++ src/Registry.cs | 7 +- 12 files changed, 704 insertions(+), 593 deletions(-) create mode 100644 src/Managers/Prefabs.cs rename src/Managers/{Visual/TribePreviewManager.cs => TribePreviews.cs} (99%) delete mode 100644 src/Managers/Visual/PrefabCreator.cs delete mode 100644 src/Managers/Visual/PrefabRegistry.cs create mode 100644 src/Prefabs/OtherPrefabInfo.cs create mode 100644 src/Prefabs/PrefabsInfo.cs rename src/{Managers/Visual => Prefabs}/SkinnedKey.cs (97%) create mode 100644 src/Prefabs/VisualPartInfo.cs diff --git a/src/Loader.cs b/src/Loader.cs index d373cf3..c431c06 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -125,7 +125,7 @@ out TribeAbility.Type tribeAbilityType } if (token["preview"] != null) { - TribePreviewManager.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; + TribePreviews.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; Registry.tribePreviews[Util.GetJTokenName(token)] = preview; } } @@ -682,12 +682,12 @@ public static void LoadPrefabsFile(Mod mod, Mod.File file) { try { - if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("all") || PrefabCreator.prefabsFilesToProcess["all"] == null) - PrefabCreator.prefabsFilesToProcess["all"] = new(); + if(!Prefabs.prefabsFilesToProcess.ContainsKey("all") || Prefabs.prefabsFilesToProcess["all"] == null) + Prefabs.prefabsFilesToProcess["all"] = new(); - PrefabCreator.prefabsFilesToProcess["all"].Add(file.bytes); + Prefabs.prefabsFilesToProcess["all"].Add(file.bytes); - // var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions // { // Converters = { new Vector2Json() }, // PropertyNameCaseInsensitive = true, @@ -695,9 +695,9 @@ public static void LoadPrefabsFile(Mod mod, Mod.File file) // if (prefab == null) // return; - // PrefabCreator.unitInfos.AddRange(prefab.units); - // PrefabCreator.improvementInfos.AddRange(prefab.improvements); - // PrefabCreator.resourceInfos.AddRange(prefab.resources); + // Prefabs.unitInfos.AddRange(prefab.units); + // Prefabs.improvementInfos.AddRange(prefab.improvements); + // Prefabs.resourceInfos.AddRange(prefab.resources); Plugin.logger.LogInfo($"Registered prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -711,12 +711,12 @@ public static void LoadUnitPrefabFile(Mod mod, Mod.File file) { try { - if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("units") || PrefabCreator.prefabsFilesToProcess["units"] == null) - PrefabCreator.prefabsFilesToProcess["units"] = new(); + if(!Prefabs.prefabsFilesToProcess.ContainsKey("units") || Prefabs.prefabsFilesToProcess["units"] == null) + Prefabs.prefabsFilesToProcess["units"] = new(); - PrefabCreator.prefabsFilesToProcess["units"].Add(file.bytes); + Prefabs.prefabsFilesToProcess["units"].Add(file.bytes); - // var unitPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // var unitPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions // { // Converters = { new Vector2Json() }, // PropertyNameCaseInsensitive = true, @@ -724,7 +724,7 @@ public static void LoadUnitPrefabFile(Mod mod, Mod.File file) // if (unitPrefab == null) // return; - // PrefabCreator.unitInfos.Add(unitPrefab); + // Prefabs.unitInfos.Add(unitPrefab); Plugin.logger.LogInfo($"Registered unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -738,12 +738,12 @@ public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) { try { - if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("improvements") || PrefabCreator.prefabsFilesToProcess["improvements"] == null) - PrefabCreator.prefabsFilesToProcess["improvements"] = new(); + if(!Prefabs.prefabsFilesToProcess.ContainsKey("improvements") || Prefabs.prefabsFilesToProcess["improvements"] == null) + Prefabs.prefabsFilesToProcess["improvements"] = new(); - PrefabCreator.prefabsFilesToProcess["improvements"].Add(file.bytes); + Prefabs.prefabsFilesToProcess["improvements"].Add(file.bytes); - // var improvementPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // var improvementPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions // { // Converters = { new Vector2Json() }, // PropertyNameCaseInsensitive = true, @@ -751,7 +751,7 @@ public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) // if (improvementPrefab == null) // return; - // PrefabCreator.improvementInfos.Add(improvementPrefab); + // Prefabs.improvementInfos.Add(improvementPrefab); Plugin.logger.LogInfo($"Registered improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -765,12 +765,12 @@ public static void LoadResourcePrefabFile(Mod mod, Mod.File file) { try { - if(!PrefabCreator.prefabsFilesToProcess.ContainsKey("resources") || PrefabCreator.prefabsFilesToProcess["resources"] == null) - PrefabCreator.prefabsFilesToProcess["resources"] = new(); + if(!Prefabs.prefabsFilesToProcess.ContainsKey("resources") || Prefabs.prefabsFilesToProcess["resources"] == null) + Prefabs.prefabsFilesToProcess["resources"] = new(); - PrefabCreator.prefabsFilesToProcess["resources"].Add(file.bytes); + Prefabs.prefabsFilesToProcess["resources"].Add(file.bytes); - // var resourcePrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + // var resourcePrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions // { // Converters = { new Vector2Json() }, // PropertyNameCaseInsensitive = true, @@ -778,7 +778,7 @@ public static void LoadResourcePrefabFile(Mod mod, Mod.File file) // if (resourcePrefab == null) // return; - // PrefabCreator.resourceInfos.Add(resourcePrefab); + // Prefabs.resourceInfos.Add(resourcePrefab); Plugin.logger.LogInfo($"Registered resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -948,7 +948,7 @@ internal static void CreateMappings(JObject rootObject) /// internal static void ProcessPrefabs() { - PrefabCreator.ProcessPrefabs(); + Prefabs.ProcessPrefabs(); } /// diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 553652c..9400b51 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -3,17 +3,12 @@ using HarmonyLib; using I2.Loc; using Il2CppInterop.Runtime; -using TMPro; using UnityEngine; -using UnityEngine.EventSystems; -using UnityEngine.UI; using static PopupBase; using PolytopiaBackendBase.Common; using System.Text.Encodings.Web; using Il2CppSystem.Linq; -using System.Text.RegularExpressions; -using Il2CppInterop.Runtime.InteropTypes.Arrays; -using UnityEngine.Experimental.U2D; +using PolyMod.Json; namespace PolyMod.Managers; @@ -343,7 +338,7 @@ internal static void DumpTribePreviewLegacy() // TODO legacy tribe preview dump. i have to update that foreach (TribeType type in Enum.GetValues(typeof(TribeType))) { - List previewTiles = new(); + List previewTiles = new(); SelectTribePopup popup = PopupManager.GetSelectTribePopup(); for (int x = -3; x <= 3; x++) { @@ -352,7 +347,7 @@ internal static void DumpTribePreviewLegacy() Vector2Int pos = new Vector2Int(x, y); if (popup.UIWorldPreview.worldPreviewData.TryGetData(pos, type, out UITileData tileData)) { - TribePreviewManager.PreviewTile previewTile = new TribePreviewManager.PreviewTile + TribePreviews.PreviewTile previewTile = new TribePreviews.PreviewTile { x = tileData.Position.x, y = tileData.Position.y, @@ -373,7 +368,50 @@ internal static void DumpTribePreviewLegacy() } internal static void DumpPrefabs() // TODO - {} + { + Directory.CreateDirectory(Plugin.PREFABS_DUMP_PATH); + PrefabsInfo prefabsInfo = new(); + foreach (KeyValuePair keyValuePairs in Prefabs.unitsNew) + { + var unit = keyValuePairs.Value; + SkinVisualsReference skinVisualsReference = unit.GetComponent(); + if (skinVisualsReference == null || skinVisualsReference.visualParts == null) + { + Plugin.logger.LogWarning($"Dump skipped {keyValuePairs.Key.unitType}: no SkinVisualsReference"); + continue; + } + UnitPrefabInfo unitPrefabInfo = new() + { + headPositionMarker = unit.headPositionMarker.gameObject.name, + skinnedKey = keyValuePairs.Key, + visualParts = new() + }; + foreach (var visualPart in skinVisualsReference.visualParts) + { + if (visualPart == null || visualPart.visualPart == null) + { + continue; + } + var visualPartInfo = new VisualPartInfo + { + coordinates = visualPart.visualPart.transform.position, + rotation = visualPart.visualPart.transform.rotation.z, + defaultSpriteName = visualPart.DefaultSpriteName, + tintable = visualPart.tintable, + skinningLogic = visualPart.skinLogic, + improvementSkinningLogic = visualPart.improvementSkinLogic, + levels = visualPart.levels + }; + unitPrefabInfo.visualParts.Add(visualPartInfo); + + } + prefabsInfo.units.Add(unitPrefabInfo); + } + File.WriteAllTextAsync( + Path.Combine(Plugin.PREFABS_DUMP_PATH, $"prefabs.json"), + JsonSerializer.Serialize(prefabsInfo, new JsonSerializerOptions { WriteIndented = true, Converters = { new Vector2Json() },}) + ); + } /// /// Shows the configuration popup. diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs new file mode 100644 index 0000000..addacf2 --- /dev/null +++ b/src/Managers/Prefabs.cs @@ -0,0 +1,518 @@ +using HarmonyLib; +using Polytopia.Data; +using PolytopiaBackendBase.Common; +using UnityEngine; +using static PrefabManager; +using static SkinVisualsReference; +using System.Text.Json; +using PolyMod.Json; + +namespace PolyMod.Managers; + +public static class Prefabs +{ + internal static Dictionary unitsNew = new(); + internal static Dictionary> unitOverridesNew = new(); + internal static Dictionary unitUIOverridesNew = new(); + + internal static Material? cachedUnitMaterial; + internal static Material? cachedResourceMaterial; + internal static int cachedResourceSortingLayerId; + + internal static Dictionary> prefabsFilesToProcess = new(); + + public static List unitInfos = new(); + + public static List improvementInfos = new(); + + public static List resourceInfos = new(); + + [HarmonyPostfix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] + private static void PrefabManager_Awake_Postfix(PrefabManager __instance) + { + unitsNew.Clear(); + unitOverridesNew.Clear(); + unitUIOverridesNew.Clear(); + + foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) + { + if(cachedUnitMaterial == null) + { + SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); + if (skinVisualsReference != null && skinVisualsReference.visualParts != null) + { + foreach (VisualPart currentPart in skinVisualsReference.visualParts) + { + if (currentPart.visualPart == null) + { + continue; + } + + SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); + if (headSpriteRenderer != null) + { + cachedUnitMaterial = headSpriteRenderer.sharedMaterial; + break; + } + } + } + } + unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; + } + + foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) + { + if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) + { + overridesForCondition = new Dictionary(); + unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; + } + overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; + } + + foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) + { + unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; + } + + Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] + public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] + public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) + { + __result = uiOverridePrefab; + } + else + { + __result = ResolveUnitPrefab(unitType, tribe, skin); + } + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] + public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) + { + __result = ResolveUnitPrefab(type, tribe, skin); + return false; + } + + [HarmonyPostfix] // prolly remove later + [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] + public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) + { + bool flag = false; + flag = visualSetting.outline != null && visualSetting.outline.transform.parent == visualSetting.visualPart.transform; + if (!flag && visualSetting.visualPart.transform.childCount > 0) + { + visualSetting.outline = visualSetting.visualPart.transform.GetChild(0).gameObject; + flag = true; + } + bool flag2 = false; + if (flag) + { + string defaultSpriteName = visualSetting.DefaultSpriteName; + if (visualSetting.outline != null && visualSetting.outline.name == defaultSpriteName + "_Outline") + { + flag2 = true; + } + } + visualSetting.hasValidOutline = flag2; + } + + private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + if (SeasonManager.IsChristmas() + && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) + && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) + && christmasPrefab != null) + { + return christmasPrefab; + } + + SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); + if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) + { + return exactPrefab; + } + + if (skinType != SkinType.Default || tribeType != TribeType.None) + { + SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); + SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); + SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); + + if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) + || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) + || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) + { + unitsNew[exactKey] = fallbackPrefab; + return fallbackPrefab; + } + } + + Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); + unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); + return lastResortPrefab!; + } + + internal static void ProcessPrefabs() + { + // get materials + Material[] allLoadedMaterials = Resources.FindObjectsOfTypeAll(); + foreach (Material loadedMaterial in allLoadedMaterials) + { + if(loadedMaterial.name == "SpriteMaterial") + { + cachedResourceMaterial = loadedMaterial; + Console.Write("MATERIAL FUCKING FOUND GOODBYE!"); + GameObject.DontDestroyOnLoad(cachedResourceMaterial); + break; + } + Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); + } + + cachedResourceSortingLayerId = MeshCache.TERRAIN_LAYER_ID; + // i will remove this bs + foreach (var keyValuePair in prefabsFilesToProcess) + { + if(keyValuePair.Key == "all") + { + foreach (var bytes in keyValuePair.Value) + { + var prefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (prefab == null) + return; + + unitInfos.AddRange(prefab.units); + improvementInfos.AddRange(prefab.improvements); + resourceInfos.AddRange(prefab.resources); + } + } + else if(keyValuePair.Key == "units") + { + foreach (var bytes in keyValuePair.Value) + { + var unitPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (unitPrefab == null) + return; + + unitInfos.Add(unitPrefab); + } + } + else if(keyValuePair.Key == "improvements") + { + foreach (var bytes in keyValuePair.Value) + { + var improvementPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (improvementPrefab == null) + return; + + improvementInfos.Add(improvementPrefab); + } + } + else if(keyValuePair.Key == "resources") + { + foreach (var bytes in keyValuePair.Value) + { + var resourcePrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (resourcePrefab == null) + return; + + resourceInfos.Add(resourcePrefab); + } + } + } + foreach (var unitPrefabInfo in unitInfos) + { + ProcessUnitPrefabInfo(unitPrefabInfo); + } + + foreach (var improvementPrefabInfo in improvementInfos) + { + ProcessImprovementPrefabInfo(improvementPrefabInfo); + } + + foreach (var resourcePrefabInfo in resourceInfos) + { + ProcessResourcePrefabInfo(resourcePrefabInfo); + } + } + + #region Units + internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) + { + // maybe just init new unit? hmmmmm will try later + var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); + if (baseUnit == null) + return; + + var unitInstance = GameObject.Instantiate(baseUnit); + if (unitInstance == null) + return; + + GameObject.Destroy(unitInstance.spriteContainer.gameObject); + + var spriteContainerObj = new GameObject("SpriteContainer"); + spriteContainerObj.transform.SetParent(unitInstance.transform, false); + var spriteContainer = spriteContainerObj.transform; + unitInstance.spriteContainer = spriteContainer; + + var visualParts = ApplyUnitVisualParts(unitPrefabInfo, spriteContainer); + + Transform? headPositionMarker = null; + foreach (var vp in visualParts) + { + if (vp.visualPart.gameObject.name == unitPrefabInfo.headPositionMarker) + { + headPositionMarker = vp.visualPart.gameObject.transform; + break; + } + } + + unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; + + var svr = unitInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(unitInstance.gameObject); + + unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; + } + + private static List ApplyUnitVisualParts( + UnitPrefabInfo unitPrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = unitPrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + var newVisualInfo = visualPartInfos; + newVisualInfo.Reverse(); + foreach (var info in newVisualInfo) + { + parts.Add(CreateUnitVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); + if(nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + Console.Write($"{visualPartInfos.Count} New orders {nextPartSortingOrder} {nextOutlineSortingOrder}"); + } + + return parts; + } + + private static SkinVisualsReference.VisualPart CreateUnitVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = info.coordinates; + outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + // this bs was hunting me for so long. that is the thing which makes outline hidden in ui + outlineObj.SetActive(false); + + var visualPart = new SkinVisualsReference.VisualPart + { + DefaultSpriteName = info.defaultSpriteName, + visualPart = visualPartObj, + outline = outlineObj, + tintable = info.tintable, + skinLogic = info.skinningLogic, + improvementSkinLogic = info.improvementSkinningLogic, + levels = info.levels + }; + + var renderer = visualPartObj.AddComponent(); + renderer.material = cachedUnitMaterial; + renderer.sortingOrder = visualPartSortingOrder; + renderer.sortingLayerName = "Units"; + visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; + + var outlineRenderer = outlineObj.AddComponent(); + outlineRenderer.material = cachedUnitMaterial; + outlineRenderer.sortingOrder = outlineSortingOrder; + outlineRenderer.sortingLayerName = "Units"; + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; + + return visualPart; + } + + #endregion + #region Improvements + internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvementPrefabInfo) + { + var baseImprovement = PrefabManager.GetPrefab(ImprovementData.Type.LumberHut); + } + + private static SkinVisualsReference.VisualPart CreateImprovementVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + return null; + } + + #endregion + #region Resources + + internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefabInfo) + { + if(resourcePrefabInfo.resourceType == null) + return; + + var baseResource = PrefabManager.GetPrefab(ResourceData.Type.Game); + if (baseResource == null) + return; + + var resourceInstance = GameObject.Instantiate(baseResource); + if (resourceInstance == null) + return; + + Transform resourceTransform = resourceInstance.transform; + for (int childIndex = resourceTransform.childCount - 1; childIndex >= 0; childIndex--) + { + GameObject.Destroy(resourceTransform.GetChild(childIndex).gameObject); + } + + var visualParts = ApplyResourceVisualParts(resourcePrefabInfo, resourceInstance.transform); + + var svr = resourceInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(resourceInstance.gameObject); + + PrefabManager.resources[(Polytopia.Data.ResourceData.Type)resourcePrefabInfo.resourceType] = resourceInstance; + } + + private static List ApplyResourceVisualParts( + ResourcePrefabInfo resourcePrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = resourcePrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + foreach (var info in visualPartInfos) + { + parts.Add(CreateResourceVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); + if(nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + Console.Write($"{visualPartInfos.Count} New orders {nextPartSortingOrder} {nextOutlineSortingOrder}"); + } + + return parts; + } + + private static SkinVisualsReference.VisualPart CreateResourceVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + outlineObj.SetActive(false); + + var visualPart = new SkinVisualsReference.VisualPart + { + DefaultSpriteName = info.defaultSpriteName, + visualPart = visualPartObj, + outline = outlineObj, + tintable = info.tintable, + skinLogic = info.skinningLogic, + improvementSkinLogic = info.improvementSkinningLogic, + levels = info.levels + }; + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); + visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; + + var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; + + return visualPart; + } + + private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject targetGameObject, int sortingOrder) + { + MeshFilter meshFilter = targetGameObject.AddComponent(); + MeshRenderer meshRenderer = targetGameObject.AddComponent(); + meshRenderer.receiveShadows = false; + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + + PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetGameObject.AddComponent(); + polytopiaSpriteRenderer.meshFilter = meshFilter; + polytopiaSpriteRenderer.meshRenderer = meshRenderer; + + polytopiaSpriteRenderer.SortingLayer = SortingLayer.NameToID("Terrain"); + polytopiaSpriteRenderer.SortingOrder = sortingOrder; + if (cachedResourceMaterial != null) + { + polytopiaSpriteRenderer.SharedMaterial = cachedResourceMaterial; + } + return polytopiaSpriteRenderer; + } + + #endregion +} \ No newline at end of file diff --git a/src/Managers/Visual/TribePreviewManager.cs b/src/Managers/TribePreviews.cs similarity index 99% rename from src/Managers/Visual/TribePreviewManager.cs rename to src/Managers/TribePreviews.cs index 5c12e7b..f3ab13d 100644 --- a/src/Managers/Visual/TribePreviewManager.cs +++ b/src/Managers/TribePreviews.cs @@ -9,7 +9,7 @@ namespace PolyMod.Managers; -public static class TribePreviewManager +public static class TribePreviews { /// /// Represents a tile in a tribe preview. diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 64cb294..f67a3f8 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -2,15 +2,9 @@ using HarmonyLib; using Polytopia.Data; using UnityEngine; -using UnityEngine.U2D; -using UnityEngine.UI; using Il2CppSystem.Linq; -using PolyMod.Json; -using System.Text.Json.Serialization; using PolytopiaBackendBase.Common; using Il2CppInterop.Runtime; -using TMPro; -using SevenZip.Compression.LZMA; namespace PolyMod.Managers; @@ -47,45 +41,6 @@ private static void TechItem_SetupComplete() { } - /// Patches the sprite atlas manager to load custom sprites. TODOOOO - // [HarmonyPrefix] - // [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), typeof(string), typeof(string), typeof(SpriteCallback))] - private static bool SpriteAtlasManager_LoadSprite(SpriteAtlasManager __instance, string atlas, string sprite, SpriteCallback completion) - { - bool found = false; - __instance.LoadSpriteAtlas(atlas, (Il2CppSystem.Action)GetAtlas); - - return !found; - - void GetAtlas(SpriteAtlas spriteAtlas) - { - if (spriteAtlas != null) - { - List names = sprite.Split('_').ToList(); - List filteredNames = new List(names); - string style = ""; - foreach (string item in names) - { - string upperitem = char.ToUpper(item[0]) + item[1..]; - if (EnumCache.TryGetType(item, out TribeType tribe) || EnumCache.TryGetType(item, out SkinType skin) - || EnumCache.TryGetType(upperitem, out TribeType tribeUpper) || EnumCache.TryGetType(upperitem, out SkinType skinUpper)) - { - filteredNames.Remove(item); - style = item; - continue; - } - } - string name = string.Join("_", filteredNames); - Sprite? newSprite = null; // Registry.GetSprite(name, style); - if (newSprite != null) - { - completion?.Invoke(atlas, sprite, newSprite); - found = true; - } - } - } - } - /// Patches the sprite atlas manager to look up custom sprites. internal static void CacheSpriteNames() { @@ -163,6 +118,25 @@ private static void SpriteAtlasManager_DoSpriteLookup(ref SpriteAtlasManager.Spr __result.outlineSprite = outlineSprite; } + [HarmonyPrefix] // its obsolete so may be removed soon by midjiwan + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[]{ typeof(string), typeof(string), typeof(SpriteCallback) })] + private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) + { + Sprite? spriteResult = Registry.GetSprite(sprite); + + string formattedName = FormatSpriteName(sprite); + Sprite? formattedSprite = Registry.GetSprite(formattedName); + if (formattedSprite != null) + spriteResult = formattedSprite; + + if (spriteResult != null) + { + completion.Invoke(atlas, sprite, spriteResult); + return false; + } + return true; + } + #endregion #region Level @@ -425,7 +399,7 @@ public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = internal static void Init() { Harmony.CreateAndPatchAll(typeof(Visual)); - Harmony.CreateAndPatchAll(typeof(PrefabRegistry)); - Harmony.CreateAndPatchAll(typeof(TribePreviewManager)); + Harmony.CreateAndPatchAll(typeof(Prefabs)); + Harmony.CreateAndPatchAll(typeof(TribePreviews)); } } diff --git a/src/Managers/Visual/PrefabCreator.cs b/src/Managers/Visual/PrefabCreator.cs deleted file mode 100644 index 6ff3bec..0000000 --- a/src/Managers/Visual/PrefabCreator.cs +++ /dev/null @@ -1,352 +0,0 @@ -using System.Text.Json; -using System.Text.Json.Serialization; -using PolyMod.Json; -using Polytopia.Data; -using PolytopiaBackendBase.Common; -using UnityEngine; -using static PolyMod.Managers.PrefabRegistry; -using static SkinVisualsReference; - -namespace PolyMod.Managers; - -public static class PrefabCreator -{ - internal static Material? cachedUnitMaterial; - internal static Dictionary> prefabsFilesToProcess = new(); - - public static List unitInfos = new(); - - public static List improvementInfos = new(); - - public static List resourceInfos = new(); - - public class VisualPartInfo - { - [JsonInclude] - public string? defaultSpriteName; - - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; - - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific - - [JsonInclude] - public Vector2 coordinates = new Vector2(); - - [JsonInclude] - public float rotation = 0f; - - [JsonInclude] - public bool tintable = false; - - [JsonInclude] - public bool levels = false; // improvement specific - } - - public class BasePrefabInfo - { - [JsonInclude] - public List visualParts = new(); - } - public class UnitPrefabInfo : BasePrefabInfo - { - [JsonInclude] - public SkinnedKey skinnedKey; - - [JsonInclude] - public string headPositionMarker = ""; - } - - public class ImprovementPrefabInfo : BasePrefabInfo - { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ImprovementData.Type? improvementType = null; - } - - public class ResourcePrefabInfo : BasePrefabInfo - { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ResourceData.Type? resourceType = null; - } - - public class PrefabsInfo - { - [JsonInclude] - public List units = new(); - - [JsonInclude] - public List improvements = new(); - - [JsonInclude] - public List resources = new(); - } - - internal static void ProcessPrefabs() - { - foreach (var keyValuePair in prefabsFilesToProcess) - { - if(keyValuePair.Key == "all") - { - foreach (var bytes in keyValuePair.Value) - { - var prefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (prefab == null) - return; - - unitInfos.AddRange(prefab.units); - improvementInfos.AddRange(prefab.improvements); - resourceInfos.AddRange(prefab.resources); - } - } - else if(keyValuePair.Key == "units") - { - foreach (var bytes in keyValuePair.Value) - { - var unitPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (unitPrefab == null) - return; - - unitInfos.Add(unitPrefab); - } - } - else if(keyValuePair.Key == "improvements") - { - foreach (var bytes in keyValuePair.Value) - { - var improvementPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (improvementPrefab == null) - return; - - improvementInfos.Add(improvementPrefab); - } - } - else if(keyValuePair.Key == "resources") - { - foreach (var bytes in keyValuePair.Value) - { - var resourcePrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (resourcePrefab == null) - return; - - PrefabCreator.resourceInfos.Add(resourcePrefab); - } - } - } - foreach (var unitPrefabInfo in unitInfos) - { - ProcessUnitPrefabInfo(unitPrefabInfo); - } - - foreach (var improvementPrefabInfo in improvementInfos) - { - ProcessImprovementPrefabInfo(improvementPrefabInfo); - } - - foreach (var resourcePrefabInfo in resourceInfos) - { - ProcessResourcePrefabInfo(resourcePrefabInfo); - } - - foreach (var item in unitsNew) - { - var skinnedKey = item.Key; - var unit = item.Value; - SkinVisualsReference skinVisualsReference = unit.GetComponent(); - if (skinVisualsReference == null) - { - skinVisualsReference = unit.GetComponentInChildren(true); - } - if (skinVisualsReference == null || skinVisualsReference.visualParts == null) - { - Plugin.logger.LogWarning($"{skinnedKey.unitType} {skinnedKey.tribeType} {skinnedKey.skinType}: no SkinVisualsReference"); - continue; - } - - for (int partIndex = 0; partIndex < skinVisualsReference.visualParts.Length; partIndex++) - { - VisualPart currentPart = skinVisualsReference.visualParts[partIndex]; - Plugin.logger.LogInfo($"{skinnedKey.unitType} {skinnedKey.tribeType} {skinnedKey.skinType} part {partIndex}"); - Plugin.logger.LogInfo($" visualPart: {DescribeVisualObject(currentPart.visualPart)}"); - Plugin.logger.LogInfo($" outline: {DescribeVisualObject(currentPart.outline)}"); - } - } - } - - private static string DescribeVisualObject(GameObject targetObject) - { - if (targetObject == null) - { - return "null"; - } - - string layerName = LayerMask.LayerToName(targetObject.layer); - string description = $"name={targetObject.name}, layer={targetObject.layer} ({layerName}), activeSelf={targetObject.activeSelf}"; - - SpriteRenderer spriteRenderer = targetObject.GetComponent(); - if (spriteRenderer != null) - { - description += $", SpriteRenderer(enabled={spriteRenderer.enabled}, sortingLayer={SortingLayer.IDToName(spriteRenderer.sortingLayerID)}, sortingOrder={spriteRenderer.sortingOrder}, hasSprite={spriteRenderer.sprite != null})"; - } - - PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetObject.GetComponent(); - if (polytopiaSpriteRenderer != null) - { - description += $", PolytopiaSpriteRenderer(enabled={polytopiaSpriteRenderer.enabled}, sortingLayer={SortingLayer.IDToName(polytopiaSpriteRenderer.SortingLayer)}, sortingOrder={polytopiaSpriteRenderer.SortingOrder}, hasSprite={polytopiaSpriteRenderer.HasSprite()})"; - } - - return description; - } - - private static List ApplyVisualParts( - UnitPrefabInfo prefab, - Transform spriteContainer) - { - - List parts = new(); - - if (prefab.visualParts.Count == 0) - return parts; - - int nextPartSortingOrder = 0; - int nextOutlineSortingOrder = -prefab.visualParts.Count; - foreach (var info in prefab.visualParts) - { - parts.Add(CreateUnitVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); - if(nextOutlineSortingOrder < -1) - { - nextOutlineSortingOrder++; - } - nextPartSortingOrder++; - Console.Write($"{prefab.visualParts.Count} New orders {nextPartSortingOrder} {nextOutlineSortingOrder}"); - } - - return parts; - } - - private static SkinVisualsReference.VisualPart CreateUnitVisualPart( - VisualPartInfo info, - Transform parent, - int visualPartSortingOrder, - int outlineSortingOrder) - { - var visualPartObj = new GameObject(info.defaultSpriteName); - visualPartObj.transform.SetParent(parent); - - var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); - outlineObj.transform.SetParent(visualPartObj.transform); - - visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; - visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - // this bs was hunting me for so long. that is the thing which makes outline hidden in ui - outlineObj.SetActive(false); - - var visualPart = new SkinVisualsReference.VisualPart - { - DefaultSpriteName = info.defaultSpriteName, - visualPart = visualPartObj, - outline = outlineObj, - tintable = info.tintable - }; - - var renderer = visualPartObj.AddComponent(); - renderer.material = cachedUnitMaterial; - renderer.sortingOrder = visualPartSortingOrder; - renderer.sortingLayerName = "Units"; - visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; - - var outlineRenderer = outlineObj.AddComponent(); - outlineRenderer.material = cachedUnitMaterial; - outlineRenderer.sortingOrder = outlineSortingOrder; - outlineRenderer.sortingLayerName = "Units"; - visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; - - return visualPart; - } - - private static SkinVisualsReference.VisualPart CreateImprovementVisualPart( - VisualPartInfo info, - Transform parent, - int visualPartSortingOrder, - int outlineSortingOrder) - { - return null; - } - - private static SkinVisualsReference.VisualPart CreateResourceVisualPart( - VisualPartInfo info, - Transform parent, - int visualPartSortingOrder, - int outlineSortingOrder) - { - return null; - } - - internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) - { - var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); - if (baseUnit == null) - return; - - var unitInstance = GameObject.Instantiate(baseUnit); - if (unitInstance == null) - return; - - GameObject.Destroy(unitInstance.spriteContainer.gameObject); - - var spriteContainerObj = new GameObject("SpriteContainer"); - spriteContainerObj.transform.SetParent(unitInstance.transform, false); - var spriteContainer = spriteContainerObj.transform; - unitInstance.spriteContainer = spriteContainer; - - var visualParts = ApplyVisualParts(unitPrefabInfo, spriteContainer); - - Transform? headPositionMarker = null; - foreach (var vp in visualParts) - { - if (vp.visualPart.gameObject.name == unitPrefabInfo.headPositionMarker) - { - headPositionMarker = vp.visualPart.gameObject.transform; - break; - } - } - - unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; - - var svr = unitInstance.GetComponent(); - svr.visualParts = visualParts.ToArray(); - - GameObject.DontDestroyOnLoad(unitInstance.gameObject); - - PrefabRegistry.unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; - } - - internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo unitPrefabInfo) - { - } - - internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo unitPrefabInfo) - { - } -} \ No newline at end of file diff --git a/src/Managers/Visual/PrefabRegistry.cs b/src/Managers/Visual/PrefabRegistry.cs deleted file mode 100644 index 4c14ec6..0000000 --- a/src/Managers/Visual/PrefabRegistry.cs +++ /dev/null @@ -1,157 +0,0 @@ -using HarmonyLib; -using Polytopia.Data; -using PolytopiaBackendBase.Common; -using UnityEngine; -using static PrefabManager; -using static SkinVisualsReference; - -namespace PolyMod.Managers; - -public static class PrefabRegistry -{ - internal static Dictionary unitsNew = new(); - internal static Dictionary> unitOverridesNew = new(); - internal static Dictionary unitUIOverridesNew = new(); - - [HarmonyPostfix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] - private static void PrefabManager_Awake_Postfix(PrefabManager __instance) - { - unitsNew.Clear(); - unitOverridesNew.Clear(); - unitUIOverridesNew.Clear(); - - foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) - { - if(PrefabCreator.cachedUnitMaterial == null) - { - SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); - if (skinVisualsReference != null && skinVisualsReference.visualParts != null) - { - foreach (VisualPart currentPart in skinVisualsReference.visualParts) - { - if (currentPart.visualPart == null) - { - continue; - } - - SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); - if (headSpriteRenderer != null) - { - PrefabCreator.cachedUnitMaterial = headSpriteRenderer.sharedMaterial; - break; - } - } - } - } - unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; - } - - foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) - { - if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) - { - overridesForCondition = new Dictionary(); - unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; - } - overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; - } - - foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) - { - unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; - } - - Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] - public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) - { - __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] - public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) - { - if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) - { - __result = uiOverridePrefab; - } - else - { - __result = ResolveUnitPrefab(unitType, tribe, skin); - } - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] - public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) - { - __result = ResolveUnitPrefab(type, tribe, skin); - return false; - } - - [HarmonyPostfix] // prolly remove later - [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] - public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) - { - bool flag = false; - flag = visualSetting.outline != null && visualSetting.outline.transform.parent == visualSetting.visualPart.transform; - if (!flag && visualSetting.visualPart.transform.childCount > 0) - { - visualSetting.outline = visualSetting.visualPart.transform.GetChild(0).gameObject; - flag = true; - } - bool flag2 = false; - if (flag) - { - string defaultSpriteName = visualSetting.DefaultSpriteName; - if (visualSetting.outline != null && visualSetting.outline.name == defaultSpriteName + "_Outline") - { - flag2 = true; - } - } - visualSetting.hasValidOutline = flag2; - } - - private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) - { - if (SeasonManager.IsChristmas() - && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) - && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) - && christmasPrefab != null) - { - return christmasPrefab; - } - - SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); - if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) - { - return exactPrefab; - } - - if (skinType != SkinType.Default || tribeType != TribeType.None) - { - SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); - SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); - SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); - - if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) - || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) - || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) - { - unitsNew[exactKey] = fallbackPrefab; - return fallbackPrefab; - } - } - - Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); - unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); - return lastResortPrefab!; - } -} \ No newline at end of file diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs new file mode 100644 index 0000000..ce5a44f --- /dev/null +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -0,0 +1,34 @@ + +using System.Text.Json.Serialization; +using PolyMod.Json; +using Polytopia.Data; + +namespace PolyMod; + +public class BasePrefabInfo +{ + [JsonInclude] + public List visualParts = new(); +} +public class UnitPrefabInfo : BasePrefabInfo +{ + [JsonInclude] + public SkinnedKey skinnedKey; + + [JsonInclude] + public string headPositionMarker = ""; +} + +public class ImprovementPrefabInfo : BasePrefabInfo +{ + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; +} + +public class ResourcePrefabInfo : BasePrefabInfo +{ + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; +} \ No newline at end of file diff --git a/src/Prefabs/PrefabsInfo.cs b/src/Prefabs/PrefabsInfo.cs new file mode 100644 index 0000000..d0b4ab3 --- /dev/null +++ b/src/Prefabs/PrefabsInfo.cs @@ -0,0 +1,16 @@ + +using System.Text.Json.Serialization; + +namespace PolyMod; + +public class PrefabsInfo +{ + [JsonInclude] + public List units = new(); + + [JsonInclude] + public List improvements = new(); + + [JsonInclude] + public List resources = new(); +} \ No newline at end of file diff --git a/src/Managers/Visual/SkinnedKey.cs b/src/Prefabs/SkinnedKey.cs similarity index 97% rename from src/Managers/Visual/SkinnedKey.cs rename to src/Prefabs/SkinnedKey.cs index 0f42c9c..080b6df 100644 --- a/src/Managers/Visual/SkinnedKey.cs +++ b/src/Prefabs/SkinnedKey.cs @@ -3,7 +3,7 @@ using Polytopia.Data; using PolytopiaBackendBase.Common; -namespace PolyMod.Managers; +namespace PolyMod; public readonly struct SkinnedKey : IEquatable { diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs new file mode 100644 index 0000000..4b6fd47 --- /dev/null +++ b/src/Prefabs/VisualPartInfo.cs @@ -0,0 +1,37 @@ +using System.Text.Json.Serialization; +using PolyMod.Json; +using UnityEngine; + +namespace PolyMod; + +public class VisualPartInfo +{ + [JsonInclude] + public string? defaultSpriteName; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific + + [JsonInclude] + public Vector2 coordinates = new Vector2(); + + [JsonInclude] + public float rotation = 0f; + + [JsonInclude] + public bool tintable = false; + + [JsonInclude] + public bool levels = false; // improvement specific + + [JsonInclude] + public int? sortingOrderOverride = null; + + [JsonInclude] + public int? outlineSortingOrderOverride = null; +} \ No newline at end of file diff --git a/src/Registry.cs b/src/Registry.cs index a3d075f..718dfdc 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -34,7 +34,7 @@ public static class Registry /// /// A dictionary of tribe previews, keyed by tribe name. /// - public static Dictionary tribePreviews = new(); + public static Dictionary tribePreviews = new(); /// /// A dictionary of sprite information, keyed by sprite name. @@ -77,6 +77,8 @@ public static class Registry /// public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", int level = -1) { + if(baseName.Contains("oil")) + Console.Write("YESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"); Sprite? sprite = null; baseName = baseName.ToLower(); tribeText = tribeText.ToLower(); @@ -104,7 +106,8 @@ public static class Registry { sprite = sprites.GetOrDefault(spriteName, sprite); } - + if(baseName.Contains("oil")) + Console.Write(sprite == null); return sprite; } From c08b968809f7831e4b7ace9226b51ce0296750bb Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sat, 17 Oct 2026 21:34:57 +0200 Subject: [PATCH 06/42] Added a queue to process files after whole gld was merged (for prefabs). Cleanup --- src/Loader.cs | 133 ++++++++++++++++++++++------------------ src/Managers/Main.cs | 22 ++----- src/Managers/Prefabs.cs | 75 +--------------------- src/Registry.cs | 7 +-- 4 files changed, 86 insertions(+), 151 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index c431c06..11fc6ad 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -682,22 +682,17 @@ public static void LoadPrefabsFile(Mod mod, Mod.File file) { try { - if(!Prefabs.prefabsFilesToProcess.ContainsKey("all") || Prefabs.prefabsFilesToProcess["all"] == null) - Prefabs.prefabsFilesToProcess["all"] = new(); - - Prefabs.prefabsFilesToProcess["all"].Add(file.bytes); - - // var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - // { - // Converters = { new Vector2Json() }, - // PropertyNameCaseInsensitive = true, - // }); - // if (prefab == null) - // return; + var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (prefab == null) + return; - // Prefabs.unitInfos.AddRange(prefab.units); - // Prefabs.improvementInfos.AddRange(prefab.improvements); - // Prefabs.resourceInfos.AddRange(prefab.resources); + Prefabs.unitInfos.AddRange(prefab.units); + Prefabs.improvementInfos.AddRange(prefab.improvements); + Prefabs.resourceInfos.AddRange(prefab.resources); Plugin.logger.LogInfo($"Registered prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -711,20 +706,15 @@ public static void LoadUnitPrefabFile(Mod mod, Mod.File file) { try { - if(!Prefabs.prefabsFilesToProcess.ContainsKey("units") || Prefabs.prefabsFilesToProcess["units"] == null) - Prefabs.prefabsFilesToProcess["units"] = new(); - - Prefabs.prefabsFilesToProcess["units"].Add(file.bytes); - - // var unitPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - // { - // Converters = { new Vector2Json() }, - // PropertyNameCaseInsensitive = true, - // }); - // if (unitPrefab == null) - // return; + var unitPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (unitPrefab == null) + return; - // Prefabs.unitInfos.Add(unitPrefab); + Prefabs.unitInfos.Add(unitPrefab); Plugin.logger.LogInfo($"Registered unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -738,20 +728,15 @@ public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) { try { - if(!Prefabs.prefabsFilesToProcess.ContainsKey("improvements") || Prefabs.prefabsFilesToProcess["improvements"] == null) - Prefabs.prefabsFilesToProcess["improvements"] = new(); - - Prefabs.prefabsFilesToProcess["improvements"].Add(file.bytes); - - // var improvementPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - // { - // Converters = { new Vector2Json() }, - // PropertyNameCaseInsensitive = true, - // }); - // if (improvementPrefab == null) - // return; + var improvementPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (improvementPrefab == null) + return; - // Prefabs.improvementInfos.Add(improvementPrefab); + Prefabs.improvementInfos.Add(improvementPrefab); Plugin.logger.LogInfo($"Registered improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -765,20 +750,15 @@ public static void LoadResourcePrefabFile(Mod mod, Mod.File file) { try { - if(!Prefabs.prefabsFilesToProcess.ContainsKey("resources") || Prefabs.prefabsFilesToProcess["resources"] == null) - Prefabs.prefabsFilesToProcess["resources"] = new(); - - Prefabs.prefabsFilesToProcess["resources"].Add(file.bytes); - - // var resourcePrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - // { - // Converters = { new Vector2Json() }, - // PropertyNameCaseInsensitive = true, - // }); - // if (resourcePrefab == null) - // return; + var resourcePrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }); + if (resourcePrefab == null) + return; - // Prefabs.resourceInfos.Add(resourcePrefab); + Prefabs.resourceInfos.Add(resourcePrefab); Plugin.logger.LogInfo($"Registered resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } @@ -833,8 +813,6 @@ internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject r { CreateMappings(rootObject); ProcessCustomTribes(); - // OKAY BASICALLY I need to find a way to load certain files at this stage (?) - ProcessPrefabs(); ProcessEmbarkOverrides(); ProcessAttractOverrides(); } @@ -946,9 +924,48 @@ internal static void CreateMappings(JObject rootObject) /// /// Processes the prefab registry and populates the PrefabManager with custom prefabs. /// - internal static void ProcessPrefabs() + internal static void ProcessFilesQueue() { - Prefabs.ProcessPrefabs(); + try + { + foreach (KeyValuePair keyValuePair in Registry.filesQueueToBeProcessedAfterGLDMerge) + { + Mod mod = keyValuePair.Key; + Mod.File file = keyValuePair.Value; + Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); + if (prefabsMatch.Success) + { + LoadPrefabsFile(mod, file); + continue; + } + + Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); + if (unitPrefabMatch.Success) + { + LoadUnitPrefabFile(mod, file); + continue; + } + + Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); + if (improvementPrefabMatch.Success) + { + LoadImprovementPrefabFile(mod, file); + continue; + } + + Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); + if (resourcePrefabMatch.Success) + { + LoadResourcePrefabFile(mod, file); + continue; + } + + } + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on processing post gld merge files queue : {e.StackTrace}"); + } } /// diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 0e36936..2ce6f4c 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -436,40 +436,28 @@ internal static void Load(GameLogicData gameLogicData, JObject json) Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); if (prefabsMatch.Success) { - Loader.LoadPrefabsFile( - mod, - file - ); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); continue; } Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); if (unitPrefabMatch.Success) { - Loader.LoadUnitPrefabFile( - mod, - file - ); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); continue; } Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); if (improvementPrefabMatch.Success) { - Loader.LoadImprovementPrefabFile( - mod, - file - ); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); continue; } Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); if (resourcePrefabMatch.Success) { - Loader.LoadResourcePrefabFile( - mod, - file - ); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); continue; } @@ -493,6 +481,8 @@ internal static void Load(GameLogicData gameLogicData, JObject json) TechItem.techTierFirebaseId.Add($"tech_research_{i}"); } Loader.ProcessGameLogicData(gameLogicData, json); + Loader.ProcessFilesQueue(); + Prefabs.CreatePrefabs(); stopwatch.Stop(); Plugin.logger.LogInfo($"Loaded all mods in {stopwatch.ElapsedMilliseconds}ms"); } diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index addacf2..8d48c13 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -4,8 +4,6 @@ using UnityEngine; using static PrefabManager; using static SkinVisualsReference; -using System.Text.Json; -using PolyMod.Json; namespace PolyMod.Managers; @@ -17,7 +15,6 @@ public static class Prefabs internal static Material? cachedUnitMaterial; internal static Material? cachedResourceMaterial; - internal static int cachedResourceSortingLayerId; internal static Dictionary> prefabsFilesToProcess = new(); @@ -169,7 +166,7 @@ private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeTyp return lastResortPrefab!; } - internal static void ProcessPrefabs() + internal static void CreatePrefabs() { // get materials Material[] allLoadedMaterials = Resources.FindObjectsOfTypeAll(); @@ -178,80 +175,12 @@ internal static void ProcessPrefabs() if(loadedMaterial.name == "SpriteMaterial") { cachedResourceMaterial = loadedMaterial; - Console.Write("MATERIAL FUCKING FOUND GOODBYE!"); GameObject.DontDestroyOnLoad(cachedResourceMaterial); break; } Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); } - cachedResourceSortingLayerId = MeshCache.TERRAIN_LAYER_ID; - // i will remove this bs - foreach (var keyValuePair in prefabsFilesToProcess) - { - if(keyValuePair.Key == "all") - { - foreach (var bytes in keyValuePair.Value) - { - var prefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (prefab == null) - return; - - unitInfos.AddRange(prefab.units); - improvementInfos.AddRange(prefab.improvements); - resourceInfos.AddRange(prefab.resources); - } - } - else if(keyValuePair.Key == "units") - { - foreach (var bytes in keyValuePair.Value) - { - var unitPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (unitPrefab == null) - return; - - unitInfos.Add(unitPrefab); - } - } - else if(keyValuePair.Key == "improvements") - { - foreach (var bytes in keyValuePair.Value) - { - var improvementPrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (improvementPrefab == null) - return; - - improvementInfos.Add(improvementPrefab); - } - } - else if(keyValuePair.Key == "resources") - { - foreach (var bytes in keyValuePair.Value) - { - var resourcePrefab = JsonSerializer.Deserialize(bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (resourcePrefab == null) - return; - - resourceInfos.Add(resourcePrefab); - } - } - } foreach (var unitPrefabInfo in unitInfos) { ProcessUnitPrefabInfo(unitPrefabInfo); @@ -395,7 +324,7 @@ private static SkinVisualsReference.VisualPart CreateImprovementVisualPart( int visualPartSortingOrder, int outlineSortingOrder) { - return null; + return new VisualPart(); } #endregion diff --git a/src/Registry.cs b/src/Registry.cs index 718dfdc..9ac5c49 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -66,6 +66,8 @@ public static class Registry /// public static int gameModesAutoidx = Enum.GetValues(typeof(GameMode)).Length; + public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it + public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1) { string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); @@ -77,8 +79,6 @@ public static class Registry /// public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", int level = -1) { - if(baseName.Contains("oil")) - Console.Write("YESSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"); Sprite? sprite = null; baseName = baseName.ToLower(); tribeText = tribeText.ToLower(); @@ -106,8 +106,7 @@ public static class Registry { sprite = sprites.GetOrDefault(spriteName, sprite); } - if(baseName.Contains("oil")) - Console.Write(sprite == null); + return sprite; } From 8fa7f3ea5dcea88c9af36a1d2f3cd2ebcdce3e37 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sat, 17 Oct 2026 22:50:33 +0200 Subject: [PATCH 07/42] Finished improvements --- src/Managers/Hub.cs | 23 +++++- src/Managers/Prefabs.cs | 143 ++++++++++++++++++++++++++------- src/Managers/Visual.cs | 36 +++------ src/Prefabs/OtherPrefabInfo.cs | 3 + 4 files changed, 149 insertions(+), 56 deletions(-) diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 9400b51..69e399d 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -392,6 +392,25 @@ internal static void DumpPrefabs() // TODO { continue; } + + int? sortingOrderOverride = null; + SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); + if (spriteRenderer != null) + { + sortingOrderOverride = spriteRenderer.sortingOrder; + } + + int? outlineSortingOrderOverride = null; + + if (visualPart.outline != null) + { + spriteRenderer = visualPart.outline.GetComponent(); + if (spriteRenderer != null) + { + outlineSortingOrderOverride = spriteRenderer.sortingOrder; + } + } + var visualPartInfo = new VisualPartInfo { coordinates = visualPart.visualPart.transform.position, @@ -400,7 +419,9 @@ internal static void DumpPrefabs() // TODO tintable = visualPart.tintable, skinningLogic = visualPart.skinLogic, improvementSkinningLogic = visualPart.improvementSkinLogic, - levels = visualPart.levels + levels = visualPart.levels, + sortingOrderOverride = sortingOrderOverride, + outlineSortingOrderOverride = outlineSortingOrderOverride }; unitPrefabInfo.visualParts.Add(visualPartInfo); diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index 8d48c13..33b2d74 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -14,7 +14,7 @@ public static class Prefabs internal static Dictionary unitUIOverridesNew = new(); internal static Material? cachedUnitMaterial; - internal static Material? cachedResourceMaterial; + internal static Material? cachedSharedMaterial; internal static Dictionary> prefabsFilesToProcess = new(); @@ -174,8 +174,8 @@ internal static void CreatePrefabs() { if(loadedMaterial.name == "SpriteMaterial") { - cachedResourceMaterial = loadedMaterial; - GameObject.DontDestroyOnLoad(cachedResourceMaterial); + cachedSharedMaterial = loadedMaterial; + GameObject.DontDestroyOnLoad(cachedSharedMaterial); break; } Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); @@ -254,7 +254,7 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) newVisualInfo.Reverse(); foreach (var info in newVisualInfo) { - parts.Add(CreateUnitVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); + parts.Add(CreateUnitVisualPart(info, spriteContainer, info.sortingOrderOverride ?? nextPartSortingOrder, info.outlineSortingOrderOverride ?? nextOutlineSortingOrder)); if(nextOutlineSortingOrder < -1) { nextOutlineSortingOrder++; @@ -315,16 +315,119 @@ private static SkinVisualsReference.VisualPart CreateUnitVisualPart( #region Improvements internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvementPrefabInfo) { - var baseImprovement = PrefabManager.GetPrefab(ImprovementData.Type.LumberHut); + if(improvementPrefabInfo.improvementType == null) + return; + + var baseBuilding = PrefabManager.GetPrefab(ImprovementData.Type.LumberHut); + if (baseBuilding == null) + return; + + var buildingInstance = GameObject.Instantiate(baseBuilding); + if (buildingInstance == null) + return; + + Transform buildingTransform = buildingInstance.transform; + for (int childIndex = buildingTransform.childCount - 1; childIndex >= 0; childIndex--) + { + GameObject.Destroy(buildingTransform.GetChild(childIndex).gameObject); + } + + var visualParts = ApplyBuildingVisualParts(improvementPrefabInfo, buildingTransform); + + var svr = buildingInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(buildingInstance.gameObject); + + PrefabManager.improvements[(Polytopia.Data.ImprovementData.Type)improvementPrefabInfo.improvementType] = buildingInstance; } - private static SkinVisualsReference.VisualPart CreateImprovementVisualPart( + private static List ApplyBuildingVisualParts( + ImprovementPrefabInfo improvementPrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = improvementPrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + foreach (var info in visualPartInfos) + { + parts.Add(CreateBuildingVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder, improvementPrefabInfo.needsOutlines)); + if(nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + } + + return parts; + } + + private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( VisualPartInfo info, Transform parent, int visualPartSortingOrder, - int outlineSortingOrder) + int outlineSortingOrder, + bool needsOutline = false) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + outlineObj.SetActive(false); + + var visualPart = new SkinVisualsReference.VisualPart + { + DefaultSpriteName = info.defaultSpriteName, + visualPart = visualPartObj, + outline = outlineObj, + tintable = info.tintable, + skinLogic = info.skinningLogic, + improvementSkinLogic = info.improvementSkinningLogic, + levels = info.levels, + isImprovement = true, + }; + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); + visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; + + if(needsOutline) + { + var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; + } + + return visualPart; + } + + private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject targetGameObject, int sortingOrder, string sortingLayerName = "Terrain") { - return new VisualPart(); + MeshFilter meshFilter = targetGameObject.AddComponent(); + MeshRenderer meshRenderer = targetGameObject.AddComponent(); + meshRenderer.receiveShadows = false; + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + + PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetGameObject.AddComponent(); + polytopiaSpriteRenderer.meshFilter = meshFilter; + polytopiaSpriteRenderer.meshRenderer = meshRenderer; + + polytopiaSpriteRenderer.SortingLayer = SortingLayer.NameToID(sortingLayerName); + polytopiaSpriteRenderer.SortingOrder = sortingOrder; + if (cachedSharedMaterial != null) + { + polytopiaSpriteRenderer.SharedMaterial = cachedSharedMaterial; + } + return polytopiaSpriteRenderer; } #endregion @@ -349,7 +452,7 @@ internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefab GameObject.Destroy(resourceTransform.GetChild(childIndex).gameObject); } - var visualParts = ApplyResourceVisualParts(resourcePrefabInfo, resourceInstance.transform); + var visualParts = ApplyResourceVisualParts(resourcePrefabInfo, resourceTransform); var svr = resourceInstance.GetComponent(); svr.visualParts = visualParts.ToArray(); @@ -421,27 +524,5 @@ private static SkinVisualsReference.VisualPart CreateResourceVisualPart( return visualPart; } - private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject targetGameObject, int sortingOrder) - { - MeshFilter meshFilter = targetGameObject.AddComponent(); - MeshRenderer meshRenderer = targetGameObject.AddComponent(); - meshRenderer.receiveShadows = false; - meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; - meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off; - meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; - - PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetGameObject.AddComponent(); - polytopiaSpriteRenderer.meshFilter = meshFilter; - polytopiaSpriteRenderer.meshRenderer = meshRenderer; - - polytopiaSpriteRenderer.SortingLayer = SortingLayer.NameToID("Terrain"); - polytopiaSpriteRenderer.SortingOrder = sortingOrder; - if (cachedResourceMaterial != null) - { - polytopiaSpriteRenderer.SharedMaterial = cachedResourceMaterial; - } - return polytopiaSpriteRenderer; - } - #endregion } \ No newline at end of file diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index f67a3f8..6f3d2cf 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -243,41 +243,29 @@ private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRende #endregion #region UI - // check if still needed - /// Provides custom sprites for improvements in the UI. [HarmonyPostfix] - [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetImprovementSprite), typeof(ImprovementData.Type), typeof(TribeType), typeof(SkinType), typeof(SpriteAtlasManager))] - private static void UIUtils_GetImprovementSprite(ref Sprite __result, ImprovementData.Type improvement, TribeType tribe, SkinType skin, SpriteAtlasManager atlasManager) + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] + private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) { - Sprite? sprite = Registry.GetSprite(EnumCache.GetName(improvement), tribe, skin); - Console.Write(EnumCache.GetName(improvement)); - Console.Write(sprite == null); - if (sprite != null) - { - __result = sprite; - } + if((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(terrain); } - /// Provides custom sprites for improvements in the UI. [HarmonyPostfix] - [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetImprovementSprite), typeof(SkinVisualsTransientData), typeof(ImprovementData.Type), typeof(SpriteAtlasManager))] - private static void UIUtils_GetImprovementSprite_2(ref Sprite __result, SkinVisualsTransientData data, ImprovementData.Type improvement, SpriteAtlasManager atlasManager) + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] + private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) { - UIUtils_GetImprovementSprite(ref __result, improvement, data.foundingTribeSettings.tribe, data.foundingTribeSettings.skin, atlasManager); + if((int)resource >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(resource); } - /// Provides custom sprites for resources in the UI. [HarmonyPostfix] - [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetResourceSprite))] - private static void UIUtils_GetResourceSprite(ref Sprite __result, SkinVisualsTransientData data, ResourceData.Type resource, SpriteAtlasManager atlasManager) + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] + private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) { - TribeAndSkin tileClimateSettings = data.tileClimateSettings; - Sprite? sprite = Registry.GetSprite(EnumCache.GetName(resource), tileClimateSettings.tribe, tileClimateSettings.skin); - if (sprite != null) - { - __result = sprite; - } + if((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(improvement); } #endregion diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index ce5a44f..46f26e2 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -24,6 +24,9 @@ public class ImprovementPrefabInfo : BasePrefabInfo [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public ImprovementData.Type? improvementType = null; + + [JsonInclude] + public bool needsOutlines = false; } public class ResourcePrefabInfo : BasePrefabInfo From 8fef382a82516b17001f0f253f54a30c4402f304 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sat, 17 Oct 2026 23:48:33 +0200 Subject: [PATCH 08/42] added improvement and resource dumping, added helpers methods to visual parts --- src/Managers/Hub.cs | 81 ++++++++++++++++++++++++----------- src/Managers/Prefabs.cs | 42 +++++------------- src/Prefabs/VisualPartInfo.cs | 44 +++++++++++++++++++ 3 files changed, 111 insertions(+), 56 deletions(-) diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 69e399d..551c527 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -393,41 +393,72 @@ internal static void DumpPrefabs() // TODO continue; } - int? sortingOrderOverride = null; - SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); - if (spriteRenderer != null) + var visualPartInfo = new VisualPartInfo { }; + visualPartInfo.CopyFromVisualPart(visualPart); + unitPrefabInfo.visualParts.Add(visualPartInfo); + + } + prefabsInfo.units.Add(unitPrefabInfo); + } + + foreach (Il2CppSystem.Collections.Generic.KeyValuePair keyValuePairs in PrefabManager.improvements) + { + var unit = keyValuePairs.Value; + SkinVisualsReference skinVisualsReference = unit.GetComponent(); + if (skinVisualsReference == null || skinVisualsReference.visualParts == null) + { + Plugin.logger.LogWarning($"Dump skipped {keyValuePairs.Key}: no SkinVisualsReference"); + continue; + } + ImprovementPrefabInfo improvementPrefabInfo = new() + { + improvementType = keyValuePairs.Key, + visualParts = new() + }; + foreach (var visualPart in skinVisualsReference.visualParts) + { + if (visualPart == null || visualPart.visualPart == null) { - sortingOrderOverride = spriteRenderer.sortingOrder; + continue; } - int? outlineSortingOrderOverride = null; + var visualPartInfo = new VisualPartInfo { }; + visualPartInfo.CopyFromVisualPart(visualPart); + improvementPrefabInfo.visualParts.Add(visualPartInfo); - if (visualPart.outline != null) + } + prefabsInfo.improvements.Add(improvementPrefabInfo); + } + + foreach (Il2CppSystem.Collections.Generic.KeyValuePair keyValuePairs in PrefabManager.resources) + { + var unit = keyValuePairs.Value; + SkinVisualsReference skinVisualsReference = unit.GetComponent(); + if (skinVisualsReference == null || skinVisualsReference.visualParts == null) + { + Plugin.logger.LogWarning($"Dump skipped {keyValuePairs.Key}: no SkinVisualsReference"); + continue; + } + ResourcePrefabInfo resourcePrefabInfo = new() + { + resourceType = keyValuePairs.Key, + visualParts = new() + }; + foreach (var visualPart in skinVisualsReference.visualParts) + { + if (visualPart == null || visualPart.visualPart == null) { - spriteRenderer = visualPart.outline.GetComponent(); - if (spriteRenderer != null) - { - outlineSortingOrderOverride = spriteRenderer.sortingOrder; - } + continue; } - var visualPartInfo = new VisualPartInfo - { - coordinates = visualPart.visualPart.transform.position, - rotation = visualPart.visualPart.transform.rotation.z, - defaultSpriteName = visualPart.DefaultSpriteName, - tintable = visualPart.tintable, - skinningLogic = visualPart.skinLogic, - improvementSkinningLogic = visualPart.improvementSkinLogic, - levels = visualPart.levels, - sortingOrderOverride = sortingOrderOverride, - outlineSortingOrderOverride = outlineSortingOrderOverride - }; - unitPrefabInfo.visualParts.Add(visualPartInfo); + var visualPartInfo = new VisualPartInfo { }; + visualPartInfo.CopyFromVisualPart(visualPart); + resourcePrefabInfo.visualParts.Add(visualPartInfo); } - prefabsInfo.units.Add(unitPrefabInfo); + prefabsInfo.resources.Add(resourcePrefabInfo); } + File.WriteAllTextAsync( Path.Combine(Plugin.PREFABS_DUMP_PATH, $"prefabs.json"), JsonSerializer.Serialize(prefabsInfo, new JsonSerializerOptions { WriteIndented = true, Converters = { new Vector2Json() },}) diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index 33b2d74..bca4d32 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -285,16 +285,9 @@ private static SkinVisualsReference.VisualPart CreateUnitVisualPart( // this bs was hunting me for so long. that is the thing which makes outline hidden in ui outlineObj.SetActive(false); - var visualPart = new SkinVisualsReference.VisualPart - { - DefaultSpriteName = info.defaultSpriteName, - visualPart = visualPartObj, - outline = outlineObj, - tintable = info.tintable, - skinLogic = info.skinningLogic, - improvementSkinLogic = info.improvementSkinningLogic, - levels = info.levels - }; + var visualPart = info.ToVisualPart(false); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; var renderer = visualPartObj.AddComponent(); renderer.material = cachedUnitMaterial; @@ -385,17 +378,10 @@ private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( outlineObj.SetActive(false); - var visualPart = new SkinVisualsReference.VisualPart - { - DefaultSpriteName = info.defaultSpriteName, - visualPart = visualPartObj, - outline = outlineObj, - tintable = info.tintable, - skinLogic = info.skinningLogic, - improvementSkinLogic = info.improvementSkinningLogic, - levels = info.levels, - isImprovement = true, - }; + var visualPart = info.ToVisualPart(true); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; @@ -505,16 +491,10 @@ private static SkinVisualsReference.VisualPart CreateResourceVisualPart( outlineObj.SetActive(false); - var visualPart = new SkinVisualsReference.VisualPart - { - DefaultSpriteName = info.defaultSpriteName, - visualPart = visualPartObj, - outline = outlineObj, - tintable = info.tintable, - skinLogic = info.skinningLogic, - improvementSkinLogic = info.improvementSkinningLogic, - levels = info.levels - }; + var visualPart = info.ToVisualPart(false); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs index 4b6fd47..1296396 100644 --- a/src/Prefabs/VisualPartInfo.cs +++ b/src/Prefabs/VisualPartInfo.cs @@ -34,4 +34,48 @@ public class VisualPartInfo [JsonInclude] public int? outlineSortingOrderOverride = null; + + public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) + { + return new SkinVisualsReference.VisualPart + { + DefaultSpriteName = defaultSpriteName, + tintable = tintable, + skinLogic = skinningLogic, + improvementSkinLogic = improvementSkinningLogic, + levels = levels, + isImprovement = isImprovement, + }; + } + + public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) + { + int? sortingOrderOverride = null; + SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); + if (spriteRenderer != null) + { + sortingOrderOverride = spriteRenderer.sortingOrder; + } + + int? outlineSortingOrderOverride = null; + + if (visualPart.outline != null) + { + spriteRenderer = visualPart.outline.GetComponent(); + if (spriteRenderer != null) + { + outlineSortingOrderOverride = spriteRenderer.sortingOrder; + } + } + + coordinates = visualPart.visualPart.transform.position; + rotation = visualPart.visualPart.transform.rotation.z; + defaultSpriteName = visualPart.DefaultSpriteName; + tintable = visualPart.tintable; + skinningLogic = visualPart.skinLogic; + improvementSkinningLogic = visualPart.improvementSkinLogic; + levels = visualPart.levels; + this.sortingOrderOverride = sortingOrderOverride; + this.outlineSortingOrderOverride = outlineSortingOrderOverride; + } } \ No newline at end of file From 593d6438d278039499bc01d6d3a44c4ced131aff Mon Sep 17 00:00:00 2001 From: Maksym Muraviov <109823841+johnklipi@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:09:19 +0200 Subject: [PATCH 09/42] minor thinghy --- src/Managers/Prefabs.cs | 9 ++++++--- src/Prefabs/OtherPrefabInfo.cs | 10 ++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index bca4d32..cae6fb9 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -10,14 +10,12 @@ namespace PolyMod.Managers; public static class Prefabs { internal static Dictionary unitsNew = new(); - internal static Dictionary> unitOverridesNew = new(); + internal static Dictionary> unitOverridesNew = new(); // maybe in the future will implement internal static Dictionary unitUIOverridesNew = new(); internal static Material? cachedUnitMaterial; internal static Material? cachedSharedMaterial; - internal static Dictionary> prefabsFilesToProcess = new(); - public static List unitInfos = new(); public static List improvementInfos = new(); @@ -235,6 +233,11 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) GameObject.DontDestroyOnLoad(unitInstance.gameObject); + if(unitPrefabInfo.uiOverride) + { + unitUIOverridesNew[unitPrefabInfo.skinnedKey] = unitInstance; + return; + } unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; } diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index 46f26e2..fd2eecf 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -17,6 +17,9 @@ public class UnitPrefabInfo : BasePrefabInfo [JsonInclude] public string headPositionMarker = ""; + + [JsonInclude] + public bool uiOverride = false; } public class ImprovementPrefabInfo : BasePrefabInfo @@ -34,4 +37,11 @@ public class ResourcePrefabInfo : BasePrefabInfo [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public ResourceData.Type? resourceType = null; +} + +public class WeaponPrefabInfo +{ + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.WeaponEnum? weaponEnum = null; } \ No newline at end of file From a5e6ea048d313bbc8fd39c2cbdedc500fabc0f1a Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Wed, 21 Oct 2026 22:15:58 +0200 Subject: [PATCH 10/42] Added creation of dummy prefabs. Refactored terrain update graphics patch. bug fixes and etc --- src/Loader.cs | 47 ++++--- src/Managers/Prefabs.cs | 41 ++++++ src/Managers/Visual.cs | 229 ++++++++++++++++++---------------- src/Prefabs/VisualPartInfo.cs | 2 +- 4 files changed, 193 insertions(+), 126 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index 11fc6ad..c0b63b5 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -157,30 +157,47 @@ out TribeAbility.Type tribeAbilityType [typeof(ImprovementData.Type)] = new List>() { new((token, duringEnumCacheCreation) => { - if (!duringEnumCacheCreation) + if (duringEnumCacheCreation) + return; + + if (token["prefab"] != null && (bool)token["prefab"]) { - string improvementId = Util.GetJTokenName(token); - if (token["attractsResource"] != null) + bool levels = false; + if(token["maxLevel"] != null && (int)token["maxLevel"] > 0) { - string attractsId = token["attractsResource"].ToString(); - Main.attractsResourceNames[improvementId] = attractsId; - } - if (token["attractsToTerrain"] != null) - { - string attractsId = token["attractsToTerrain"].ToString(); - Main.attractsTerrainNames[improvementId] = attractsId; - } - if(token["infoOverride"] != null) - { - Loc.buildingsInfoOverrides[improvementId] = Loc.ReplaceDashesWithDots(token["infoOverride"].ToString()); + levels = true; } + Prefabs.improvementPrefabInfosToCreate[(ImprovementData.Type)(int)token["idx"]] = levels; + } + string improvementId = Util.GetJTokenName(token); + if (token["attractsResource"] != null) + { + string attractsId = token["attractsResource"].ToString(); + Main.attractsResourceNames[improvementId] = attractsId; + } + if (token["attractsToTerrain"] != null) + { + string attractsId = token["attractsToTerrain"].ToString(); + Main.attractsTerrainNames[improvementId] = attractsId; + } + if(token["infoOverride"] != null) + { + Loc.buildingsInfoOverrides[improvementId] = Loc.ReplaceDashesWithDots(token["infoOverride"].ToString()); } }) }, [typeof(ResourceData.Type)] = new List>() { new((token, duringEnumCacheCreation) => - { }) + { + if (duringEnumCacheCreation) + return; + + if (token["prefab"] != null && (bool)token["prefab"]) + { + Prefabs.resourcePrefabsInfosToCreate.Add((ResourceData.Type)(int)token["idx"]); + } + }) }, [typeof(SkinData)] = new List>() { diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index cae6fb9..3ca2fca 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -22,6 +22,9 @@ public static class Prefabs public static List resourceInfos = new(); + internal static Dictionary improvementPrefabInfosToCreate = new(); + internal static List resourcePrefabsInfosToCreate = new(); + [HarmonyPostfix] [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] private static void PrefabManager_Awake_Postfix(PrefabManager __instance) @@ -179,6 +182,44 @@ internal static void CreatePrefabs() Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); } + // creates dummy improvements. those have one visual part, and default name is the enum cache name of the type + foreach (KeyValuePair improvementInfo in improvementPrefabInfosToCreate) + { + ImprovementData.Type improvementType = improvementInfo.Key; + improvementInfos.Add( + new ImprovementPrefabInfo() + { + improvementType = improvementType, + visualParts = new() + { + new() + { + defaultSpriteName = EnumCache.GetName(improvementType), + levels = improvementInfo.Value, + } + } + } + ); + } + + // creates dummy resources. those have one visual part, and default name is the enum cache name of the type + foreach (ResourceData.Type resourceType in resourcePrefabsInfosToCreate) + { + resourceInfos.Add( + new ResourcePrefabInfo() + { + resourceType = resourceType, + visualParts = new() + { + new() + { + defaultSpriteName = EnumCache.GetName(resourceType), + } + } + } + ); + } + foreach (var unitPrefabInfo in unitInfos) { ProcessUnitPrefabInfo(unitPrefabInfo); diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 6f3d2cf..459b5e3 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -1,4 +1,3 @@ -using System.Reflection; using HarmonyLib; using Polytopia.Data; using UnityEngine; @@ -92,108 +91,148 @@ internal static string FormatSpriteName(string baseName) formattedName = formattedName.Replace(valuePair.Key, valuePair.Value); } cachedReversedNames[baseName] = formattedName; - return baseName; + return formattedName; } [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] - private static void SpriteAtlasManager_DoSpriteLookup(ref SpriteAtlasManager.SpriteLookupResult __result, SpriteAtlasManager __instance, - string baseName, TribeType tribe, SkinType skin, int level) + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.TrySolveSpriteNameForLevelSprites))] + private static void SpriteAtlasManager_TrySolveSpriteNameForLevelSprites( + ref bool __result, + SpriteAtlasManager __instance, + Il2CppInterop.Runtime.InteropTypes.Arrays.Il2CppStringArray spriteNameVariants, int level, ref string result) { - Sprite? sprite = Registry.GetSprite(baseName, tribe, skin, level); - if (sprite != null) - __result.sprite = sprite; + if(!__result) __result = true; // will crash original lookup if false.... + } - Sprite? outlineSprite = Registry.GetSprite(baseName + "_outline", tribe, skin, level); - if (outlineSprite != null) - __result.outlineSprite = outlineSprite; + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] + private static void SpriteAtlasManager_DoSpriteLookup( + ref SpriteAtlasManager.SpriteLookupResult __result, + SpriteAtlasManager __instance, + string baseName, TribeType tribe, SkinType skin, int level) + { + ApplyRegisteredSprites(ref __result, baseName, tribe, skin, level); string formattedName = FormatSpriteName(baseName); - sprite = Registry.GetSprite(formattedName, tribe, skin, level); - if (sprite != null) - __result.sprite = sprite; + if (formattedName != baseName) + { + ApplyRegisteredSprites(ref __result, formattedName, tribe, skin, level); + } + } + + private static void ApplyRegisteredSprites( + ref SpriteAtlasManager.SpriteLookupResult lookupResult, + string spriteName, TribeType tribe, SkinType skin, int level) + { + Sprite? registeredSprite = Registry.GetSprite(spriteName, tribe, skin, level); + if (registeredSprite != null) + lookupResult.sprite = registeredSprite; - outlineSprite = Registry.GetSprite(formattedName + "_outline", tribe, skin, level); - if (outlineSprite != null) - __result.outlineSprite = outlineSprite; + Sprite? registeredOutlineSprite = Registry.GetSprite(spriteName + "_outline", tribe, skin, level); + if (registeredOutlineSprite != null) + lookupResult.outlineSprite = registeredOutlineSprite; } [HarmonyPrefix] // its obsolete so may be removed soon by midjiwan [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[]{ typeof(string), typeof(string), typeof(SpriteCallback) })] private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) { - Sprite? spriteResult = Registry.GetSprite(sprite); - string formattedName = FormatSpriteName(sprite); - Sprite? formattedSprite = Registry.GetSprite(formattedName); - if (formattedSprite != null) - spriteResult = formattedSprite; - if (spriteResult != null) + Sprite? resolvedSprite = Registry.GetSprite(formattedName); + + if (resolvedSprite == null && formattedName != sprite) { - completion.Invoke(atlas, sprite, spriteResult); - return false; + resolvedSprite = Registry.GetSprite(sprite); } - return true; + + if (resolvedSprite == null) + { + return true; + } + + completion.Invoke(atlas, sprite, resolvedSprite); + return false; } - #endregion - #region Level + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] + private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) + { + if((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(terrain); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] + private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) + { + if((int)resource >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(resource); + } - /// Updates the terrain graphics with custom sprites. [HarmonyPostfix] - [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] // recheck that - private static void TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile) + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] + private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) { - string terrain = EnumCache.GetName(tile.data.terrain) ?? string.Empty; + if((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(improvement); + } - TribeType tribe = tile.data.climate; - SkinType skinType = tile.data.Skin; + #endregion + #region Level - string flood = ""; - if ( - tile.data.effects.Contains(TileData.EffectType.Flooded) || - (tribe == TribeType.Aquarion && tile.data.terrain == Polytopia.Data.TerrainData.Type.Mountain) - ) // TODO: Check all tribes with flooded abil instead of Aquarion only. + private static string GetLandSpriteName(TileData tileData) + { + if (!tileData.HasEffect(TileData.EffectType.Flooded)) { - foreach (var effect in tile.data.effects) - { - if(customFloodingSkins.ContainsKey(effect)) - { - skinType = customFloodingSkins[effect]; - break; - } - } - flood = "_flooded"; + return SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Field); } - if (tile.data.terrain is Polytopia.Data.TerrainData.Type.Forest or Polytopia.Data.TerrainData.Type.Mountain) - { - string propertyName = terrain.ToLower(); - terrain = "field"; - PropertyInfo? rendererProperty = tile.GetType().GetProperty(propertyName + "Renderer", - BindingFlags.Public | BindingFlags.Instance); + string wetlandSpriteName = SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Wetland); - if (rendererProperty != null) + if (tileData.HasEffect(TileData.EffectType.Swamped)) + { + return wetlandSpriteName + "_swamp"; + } + + foreach (TileData.EffectType effectType in tileData.effects) + { + if (customFloodingSkins.TryGetValue(effectType, out SkinType skinType)) { - PolytopiaSpriteRenderer? renderer = (PolytopiaSpriteRenderer?)rendererProperty.GetValue(tile); - if (renderer != null) - { - Sprite? additionalSprite = Registry.GetSprite(propertyName + flood, tribe, skinType); - if (additionalSprite != null) - { - renderer.Sprite = additionalSprite; - rendererProperty.SetValue(tile, renderer); - } - } + return $"{wetlandSpriteName}_{EnumCache.GetName(skinType)}"; } } - Sprite? sprite = Registry.GetSprite(terrain + flood, tribe, skinType); - if (sprite != null) + return wetlandSpriteName; + } + + /// Updates the terrain graphics with custom sprites. + [HarmonyPrefix] + [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] // Why prefix? I really hate repeating the logic. I would have to do the same bs 2 times.... anyway reviewers tell me ok? + private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile, TribeType climate, SkinType skin, bool shouldDesaturate) + { + + string spriteName = tile.Data.terrain switch + { + Polytopia.Data.TerrainData.Type.Water => __instance.waterSprites.GetSpriteName(tile), + Polytopia.Data.TerrainData.Type.Ocean => __instance.oceanSprites.GetSpriteName(tile), + Polytopia.Data.TerrainData.Type.Ice => __instance.iceSprites.GetSpriteName(tile), + _ => GetLandSpriteName(tile.Data), + }; + + SpriteAtlasManager.SpriteLookupResult spriteLookupResult = GameManager.GetSpriteAtlasManager().DoSpriteLookup(spriteName, climate, skin); + if (spriteLookupResult.HasSprite()) { - __instance.spriteRenderer.Sprite = sprite; + __instance.spriteRenderer.Sprite = spriteLookupResult.sprite; } + if (shouldDesaturate != __instance.isDesaturated) + { + TerrainMaterialHelper.SetSpriteSaturated(__instance.SpriteRenderer, shouldDesaturate); + __instance.isDesaturated = shouldDesaturate; + } + + return false; } /// Adds custom flood tile effect when tile is flooded for custom aqua skins. @@ -229,43 +268,13 @@ public static void GetTileTipHeader(ref string __result, TileData tileData, Skin [HarmonyPatch(typeof(PolytopiaSpriteRenderer), nameof(PolytopiaSpriteRenderer.ForceUpdateMesh))] private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRenderer __instance) { - if (__instance.sprite != null && string.IsNullOrEmpty(__instance.atlasName)) - { - MaterialPropertyBlock materialPropertyBlock = new(); - materialPropertyBlock.SetVector("_Flip", new Vector4(1f, 1f, 0f, 0f)); - materialPropertyBlock.SetTexture("_MainTex", __instance.sprite.texture); - __instance.meshRenderer.SetPropertyBlock(materialPropertyBlock); - } - } - - #endregion - #region Tribe Preview + if (__instance.sprite == null || !string.IsNullOrEmpty(__instance.atlasName)) + return; - #endregion - #region UI - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] - private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) - { - if((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) - __result = EnumCache.GetName(terrain); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] - private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) - { - if((int)resource >= Plugin.AUTOIDX_STARTS_FROM) - __result = EnumCache.GetName(resource); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] - private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) - { - if((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) - __result = EnumCache.GetName(improvement); + MaterialPropertyBlock materialPropertyBlock = new(); + materialPropertyBlock.SetVector("_Flip", new Vector4(1f, 1f, 0f, 0f)); + materialPropertyBlock.SetTexture("_MainTex", __instance.sprite.texture); + __instance.meshRenderer.SetPropertyBlock(materialPropertyBlock); } #endregion @@ -357,12 +366,12 @@ public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixel { Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); texture.LoadImage(data); - Color[] pixels = texture.GetPixels(); - for (int i = 0; i < pixels.Length; i++) - { - pixels[i] = new Color(pixels[i].r, pixels[i].g, pixels[i].b, pixels[i].a); - } - texture.SetPixels(pixels); + // Color[] pixels = texture.GetPixels(); + // for (int i = 0; i < pixels.Length; i++) + // { + // pixels[i] = new Color(pixels[i].r, pixels[i].g, pixels[i].b, pixels[i].a); + // } + // texture.SetPixels(pixels); texture.filterMode = FilterMode.Trilinear; texture.Apply(); return BuildSpriteWithTexture(texture, pivot, pixelsPerUnit); diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs index 1296396..27105a2 100644 --- a/src/Prefabs/VisualPartInfo.cs +++ b/src/Prefabs/VisualPartInfo.cs @@ -18,7 +18,7 @@ public class VisualPartInfo public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific [JsonInclude] - public Vector2 coordinates = new Vector2(); + public Vector2 coordinates = new Vector2(0, 0); [JsonInclude] public float rotation = 0f; From 28c8cd99cda81db1b7c3aef71ed82a6d3e09007f Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 22 Oct 2026 11:53:07 +0200 Subject: [PATCH 11/42] added a way to precise sprite origin in sprite info --- src/Loader.cs | 95 ++++++++++++++++++++++++++++++++++++++++++ src/Managers/Main.cs | 3 +- src/Managers/Visual.cs | 31 ++++++++------ src/Registry.cs | 2 + 4 files changed, 118 insertions(+), 13 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index c0b63b5..d8d45b3 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -599,6 +599,96 @@ public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) } } + /// + /// Loads a sprite file from a mod. + /// + /// The mod the sprite file belongs to. + /// The sprite file to load. + public static void LoadTextureFile(Mod mod, Mod.File file) + { + string name = Path.GetFileNameWithoutExtension(file.name); + Texture2D texture2D = Visual.BuildTexture(file.bytes); + Registry.textures[name] = texture2D; + } + + public static void CreateSprites() + { + foreach (var spriteInfo in Registry.spriteInfos) + { + string name = spriteInfo.Key; + + Visual.SpriteInfo spriteData = spriteInfo.Value; + + Vector2 pivotPreset = name.Split("_")[0] switch + { + "field" => new(0.5f, 0.0f), + "mountain" => new(0.5f, -0.375f), + _ => new(0.5f, 0.5f), + }; + + float pixelsPerUnitPreset = 2112f; + + Vector2 pivot = spriteData.pivot ?? pivotPreset; + float pixelsPerUnit = spriteData.pixelsPerUnit ?? pixelsPerUnitPreset; + + Sprite? sprite = null; + + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + + if (spriteData.spriteOrigin != null && spriteData.spriteOrigin.originType == Visual.OriginType.Inner) + { + Sprite originalSprite = spriteAtlasManager.DoSpriteLookup(spriteData.spriteOrigin.name, TribeType.None, SkinType.Default).sprite; + + if (originalSprite != null) + { + bool hasPivotOverride = spriteData.pivot != null; + bool hasPixelsPerUnitOverride = spriteData.pixelsPerUnit != null; + + if (hasPivotOverride || hasPixelsPerUnitOverride) + { + Rect originalTextureRectangle = originalSprite.textureRect; + + Vector2 normalizedOriginalPivot = new( + originalSprite.pivot.x / originalTextureRectangle.width, + originalSprite.pivot.y / originalTextureRectangle.height + ); + + Vector2 finalPivot = hasPivotOverride ? spriteData.pivot!.Value : normalizedOriginalPivot; + float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteData.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; + + sprite = Sprite.Create( + originalSprite.texture, + originalTextureRectangle, + finalPivot, + finalPixelsPerUnit, + 0, + SpriteMeshType.FullRect, + originalSprite.border + ); + sprite.name = name; + } + else + { + sprite = originalSprite; + } + } + } + else + { + if(Registry.textures.TryGetValue(name, out Texture2D? texture2D)) + sprite = Visual.BuildSpriteWithTexture(texture2D, pivot, pixelsPerUnit); + } + + if(sprite != null) + { + spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); + spriteAtlasManager.cachedSprites["Heads"][name] = sprite; + + Registry.sprites[name] = sprite; + } + } + } + /// /// Loads a sprite file from a mod. /// @@ -613,16 +703,21 @@ public static void LoadSpriteFile(Mod mod, Mod.File file) "mountain" => new(0.5f, -0.375f), _ => new(0.5f, 0.5f), }; + float pixelsPerUnit = 2112f; + if (Registry.spriteInfos.ContainsKey(name)) { Visual.SpriteInfo spriteData = Registry.spriteInfos[name]; pivot = spriteData.pivot ?? pivot; pixelsPerUnit = spriteData.pixelsPerUnit ?? pixelsPerUnit; } + Sprite sprite = Visual.BuildSprite(file.bytes, pivot, pixelsPerUnit); + GameManager.GetSpriteAtlasManager().cachedSprites.TryAdd("Heads", new()); GameManager.GetSpriteAtlasManager().cachedSprites["Heads"][name] = sprite; + Registry.sprites[name] = sprite; } diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 2ce6f4c..c0ebde1 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -464,7 +464,7 @@ internal static void Load(GameLogicData gameLogicData, JObject json) switch (Path.GetExtension(file.name)) { case ".png": - Loader.LoadSpriteFile(mod, file); + Loader.LoadTextureFile(mod, file); break; case ".wav": Loader.LoadAudioFile(mod, file); @@ -481,6 +481,7 @@ internal static void Load(GameLogicData gameLogicData, JObject json) TechItem.techTierFirebaseId.Add($"tech_research_{i}"); } Loader.ProcessGameLogicData(gameLogicData, json); + Loader.CreateSprites(); Loader.ProcessFilesQueue(); Prefabs.CreatePrefabs(); stopwatch.Stop(); diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 459b5e3..2c6b5a9 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -13,7 +13,15 @@ namespace PolyMod.Managers; public static class Visual { /// Represents information about a sprite, such as its pivot and pixels per unit. - public record SpriteInfo(float? pixelsPerUnit, Vector2? pivot); + public record SpriteInfo(float? pixelsPerUnit, Vector2? pivot, SpriteOrigin? spriteOrigin = null); + + public record SpriteOrigin(string name, OriginType originType); + + public enum OriginType + { + Outer, // Outer means sprite comes from a mod, and not from game's files + Inner // Inner means sprite is to be fetched from game's files + } /// Represents information about a custom skin. public record SkinInfo(int idx, string id, SkinData? skinData); @@ -357,6 +365,15 @@ internal static BasicPopupLegacy GetBasicPopupLegacy() return basicPopupLegacy; } + public static Texture2D BuildTexture(byte[] data) + { + Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); + texture.LoadImage(data); + texture.filterMode = FilterMode.Trilinear; + texture.Apply(); + return texture; + } + /// Builds a sprite from raw byte data. /// The raw byte data of the image. /// The pivot point of the sprite. @@ -364,17 +381,7 @@ internal static BasicPopupLegacy GetBasicPopupLegacy() /// The created sprite. public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f) { - Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); - texture.LoadImage(data); - // Color[] pixels = texture.GetPixels(); - // for (int i = 0; i < pixels.Length; i++) - // { - // pixels[i] = new Color(pixels[i].r, pixels[i].g, pixels[i].b, pixels[i].a); - // } - // texture.SetPixels(pixels); - texture.filterMode = FilterMode.Trilinear; - texture.Apply(); - return BuildSpriteWithTexture(texture, pivot, pixelsPerUnit); + return BuildSpriteWithTexture(BuildTexture(data), pivot, pixelsPerUnit); } /// Builds a sprite from a texture. diff --git a/src/Registry.cs b/src/Registry.cs index 9ac5c49..29f7348 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -21,6 +21,8 @@ public static class Registry /// public static Dictionary sprites = new(); + public static Dictionary textures = new(); + /// /// A dictionary of all loaded audio clips, keyed by their name. /// From 1a4d6d658b63338c03cc784b4c4eec7596361be3 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 22 Oct 2026 13:07:16 +0200 Subject: [PATCH 12/42] fix --- src/Loader.cs | 36 ++++++++++++++++++++++++++++++------ src/Managers/Main.cs | 2 +- src/Registry.cs | 2 +- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index d8d45b3..dcbf1b6 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -408,7 +408,6 @@ internal static void LoadMods(Dictionary mods, out bool dependencyC } } Compatibility.HashSignatures(checksumString); - } private static void CheckDependencies(Dictionary mods) { @@ -608,11 +607,13 @@ public static void LoadTextureFile(Mod mod, Mod.File file) { string name = Path.GetFileNameWithoutExtension(file.name); Texture2D texture2D = Visual.BuildTexture(file.bytes); - Registry.textures[name] = texture2D; + Registry.textures[name] = new KeyValuePair(texture2D, false); } public static void CreateSprites() { + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + foreach (var spriteInfo in Registry.spriteInfos) { string name = spriteInfo.Key; @@ -633,8 +634,6 @@ public static void CreateSprites() Sprite? sprite = null; - SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); - if (spriteData.spriteOrigin != null && spriteData.spriteOrigin.originType == Visual.OriginType.Inner) { Sprite originalSprite = spriteAtlasManager.DoSpriteLookup(spriteData.spriteOrigin.name, TribeType.None, SkinType.Default).sprite; @@ -675,8 +674,11 @@ public static void CreateSprites() } else { - if(Registry.textures.TryGetValue(name, out Texture2D? texture2D)) - sprite = Visual.BuildSpriteWithTexture(texture2D, pivot, pixelsPerUnit); + if(Registry.textures.TryGetValue(name, out KeyValuePair textureKeyValue)) + { + sprite = Visual.BuildSpriteWithTexture(textureKeyValue.Key, pivot, pixelsPerUnit); + Registry.textures[name] = new KeyValuePair(textureKeyValue.Key, true); + } } if(sprite != null) @@ -687,6 +689,28 @@ public static void CreateSprites() Registry.sprites[name] = sprite; } } + + foreach (var texturePair in Registry.textures) + { + if(!texturePair.Value.Value) + { + string name = texturePair.Key; + + Vector2 pivot = name.Split("_")[0] switch + { + "field" => new(0.5f, 0.0f), + "mountain" => new(0.5f, -0.375f), + _ => new(0.5f, 0.5f), + }; + + float pixelsPerUnit = 2112f; + + Sprite? sprite = Visual.BuildSpriteWithTexture(texturePair.Value.Key, pivot, pixelsPerUnit); + spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); + spriteAtlasManager.cachedSprites["Heads"][name] = sprite; + Registry.sprites[name] = sprite; + } + } } /// diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index c0ebde1..bebc1d3 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -481,8 +481,8 @@ internal static void Load(GameLogicData gameLogicData, JObject json) TechItem.techTierFirebaseId.Add($"tech_research_{i}"); } Loader.ProcessGameLogicData(gameLogicData, json); - Loader.CreateSprites(); Loader.ProcessFilesQueue(); + Loader.CreateSprites(); Prefabs.CreatePrefabs(); stopwatch.Stop(); Plugin.logger.LogInfo($"Loaded all mods in {stopwatch.ElapsedMilliseconds}ms"); diff --git a/src/Registry.cs b/src/Registry.cs index 29f7348..3943b5d 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -21,7 +21,7 @@ public static class Registry /// public static Dictionary sprites = new(); - public static Dictionary textures = new(); + public static Dictionary> textures = new(); // string = texture name, bool, whether texture was processed or not. reviwers, pls tell me how to improve /// /// A dictionary of all loaded audio clips, keyed by their name. From 0cda9a6d0c0ccbfdff06932a9c1ea1e6f9f2a227 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 22 Oct 2026 14:21:35 +0200 Subject: [PATCH 13/42] added sprite origin to sprite info, refactor --- src/Loader.cs | 154 ----------------------------- src/Managers/Hub.cs | 116 ++++++---------------- src/Managers/Main.cs | 2 +- src/Managers/Visual.cs | 214 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 245 insertions(+), 241 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index dcbf1b6..419e3bf 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -610,160 +610,6 @@ public static void LoadTextureFile(Mod mod, Mod.File file) Registry.textures[name] = new KeyValuePair(texture2D, false); } - public static void CreateSprites() - { - SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); - - foreach (var spriteInfo in Registry.spriteInfos) - { - string name = spriteInfo.Key; - - Visual.SpriteInfo spriteData = spriteInfo.Value; - - Vector2 pivotPreset = name.Split("_")[0] switch - { - "field" => new(0.5f, 0.0f), - "mountain" => new(0.5f, -0.375f), - _ => new(0.5f, 0.5f), - }; - - float pixelsPerUnitPreset = 2112f; - - Vector2 pivot = spriteData.pivot ?? pivotPreset; - float pixelsPerUnit = spriteData.pixelsPerUnit ?? pixelsPerUnitPreset; - - Sprite? sprite = null; - - if (spriteData.spriteOrigin != null && spriteData.spriteOrigin.originType == Visual.OriginType.Inner) - { - Sprite originalSprite = spriteAtlasManager.DoSpriteLookup(spriteData.spriteOrigin.name, TribeType.None, SkinType.Default).sprite; - - if (originalSprite != null) - { - bool hasPivotOverride = spriteData.pivot != null; - bool hasPixelsPerUnitOverride = spriteData.pixelsPerUnit != null; - - if (hasPivotOverride || hasPixelsPerUnitOverride) - { - Rect originalTextureRectangle = originalSprite.textureRect; - - Vector2 normalizedOriginalPivot = new( - originalSprite.pivot.x / originalTextureRectangle.width, - originalSprite.pivot.y / originalTextureRectangle.height - ); - - Vector2 finalPivot = hasPivotOverride ? spriteData.pivot!.Value : normalizedOriginalPivot; - float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteData.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; - - sprite = Sprite.Create( - originalSprite.texture, - originalTextureRectangle, - finalPivot, - finalPixelsPerUnit, - 0, - SpriteMeshType.FullRect, - originalSprite.border - ); - sprite.name = name; - } - else - { - sprite = originalSprite; - } - } - } - else - { - if(Registry.textures.TryGetValue(name, out KeyValuePair textureKeyValue)) - { - sprite = Visual.BuildSpriteWithTexture(textureKeyValue.Key, pivot, pixelsPerUnit); - Registry.textures[name] = new KeyValuePair(textureKeyValue.Key, true); - } - } - - if(sprite != null) - { - spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); - spriteAtlasManager.cachedSprites["Heads"][name] = sprite; - - Registry.sprites[name] = sprite; - } - } - - foreach (var texturePair in Registry.textures) - { - if(!texturePair.Value.Value) - { - string name = texturePair.Key; - - Vector2 pivot = name.Split("_")[0] switch - { - "field" => new(0.5f, 0.0f), - "mountain" => new(0.5f, -0.375f), - _ => new(0.5f, 0.5f), - }; - - float pixelsPerUnit = 2112f; - - Sprite? sprite = Visual.BuildSpriteWithTexture(texturePair.Value.Key, pivot, pixelsPerUnit); - spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); - spriteAtlasManager.cachedSprites["Heads"][name] = sprite; - Registry.sprites[name] = sprite; - } - } - } - - /// - /// Loads a sprite file from a mod. - /// - /// The mod the sprite file belongs to. - /// The sprite file to load. - public static void LoadSpriteFile(Mod mod, Mod.File file) - { - string name = Path.GetFileNameWithoutExtension(file.name); - Vector2 pivot = name.Split("_")[0] switch - { - "field" => new(0.5f, 0.0f), - "mountain" => new(0.5f, -0.375f), - _ => new(0.5f, 0.5f), - }; - - float pixelsPerUnit = 2112f; - - if (Registry.spriteInfos.ContainsKey(name)) - { - Visual.SpriteInfo spriteData = Registry.spriteInfos[name]; - pivot = spriteData.pivot ?? pivot; - pixelsPerUnit = spriteData.pixelsPerUnit ?? pixelsPerUnit; - } - - Sprite sprite = Visual.BuildSprite(file.bytes, pivot, pixelsPerUnit); - - GameManager.GetSpriteAtlasManager().cachedSprites.TryAdd("Heads", new()); - GameManager.GetSpriteAtlasManager().cachedSprites["Heads"][name] = sprite; - - Registry.sprites[name] = sprite; - } - - /// - /// Updates a sprite with new information. - /// - /// The name of the sprite to update. - public static void UpdateSprite(string name) - { - if (Registry.spriteInfos.ContainsKey(name) && Registry.sprites.ContainsKey(name)) - { - Visual.SpriteInfo spriteData = Registry.spriteInfos[name]; - Sprite sprite = Visual.BuildSpriteWithTexture( - Registry.sprites[name].texture, - spriteData.pivot, - spriteData.pixelsPerUnit - ); - GameManager.GetSpriteAtlasManager().cachedSprites["Heads"][name] = sprite; - Registry.sprites[name] = sprite; - } - } - /// /// Loads a sprite info file from a mod. /// diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 551c527..22ab356 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -145,35 +145,36 @@ private static void GameManager_Update() /// /// Updates sprite information from dumped files. /// - internal static void UpdateSpriteInfos() + internal static void HotReload() { - string message = string.Empty; - Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); - - foreach (var file in Directory.GetFiles(Plugin.DUMPED_DATA_PATH)) - { - string? name = Path.GetFileNameWithoutExtension(file); - List subnames = new(); - if (name.Contains("sprites_")) - { - subnames = name.Split('_').ToList(); - Mod.File spriteInfo = new(Path.GetFileNameWithoutExtension(file), File.ReadAllBytes(file)); - Dictionary? deserialized = Loader.LoadSpriteInfoFile(Registry.mods[subnames[1]], spriteInfo); - if (deserialized != null) - { - foreach (var kvp in deserialized) - { - Loader.UpdateSprite(kvp.Key); - } - message += Localization.Get("polymod.hotreload.success", new Il2CppSystem.Object[] { subnames[1] }); - } - } - } - if (message == string.Empty) - { - message = Localization.Get("polymod.hotreload.failure"); - } - NotificationManager.Notify(message); + NotificationManager.Notify("FAILED: wip"); + // string message = string.Empty; + // Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); + + // foreach (var file in Directory.GetFiles(Plugin.DUMPED_DATA_PATH)) + // { + // string? name = Path.GetFileNameWithoutExtension(file); + // List subnames = new(); + // if (name.Contains("sprites_")) + // { + // subnames = name.Split('_').ToList(); + // Mod.File spriteInfo = new(Path.GetFileNameWithoutExtension(file), File.ReadAllBytes(file)); + // Dictionary? deserialized = Loader.LoadSpriteInfoFile(Registry.mods[subnames[1]], spriteInfo); + // if (deserialized != null) + // { + // foreach (var kvp in deserialized) + // { + // Loader.UpdateSprite(kvp.Key); + // } + // message += Localization.Get("polymod.hotreload.success", new Il2CppSystem.Object[] { subnames[1] }); + // } + // } + // } + // if (message == string.Empty) + // { + // message = Localization.Get("polymod.hotreload.failure"); + // } + // NotificationManager.Notify(message); } /// @@ -269,7 +270,7 @@ private static void DumpSprites() Sprite sprite = spriteAtlasManager.GetSprite(spriteName, atlasName); if (sprite == null) continue; - (byte[] bytes, Visual.SpriteInfo spriteInfo) = SpriteToPng(sprite); + (byte[] bytes, Visual.SpriteInfo spriteInfo) = Visual.SpriteToPng(sprite); File.WriteAllBytesAsync(Path.Combine(dir, spriteName + ".png"), bytes); atlasSpriteInfo.Add(spriteName, spriteInfo); } @@ -280,59 +281,6 @@ private static void DumpSprites() } } - private static (byte[], Visual.SpriteInfo) SpriteToPng(Sprite sprite) - { - Texture2D atlasTexture = sprite.texture; - int spriteWidth = (int)sprite.rect.width; - int spriteHeight = (int)sprite.rect.height; - float pixelsPerUnit = sprite.pixelsPerUnit; - Vector2 spritePivot = sprite.pivot; - - var meshVertices = sprite.vertices; - var meshUvs = sprite.uv; - var meshTriangles = sprite.triangles; - - RenderTexture renderTexture = RenderTexture.GetTemporary( - spriteWidth, spriteHeight, 0, - RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); - RenderTexture previousActiveRenderTexture = RenderTexture.active; - RenderTexture.active = renderTexture; - GL.Clear(true, true, Color.clear); - - var spriteMaterial = new Material(Shader.Find("Sprites/Default")); - spriteMaterial.mainTexture = atlasTexture; - spriteMaterial.SetPass(0); - - GL.PushMatrix(); - GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); - GL.Begin(GL.TRIANGLES); - for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) - { - int vertexIndex = meshTriangles[triangleCornerIndex]; - Vector2 uv = meshUvs[vertexIndex]; - Vector2 vertex = meshVertices[vertexIndex]; - - GL.TexCoord(new Vector3(uv.x, uv.y, 0)); - GL.Vertex3(vertex.x * pixelsPerUnit + spritePivot.x, - vertex.y * pixelsPerUnit + spritePivot.y, 0); - } - GL.End(); - GL.PopMatrix(); - - var croppedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); - croppedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); - croppedTexture.Apply(); - - RenderTexture.active = previousActiveRenderTexture; - RenderTexture.ReleaseTemporary(renderTexture); - - byte[] pngBytes = ImageConversion.EncodeToPNG(croppedTexture); - UnityEngine.Object.Destroy(croppedTexture); - UnityEngine.Object.Destroy(spriteMaterial); - UnityEngine.Object.Destroy(sprite); - return (pngBytes, new Visual.SpriteInfo(pixelsPerUnit, spritePivot)); - } - internal static void DumpTribePreviewLegacy() { // TODO legacy tribe preview dump. i have to update that @@ -528,7 +476,7 @@ void OpenDiscord() )); popupButtons.Add(new( "polymod.hub.hotreload", - callback: DelegateSupport.ConvertDelegate(UpdateSpriteInfos), + callback: DelegateSupport.ConvertDelegate(HotReload), closesPopup: false )); } @@ -577,7 +525,7 @@ void OnDebugButtonClicked() void OnUpdateSpritesButtonClicked() { - UpdateSpriteInfos(); + HotReload(); isConfigPopupActive = false; } diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index bebc1d3..188544b 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -482,7 +482,7 @@ internal static void Load(GameLogicData gameLogicData, JObject json) } Loader.ProcessGameLogicData(gameLogicData, json); Loader.ProcessFilesQueue(); - Loader.CreateSprites(); + Visual.CreateSprites(); Prefabs.CreatePrefabs(); stopwatch.Stop(); Plugin.logger.LogInfo($"Loaded all mods in {stopwatch.ElapsedMilliseconds}ms"); diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 2c6b5a9..5d739ac 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -4,6 +4,8 @@ using Il2CppSystem.Linq; using PolytopiaBackendBase.Common; using Il2CppInterop.Runtime; +using System.Text.Json.Serialization; +using PolyMod.Json; namespace PolyMod.Managers; @@ -13,9 +15,34 @@ namespace PolyMod.Managers; public static class Visual { /// Represents information about a sprite, such as its pivot and pixels per unit. - public record SpriteInfo(float? pixelsPerUnit, Vector2? pivot, SpriteOrigin? spriteOrigin = null); + public class SpriteInfo + { + [JsonInclude] + public float? pixelsPerUnit; + + [JsonInclude] + public Vector2? pivot; + + [JsonInclude] + public SpriteOrigin? spriteOrigin = null; + + public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, SpriteOrigin? spriteOrigin = null) + { + this.pixelsPerUnit = pixelsPerUnit; + this.pivot = pivot; + this.spriteOrigin = spriteOrigin; + } + } - public record SpriteOrigin(string name, OriginType originType); + public class SpriteOrigin + { + [JsonInclude] + public string? name; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public OriginType originType = OriginType.Outer; + } public enum OriginType { @@ -311,6 +338,13 @@ private static void PopupBase_Hide(PopupBase __instance) basicPopupWidths.Remove(__instance.GetInstanceID()); } + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] + private static void StartScreen_UI2_OnShow() + { + CreateInnerOriginSprites(); + } + [HarmonyPrefix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] private static bool StartScreen_OnWeeklyChallengeClicked(StartScreen_UI2 __instance) @@ -399,6 +433,182 @@ public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = ); } + internal static List> pendingInnerOriginSpriteInfos = new(); + + private static Vector2 GetPivotPreset(string spriteName) + { + return spriteName.Split("_")[0] switch + { + "field" => new Vector2(0.5f, 0.0f), + "mountain" => new Vector2(0.5f, -0.375f), + _ => new Vector2(0.5f, 0.5f), + }; + } + + internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, string spriteName, Sprite sprite) + { + spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); + spriteAtlasManager.cachedSprites["Heads"][spriteName] = sprite; + Registry.sprites[spriteName] = sprite; + } + + // Runs early: only touches your own textures, nothing from SpriteAtlasManager's lookup state. + public static void CreateSprites() + { + pendingInnerOriginSpriteInfos.Clear(); + + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + const float defaultPixelsPerUnit = 2112f; + + foreach (KeyValuePair spriteInfoPair in Registry.spriteInfos) + { + string spriteName = spriteInfoPair.Key; + Visual.SpriteInfo spriteData = spriteInfoPair.Value; + + bool isInnerOrigin = spriteData.spriteOrigin != null + && spriteData.spriteOrigin.originType == Visual.OriginType.Inner; + + if (isInnerOrigin) + { + pendingInnerOriginSpriteInfos.Add(spriteInfoPair); + continue; + } + + if (!Registry.textures.TryGetValue(spriteName, out KeyValuePair textureEntry)) + { + continue; + } + + Vector2 pivot = spriteData.pivot ?? GetPivotPreset(spriteName); + float pixelsPerUnit = spriteData.pixelsPerUnit ?? defaultPixelsPerUnit; + + Sprite sprite = Visual.BuildSpriteWithTexture(textureEntry.Key, pivot, pixelsPerUnit); + Registry.textures[spriteName] = new KeyValuePair(textureEntry.Key, true); + RegisterSprite(spriteAtlasManager, spriteName, sprite); + } + + foreach (KeyValuePair> texturePair in Registry.textures) + { + if (texturePair.Value.Value) + { + continue; + } + + string spriteName = texturePair.Key; + Sprite sprite = Visual.BuildSpriteWithTexture(texturePair.Value.Key, GetPivotPreset(spriteName), defaultPixelsPerUnit); + RegisterSprite(spriteAtlasManager, spriteName, sprite); + } + } + + internal static (byte[], Visual.SpriteInfo) SpriteToPng(Sprite sprite) + { + Texture2D bakedTexture = BakeSpriteToTexture(sprite); + + byte[] pngBytes = ImageConversion.EncodeToPNG(bakedTexture); + UnityEngine.Object.Destroy(bakedTexture); + + return (pngBytes, new Visual.SpriteInfo(sprite.pixelsPerUnit, sprite.pivot)); + } + + private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) + { + Texture2D atlasTexture = sourceSprite.texture; + int spriteWidth = (int)sourceSprite.rect.width; + int spriteHeight = (int)sourceSprite.rect.height; + float sourcePixelsPerUnit = sourceSprite.pixelsPerUnit; + Vector2 sourcePivotInPixels = sourceSprite.pivot; + + var meshVertices = sourceSprite.vertices; + var meshUvs = sourceSprite.uv; + var meshTriangles = sourceSprite.triangles; + + RenderTexture renderTexture = RenderTexture.GetTemporary( + spriteWidth, spriteHeight, 0, + RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); + RenderTexture previousActiveRenderTexture = RenderTexture.active; + RenderTexture.active = renderTexture; + GL.Clear(true, true, Color.clear); + + Material spriteMaterial = new Material(Shader.Find("Sprites/Default")); + spriteMaterial.mainTexture = atlasTexture; + spriteMaterial.SetPass(0); + + GL.PushMatrix(); + GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); + GL.Begin(GL.TRIANGLES); + for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) + { + int vertexIndex = meshTriangles[triangleCornerIndex]; + Vector2 uv = meshUvs[vertexIndex]; + Vector2 vertex = meshVertices[vertexIndex]; + + GL.TexCoord(new Vector3(uv.x, uv.y, 0)); + GL.Vertex3( + vertex.x * sourcePixelsPerUnit + sourcePivotInPixels.x, + vertex.y * sourcePixelsPerUnit + sourcePivotInPixels.y, + 0); + } + GL.End(); + GL.PopMatrix(); + + Texture2D bakedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); + bakedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); + bakedTexture.Apply(); + bakedTexture.wrapMode = TextureWrapMode.Clamp; + + RenderTexture.active = previousActiveRenderTexture; + RenderTexture.ReleaseTemporary(renderTexture); + UnityEngine.Object.Destroy(spriteMaterial); + + return bakedTexture; + } + + public static void CreateInnerOriginSprites() + { + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + + foreach (KeyValuePair spriteInfoPair in pendingInnerOriginSpriteInfos) + { + Console.Write(spriteInfoPair.Key); + string spriteName = spriteInfoPair.Key; + SpriteInfo spriteData = spriteInfoPair.Value; + + Sprite originalSprite = spriteAtlasManager + .DoSpriteLookup(spriteData.spriteOrigin!.name, TribeType.None, SkinType.Default) + .sprite; + + if (originalSprite == null) + { + Plugin.logger.LogWarning($"Inner origin sprite '{spriteData.spriteOrigin.name}' not found for '{spriteName}'"); + continue; + } + + bool hasPivotOverride = spriteData.pivot != null; + bool hasPixelsPerUnitOverride = spriteData.pixelsPerUnit != null; + + Sprite sprite = originalSprite; + + if (hasPivotOverride || hasPixelsPerUnitOverride) + { + Vector2 normalizedOriginalPivot = new( + originalSprite.pivot.x / originalSprite.rect.width, + originalSprite.pivot.y / originalSprite.rect.height + ); + + Vector2 finalPivot = hasPivotOverride ? spriteData.pivot!.Value : normalizedOriginalPivot; + float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteData.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; + + Texture2D bakedTexture = BakeSpriteToTexture(originalSprite); + sprite = BuildSpriteWithTexture(bakedTexture, finalPivot, finalPixelsPerUnit); + sprite.name = spriteName; + } + + RegisterSprite(spriteAtlasManager, spriteName, sprite); + } + + pendingInnerOriginSpriteInfos.Clear(); + } + /// Initializes the Visual manager by patching the necessary methods. internal static void Init() { From 248f4d0d54932f04f48a011bd949c716e2bfce8a Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 22 Oct 2026 15:46:57 +0200 Subject: [PATCH 14/42] fixed outer sprites origins not being fetched at all --- src/Managers/Prefabs.cs | 8 ++++---- src/Managers/Visual.cs | 25 ++++++++++++++++--------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index 3ca2fca..343aa8c 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -15,6 +15,7 @@ public static class Prefabs internal static Material? cachedUnitMaterial; internal static Material? cachedSharedMaterial; + internal const string CACHED_SHARED_MATERIAL_NAME = "SpriteMaterial"; public static List unitInfos = new(); @@ -173,13 +174,14 @@ internal static void CreatePrefabs() Material[] allLoadedMaterials = Resources.FindObjectsOfTypeAll(); foreach (Material loadedMaterial in allLoadedMaterials) { - if(loadedMaterial.name == "SpriteMaterial") + // Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); + + if(loadedMaterial.name == CACHED_SHARED_MATERIAL_NAME) { cachedSharedMaterial = loadedMaterial; GameObject.DontDestroyOnLoad(cachedSharedMaterial); break; } - Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); } // creates dummy improvements. those have one visual part, and default name is the enum cache name of the type @@ -304,7 +306,6 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) nextOutlineSortingOrder++; } nextPartSortingOrder++; - Console.Write($"{visualPartInfos.Count} New orders {nextPartSortingOrder} {nextOutlineSortingOrder}"); } return parts; @@ -512,7 +513,6 @@ internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefab nextOutlineSortingOrder++; } nextPartSortingOrder++; - Console.Write($"{visualPartInfos.Count} New orders {nextPartSortingOrder} {nextOutlineSortingOrder}"); } return parts; diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 5d739ac..c4ebd69 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -460,13 +460,13 @@ public static void CreateSprites() SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); const float defaultPixelsPerUnit = 2112f; - foreach (KeyValuePair spriteInfoPair in Registry.spriteInfos) + foreach (KeyValuePair spriteInfoPair in Registry.spriteInfos) { string spriteName = spriteInfoPair.Key; - Visual.SpriteInfo spriteData = spriteInfoPair.Value; + SpriteInfo spriteInfo = spriteInfoPair.Value; - bool isInnerOrigin = spriteData.spriteOrigin != null - && spriteData.spriteOrigin.originType == Visual.OriginType.Inner; + bool isInnerOrigin = spriteInfo.spriteOrigin != null + && spriteInfo.spriteOrigin.originType == OriginType.Inner; if (isInnerOrigin) { @@ -474,13 +474,21 @@ public static void CreateSprites() continue; } - if (!Registry.textures.TryGetValue(spriteName, out KeyValuePair textureEntry)) + KeyValuePair textureEntry; + if (!Registry.textures.TryGetValue(spriteName, out textureEntry)) // search texture { - continue; + if (spriteInfo.spriteOrigin == null || + spriteInfo.spriteOrigin.originType != OriginType.Outer || + spriteInfo.spriteOrigin.name == null || + !Registry.textures.TryGetValue(spriteInfo.spriteOrigin.name, out textureEntry)) // search texture in outer sprite origin + { + continue; + } } - Vector2 pivot = spriteData.pivot ?? GetPivotPreset(spriteName); - float pixelsPerUnit = spriteData.pixelsPerUnit ?? defaultPixelsPerUnit; + + Vector2 pivot = spriteInfo.pivot ?? GetPivotPreset(spriteName); + float pixelsPerUnit = spriteInfo.pixelsPerUnit ?? defaultPixelsPerUnit; Sprite sprite = Visual.BuildSpriteWithTexture(textureEntry.Key, pivot, pixelsPerUnit); Registry.textures[spriteName] = new KeyValuePair(textureEntry.Key, true); @@ -569,7 +577,6 @@ public static void CreateInnerOriginSprites() foreach (KeyValuePair spriteInfoPair in pendingInnerOriginSpriteInfos) { - Console.Write(spriteInfoPair.Key); string spriteName = spriteInfoPair.Key; SpriteInfo spriteData = spriteInfoPair.Value; From 754fb7226873d6a35f8e8cea6a8b602ab527cbdf Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sun, 25 Oct 2026 19:28:27 +0100 Subject: [PATCH 15/42] added auto outline creation (just fills sprite with white) and gaussian blur options to sprite info. --- src/Managers/Visual.cs | 228 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 210 insertions(+), 18 deletions(-) diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index c4ebd69..9208583 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -26,11 +26,19 @@ public class SpriteInfo [JsonInclude] public SpriteOrigin? spriteOrigin = null; - public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, SpriteOrigin? spriteOrigin = null) + [JsonInclude] + public bool transformToOutline = false; + + [JsonInclude] + public float? gaussianBlurRadius = null; + + public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, bool transformToOutline = false, SpriteOrigin? spriteOrigin = null, float? gaussianBlurRadius = null) { this.pixelsPerUnit = pixelsPerUnit; this.pivot = pivot; this.spriteOrigin = spriteOrigin; + this.transformToOutline = transformToOutline; + this.gaussianBlurRadius = gaussianBlurRadius; } } @@ -413,9 +421,9 @@ public static Texture2D BuildTexture(byte[] data) /// The pivot point of the sprite. /// The number of pixels per unit for the sprite. /// The created sprite. - public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f) + public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) { - return BuildSpriteWithTexture(BuildTexture(data), pivot, pixelsPerUnit); + return BuildSpriteWithTexture(BuildTexture(data), pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); } /// Builds a sprite from a texture. @@ -423,17 +431,184 @@ public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixel /// The pivot point of the sprite. /// The number of pixels per unit for the sprite. /// The created sprite. - public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f) + public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) { + if(transformToOutline) texture = TransformToOutline(texture); + + if(gaussianBlurRadius != null) texture = ApplyGaussianBlur(texture, gaussianBlurRadius.Value); + return Sprite.Create( texture, new(0, 0, texture.width, texture.height), pivot ?? new(0.5f, 0.5f), pixelsPerUnit ?? 2112f - ); + );; + } + + public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSizeInPixels = 8, Color? color = null) + { + Plugin.logger.LogInfo("Transforming texture to outline..."); + if(color == null) + color = Color.white; + + int sourceWidthInPixels = sourceTexture.width; + int sourceHeightInPixels = sourceTexture.height; + int outputWidthInPixels = sourceWidthInPixels + borderSizeInPixels * 2; + int outputHeightInPixels = sourceHeightInPixels + borderSizeInPixels * 2; + + Color[] sourcePixels = sourceTexture.GetPixels(); + bool[] filledMask = new bool[outputWidthInPixels * outputHeightInPixels]; + int borderSquared = borderSizeInPixels * borderSizeInPixels; + + for (int pixelY = 0; pixelY < sourceHeightInPixels; pixelY++) + { + for (int pixelX = 0; pixelX < sourceWidthInPixels; pixelX++) + { + if (sourcePixels[pixelY * sourceWidthInPixels + pixelX].a <= 0.01f) continue; + + int centerX = pixelX + borderSizeInPixels; + int centerY = pixelY + borderSizeInPixels; + + for (int offsetY = -borderSizeInPixels; offsetY <= borderSizeInPixels; offsetY++) + { + for (int offsetX = -borderSizeInPixels; offsetX <= borderSizeInPixels; offsetX++) + { + if (offsetX * offsetX + offsetY * offsetY > borderSquared) continue; + + filledMask[(centerY + offsetY) * outputWidthInPixels + (centerX + offsetX)] = true; + } + } + } + } + + Color[] outputPixels = new Color[filledMask.Length]; + for (int pixelIndex = 0; pixelIndex < outputPixels.Length; pixelIndex++) + { + outputPixels[pixelIndex] = filledMask[pixelIndex] ? color.Value : Color.clear; + } + + Texture2D whiteSilhouetteTexture = new Texture2D(outputWidthInPixels, outputHeightInPixels, TextureFormat.RGBA32, false); + whiteSilhouetteTexture.SetPixels(outputPixels); + whiteSilhouetteTexture.Apply(); + return whiteSilhouetteTexture; + } + + private static float[] BuildGaussianKernelWeights(float sigma, int kernelRadiusInPixels) + { + float[] kernelWeights = new float[kernelRadiusInPixels * 2 + 1]; + float kernelWeightSum = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int distanceFromCenter = kernelIndex - kernelRadiusInPixels; + kernelWeights[kernelIndex] = MathF.Exp(-(distanceFromCenter * distanceFromCenter) / (2f * sigma * sigma)); + kernelWeightSum += kernelWeights[kernelIndex]; + } + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + kernelWeights[kernelIndex] /= kernelWeightSum; + } + return kernelWeights; + } + + private static byte ConvertUnitFloatToByte(float unitValue) + { + return (byte)Math.Clamp(unitValue * 255f + 0.5f, 0f, 255f); + } + + // basically ai generated as my bs was working, but 15 times slower + public static Texture2D ApplyGaussianBlur(Texture2D sourceTexture, float radius = 2f) + { + Plugin.logger.LogInfo($"Applying blur with radius {radius}..."); + int textureWidthInPixels = sourceTexture.width; + int textureHeightInPixels = sourceTexture.height; + + float sigma = Math.Max(radius / 2f, 0.01f); + int kernelRadiusInPixels = Math.Max(1, (int)MathF.Ceiling(sigma * 3f)); + float[] kernelWeights = BuildGaussianKernelWeights(sigma, kernelRadiusInPixels); + + Color32[] sourcePixels = sourceTexture.GetPixels32(); + int totalPixelCount = sourcePixels.Length; + const float byteToUnitFloat = 1f / 255f; + + float[] premultipliedChannels = new float[totalPixelCount * 4]; + for (int pixelIndex = 0; pixelIndex < totalPixelCount; pixelIndex++) + { + Color32 sourcePixel = sourcePixels[pixelIndex]; + float alpha = sourcePixel.a * byteToUnitFloat; + int channelOffset = pixelIndex * 4; + premultipliedChannels[channelOffset + 0] = sourcePixel.r * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 1] = sourcePixel.g * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 2] = sourcePixel.b * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 3] = alpha; + } + + float[] horizontallyBlurredChannels = new float[premultipliedChannels.Length]; + Parallel.For(0, textureHeightInPixels, pixelY => + { + int rowStartPixelIndex = pixelY * textureWidthInPixels; + for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) + { + float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int sampleX = pixelX + kernelIndex - kernelRadiusInPixels; + if (sampleX < 0) sampleX = 0; + else if (sampleX >= textureWidthInPixels) sampleX = textureWidthInPixels - 1; + + int sampleOffset = (rowStartPixelIndex + sampleX) * 4; + float kernelWeight = kernelWeights[kernelIndex]; + accumulatedRed += premultipliedChannels[sampleOffset + 0] * kernelWeight; + accumulatedGreen += premultipliedChannels[sampleOffset + 1] * kernelWeight; + accumulatedBlue += premultipliedChannels[sampleOffset + 2] * kernelWeight; + accumulatedAlpha += premultipliedChannels[sampleOffset + 3] * kernelWeight; + } + int outputOffset = (rowStartPixelIndex + pixelX) * 4; + horizontallyBlurredChannels[outputOffset + 0] = accumulatedRed; + horizontallyBlurredChannels[outputOffset + 1] = accumulatedGreen; + horizontallyBlurredChannels[outputOffset + 2] = accumulatedBlue; + horizontallyBlurredChannels[outputOffset + 3] = accumulatedAlpha; + } + }); + + Color32[] blurredPixels = new Color32[totalPixelCount]; + Parallel.For(0, textureHeightInPixels, pixelY => + { + for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) + { + float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int sampleY = pixelY + kernelIndex - kernelRadiusInPixels; + if (sampleY < 0) sampleY = 0; + else if (sampleY >= textureHeightInPixels) sampleY = textureHeightInPixels - 1; + + int sampleOffset = (sampleY * textureWidthInPixels + pixelX) * 4; + float kernelWeight = kernelWeights[kernelIndex]; + accumulatedRed += horizontallyBlurredChannels[sampleOffset + 0] * kernelWeight; + accumulatedGreen += horizontallyBlurredChannels[sampleOffset + 1] * kernelWeight; + accumulatedBlue += horizontallyBlurredChannels[sampleOffset + 2] * kernelWeight; + accumulatedAlpha += horizontallyBlurredChannels[sampleOffset + 3] * kernelWeight; + } + + Color32 blurredPixel = default; + if (accumulatedAlpha > 0.0001f) + { + blurredPixel.r = ConvertUnitFloatToByte(accumulatedRed / accumulatedAlpha); + blurredPixel.g = ConvertUnitFloatToByte(accumulatedGreen / accumulatedAlpha); + blurredPixel.b = ConvertUnitFloatToByte(accumulatedBlue / accumulatedAlpha); + blurredPixel.a = ConvertUnitFloatToByte(accumulatedAlpha); + } + blurredPixels[pixelY * textureWidthInPixels + pixelX] = blurredPixel; + } + }); + + Texture2D blurredTexture = new Texture2D(textureWidthInPixels, textureHeightInPixels, TextureFormat.RGBA32, false); + blurredTexture.SetPixels32(blurredPixels); + blurredTexture.Apply(); + return blurredTexture; } - internal static List> pendingInnerOriginSpriteInfos = new(); + internal static List> pendingInnerOriginSpriteInfos = new(); private static Vector2 GetPivotPreset(string spriteName) { @@ -447,6 +622,7 @@ private static Vector2 GetPivotPreset(string spriteName) internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, string spriteName, Sprite sprite) { + Plugin.logger.LogInfo($"Registering sprite {spriteName}"); spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); spriteAtlasManager.cachedSprites["Heads"][spriteName] = sprite; Registry.sprites[spriteName] = sprite; @@ -455,6 +631,7 @@ internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, strin // Runs early: only touches your own textures, nothing from SpriteAtlasManager's lookup state. public static void CreateSprites() { + Plugin.logger.LogInfo($"Creating sprites with outer origin..."); pendingInnerOriginSpriteInfos.Clear(); SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); @@ -489,8 +666,10 @@ public static void CreateSprites() Vector2 pivot = spriteInfo.pivot ?? GetPivotPreset(spriteName); float pixelsPerUnit = spriteInfo.pixelsPerUnit ?? defaultPixelsPerUnit; + bool transformToOutline = spriteInfo.transformToOutline; + float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; - Sprite sprite = Visual.BuildSpriteWithTexture(textureEntry.Key, pivot, pixelsPerUnit); + Sprite sprite = BuildSpriteWithTexture(textureEntry.Key, pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); Registry.textures[spriteName] = new KeyValuePair(textureEntry.Key, true); RegisterSprite(spriteAtlasManager, spriteName, sprite); } @@ -503,19 +682,29 @@ public static void CreateSprites() } string spriteName = texturePair.Key; - Sprite sprite = Visual.BuildSpriteWithTexture(texturePair.Value.Key, GetPivotPreset(spriteName), defaultPixelsPerUnit); + Sprite sprite = BuildSpriteWithTexture(texturePair.Value.Key, GetPivotPreset(spriteName), defaultPixelsPerUnit); RegisterSprite(spriteAtlasManager, spriteName, sprite); } } - internal static (byte[], Visual.SpriteInfo) SpriteToPng(Sprite sprite) + internal static (byte[], SpriteInfo) SpriteToPng(Sprite sprite) { Texture2D bakedTexture = BakeSpriteToTexture(sprite); byte[] pngBytes = ImageConversion.EncodeToPNG(bakedTexture); UnityEngine.Object.Destroy(bakedTexture); - return (pngBytes, new Visual.SpriteInfo(sprite.pixelsPerUnit, sprite.pivot)); + Vector2 normalizedPivot = GetNormalizedPivot(sprite); + + return (pngBytes, new SpriteInfo(sprite.pixelsPerUnit, normalizedPivot)); + } + + private static Vector2 GetNormalizedPivot(Sprite sourceSprite) + { + return new Vector2( + sourceSprite.pivot.x / sourceSprite.rect.width, + sourceSprite.pivot.y / sourceSprite.rect.height + ); } private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) @@ -573,25 +762,26 @@ private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) public static void CreateInnerOriginSprites() { + Plugin.logger.LogInfo($"Creating sprites with inner origin..."); SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); foreach (KeyValuePair spriteInfoPair in pendingInnerOriginSpriteInfos) { string spriteName = spriteInfoPair.Key; - SpriteInfo spriteData = spriteInfoPair.Value; + SpriteInfo spriteInfo = spriteInfoPair.Value; Sprite originalSprite = spriteAtlasManager - .DoSpriteLookup(spriteData.spriteOrigin!.name, TribeType.None, SkinType.Default) + .DoSpriteLookup(spriteInfo.spriteOrigin!.name, TribeType.None, SkinType.Default) .sprite; if (originalSprite == null) { - Plugin.logger.LogWarning($"Inner origin sprite '{spriteData.spriteOrigin.name}' not found for '{spriteName}'"); + Plugin.logger.LogWarning($"Inner origin sprite '{spriteInfo.spriteOrigin.name}' not found for '{spriteName}'"); continue; } - bool hasPivotOverride = spriteData.pivot != null; - bool hasPixelsPerUnitOverride = spriteData.pixelsPerUnit != null; + bool hasPivotOverride = spriteInfo.pivot != null; + bool hasPixelsPerUnitOverride = spriteInfo.pixelsPerUnit != null; Sprite sprite = originalSprite; @@ -602,11 +792,13 @@ public static void CreateInnerOriginSprites() originalSprite.pivot.y / originalSprite.rect.height ); - Vector2 finalPivot = hasPivotOverride ? spriteData.pivot!.Value : normalizedOriginalPivot; - float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteData.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; + Vector2 finalPivot = hasPivotOverride ? spriteInfo.pivot!.Value : normalizedOriginalPivot; + float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteInfo.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; + bool transformToOutline = spriteInfo.transformToOutline; + float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; Texture2D bakedTexture = BakeSpriteToTexture(originalSprite); - sprite = BuildSpriteWithTexture(bakedTexture, finalPivot, finalPixelsPerUnit); + sprite = BuildSpriteWithTexture(bakedTexture, finalPivot, finalPixelsPerUnit, transformToOutline, gaussianBlurRadius); sprite.name = spriteName; } From 0a8f537caca7041b7d5dc6e0fce1a8c338d3ee82 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sun, 25 Oct 2026 21:55:26 +0100 Subject: [PATCH 16/42] now it dumps new tribe preview and not legacy ones, added tile effects to the tribe previews --- src/Managers/Hub.cs | 36 +++++++++++++++++++---------------- src/Managers/TribePreviews.cs | 9 +++++++++ 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 22ab356..4351427 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -286,26 +286,30 @@ internal static void DumpTribePreviewLegacy() // TODO legacy tribe preview dump. i have to update that foreach (TribeType type in Enum.GetValues(typeof(TribeType))) { + SaveStateData saveStateData = TribePreviewRegistry.GetTribePreviewData(type, SkinType.Default); // we should add to dump and create previews for skins + List previewTiles = new(); + SelectTribePopup popup = PopupManager.GetSelectTribePopup(); - for (int x = -3; x <= 3; x++) + if (DiskSerializationHelpers.FromLZ4CompressedByteArray( + saveStateData.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) { - for (int y = -7; y <= 7; y++) + GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); + + foreach (var tileData in currentGameState.Map.Tiles) { - Vector2Int pos = new Vector2Int(x, y); - if (popup.UIWorldPreview.worldPreviewData.TryGetData(pos, type, out UITileData tileData)) + TribePreviews.PreviewTile previewTile = new TribePreviews.PreviewTile { - TribePreviews.PreviewTile previewTile = new TribePreviews.PreviewTile - { - x = tileData.Position.x, - y = tileData.Position.y, - terrainType = tileData.terrainType, - resourceType = tileData.resourceType, - unitType = tileData.unitType, - improvementType = tileData.improvementType - }; - previewTiles.Add(previewTile); - } + x = tileData.coordinates.x, + y = tileData.coordinates.y, + terrainType = tileData.terrain, + resourceType = tileData.resource != null ? tileData.resource.type : null, + unitType = tileData.unit != null ? tileData.unit.type : null, + improvementType = tileData.improvement != null ? tileData.improvement.type : null, + tileEffects = tileData.effects.ToArray().ToList() + }; + + previewTiles.Add(previewTile); } } File.WriteAllTextAsync( @@ -315,7 +319,7 @@ internal static void DumpTribePreviewLegacy() } } - internal static void DumpPrefabs() // TODO + internal static void DumpPrefabs() { Directory.CreateDirectory(Plugin.PREFABS_DUMP_PATH); PrefabsInfo prefabsInfo = new(); diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index f3ab13d..25ce12b 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -38,6 +38,10 @@ public class PreviewTile [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public ImprovementData.Type? improvementType = null; + /// The effect types on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheListJson))] + public List tileEffects = new(); } public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); @@ -162,6 +166,11 @@ private static string GetTribePreviewName(string tribeType) }; } } + + foreach (TileData.EffectType tileEffect in previewTile.tileEffects) + { + tileData.AddEffect(tileEffect); + } } saveStateData = ScriptableObject.CreateInstance(); From 366c615333b8e2c32363df4687dc336bd2fb3672 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 26 Oct 2026 12:08:20 +0100 Subject: [PATCH 17/42] fixed preview tile effects --- src/Managers/TribePreviews.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index 25ce12b..e6e7395 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -167,6 +167,9 @@ private static string GetTribePreviewName(string tribeType) } } + if(previewTile.tileEffects.Count > 0) + tileData.effects = new(); + foreach (TileData.EffectType tileEffect in previewTile.tileEffects) { tileData.AddEffect(tileEffect); From a1fff8c41e6063e86e7be824d815ffce07ba9e65 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 26 Oct 2026 18:08:22 +0100 Subject: [PATCH 18/42] new tribe preview stufff --- src/Managers/Hub.cs | 5 +- src/Managers/TribePreviews.cs | 100 ++++++++++++++++------------------ src/Managers/Visual.cs | 23 ++++++++ 3 files changed, 72 insertions(+), 56 deletions(-) diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 4351427..a04002e 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -186,7 +186,7 @@ internal static void DumpData() DumpLogic(); DumpLocalization(); DumpSprites(); - DumpTribePreviewLegacy(); + DumpTribePreview(); DumpPrefabs(); NotificationManager.Notify(Localization.Get("polymod.hub.dumped")); } @@ -281,9 +281,8 @@ private static void DumpSprites() } } - internal static void DumpTribePreviewLegacy() + internal static void DumpTribePreview() { - // TODO legacy tribe preview dump. i have to update that foreach (TribeType type in Enum.GetValues(typeof(TribeType))) { SaveStateData saveStateData = TribePreviewRegistry.GetTribePreviewData(type, SkinType.Default); // we should add to dump and create previews for skins diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index e6e7395..4388e98 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -5,7 +5,6 @@ using PolyMod.Json; using System.Text.Json.Serialization; using PolytopiaBackendBase.Common; -using TMPro; namespace PolyMod.Managers; @@ -46,9 +45,6 @@ public class PreviewTile public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); - private static bool isTakingSnapshot = false; - private static float? baseOrthographicCameraSize = null; - [HarmonyPostfix] [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] public static void PreloadTribePreviews() @@ -58,7 +54,7 @@ public static void PreloadTribePreviews() SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; foreach(string tribe in Registry.tribePreviews.Keys) { - string previewId = GetTribePreviewName(tribe); + string previewId = "worldpreview_" + tribe; PreviewTile[] customPreview = Registry.tribePreviews[tribe]; previewSaveStateDatas[previewId] = new(TribePreviewRegistry.fallbackStateIndex, fallbackSaveStateData, customPreview); } @@ -92,11 +88,6 @@ public static void PreloadTribePreviews() } } - private static string GetTribePreviewName(string tribeType) - { - return "worldpreview_" + tribeType; - } - private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) { SaveStateData? saveStateData = null; @@ -184,52 +175,55 @@ private static string GetTribePreviewName(string tribeType) return saveStateData; } - [HarmonyPrefix] - [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] - private static bool SpriteCamera_TakeSnapshotOfMapState(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, - float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) - { - if(!Plugin.config.debug) - return true; - - var instance = SpriteCamera.instance; - if(baseOrthographicCameraSize == null) - baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; - - instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; - isTakingSnapshot = true; - - return true; - } - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] - private static void SpriteCamera_TakeSnapshotOfMapState_Postfix(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, - float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) + [HarmonyPatch(typeof(SelectTribePopup), nameof(SelectTribePopup.SetBackground))] + private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) { - if(isTakingSnapshot) - isTakingSnapshot = false; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] - public static void Tile_RenderDebug(Tile __instance) - { - if(!isTakingSnapshot) + if(!Plugin.config.debug) return; - GameObject textObj = new GameObject("CoordinateText"); - textObj.transform.SetParent(__instance.transform); - textObj.transform.localPosition = new Vector3(0, 0.0f, 0); - - TextMeshPro textMesh = textObj.AddComponent(); - textMesh.text = __instance.Data.coordinates.ToString(); - textMesh.fontSize = 3; - textMesh.alignment = TextAlignmentOptions.Center; - textMesh.color = Color.white; - - MeshRenderer renderer = textObj.GetComponent(); - renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; - renderer.sortingOrder = __instance.Depth + 10; + try + { + TribeType tribeType = (__instance.mixTribeData != null) ? __instance.mixTribeData.type : __instance.tribeData.type; + + __instance.mapSnapshot = new SpriteCamera.SnapshotMapData(); + __instance.mapSnapshot.LoadMapState( + TribePreviewRegistry.GetTribePreviewData(tribeType, __instance.SkinType) + ); + + float width = __instance.worldPreviewRawImage.rectTransform.GetWidth(); + float height = __instance.worldPreviewRawImage.rectTransform.GetHeight(); + + int tribeColor = PolytopiaDataManager.GetGameLogicData( + VersionManager.GameLogicDataVersion + ).GetTribeColor( + tribeType, + __instance.SkinType + ); + + var instance = SpriteCamera.instance; + float baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; + + instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; + + Texture2D texture2D = SpriteCamera.TakeSnapshotOfMapState( + __instance.mapSnapshot, + width, + height, + tribeType, + __instance.SkinType, + tribeType, + tribeColor + ); + + instance.spriteCamera.orthographicSize = baseOrthographicCameraSize; + + __instance.worldPreviewRawImage.texture = texture2D; + __instance.worldPreviewRawImage.color = Color.white; + } + catch (Exception ex) + { + Plugin.logger.LogWarning($"Failed to load debug tribe preview {ex.Message}"); + } } } \ No newline at end of file diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 9208583..ece1476 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -6,6 +6,7 @@ using Il2CppInterop.Runtime; using System.Text.Json.Serialization; using PolyMod.Json; +using TMPro; namespace PolyMod.Managers; @@ -225,6 +226,28 @@ private static void SpriteData_ImprovementToString(ref string __result, Improvem #endregion #region Level + [HarmonyPostfix] + [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] + public static void Tile_RenderDebug(Tile __instance) + { + if(!Plugin.config.debug) + return; + + GameObject textObj = new GameObject("CoordinateText"); + textObj.transform.SetParent(__instance.transform); + textObj.transform.localPosition = new Vector3(0, 0.0f, 0); + + TextMeshPro textMesh = textObj.AddComponent(); + textMesh.text = __instance.Data.coordinates.ToString(); + textMesh.fontSize = 3; + textMesh.alignment = TextAlignmentOptions.Center; + textMesh.color = Color.white; + + MeshRenderer renderer = textObj.GetComponent(); + renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; + renderer.sortingOrder = __instance.Depth + 10; + } + private static string GetLandSpriteName(TileData tileData) { if (!tileData.HasEffect(TileData.EffectType.Flooded)) From 2018748d413346f54002aad74159ee6b4114c190 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Wed, 28 Oct 2026 22:02:20 +0100 Subject: [PATCH 19/42] bunch of new stuff --- resources/localization.json | 54 +- src/Dumper.cs | 271 ++++++++++ src/Loader.cs | 5 + src/Managers/Hub.cs | 898 ++++++++++++++-------------------- src/Managers/TribePreviews.cs | 2 +- src/Managers/Visual.cs | 161 +++++- src/Plugin.cs | 1 + src/Registry.cs | 31 +- 8 files changed, 855 insertions(+), 568 deletions(-) create mode 100644 src/Dumper.cs diff --git a/resources/localization.json b/resources/localization.json index b1219e2..455c1ef 100644 --- a/resources/localization.json +++ b/resources/localization.json @@ -60,9 +60,13 @@ "German (Germany)": "DATENDUMP" }, "polymod_hub_dumped": { - "English": "Dump completed successfully!", - "Russian": "Дамп завершен успешно!", - "German (Germany)": "Dump erfolgreich beendet!" + "English": "Dump completed successfully!\n\n{0}", + "Russian": "Дамп завершен успешно!\n\n{0}", + "German (Germany)": "Dump erfolgreich beendet!\n\n{0}" + }, + "polymod_hub_openfolder": { + "English": "OPEN FOLDER", + "Russian": "ОТКРЫТЬ ПАПКУ" }, "polymod_cycle": { "English": "Dependency cycle detected", @@ -250,5 +254,49 @@ "buttons_download_launcher": { "English": "OUR SITE", "Russian": "НАШ САЙТ" + }, + "polymod_hub_summary": { + "English": "{0} of {1} mods loaded.", + "Russian": "Загружено модов: {0} из {1}." + }, + "polymod_hub_mods_none": { + "English": "No mods are installed yet. Put mod archives into the Mods folder next to the game and restart it.", + "Russian": "Моды пока не установлены. Положите архивы модов в папку Mods рядом с игрой и перезапустите её." + }, + "polymod_hub_mod_authors": { + "English": "by {0}", + "Russian": "от {0}" + }, + "polymod_hub_config_debug": { + "English": "DEBUG", + "Russian": "ОТЛАДКА" + }, + "polymod_hub_config_coordinates": { + "English": "COORDINATES", + "Russian": "КООРДИНАТЫ" + }, + "polymod_debug_description": { + "English": "Opens the developer console and writes verbose logs.", + "Russian": "Открывает консоль разработчика и включает подробные логи." + }, + "polymod_coordinates": { + "English": "Coordinates", + "Russian": "Координаты" + }, + "polymod_coordinates_description": { + "English": "Shows the coordinates of every tile on the map.", + "Russian": "Показывает координаты каждой клетки на карте." + }, + "polymod_on": { + "English": "ON", + "Russian": "ВКЛ" + }, + "polymod_off": { + "English": "OFF", + "Russian": "ВЫКЛ" + }, + "polymod_hotreload_unavailable": { + "English": "Hot reload is not available yet.", + "Russian": "Горячая перезагрузка пока недоступна." } } \ No newline at end of file diff --git a/src/Dumper.cs b/src/Dumper.cs new file mode 100644 index 0000000..cd30c2a --- /dev/null +++ b/src/Dumper.cs @@ -0,0 +1,271 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using Il2CppSystem.Linq; +using PolyMod.Json; +using PolytopiaBackendBase.Common; +using UnityEngine; + +namespace PolyMod.Managers; + +/// +/// Writes the game's own data (logic, localization, sprites, tribe previews and prefabs) to disk +/// so that mod authors can use it as a reference. +/// +internal static class Dumper +{ + private static readonly JsonSerializerOptions INDENTED = new() + { + WriteIndented = true, + }; + + private static readonly JsonSerializerOptions INDENTED_WITH_VECTORS = new() + { + WriteIndented = true, + Converters = { new Vector2Json() }, + }; + + private static readonly JsonSerializerOptions LOCALIZATION = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + internal static string RootPath => Path.GetFullPath(Plugin.DUMPED_DATA_PATH); + + internal static void DumpAll() + { + Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); + DumpLogic(); + DumpLocalization(); + DumpSprites(); + DumpTribePreviews(); + DumpPrefabs(); + } + + /// + /// Dumps every version of the game logic and avatar data. + /// + internal static void DumpLogic() + { + try + { + Directory.CreateDirectory(Plugin.LOGIC_DUMP_PATH); + for (int version = 1; version <= VersionManager.GameLogicDataVersion; version++) + { + File.WriteAllText( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"GameLogicData{version}.json"), + PolytopiaDataManager.provider.LoadGameLogicData(version) + ); + } + for (int version = 1; version <= VersionManager.AvatarDataVersion; version++) + { + File.WriteAllText( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"AvatarData{version}.json"), + PolytopiaDataManager.provider.LoadAvatarData(version) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping logic failed: {exception}"); + } + } + + internal static void DumpLocalization() + { + try + { + Directory.CreateDirectory(Plugin.LOCALIZATION_DUMP_PATH); + var source = I2.Loc.LocalizationManager.Sources[0]; + + foreach (var language in source.GetLanguages()) + { + int languageIndex = source.GetLanguageIndex(language); + Dictionary translations = new(); + foreach (var term in source.mTerms) + { + string translation = term.GetTranslation(languageIndex); + if (!string.IsNullOrEmpty(translation)) + translations[term.Term] = translation; + } + File.WriteAllText( + Path.Combine( + Plugin.LOCALIZATION_DUMP_PATH, + $"language_{source.mLanguages[languageIndex].Code}.json" + ), + JsonSerializer.Serialize(translations, LOCALIZATION) + ); + } + + foreach (var category in source.GetCategories()) + { + File.WriteAllText( + Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"localization_{category}.csv"), + source.Export_CSV(category) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping localization failed: {exception}"); + } + } + + internal static void DumpSprites() + { + try + { + Directory.CreateDirectory(Plugin.SPRITES_DUMP_PATH); + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + + for (int i = 0; i < AtlasData.raw.Count; i++) + { + if (spriteAtlasManager.loadedAtlases[i] == null) continue; + + string[] row = AtlasData.raw[i]; + string atlasName = row[0]; + string directory = Path.Combine(Plugin.SPRITES_DUMP_PATH, atlasName); + Directory.CreateDirectory(directory); + + Dictionary atlasSpriteInfo = new(); + for (int j = 1; j < row.Length; j++) + { + string spriteName = row[j]; + Sprite sprite = spriteAtlasManager.GetSprite(spriteName, atlasName); + if (sprite == null) continue; + + (byte[] bytes, Visual.SpriteInfo spriteInfo) = Visual.SpriteToPng(sprite); + File.WriteAllBytes(Path.Combine(directory, $"{spriteName}.png"), bytes); + atlasSpriteInfo[spriteName] = spriteInfo; + } + File.WriteAllText( + Path.Combine(directory, $"sprites_{atlasName}.json"), + JsonSerializer.Serialize(atlasSpriteInfo, INDENTED_WITH_VECTORS) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping sprites failed: {exception}"); + } + } + + internal static void DumpTribePreviews() + { + try + { + foreach (TribeType type in Enum.GetValues()) + { + SaveStateData saveStateData = TribePreviewRegistry.GetTribePreviewData(type, SkinType.Default); // TODO: skins + if (saveStateData == null) continue; + + if (!DiskSerializationHelpers.FromLZ4CompressedByteArray( + saveStateData.byteArray, out ClientSerializationWrapper wrapper, out int _)) + { + Plugin.logger.LogWarning($"Dump skipped preview of {type}: save state could not be read"); + continue; + } + + List previewTiles = new(); + foreach (var tileData in wrapper.GetCurrentGameState().Map.Tiles) + { + previewTiles.Add(new TribePreviews.PreviewTile + { + x = tileData.coordinates.x, + y = tileData.coordinates.y, + terrainType = tileData.terrain, + resourceType = tileData.resource != null ? tileData.resource.type : null, + unitType = tileData.unit != null ? tileData.unit.type : null, + improvementType = tileData.improvement != null ? tileData.improvement.type : null, + tileEffects = tileData.effects.ToArray().ToList(), + }); + } + + File.WriteAllText( + Path.Combine(Plugin.DUMPED_DATA_PATH, $"preview_{type}.json"), + JsonSerializer.Serialize(previewTiles, INDENTED) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping tribe previews failed: {exception}"); + } + } + + internal static void DumpPrefabs() + { + try + { + Directory.CreateDirectory(Plugin.PREFABS_DUMP_PATH); + PrefabsInfo prefabsInfo = new(); + + foreach (var entry in Prefabs.unitsNew) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key.unitType); + if (visualParts == null) continue; + + prefabsInfo.units.Add(new UnitPrefabInfo + { + headPositionMarker = entry.Value.headPositionMarker.gameObject.name, + skinnedKey = entry.Key, + visualParts = visualParts, + }); + } + + foreach (var entry in PrefabManager.improvements) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key); + if (visualParts == null) continue; + + prefabsInfo.improvements.Add(new ImprovementPrefabInfo + { + improvementType = entry.Key, + visualParts = visualParts, + }); + } + + foreach (var entry in PrefabManager.resources) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key); + if (visualParts == null) continue; + + prefabsInfo.resources.Add(new ResourcePrefabInfo + { + resourceType = entry.Key, + visualParts = visualParts, + }); + } + + File.WriteAllText( + Path.Combine(Plugin.PREFABS_DUMP_PATH, "prefabs.json"), + JsonSerializer.Serialize(prefabsInfo, INDENTED_WITH_VECTORS) + ); + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping prefabs failed: {exception}"); + } + } + + private static List? CollectVisualParts(Component prefab, object key) + { + SkinVisualsReference skinVisualsReference = prefab.GetComponent(); + if (skinVisualsReference == null || skinVisualsReference.visualParts == null) + { + Plugin.logger.LogWarning($"Dump skipped {key}: no SkinVisualsReference"); + return null; + } + + List visualParts = new(); + foreach (var visualPart in skinVisualsReference.visualParts) + { + if (visualPart == null || visualPart.visualPart == null) continue; + + VisualPartInfo visualPartInfo = new(); + visualPartInfo.CopyFromVisualPart(visualPart); + visualParts.Add(visualPartInfo); + } + return visualParts; + } +} diff --git a/src/Loader.cs b/src/Loader.cs index 419e3bf..56ade47 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -326,6 +326,11 @@ ref manifest Plugin.logger.LogError($"Mod id {manifest.id} is invalid in {modContainer}"); continue; } + if (Plugin.config.disabledMods.Contains(manifest.id)) + { + Plugin.logger.LogError($"Mod {manifest.id} is disabled, skipping"); + continue; + } if (manifest.version == null) { Plugin.logger.LogError($"Mod version not found in {modContainer}"); diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index a04002e..e8bdd03 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -1,548 +1,370 @@ -using System.Text.Json; using Cpp2IL.Core.Extensions; using HarmonyLib; -using I2.Loc; using Il2CppInterop.Runtime; using UnityEngine; using static PopupBase; -using PolytopiaBackendBase.Common; -using System.Text.Encodings.Web; -using Il2CppSystem.Linq; -using PolyMod.Json; - namespace PolyMod.Managers; -/// -/// Manages the PolyMod hub, including UI elements and popups. -/// internal static class Hub { - private const string HEADER_PREFIX = ""; - private const string HEADER_POSTFIX = ""; - private const int POPUP_WIDTH = 1400; - private static UIRoundButton_UI2? polyModButton = null; - private static UIRoundButton_UI2? polyModVersion = null; - - /// - /// Whether the configuration popup is currently active. - /// - public static bool isConfigPopupActive = false; - - /// - /// Patches the splash screen to play a custom intro video. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(SplashController), nameof(SplashController.LoadAndPlayClip))] - private static bool SplashController_LoadAndPlayClip(SplashController __instance) - { - string name = "intro.mp4"; - string path = Path.Combine(Application.persistentDataPath, name); - File.WriteAllBytesAsync(path, Plugin.GetResource(name).ReadBytes()); - __instance.lastPlayTime = Time.realtimeSinceStartup; - __instance.videoPlayer.url = path; - __instance.videoPlayer.Play(); - return false; - } - - /// - /// Patches the popup button container to correctly anchor buttons. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupButtonContainer), nameof(PopupButtonContainer.SetButtonData))] - private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __instance) - { - int num = __instance.buttons.Length; - for (int i = 0; i < num; i++) - { - UITextButton uitextButton = __instance.buttons[i]; - Vector2 vector = new((num == 1) ? 0.5f : (i / (num - 1.0f)), 0.5f); - uitextButton.rectTransform.anchorMin = vector; - uitextButton.rectTransform.anchorMax = vector; - uitextButton.rectTransform.pivot = vector; - } - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.Init))] - private static void StartScreen_UI2_Init(StartScreen_UI2 __instance, RectTransform transform) - { - polyModButton = UILibrary.NewRoundButton(transform).SetStyle(UIButtonBase_UI2.ButtonStyle.Suggested); - polyModButton.bg.sprite = Visual.BuildSprite(Plugin.GetResource("polymod_icon.png").ReadBytes()); - polyModButton.OnClickedSignal.Add(DelegateSupport.ConvertDelegate(ShowPolyModHub)); - - polyModVersion = UILibrary.NewRoundButton(transform).SetStyle(UIButtonBase_UI2.ButtonStyle.Suggested); - polyModVersion.Text = $"PolyMod {Plugin.VERSION}"; - polyModVersion.titleTextField.textField.fontSize = 18f; - - if (Main.dependencyCycle) - { - BasicPopup popup = PopupManager.GetBasicPopupWithData( - new( - Localization.Get("polymod.cycle"), - Localization.Get("polymod.cycle.description"), - new PopupBase.PopupButtonData[] { - new( - "buttons.exitgame", - PopupBase.PopupButtonData.States.None, - (Il2CppSystem.Action)Application.Quit, - closesPopup: false, - customColorStates: ColorConstants.redButtonColorStates - ) - } - ) - ); - - popup.IsUnskippable = true; - popup.Show(); - } - - } - - /// - /// Patches the start screen to add the PolyMod hub button and version text. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RunLayout))] - private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, ScreenBase_UI2.ScreenSize screenSize) - { - if(polyModButton == null) - { - Plugin.logger.LogWarning("PolyMod Hub button is null when running layout!"); - return; - } - polyModButton.iconContainer.gameObject.SetActive(false); - polyModButton.outline.gameObject.SetActive(false); - polyModButton.bg.color = Color.white; - polyModButton.Text = Localization.Get("polymod.hub"); - float num = 50f; - polyModButton.SetPosition(screenSize.safeRect.Right - (num * 2.5f), screenSize.safeRect.Top - num); - - if(polyModVersion == null) - { - Plugin.logger.LogWarning("PolyMod Version is null when running layout!"); - return; - } - polyModVersion.iconContainer.gameObject.SetActive(false); - polyModVersion.outline.gameObject.SetActive(false); - polyModVersion.bg.gameObject.SetActive(false); - polyModVersion.SetPosition(screenSize.safeRect.Left + num * 1.15f, screenSize.safeRect.Bottom + num * 1.15f); - } - - /// - /// Patches the game manager to handle key presses for the config popup. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(GameManager), nameof(GameManager.Update))] - private static void GameManager_Update() - { - if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.Tab) && !isConfigPopupActive) - { - ShowConfigPopup(); - } - } - - /// - /// Updates sprite information from dumped files. - /// - internal static void HotReload() - { - NotificationManager.Notify("FAILED: wip"); - // string message = string.Empty; - // Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); - - // foreach (var file in Directory.GetFiles(Plugin.DUMPED_DATA_PATH)) - // { - // string? name = Path.GetFileNameWithoutExtension(file); - // List subnames = new(); - // if (name.Contains("sprites_")) - // { - // subnames = name.Split('_').ToList(); - // Mod.File spriteInfo = new(Path.GetFileNameWithoutExtension(file), File.ReadAllBytes(file)); - // Dictionary? deserialized = Loader.LoadSpriteInfoFile(Registry.mods[subnames[1]], spriteInfo); - // if (deserialized != null) - // { - // foreach (var kvp in deserialized) - // { - // Loader.UpdateSprite(kvp.Key); - // } - // message += Localization.Get("polymod.hotreload.success", new Il2CppSystem.Object[] { subnames[1] }); - // } - // } - // } - // if (message == string.Empty) - // { - // message = Localization.Get("polymod.hotreload.failure"); - // } - // NotificationManager.Notify(message); - } - - /// - /// Dump all data. - /// - internal static void DumpData() - { - Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); - DumpLogic(); - DumpLocalization(); - DumpSprites(); - DumpTribePreview(); - DumpPrefabs(); - NotificationManager.Notify(Localization.Get("polymod.hub.dumped")); - } - - internal static void DumpLogic() - { - Directory.CreateDirectory(Plugin.LOGIC_DUMP_PATH); - for (int version = 1; version <= VersionManager.GameLogicDataVersion; version++) - { - File.WriteAllTextAsync( - Path.Combine(Plugin.LOGIC_DUMP_PATH, $"GameLogicData{version}.json"), - PolytopiaDataManager.provider.LoadGameLogicData(version) - ); - } - for (int version = 1; version <= VersionManager.AvatarDataVersion; version++) - { - File.WriteAllTextAsync( - Path.Combine(Plugin.LOGIC_DUMP_PATH, $"AvatarData{version}.json"), - PolytopiaDataManager.provider.LoadAvatarData(version) - ); - } - } - - internal static void DumpLocalization() - { - Directory.CreateDirectory(Plugin.LOCALIZATION_DUMP_PATH); - - // Languages dump - var source = LocalizationManager.Sources[0]; - foreach (var language in source.GetLanguages()) - { - int languageIndex = source.GetLanguageIndex(language); - var dict = new Dictionary(); - - foreach (var term in source.mTerms) - { - var translation = term.GetTranslation(languageIndex); - - if (!string.IsNullOrEmpty(translation)) - dict[term.Term] = translation; - } - var options = new JsonSerializerOptions - { - WriteIndented = true, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping - }; - - string json = JsonSerializer.Serialize(dict, options); - - File.WriteAllText( - Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"language_{source.mLanguages[languageIndex].Code}.json"), - json - ); - } - // Full loc dump - foreach (var category in source.GetCategories()) - File.WriteAllTextAsync( - Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"localization_{category}.csv"), - source.Export_CSV(category) - ); - } - - private static void DumpSprites() - { - Directory.CreateDirectory(Plugin.SPRITES_DUMP_PATH); - SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); - - for (int i = 0; i < AtlasData.raw.Count; i++) - { - if (spriteAtlasManager.loadedAtlases[i] == null) continue; // not loaded, skip - - string[] row = AtlasData.raw[i]; - string atlasName = row[0]; - string dir = Path.Combine(Plugin.SPRITES_DUMP_PATH, atlasName); - Directory.CreateDirectory(dir); - - Dictionary atlasSpriteInfo = new(); - for (int j = 1; j < row.Length; j++) - { - string spriteName = row[j]; - Sprite sprite = spriteAtlasManager.GetSprite(spriteName, atlasName); - if (sprite == null) continue; - - (byte[] bytes, Visual.SpriteInfo spriteInfo) = Visual.SpriteToPng(sprite); - File.WriteAllBytesAsync(Path.Combine(dir, spriteName + ".png"), bytes); - atlasSpriteInfo.Add(spriteName, spriteInfo); - } - File.WriteAllTextAsync( - Path.Combine(dir, $"sprites_{atlasName}.json"), - JsonSerializer.Serialize(atlasSpriteInfo, new JsonSerializerOptions { WriteIndented = true, Converters = { new PolyMod.Json.Vector2Json() }}) - ); - } - } - - internal static void DumpTribePreview() - { - foreach (TribeType type in Enum.GetValues(typeof(TribeType))) - { - SaveStateData saveStateData = TribePreviewRegistry.GetTribePreviewData(type, SkinType.Default); // we should add to dump and create previews for skins - - List previewTiles = new(); - - SelectTribePopup popup = PopupManager.GetSelectTribePopup(); - if (DiskSerializationHelpers.FromLZ4CompressedByteArray( - saveStateData.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) - { - GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); - - foreach (var tileData in currentGameState.Map.Tiles) - { - TribePreviews.PreviewTile previewTile = new TribePreviews.PreviewTile - { - x = tileData.coordinates.x, - y = tileData.coordinates.y, - terrainType = tileData.terrain, - resourceType = tileData.resource != null ? tileData.resource.type : null, - unitType = tileData.unit != null ? tileData.unit.type : null, - improvementType = tileData.improvement != null ? tileData.improvement.type : null, - tileEffects = tileData.effects.ToArray().ToList() - }; - - previewTiles.Add(previewTile); - } - } - File.WriteAllTextAsync( - Path.Combine(Plugin.DUMPED_DATA_PATH, $"preview_{type}.json"), - JsonSerializer.Serialize(previewTiles, new JsonSerializerOptions { WriteIndented = true }) - ); - } - } - - internal static void DumpPrefabs() - { - Directory.CreateDirectory(Plugin.PREFABS_DUMP_PATH); - PrefabsInfo prefabsInfo = new(); - foreach (KeyValuePair keyValuePairs in Prefabs.unitsNew) - { - var unit = keyValuePairs.Value; - SkinVisualsReference skinVisualsReference = unit.GetComponent(); - if (skinVisualsReference == null || skinVisualsReference.visualParts == null) - { - Plugin.logger.LogWarning($"Dump skipped {keyValuePairs.Key.unitType}: no SkinVisualsReference"); - continue; - } - UnitPrefabInfo unitPrefabInfo = new() - { - headPositionMarker = unit.headPositionMarker.gameObject.name, - skinnedKey = keyValuePairs.Key, - visualParts = new() - }; - foreach (var visualPart in skinVisualsReference.visualParts) - { - if (visualPart == null || visualPart.visualPart == null) - { - continue; - } - - var visualPartInfo = new VisualPartInfo { }; - visualPartInfo.CopyFromVisualPart(visualPart); - unitPrefabInfo.visualParts.Add(visualPartInfo); - - } - prefabsInfo.units.Add(unitPrefabInfo); - } - - foreach (Il2CppSystem.Collections.Generic.KeyValuePair keyValuePairs in PrefabManager.improvements) - { - var unit = keyValuePairs.Value; - SkinVisualsReference skinVisualsReference = unit.GetComponent(); - if (skinVisualsReference == null || skinVisualsReference.visualParts == null) - { - Plugin.logger.LogWarning($"Dump skipped {keyValuePairs.Key}: no SkinVisualsReference"); - continue; - } - ImprovementPrefabInfo improvementPrefabInfo = new() - { - improvementType = keyValuePairs.Key, - visualParts = new() - }; - foreach (var visualPart in skinVisualsReference.visualParts) - { - if (visualPart == null || visualPart.visualPart == null) - { - continue; - } - - var visualPartInfo = new VisualPartInfo { }; - visualPartInfo.CopyFromVisualPart(visualPart); - improvementPrefabInfo.visualParts.Add(visualPartInfo); - - } - prefabsInfo.improvements.Add(improvementPrefabInfo); - } - - foreach (Il2CppSystem.Collections.Generic.KeyValuePair keyValuePairs in PrefabManager.resources) - { - var unit = keyValuePairs.Value; - SkinVisualsReference skinVisualsReference = unit.GetComponent(); - if (skinVisualsReference == null || skinVisualsReference.visualParts == null) - { - Plugin.logger.LogWarning($"Dump skipped {keyValuePairs.Key}: no SkinVisualsReference"); - continue; - } - ResourcePrefabInfo resourcePrefabInfo = new() - { - resourceType = keyValuePairs.Key, - visualParts = new() - }; - foreach (var visualPart in skinVisualsReference.visualParts) - { - if (visualPart == null || visualPart.visualPart == null) - { - continue; - } - - var visualPartInfo = new VisualPartInfo { }; - visualPartInfo.CopyFromVisualPart(visualPart); - resourcePrefabInfo.visualParts.Add(visualPartInfo); - - } - prefabsInfo.resources.Add(resourcePrefabInfo); - } - - File.WriteAllTextAsync( - Path.Combine(Plugin.PREFABS_DUMP_PATH, $"prefabs.json"), - JsonSerializer.Serialize(prefabsInfo, new JsonSerializerOptions { WriteIndented = true, Converters = { new Vector2Json() },}) - ); - } - - /// - /// Shows the configuration popup. - /// - internal static void ShowConfigPopup() - { - BasicPopup polymodPopup = PopupManager.GetBasicPopup(); - polymodPopup.Header = Localization.Get("polymod.hub.config"); - polymodPopup.Description = ""; - polymodPopup.buttonData = CreateConfigPopupButtonData(); - polymodPopup.Show(); - } - - internal static void ShowPolyModHub() - { - BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); - popup.Header = Localization.Get("polymod.hub"); - popup.Description = Localization.Get("polymod.hub.header", new Il2CppSystem.Object[] { - HEADER_PREFIX, - HEADER_POSTFIX - }) + "\n\n"; - foreach (var mod in Registry.mods.Values) - { - popup.Description += Localization.Get("polymod.hub.mod", new Il2CppSystem.Object[] { - mod.name, - Localization.Get("polymod.hub.mod.status." - + Enum.GetName(typeof(Mod.Status), mod.status)!.ToLower()), - string.Join(", ", mod.authors), - mod.version.ToString(), - mod.description ?? "" - }); - popup.Description += "\n\n"; - } - popup.Description += Localization.Get("polymod.hub.footer", new Il2CppSystem.Object[] { - HEADER_PREFIX, - HEADER_POSTFIX - }); - - void OpenDiscord() - { - NativeHelpers.OpenURL(Plugin.DISCORD_LINK, false); - } - - List popupButtons = new() - { - new("buttons.back"), - new( - "polymod.hub.discord", - callback: DelegateSupport.ConvertDelegate(OpenDiscord) - ), - new( - "polymod.hub.config", - callback: DelegateSupport.ConvertDelegate(ShowConfigPopup) - ) - }; - if (Plugin.config.debug) - { - popupButtons.Add(new( - "polymod.hub.dump", - callback: DelegateSupport.ConvertDelegate(DumpData), - closesPopup: false - )); - popupButtons.Add(new( - "polymod.hub.hotreload", - callback: DelegateSupport.ConvertDelegate(HotReload), - closesPopup: false - )); - } - popup.buttonData = popupButtons.ToArray(); - popup.ShowSetWidth(POPUP_WIDTH); - } - - /// - /// Creates the button data for the configuration popup. - /// - /// An array of popup button data. - internal static PopupButtonData[] CreateConfigPopupButtonData() - { - List popupButtons = new() - { - new(Localization.Get("buttons.back"), PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnBackButtonClicked), -1, true, null) - }; - - if (GameManager.Instance.isLevelLoaded) - { - popupButtons.Add(new PopupButtonData(Localization.Get("polymod.hub.hotreload"), PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnUpdateSpritesButtonClicked), -1, true, null)); - } - else - { - string debugButtonName = Localization.Get( - Plugin.config.debug ? "polymod.hub.config.disable" : "polymod.hub.config.enable", - new Il2CppSystem.Object[] { Localization.Get("polymod.debug", - new Il2CppSystem.Object[]{}).ToUpperInvariant() } - ); - popupButtons.Add(new PopupButtonData(debugButtonName, PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnDebugButtonClicked), -1, true, null)); - } - return popupButtons.ToArray(); - - void OnDebugButtonClicked() - { - Plugin.config = new(debug: !Plugin.config.debug); - Plugin.WriteConfig(); - Plugin.UpdateConsole(); - NotificationManager.Notify(Localization.Get( - "polymod.config.setto", - new Il2CppSystem.Object[] { Localization.Get("polymod.debug", - new Il2CppSystem.Object[]{}), Plugin.config.debug } - )); - isConfigPopupActive = false; - } - - void OnUpdateSpritesButtonClicked() - { - HotReload(); - isConfigPopupActive = false; - } - - void OnBackButtonClicked() - { - isConfigPopupActive = false; - } - } - - /// - /// Initializes the Hub manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Hub)); - } -} \ No newline at end of file + private record Setting( + string buttonKey, + string nameKey, + string descriptionKey, + Func isEnabled, + Action toggle + ); + + private const string HEADER_PREFIX = ""; + private const string HEADER_POSTFIX = ""; + + private const string COLOR_MUTED = "#9AA0A6"; + private const string COLOR_ENABLED = "#4CC76A"; + private const string COLOR_DISABLED = "#E36A5B"; + private const string COLOR_WARNING = "#E0A52E"; + private const float HUB_POPUP_WIDTH_SHARE = 0.78f; + private const float HUB_POPUP_MAX_WIDTH = 1400f; + private const float SETTINGS_POPUP_WIDTH_SHARE = 0.5f; + private const float SETTINGS_POPUP_MAX_WIDTH = 900f; + private const float START_SCREEN_MARGIN = 50f; + private const float VERSION_LABEL_FONT_SIZE = 18f; + + private const KeyCode HOTKEY_MODIFIER = KeyCode.LeftControl; + private const KeyCode HOTKEY_MODIFIER_ALTERNATIVE = KeyCode.RightControl; + private const KeyCode HOTKEY = KeyCode.Tab; + + private static readonly Setting[] SETTINGS = new Setting[] + { + new( + "polymod.hub.config.debug", + "polymod.debug", + "polymod.debug.description", + () => Plugin.config.debug, + () => + { + Plugin.config = Plugin.config with { debug = !Plugin.config.debug }; + Plugin.UpdateConsole(); + } + ), + new( + "polymod.hub.config.coordinates", + "polymod.coordinates", + "polymod.coordinates.description", + () => Plugin.config.showCoordinates, + () => Plugin.config = Plugin.config with { showCoordinates = !Plugin.config.showCoordinates } + ), + }; + + private static UIRoundButton_UI2? polyModButton = null; + private static NotificationBadge? brokenModsBadge = null; + private static TextField_UI2? polyModVersion = null; + + private static PopupBase? openPopup = null; + + public static bool IsPopupOpen + { + get + { + if (openPopup != null) + { + try + { + if (openPopup.IsShowing()) return true; + } + catch (Exception) {} + openPopup = null; + } + return false; + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SplashController), nameof(SplashController.LoadAndPlayClip))] + private static bool SplashController_LoadAndPlayClip(SplashController __instance) + { + string name = "intro.mp4"; + string path = Path.Combine(Application.persistentDataPath, name); + File.WriteAllBytesAsync(path, Plugin.GetResource(name).ReadBytes()); + __instance.lastPlayTime = Time.realtimeSinceStartup; + __instance.videoPlayer.url = path; + __instance.videoPlayer.Play(); + return false; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.Init))] + private static void StartScreen_UI2_Init(RectTransform transform) + { + polyModButton = UILibrary.NewRoundButton(transform).SetStyle(UIButtonBase_UI2.ButtonStyle.Suggested); + polyModButton.bg.sprite = Visual.BuildSprite(Plugin.GetResource("polymod_icon.png").ReadBytes()); + polyModButton.OnClickedSignal.Add(Callback(ShowPolyModHub)); + + brokenModsBadge = UILibrary.NewNotificationBadge(polyModButton.rectTransform).SetValue(CountBrokenMods()); + polyModButton.SetOverlay(brokenModsBadge, UIButtonBase_UI2.OverlayPosition.TopRight); + + polyModVersion = UILibrary.NewText(transform, "PolyModVersion"); + polyModVersion.textField.fontSize = VERSION_LABEL_FONT_SIZE; + polyModVersion.textField.color = Color.white; + polyModVersion.Text = $"PolyMod {Plugin.VERSION}"; + + if (Main.dependencyCycle) + ShowDependencyCyclePopup(); + } + + /// + /// Patches the start screen layout to place the PolyMod hub button and the version label. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RunLayout))] + private static void StartScreen_UI2_RunLayout(ScreenBase_UI2.ScreenSize screenSize) + { + if (polyModButton == null || polyModVersion == null) + { + Plugin.logger.LogWarning("PolyMod start screen widgets are missing, skipping their layout."); + return; + } + + polyModButton.iconContainer.gameObject.SetActive(false); + polyModButton.outline.gameObject.SetActive(false); + polyModButton.bg.color = Color.white; + // Setting the text re-runs the button's own layout, which also repositions the badge. + polyModButton.Text = Localization.Get("polymod.hub"); + polyModButton.SetPosition( + screenSize.safeRect.Right - START_SCREEN_MARGIN * 2.5f, + screenSize.safeRect.Top - START_SCREEN_MARGIN + ); + brokenModsBadge?.SetValue(CountBrokenMods()); + + polyModVersion.SetPosition( + screenSize.safeRect.Left + START_SCREEN_MARGIN * 1.15f, + screenSize.safeRect.Bottom + START_SCREEN_MARGIN * 1.15f + ); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(GameManager), nameof(GameManager.Update))] + private static void GameManager_Update() + { + bool modifierHeld = Input.GetKey(HOTKEY_MODIFIER) || Input.GetKey(HOTKEY_MODIFIER_ALTERNATIVE); + if (modifierHeld && Input.GetKeyDown(HOTKEY) && !IsPopupOpen) + ShowPolyModHub(); + } + + internal static void ShowPolyModHub() + { + BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = string.Join( + "\n\n", + Localization.Get("polymod.hub.header", Args(HEADER_PREFIX, HEADER_POSTFIX)), + BuildModList(), + Localization.Get("polymod.hub.footer", Args(HEADER_PREFIX, HEADER_POSTFIX)) + ); + + void OpenDiscord() => NativeHelpers.OpenURL(Plugin.DISCORD_LINK, false); + + List buttons = new() + { + new("buttons.back"), + new("polymod.hub.discord", callback: Callback(OpenDiscord)), + new("polymod.hub.config", callback: Callback(ShowConfigPopup)), + }; + if (Plugin.config.debug) + { + buttons.Add(new("polymod.hub.dump", callback: Callback(DumpData), closesPopup: false)); + buttons.Add(new("polymod.hub.hotreload", callback: Callback(HotReload), closesPopup: false)); + } + + popup.buttonData = buttons.ToArray(); + openPopup = popup; + popup.ShowSetWidth(HUB_POPUP_WIDTH_SHARE, HUB_POPUP_MAX_WIDTH); + } + + internal static void ShowConfigPopup() + { + BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); + popup.Header = Localization.Get("polymod.hub.config"); + popup.Description = BuildSettingsList(); + + List buttons = new() + { + new("buttons.back", callback: Callback(ShowPolyModHub)), + }; + foreach (Setting setting in SETTINGS) + { + void OnSettingClicked() + { + setting.toggle(); + Plugin.WriteConfig(); + popup.Description = BuildSettingsList(); + } + buttons.Add(new(setting.buttonKey, callback: Callback(OnSettingClicked), closesPopup: false)); + } + + popup.buttonData = buttons.ToArray(); + openPopup = popup; + popup.ShowSetWidth(SETTINGS_POPUP_WIDTH_SHARE, SETTINGS_POPUP_MAX_WIDTH); + } + + private static void ShowDependencyCyclePopup() + { + BasicPopup popup = PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.cycle"), + Localization.Get("polymod.cycle.description"), + new PopupButtonData[] + { + new( + "buttons.exitgame", + PopupButtonData.States.None, + (Il2CppSystem.Action)Application.Quit, + closesPopup: false, + customColorStates: ColorConstants.redButtonColorStates + ), + } + ) + ); + popup.IsUnskippable = true; + popup.Show(); + } + + private static void DumpData() + { + Dumper.DumpAll(); + string path = Dumper.RootPath; + + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub.dump"); + popup.Description = Localization.Get("polymod.hub.dumped", Args(path)); + + void OpenDumpFolder() + { + try + { + Application.OpenURL(new Uri(path).AbsoluteUri); + } + catch (Exception exception) + { + Plugin.logger.LogError($"Could not open the dump folder at {path}: {exception}"); + } + } + + popup.buttonData = new PopupButtonData[] + { + new("polymod.hub.openfolder", callback: Callback(OpenDumpFolder)), + new("buttons.ok"), + }; + popup.Show(); + } + + private static void HotReload() + { + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub.hotreload"); + popup.Description = Localization.Get("polymod.hotreload.unavailable"); + popup.SetDefaultOkbutton(); + popup.Show(); + } + + private static string BuildModList() + { + if (Registry.mods.Count == 0) + return Muted(Localization.Get("polymod.hub.mods.none")); + + int loaded = 0; + foreach (Mod mod in Registry.mods.Values) + { + if (mod.status == Mod.Status.Success) loaded++; + } + + List blocks = new() + { + Muted(Localization.Get( + "polymod.hub.summary", + Args(loaded.ToString(), Registry.mods.Count.ToString()) + )), + }; + foreach (Mod mod in Registry.mods.Values) + { + blocks.Add(BuildModEntry(mod)); + } + return string.Join("\n\n", blocks); + } + + private static string BuildModEntry(Mod mod) + { + string status = Localization.Get( + "polymod.hub.mod.status." + Enum.GetName(mod.status)!.ToLowerInvariant() + ); + string title = $"{mod.name} " + Muted($"v{mod.version}"); + string meta = $"{status}"; + if (mod.authors.Length > 0) + { + string authors = Localization.Get( + "polymod.hub.mod.authors", + Args(string.Join(", ", mod.authors)) + ); + meta += " " + Muted($"{authors}"); + } + + List lines = new() { title, meta }; + if (!string.IsNullOrWhiteSpace(mod.description)) + lines.Add($"{mod.description}"); + + return string.Join("\n", lines); + } + + private static string BuildSettingsList() + { + List blocks = new(); + foreach (Setting setting in SETTINGS) + { + bool enabled = setting.isEnabled(); + string state = Localization.Get(enabled ? "polymod.on" : "polymod.off"); + string color = enabled ? COLOR_ENABLED : COLOR_DISABLED; + blocks.Add( + $"{Localization.Get(setting.nameKey)} {state}\n" + + Muted($"{Localization.Get(setting.descriptionKey)}") + ); + } + return string.Join("\n\n", blocks); + } + + private static string Muted(string text) => $"{text}"; + + private static string StatusColor(Mod.Status status) => status switch + { + Mod.Status.Success => COLOR_ENABLED, + Mod.Status.DependenciesUnsatisfied => COLOR_WARNING, + _ => COLOR_DISABLED, + }; + + private static int CountBrokenMods() + { + int broken = 0; + foreach (Mod mod in Registry.mods.Values) + { + if (mod.status != Mod.Status.Success) broken++; + } + return broken; + } + + private static Il2CppSystem.Action Callback(Action callback) + => DelegateSupport.ConvertDelegate(callback)!; + + private static Il2CppSystem.Object[] Args(params string[] values) + { + Il2CppSystem.Object[] arguments = new Il2CppSystem.Object[values.Length]; + for (int i = 0; i < values.Length; i++) + { + arguments[i] = values[i]; + } + return arguments; + } + + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Hub)); + } +} diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index 4388e98..65f048d 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -179,7 +179,7 @@ public static void PreloadTribePreviews() [HarmonyPatch(typeof(SelectTribePopup), nameof(SelectTribePopup.SetBackground))] private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) { - if(!Plugin.config.debug) + if(!Plugin.config.showCoordinates) return; try diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index ece1476..aa71927 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -63,9 +63,20 @@ public enum OriginType public record SkinInfo(int idx, string id, SkinData? skinData); /// A dictionary of custom widths for basic popups. - public static Dictionary basicPopupWidths = new(); + public static Dictionary basicPopupWidths = new(); + + public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); private const int BASIC_POPUP_LEGACY_ID = 29; + + /// The width the game gives its own popups, used as the floor for custom widths. + private const float DEFAULT_POPUP_WIDTH = 402f; + + /// Smallest gap left between two buttons before they are moved onto separate rows. + private const float POPUP_BUTTON_GAP = 8f; + + /// Vertical gap between two rows of popup buttons. + private const float POPUP_BUTTON_ROW_GAP = 10f; /// /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. /// @@ -230,7 +241,7 @@ private static void SpriteData_ImprovementToString(ref string __result, Improvem [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] public static void Tile_RenderDebug(Tile __instance) { - if(!Plugin.config.debug) + if(!Plugin.config.showCoordinates) return; GameObject textObj = new GameObject("CoordinateText"); @@ -354,11 +365,140 @@ private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines UpdateWidth(__instance); } - private static void UpdateWidth(PopupBase __instance) + private static void UpdateWidth(PopupBase popup) + { + if (!basicPopupWidths.TryGetValue(popup.GetInstanceID(), out PopupWidth? width)) return; + + popup.rectTransform.SetWidth(GetResponsivePopupWidth(width.share, width.maximum)); + BasicPopupLegacy? legacy = popup.TryCast(); + if (legacy != null && legacy.buttonContainer != null) + LayoutPopupButtons(legacy.buttonContainer); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.ScreenSizeChanged))] + private static void SystemEvents_ScreenSizeChanged() + { + RelayoutSizedPopups(); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.SafeAreaChanged))] + private static void SystemEvents_SafeAreaChanged() + { + RelayoutSizedPopups(); + } + + private static void RelayoutSizedPopups() + { + foreach (PopupWidth width in new List(basicPopupWidths.Values)) + { + try + { + if (width.popup == null || !width.popup.IsShowing()) continue; + width.popup.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(ScreenManager.SafeHeight); + } + catch (Exception exception) + { + Plugin.logger.LogError($"Could not lay a popup out after a screen size change: {exception}"); + } + } + } + + /// + /// Turns a share of the usable screen width into a popup width in canvas units. + /// The safe area is reported in screen pixels, so it is converted with the canvas scale the + /// game itself uses when it sizes popups. + /// + /// Share of the usable width to take, between 0 and 1. + /// Widest the popup may get, so that text stays readable on wide screens. + /// A width in canvas units, never below the width of the game's own popups. + public static int GetResponsivePopupWidth(float share, float maximum) + { + if (share <= 0f) return Mathf.RoundToInt(maximum); + float usable = ScreenManager.SafeWidth * UICanvasScalerHelper.GetInvertedUIScale(); + float width = Mathf.Min(usable * share, maximum); + return Mathf.RoundToInt(Mathf.Max(width, DEFAULT_POPUP_WIDTH)); + } + + /// + /// Replaces the game's popup button layout. The game spaces the buttons with an integer division, + /// which stacks every button but the last on the left edge, and it never wraps, so a popup too + /// narrow for its buttons draws them on top of each other. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(PopupButtonContainer), nameof(PopupButtonContainer.SetButtonData))] + private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __instance) { - int id = __instance.GetInstanceID(); - if (basicPopupWidths.ContainsKey(id)) - __instance.rectTransform.SetWidth(basicPopupWidths[id]); + LayoutPopupButtons(__instance); + } + + /// + /// Lays a popup's buttons out in as many rows as the container's width needs. + /// + internal static void LayoutPopupButtons(PopupButtonContainer container) + { + if (container.buttons == null || container.buttons.Length == 0) return; + + float available = container.rectTransform.rect.width; + if (available <= 0f) return; + + List> rows = PackButtonsIntoRows(container, available); + + float rowHeight = 0f; + foreach (UITextButton button in container.buttons) + { + rowHeight = Mathf.Max(rowHeight, button.rectTransform.rect.height); + } + float stackHeight = rows.Count * rowHeight + (rows.Count - 1) * POPUP_BUTTON_ROW_GAP; + + // The container sits at the bottom of the popup with a bottom pivot, so it grows upwards. + container.rectTransform.SetHeight(stackHeight); + + for (int row = 0; row < rows.Count; row++) + { + float offsetY = stackHeight / 2f - rowHeight / 2f - row * (rowHeight + POPUP_BUTTON_ROW_GAP); + PlaceButtonRow(rows[row], offsetY); + } + } + + /// + /// Fills one row at a time until the next button would no longer fit beside the previous ones. + /// + private static List> PackButtonsIntoRows(PopupButtonContainer container, float available) + { + List> rows = new() { new() }; + float rowWidth = 0f; + foreach (UITextButton button in container.buttons) + { + float width = button.rectTransform.rect.width; + if (rows[^1].Count > 0 && rowWidth + POPUP_BUTTON_GAP + width > available) + { + rows.Add(new()); + rowWidth = 0f; + } + rowWidth += (rows[^1].Count > 0 ? POPUP_BUTTON_GAP : 0f) + width; + rows[^1].Add(button); + } + return rows; + } + + /// + /// Spreads one row of buttons across the container, or centres it when it holds a single button. + /// + private static void PlaceButtonRow(List row, float offsetY) + { + for (int i = 0; i < row.Count; i++) + { + // Anchoring to a fraction of the container keeps the row spread as the popup resizes, + // which is how the game places the buttons of its own popups. + Vector2 anchor = new((row.Count == 1) ? 0.5f : (i / (row.Count - 1.0f)), 0.5f); + RectTransform rect = row[i].rectTransform; + rect.anchorMin = anchor; + rect.anchorMax = anchor; + rect.pivot = anchor; + rect.anchoredPosition = new Vector2(0f, offsetY); + } } /// Removes a popup's custom width when it is hidden. @@ -410,7 +550,14 @@ void WCProceed() /// Shows a basic popup with a custom width. public static void ShowSetWidth(this BasicPopupLegacy self, int width) { - basicPopupWidths.Add(self.GetInstanceID(), width); + basicPopupWidths[self.GetInstanceID()] = new(self, 0f, width); + self.Show(); + } + + /// Shows a basic popup sized to a share of the usable screen width. + public static void ShowSetWidth(this BasicPopupLegacy self, float share, float maximum) + { + basicPopupWidths[self.GetInstanceID()] = new(self, share, maximum); self.Show(); } diff --git a/src/Plugin.cs b/src/Plugin.cs index 5cc311d..25c5e1e 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -24,6 +24,7 @@ public partial class Plugin : BepInEx.Unity.IL2CPP.BasePlugin /// Whether to enable debug mode. internal record PolyConfig( bool debug = false, + bool showCoordinates = false, bool allowUnsafeIndexes = false, string overrideDeviceId = "" ) diff --git a/src/Registry.cs b/src/Registry.cs index 3943b5d..ba47160 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -70,16 +70,17 @@ public static class Registry public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it - public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1) + public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1, bool outline = false) { string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); - return GetSpriteByText(baseName, tribeText, skinText, level); + string levelText = (level == -1) ? "" : level.ToString(); + return GetSpriteByText(baseName, tribeText, skinText, levelText, outline); } /// /// Gets a sprite from the registry, trying to find the best match. /// - public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", int level = -1) + public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", string levelText = "", bool outline = false) { Sprite? sprite = null; baseName = baseName.ToLower(); @@ -88,25 +89,17 @@ public static class Registry List spriteNameVariants = new(); - if (level >= 0) - { - string levelText = level.ToString(); - spriteNameVariants.Add(baseName + "_" + levelText); - spriteNameVariants.Add(baseName + "_" + levelText + "_" + tribeText); - spriteNameVariants.Add(baseName + "_" + levelText + "_" + skinText); - spriteNameVariants.Add(baseName + "_" + levelText + "_" + tribeText + "_" + skinText); - } - else - { - spriteNameVariants.Add(baseName); - spriteNameVariants.Add(baseName + "_" + tribeText); - spriteNameVariants.Add(baseName + "_" + skinText); - spriteNameVariants.Add(baseName + "_" + tribeText + "_" + skinText); - } + if (levelText != string.Empty) + baseName += $"_{levelText}"; + + spriteNameVariants.Add(baseName); + spriteNameVariants.Add(baseName + "_" + tribeText); + spriteNameVariants.Add(baseName + "_" + skinText); + spriteNameVariants.Add(baseName + "_" + tribeText + "_" + skinText); foreach(string spriteName in spriteNameVariants) { - sprite = sprites.GetOrDefault(spriteName, sprite); + sprite = sprites.GetOrDefault(outline ? spriteName + "_outline" : spriteName, sprite); } return sprite; From 3b7e3b703ea7f5e3602a3ee3b889229bb732bcc2 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 29 Oct 2026 11:21:27 +0100 Subject: [PATCH 20/42] Weapon prefabs stuff! --- src/Dumper.cs | 19 ++++++ src/Managers/Hub.cs | 6 +- src/Managers/Prefabs.cs | 104 +++++++++++++++++++++++++++++++++ src/Managers/TribePreviews.cs | 5 ++ src/Managers/Visual.cs | 2 - src/Plugin.cs | 6 +- src/Prefabs/OtherPrefabInfo.cs | 74 +++++++++++++++++++++++ src/Prefabs/PrefabsInfo.cs | 3 + 8 files changed, 213 insertions(+), 6 deletions(-) diff --git a/src/Dumper.cs b/src/Dumper.cs index cd30c2a..032f5e4 100644 --- a/src/Dumper.cs +++ b/src/Dumper.cs @@ -237,6 +237,25 @@ internal static void DumpPrefabs() }); } + foreach (var entry in PrefabManager.weapons) + { + WeaponGFX weaponGFX = entry.Value; + prefabsInfo.weapons.Add(new WeaponPrefabInfo + { + weaponEnum = entry.Key, + spriteName = weaponGFX.defaultSprite.name, + pathType = weaponGFX.pathType, + pathMode = weaponGFX.pathMode, + pathResolution = weaponGFX.pathResolution, + pathEase = weaponGFX.pathEase, + lookAheadOffset = weaponGFX.lookAheadOffset, + handleAngleOffset = weaponGFX.handleAngleOffset, + sfxType = SFXTypes.None, //TODO + weaponPuffInfo = null, //TODO + weaponRangedInfo = null //TODO + }); + } + File.WriteAllText( Path.Combine(Plugin.PREFABS_DUMP_PATH, "prefabs.json"), JsonSerializer.Serialize(prefabsInfo, INDENTED_WITH_VECTORS) diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index e8bdd03..5a937a4 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -29,6 +29,7 @@ Action toggle private const float SETTINGS_POPUP_MAX_WIDTH = 900f; private const float START_SCREEN_MARGIN = 50f; private const float VERSION_LABEL_FONT_SIZE = 18f; + private const string INTRO = "intro.mp4"; private const KeyCode HOTKEY_MODIFIER = KeyCode.LeftControl; private const KeyCode HOTKEY_MODIFIER_ALTERNATIVE = KeyCode.RightControl; @@ -83,9 +84,8 @@ public static bool IsPopupOpen [HarmonyPatch(typeof(SplashController), nameof(SplashController.LoadAndPlayClip))] private static bool SplashController_LoadAndPlayClip(SplashController __instance) { - string name = "intro.mp4"; - string path = Path.Combine(Application.persistentDataPath, name); - File.WriteAllBytesAsync(path, Plugin.GetResource(name).ReadBytes()); + string path = Path.Combine(Application.persistentDataPath, INTRO); + File.WriteAllBytesAsync(path, Plugin.GetResource(INTRO).ReadBytes()); __instance.lastPlayTime = Time.realtimeSinceStartup; __instance.videoPlayer.url = path; __instance.videoPlayer.Play(); diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index 343aa8c..d37c8f0 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -1,4 +1,5 @@ using HarmonyLib; +using Il2CppInterop.Runtime; using Polytopia.Data; using PolytopiaBackendBase.Common; using UnityEngine; @@ -23,9 +24,23 @@ public static class Prefabs public static List resourceInfos = new(); + public static List weaponInfos = new(); + internal static Dictionary improvementPrefabInfosToCreate = new(); internal static List resourcePrefabsInfosToCreate = new(); + internal static Dictionary weaponProjectilesCache = new(); + internal static Dictionary weaponAnimTimeCache = new() + { + {UnitData.WeaponEnum.Sting, 0.5f}, + {UnitData.WeaponEnum.IceArrow, 1f}, + {UnitData.WeaponEnum.Gun, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnDarkPuff(); + {UnitData.WeaponEnum.FireBlow, 2f}, // __instance.Tile.SpawnDarkPuff(); + {UnitData.WeaponEnum.Poison, 2f}, // __instance.Tile.SpawnPoison(__instance.Owner.GetVisualSkin()); + {UnitData.WeaponEnum.Pierce, 1f}, + {UnitData.WeaponEnum.Water, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnPuff(); + }; + [HarmonyPostfix] [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] private static void PrefabManager_Awake_Postfix(PrefabManager __instance) @@ -132,6 +147,90 @@ public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovem visualSetting.hasValidOutline = flag2; } + [HarmonyPrefix] // overrides again....... + [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] + private static bool Unit_IsProjectile(ref bool __result, UnitData.WeaponEnum weapon) + { + if(!weaponProjectilesCache.ContainsKey(weapon)) + return true; + + __result = weaponProjectilesCache[weapon]; + return false; + } + + [HarmonyPrefix] // overrides again....... + [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] + private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Action onComplete) + { + UnitData.WeaponEnum weaponEnum = __instance.unitData.weapon; + List weaponPrefabInfos = weaponInfos.Where(weaponInfo => weaponInfo.weaponEnum == weaponEnum).ToList(); + if(weaponPrefabInfos.Count == 0) + return true; + + WeaponPrefabInfo weaponPrefabInfo = weaponPrefabInfos.Last(); + float chebyshevDistance = MapDataExtensions.ChebyshevDistance(__instance.Tile.Coordinates, target); + + float animationTime = 0.2f + chebyshevDistance * 0.05f; + Tile targetTile = MapRenderer.Current.GetTileInstance(target); + + WeaponGFX pooledObject = ObjectPool.GetPooledObject(GetPrefab(weaponEnum).gameObject); + pooledObject.IsUsed = true; + Vector3 center = SkinVisualsRenderer.GetSpriteBounds(__instance.skinVisuals).center; + pooledObject.transform.position = __instance.transform.position + center; + pooledObject.SetSkin(__instance.Owner.GetVisualSkin()); + + if ((bool)targetTile.Unit) + { + targetTile.Unit.Flipped = targetTile.Unit.UnitState.flipped; + } + __instance.Flipped = __instance.UnitState.flipped; + + if(weaponPrefabInfo.weaponPuffInfo != null) + { + animationTime *= weaponPrefabInfo.weaponPuffInfo.animationMultiplier; + if(weaponPrefabInfo.weaponPuffInfo.sway) + __instance.Sway(); + } + if (Unit.IsProjectile(weaponEnum)) + { + if(weaponPrefabInfo.weaponPuffInfo != null && weaponPrefabInfo.weaponPuffInfo!.animationDelegate != null) + pooledObject.AnimateRanged(animationTime, target, DelegateSupport.ConvertDelegate(weaponPrefabInfo.weaponPuffInfo!.animationDelegate!)); + else + pooledObject.AnimateRanged(animationTime, target); + } + else + { + pooledObject.AnimateCloseRangeAttack(0.2f); + } + + if (__instance.unitData.GetRange() < 2) + { + __instance.AnimateMeleeAttackMovement(targetTile, moveToTarget, onComplete); + } + else + { + GameManager.DelayCall((int)(animationTime * 1000f), onComplete); + } + + return false; + } + + [HarmonyPrefix] // testing....... + [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] + public static bool WeaponGFX_AnimateCloseRangeAttack(ref float animTime, Action onComplete) + { + animTime = 100000f; + return true; + } + + [HarmonyPrefix] // testing....... + [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] + public static bool WeaponGFX_AnimateRanged(ref float animTime, WorldCoordinates to, Action onComplete) + { + animTime = 100000f; + return true; + } + private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) { if (SeasonManager.IsChristmas() @@ -549,4 +648,9 @@ private static SkinVisualsReference.VisualPart CreateResourceVisualPart( } #endregion + + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Prefabs)); + } } \ No newline at end of file diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index 65f048d..b0c41fd 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -226,4 +226,9 @@ private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) Plugin.logger.LogWarning($"Failed to load debug tribe preview {ex.Message}"); } } + + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(TribePreviews)); + } } \ No newline at end of file diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index aa71927..ef5a062 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -982,7 +982,5 @@ public static void CreateInnerOriginSprites() internal static void Init() { Harmony.CreateAndPatchAll(typeof(Visual)); - Harmony.CreateAndPatchAll(typeof(Prefabs)); - Harmony.CreateAndPatchAll(typeof(TribePreviews)); } } diff --git a/src/Plugin.cs b/src/Plugin.cs index 25c5e1e..4803778 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -145,11 +145,15 @@ public override void Load() return; Compatibility.Init(); + Audio.Init(); Loc.Init(); + Visual.Init(); - Hub.Init(); + Prefabs.Init(); + TribePreviews.Init(); + Hub.Init(); Main.Init(); } diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index fd2eecf..a40302e 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -2,6 +2,11 @@ using System.Text.Json.Serialization; using PolyMod.Json; using Polytopia.Data; +using System; +using DG.Tweening; +using Polytopia.Data; +using PolytopiaBackendBase.Common; +using UnityEngine; namespace PolyMod; @@ -44,4 +49,73 @@ public class WeaponPrefabInfo [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public UnitData.WeaponEnum? weaponEnum = null; + + [JsonInclude] + public string spriteName = ""; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public PathType pathType = PathType.CatmullRom; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public PathMode pathMode = PathMode.Sidescroller2D; + + [JsonInclude] + public int pathResolution = 10; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public Ease pathEase = Ease.Linear; + + [JsonInclude] + public float lookAheadOffset = 0.01f; + + [JsonInclude] + public float handleAngleOffset = 0.3f; + + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public SFXTypes sfxType = SFXTypes.None; + + [JsonInclude] + public WeaponPuffInfo? weaponPuffInfo = null; + + [JsonInclude] + public WeaponRangedInfo? weaponRangedInfo = null; +} + +public class WeaponPuffInfo +{ + [JsonInclude] + public bool sway = false; + + public float animationMultiplier = 1f; + + public Action? initialDelegate = null; + + public Action? animationDelegate = null; + + // [JsonInclude] Nuh uh, I wont do ts + // public List puffsToSpawn = new(); +} + +public class WeaponRangedInfo +{ + [JsonInclude] + public float centerOffset = 0.15f; +} + +public class GFXPrefabInfo +{ + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public GFXType? gfxType = null; +} + +public class UnitEffectPrefabInfo +{ + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitEffect? unitEffect = null; } \ No newline at end of file diff --git a/src/Prefabs/PrefabsInfo.cs b/src/Prefabs/PrefabsInfo.cs index d0b4ab3..416985f 100644 --- a/src/Prefabs/PrefabsInfo.cs +++ b/src/Prefabs/PrefabsInfo.cs @@ -13,4 +13,7 @@ public class PrefabsInfo [JsonInclude] public List resources = new(); + + [JsonInclude] + public List weapons = new(); } \ No newline at end of file From d7c0ee0f0cca5aa79ec846abd2dbfc0e3bada1ca Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 29 Oct 2026 12:55:12 +0100 Subject: [PATCH 21/42] warn fix --- src/Prefabs/OtherPrefabInfo.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index a40302e..bbd854e 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -2,11 +2,7 @@ using System.Text.Json.Serialization; using PolyMod.Json; using Polytopia.Data; -using System; using DG.Tweening; -using Polytopia.Data; -using PolytopiaBackendBase.Common; -using UnityEngine; namespace PolyMod; From f72876ad8690e38e8dc6d223255211c08882c85e Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 29 Oct 2026 13:13:50 +0100 Subject: [PATCH 22/42] Dummy audio clip creation stuff --- src/Loader.cs | 23 +++++-- src/Managers/Audio.cs | 36 ++++++++-- src/Registry.cs | 27 +++++++- src/WavDecoder.cs | 157 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 231 insertions(+), 12 deletions(-) create mode 100644 src/WavDecoder.cs diff --git a/src/Loader.cs b/src/Loader.cs index 56ade47..9926193 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -658,11 +658,24 @@ public static void LoadTextureFile(Mod mod, Mod.File file) /// The audio file to load. public static void LoadAudioFile(Mod mod, Mod.File file) { - // AudioSource audioSource = new GameObject().AddComponent(); - // GameObject.DontDestroyOnLoad(audioSource); - // audioSource.clip = Managers.Audio.BuildAudioClip(file.bytes); - // Registry.audioClips.Add(Path.GetFileNameWithoutExtension(file.name), audioSource); - // TODO: issue #71 + string name = Path.GetFileNameWithoutExtension(file.name).ToLower(); + try + { + AudioClip clip = Managers.Audio.BuildAudioClip(file.bytes, name); + AudioSource audioSource = new GameObject($"PolyModAudio_{name}").AddComponent(); + UnityEngine.Object.DontDestroyOnLoad(audioSource.gameObject); + audioSource.clip = clip; + Registry.audioClips[name] = audioSource; + + Plugin.logger.LogInfo( + $"Registered audio {name} file from {mod.id} mod" + + $" ({clip.channels}ch {clip.frequency}Hz {clip.length:F2}s)." + ); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading audio {name} file from {mod.id} mod: {e.Message}"); + } } public static void LoadPrefabsFile(Mod mod, Mod.File file) diff --git a/src/Managers/Audio.cs b/src/Managers/Audio.cs index d6fb90e..aefd86c 100644 --- a/src/Managers/Audio.cs +++ b/src/Managers/Audio.cs @@ -60,15 +60,43 @@ private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, Sk return true; } + private const string CLIP_CREATION_UNAVAILABLE = + "this game build cannot create audio clips at runtime." + + " AudioClip.Create marshals its arguments as spans, and" + + " Il2CppSystem.ReadOnlySpan.GetPinnableReference() is missing from its IL2CPP build." + + " Custom audio stays disabled until the game ships calling AudioClip.Create and SetData"; + + private static bool clipCreationUnavailable = false; + /// /// Builds an audio clip from raw byte data. /// - /// The byte data of the audio file. + /// The byte data of the audio file, which has to be a WAVE file. + /// The name to give the clip inside Unity. /// The created audio clip. - public static AudioClip BuildAudioClip(byte[] data) + /// The data is not a WAVE file that can be decoded. + /// The game build cannot create audio clips. + public static AudioClip BuildAudioClip(byte[] data, string name = "polymod_audio") { - // TODO: This is a placeholder. The actual implementation is tracked in issue #71. - return new AudioClip(new()); + WavDecoder.WavData wav = WavDecoder.Decode(data); + if (clipCreationUnavailable) + throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}."); + + try + { + AudioClip clip = AudioClip.Create(name, wav.lengthSamples, wav.channels, wav.frequency, false); + if (clip == null) + throw new InvalidOperationException($"Unity returned no audio clip for {name}."); + if (!clip.SetData(wav.samples, 0)) + throw new InvalidOperationException($"Unity rejected the samples for {name}."); + return clip; + } + catch (MissingMethodException exception) + { + // Remembered so that a mod shipping many files reports this once rather than per file. + clipCreationUnavailable = true; + throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}.", exception); + } } /// diff --git a/src/Registry.cs b/src/Registry.cs index ba47160..bfb5066 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -113,13 +113,34 @@ public static class Registry /// The requested audio clip, or null if not found. public static AudioClip? GetAudioClip(string name, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default) { - AudioSource? audioSource = null; - name = name.ToLower(); string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); + return GetAudioClipByText(name, tribeText, skinText); + } + + /// + /// Gets an audio clip from the registry, trying to find the best match. + /// + public static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") + { + AudioSource? audioSource = null; + baseName = baseName.ToLower(); tribeText = tribeText.ToLower(); skinText = skinText.ToLower(); - audioSource = audioClips.GetOrDefault($"{name}_{tribeText}_{skinText}", audioSource); + + List audioNameVariants = new() + { + baseName, + baseName + "_" + tribeText, + baseName + "_" + skinText, + baseName + "_" + tribeText + "_" + skinText, + }; + + foreach (string audioName in audioNameVariants) + { + audioSource = audioClips.GetOrDefault(audioName, audioSource); + } + if (audioSource == null) return null; return audioSource.clip; } diff --git a/src/WavDecoder.cs b/src/WavDecoder.cs new file mode 100644 index 0000000..736ca52 --- /dev/null +++ b/src/WavDecoder.cs @@ -0,0 +1,157 @@ +using System.Buffers.Binary; + +namespace PolyMod; + +/// +/// Decodes RIFF WAVE files into the interleaved float samples Unity wants. +/// +public static class WavDecoder +{ + /// + /// The decoded contents of a WAVE file. + /// + /// Interleaved samples in the -1 to 1 range, channel by channel. + /// Number of channels the samples are interleaved across. + /// Sample rate in hertz. + public record WavData(float[] samples, int channels, int frequency) + { + /// Number of sample frames, which is the length Unity asks for. + public int lengthSamples => samples.Length / channels; + } + + private const ushort FORMAT_PCM = 1; + private const ushort FORMAT_FLOAT = 3; + private const ushort FORMAT_EXTENSIBLE = 0xFFFE; + + private const int HEADER_LENGTH = 12; + private const int CHUNK_HEADER_LENGTH = 8; + private const int FORMAT_CHUNK_LENGTH = 16; + private const int EXTENSIBLE_CHUNK_LENGTH = 40; + + /// + /// Decodes a WAVE file held in memory. + /// + /// The whole file, starting at its RIFF header. + /// The samples plus the channel count and sample rate needed to play them. + /// The file is not a WAVE file this can decode. + public static WavData Decode(byte[] data) + { + ReadOnlySpan file = data; + if (file.Length < HEADER_LENGTH || ReadId(file, 0) != "RIFF" || ReadId(file, 8) != "WAVE") + throw new InvalidDataException("Not a RIFF WAVE file."); + + ushort format = 0; + ushort channels = 0; + ushort bitsPerSample = 0; + int frequency = 0; + int dataOffset = -1; + int dataLength = 0; + + int offset = HEADER_LENGTH; + while (offset + CHUNK_HEADER_LENGTH <= file.Length) + { + string id = ReadId(file, offset); + uint declared = BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(offset + 4, 4)); + int payload = offset + CHUNK_HEADER_LENGTH; + int size = (int)Math.Min(declared, (uint)(file.Length - payload)); + + if (id == "fmt " && size >= FORMAT_CHUNK_LENGTH) + { + format = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload, 2)); + channels = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload + 2, 2)); + frequency = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(payload + 4, 4)); + bitsPerSample = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload + 14, 2)); + if (format == FORMAT_EXTENSIBLE && size >= EXTENSIBLE_CHUNK_LENGTH) + format = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload + 24, 2)); + } + else if (id == "data") + { + dataOffset = payload; + dataLength = size; + } + + offset = payload + size + (size & 1); + } + + if (channels < 1) throw new InvalidDataException("WAVE file declares no channels."); + if (frequency < 1) throw new InvalidDataException("WAVE file declares no sample rate."); + if (bitsPerSample < 8 || bitsPerSample % 8 != 0) + throw new InvalidDataException($"Unsupported WAVE bit depth {bitsPerSample}."); + if (dataOffset < 0) throw new InvalidDataException("WAVE file has no data chunk."); + + int bytesPerSample = bitsPerSample / 8; + int count = dataLength / bytesPerSample; + count -= count % channels; + if (count < 1) throw new InvalidDataException("WAVE file holds no samples."); + + float[] samples = ReadSamples(file.Slice(dataOffset), format, bitsPerSample, count); + return new WavData(samples, channels, frequency); + } + + private static float[] ReadSamples(ReadOnlySpan payload, ushort format, ushort bitsPerSample, int count) + { + float[] samples = new float[count]; + int step = bitsPerSample / 8; + + if (format == FORMAT_PCM) + { + switch (bitsPerSample) + { + case 8: + for (int i = 0; i < count; i++) + samples[i] = (payload[i] - 128) / 128f; + return samples; + case 16: + for (int i = 0; i < count; i++) + samples[i] = BinaryPrimitives.ReadInt16LittleEndian(payload.Slice(i * step, 2)) / 32768f; + return samples; + case 24: + for (int i = 0; i < count; i++) + { + int at = i * step; + int value = payload[at] | (payload[at + 1] << 8) | ((sbyte)payload[at + 2] << 16); + samples[i] = value / 8388608f; + } + return samples; + case 32: + for (int i = 0; i < count; i++) + samples[i] = BinaryPrimitives.ReadInt32LittleEndian(payload.Slice(i * step, 4)) / 2147483648f; + return samples; + } + } + else if (format == FORMAT_FLOAT) + { + switch (bitsPerSample) + { + case 32: + for (int i = 0; i < count; i++) + samples[i] = BitConverter.Int32BitsToSingle( + BinaryPrimitives.ReadInt32LittleEndian(payload.Slice(i * step, 4)) + ); + return samples; + case 64: + for (int i = 0; i < count; i++) + samples[i] = (float)BitConverter.Int64BitsToDouble( + BinaryPrimitives.ReadInt64LittleEndian(payload.Slice(i * step, 8)) + ); + return samples; + } + } + + throw new InvalidDataException( + $"Unsupported WAVE format {format} at {bitsPerSample} bits per sample. " + + "Save the file as PCM or float WAVE." + ); + } + + private static string ReadId(ReadOnlySpan file, int offset) + { + return new string(new char[] + { + (char)file[offset], + (char)file[offset + 1], + (char)file[offset + 2], + (char)file[offset + 3], + }); + } +} From 5940444869dc3031255615f6fbaf0bffd3bc2bd9 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 29 Oct 2026 14:13:19 +0100 Subject: [PATCH 23/42] fix for the polymod ver position and text --- src/Managers/Hub.cs | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 5a937a4..99db641 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -29,6 +29,9 @@ Action toggle private const float SETTINGS_POPUP_MAX_WIDTH = 900f; private const float START_SCREEN_MARGIN = 50f; private const float VERSION_LABEL_FONT_SIZE = 18f; + private const float VERSION_LABEL_GAP = 10f; + /// Margin the game keeps between the safe area and its own corner widgets. + private const float VERSION_LABEL_MARGIN = 15f; private const string INTRO = "intro.mp4"; private const KeyCode HOTKEY_MODIFIER = KeyCode.LeftControl; @@ -103,7 +106,10 @@ private static void StartScreen_UI2_Init(RectTransform transform) brokenModsBadge = UILibrary.NewNotificationBadge(polyModButton.rectTransform).SetValue(CountBrokenMods()); polyModButton.SetOverlay(brokenModsBadge, UIButtonBase_UI2.OverlayPosition.TopRight); - polyModVersion = UILibrary.NewText(transform, "PolyModVersion"); + // NewHeaderTinyText is the prefab a round button builds its own title from, so the label + // keeps the game's header font rather than the lighter body font NewText would give it. + polyModVersion = UILibrary.NewHeaderTinyText(transform); + polyModVersion.gameObject.name = "PolyModVersion"; polyModVersion.textField.fontSize = VERSION_LABEL_FONT_SIZE; polyModVersion.textField.color = Color.white; polyModVersion.Text = $"PolyMod {Plugin.VERSION}"; @@ -117,7 +123,7 @@ private static void StartScreen_UI2_Init(RectTransform transform) /// [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RunLayout))] - private static void StartScreen_UI2_RunLayout(ScreenBase_UI2.ScreenSize screenSize) + private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, ScreenBase_UI2.ScreenSize screenSize) { if (polyModButton == null || polyModVersion == null) { @@ -136,10 +142,22 @@ private static void StartScreen_UI2_RunLayout(ScreenBase_UI2.ScreenSize screenSi ); brokenModsBadge?.SetValue(CountBrokenMods()); - polyModVersion.SetPosition( - screenSize.safeRect.Left + START_SCREEN_MARGIN * 1.15f, - screenSize.safeRect.Bottom + START_SCREEN_MARGIN * 1.15f - ); + // Anchored by its edges, not its centre, so a longer version string cannot run off screen. + float versionX = screenSize.safeRect.Left + VERSION_LABEL_MARGIN + polyModVersion.GetHalfWidth(); + float versionY = screenSize.safeRect.Bottom + VERSION_LABEL_MARGIN + polyModVersion.GetHalfHeight(); + polyModVersion.SetPosition(versionX, versionY); + + // The bottom row of buttons is centred and of fixed width, so a narrow window walks it into + // the version label. The row is already laid out by now, so lift the label clear of it. + UIRoundButton_UI2 bottomRowStart = __instance.settingsButton; + if (bottomRowStart != null + && polyModVersion.GetRight() + VERSION_LABEL_GAP > bottomRowStart.GetLeft()) + { + polyModVersion.SetPosition( + versionX, + bottomRowStart.GetTop() + polyModVersion.GetHalfHeight() + VERSION_LABEL_GAP + ); + } } [HarmonyPostfix] From b23a6cdde1ae343f2dc8d126b9e4a33653649ee8 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sun, 1 Nov 2026 17:51:42 +0100 Subject: [PATCH 24/42] removed debug stuff --- src/Managers/Prefabs.cs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index d37c8f0..b93c3c1 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -215,21 +215,21 @@ private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool m return false; } - [HarmonyPrefix] // testing....... - [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] - public static bool WeaponGFX_AnimateCloseRangeAttack(ref float animTime, Action onComplete) - { - animTime = 100000f; - return true; - } - - [HarmonyPrefix] // testing....... - [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] - public static bool WeaponGFX_AnimateRanged(ref float animTime, WorldCoordinates to, Action onComplete) - { - animTime = 100000f; - return true; - } + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] + // public static bool WeaponGFX_AnimateCloseRangeAttack(ref float animTime, Action onComplete) + // { + // animTime = 100000f; + // return true; + // } + + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] + // public static bool WeaponGFX_AnimateRanged(ref float animTime, WorldCoordinates to, Action onComplete) + // { + // animTime = 100000f; + // return true; + // } private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) { From 852c79648c531e14dc06277db1e5b62d8bee5d55 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sun, 1 Nov 2026 18:40:45 +0100 Subject: [PATCH 25/42] Disabled all of the weapons related stuff --- src/Dumper.cs | 37 ++++----- src/Managers/Prefabs.cs | 140 ++++++++++++++++----------------- src/Prefabs/OtherPrefabInfo.cs | 46 +++++------ src/Prefabs/PrefabsInfo.cs | 4 +- 4 files changed, 113 insertions(+), 114 deletions(-) diff --git a/src/Dumper.cs b/src/Dumper.cs index 032f5e4..0bd3c20 100644 --- a/src/Dumper.cs +++ b/src/Dumper.cs @@ -237,24 +237,25 @@ internal static void DumpPrefabs() }); } - foreach (var entry in PrefabManager.weapons) - { - WeaponGFX weaponGFX = entry.Value; - prefabsInfo.weapons.Add(new WeaponPrefabInfo - { - weaponEnum = entry.Key, - spriteName = weaponGFX.defaultSprite.name, - pathType = weaponGFX.pathType, - pathMode = weaponGFX.pathMode, - pathResolution = weaponGFX.pathResolution, - pathEase = weaponGFX.pathEase, - lookAheadOffset = weaponGFX.lookAheadOffset, - handleAngleOffset = weaponGFX.handleAngleOffset, - sfxType = SFXTypes.None, //TODO - weaponPuffInfo = null, //TODO - weaponRangedInfo = null //TODO - }); - } + // TODO + // foreach (var entry in PrefabManager.weapons) + // { + // WeaponGFX weaponGFX = entry.Value; + // prefabsInfo.weapons.Add(new WeaponPrefabInfo + // { + // weaponEnum = entry.Key, + // spriteName = weaponGFX.defaultSprite.name, + // pathType = weaponGFX.pathType, + // pathMode = weaponGFX.pathMode, + // pathResolution = weaponGFX.pathResolution, + // pathEase = weaponGFX.pathEase, + // lookAheadOffset = weaponGFX.lookAheadOffset, + // handleAngleOffset = weaponGFX.handleAngleOffset, + // sfxType = SFXTypes.None, //TODO + // weaponPuffInfo = null, //TODO + // weaponRangedInfo = null //TODO + // }); + // } File.WriteAllText( Path.Combine(Plugin.PREFABS_DUMP_PATH, "prefabs.json"), diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index b93c3c1..3295f59 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -20,17 +20,15 @@ public static class Prefabs public static List unitInfos = new(); - public static List improvementInfos = new(); - public static List resourceInfos = new(); - public static List weaponInfos = new(); - + public static List improvementInfos = new(); internal static Dictionary improvementPrefabInfosToCreate = new(); internal static List resourcePrefabsInfosToCreate = new(); - internal static Dictionary weaponProjectilesCache = new(); - internal static Dictionary weaponAnimTimeCache = new() + private static List weaponInfos = new(); + private static Dictionary weaponProjectilesCache = new(); + private static Dictionary weaponAnimTimeCache = new() { {UnitData.WeaponEnum.Sting, 0.5f}, {UnitData.WeaponEnum.IceArrow, 1f}, @@ -147,73 +145,73 @@ public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovem visualSetting.hasValidOutline = flag2; } - [HarmonyPrefix] // overrides again....... - [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] - private static bool Unit_IsProjectile(ref bool __result, UnitData.WeaponEnum weapon) - { - if(!weaponProjectilesCache.ContainsKey(weapon)) - return true; - - __result = weaponProjectilesCache[weapon]; - return false; - } - - [HarmonyPrefix] // overrides again....... - [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] - private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Action onComplete) - { - UnitData.WeaponEnum weaponEnum = __instance.unitData.weapon; - List weaponPrefabInfos = weaponInfos.Where(weaponInfo => weaponInfo.weaponEnum == weaponEnum).ToList(); - if(weaponPrefabInfos.Count == 0) - return true; - - WeaponPrefabInfo weaponPrefabInfo = weaponPrefabInfos.Last(); - float chebyshevDistance = MapDataExtensions.ChebyshevDistance(__instance.Tile.Coordinates, target); - - float animationTime = 0.2f + chebyshevDistance * 0.05f; - Tile targetTile = MapRenderer.Current.GetTileInstance(target); - - WeaponGFX pooledObject = ObjectPool.GetPooledObject(GetPrefab(weaponEnum).gameObject); - pooledObject.IsUsed = true; - Vector3 center = SkinVisualsRenderer.GetSpriteBounds(__instance.skinVisuals).center; - pooledObject.transform.position = __instance.transform.position + center; - pooledObject.SetSkin(__instance.Owner.GetVisualSkin()); - - if ((bool)targetTile.Unit) - { - targetTile.Unit.Flipped = targetTile.Unit.UnitState.flipped; - } - __instance.Flipped = __instance.UnitState.flipped; - - if(weaponPrefabInfo.weaponPuffInfo != null) - { - animationTime *= weaponPrefabInfo.weaponPuffInfo.animationMultiplier; - if(weaponPrefabInfo.weaponPuffInfo.sway) - __instance.Sway(); - } - if (Unit.IsProjectile(weaponEnum)) - { - if(weaponPrefabInfo.weaponPuffInfo != null && weaponPrefabInfo.weaponPuffInfo!.animationDelegate != null) - pooledObject.AnimateRanged(animationTime, target, DelegateSupport.ConvertDelegate(weaponPrefabInfo.weaponPuffInfo!.animationDelegate!)); - else - pooledObject.AnimateRanged(animationTime, target); - } - else - { - pooledObject.AnimateCloseRangeAttack(0.2f); - } + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] + // private static bool Unit_IsProjectile(ref bool __result, UnitData.WeaponEnum weapon) + // { + // if(!weaponProjectilesCache.ContainsKey(weapon)) + // return true; - if (__instance.unitData.GetRange() < 2) - { - __instance.AnimateMeleeAttackMovement(targetTile, moveToTarget, onComplete); - } - else - { - GameManager.DelayCall((int)(animationTime * 1000f), onComplete); - } + // __result = weaponProjectilesCache[weapon]; + // return false; + // } - return false; - } + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] + // private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Action onComplete) + // { + // UnitData.WeaponEnum weaponEnum = __instance.unitData.weapon; + // List weaponPrefabInfos = weaponInfos.Where(weaponInfo => weaponInfo.weaponEnum == weaponEnum).ToList(); + // if(weaponPrefabInfos.Count == 0) + // return true; + + // WeaponPrefabInfo weaponPrefabInfo = weaponPrefabInfos.Last(); + // float chebyshevDistance = MapDataExtensions.ChebyshevDistance(__instance.Tile.Coordinates, target); + + // float animationTime = 0.2f + chebyshevDistance * 0.05f; + // Tile targetTile = MapRenderer.Current.GetTileInstance(target); + + // WeaponGFX pooledObject = ObjectPool.GetPooledObject(GetPrefab(weaponEnum).gameObject); + // pooledObject.IsUsed = true; + // Vector3 center = SkinVisualsRenderer.GetSpriteBounds(__instance.skinVisuals).center; + // pooledObject.transform.position = __instance.transform.position + center; + // pooledObject.SetSkin(__instance.Owner.GetVisualSkin()); + + // if ((bool)targetTile.Unit) + // { + // targetTile.Unit.Flipped = targetTile.Unit.UnitState.flipped; + // } + // __instance.Flipped = __instance.UnitState.flipped; + + // if(weaponPrefabInfo.weaponPuffInfo != null) + // { + // animationTime *= weaponPrefabInfo.weaponPuffInfo.animationMultiplier; + // if(weaponPrefabInfo.weaponPuffInfo.sway) + // __instance.Sway(); + // } + // if (Unit.IsProjectile(weaponEnum)) + // { + // if(weaponPrefabInfo.weaponPuffInfo != null && weaponPrefabInfo.weaponPuffInfo!.animationDelegate != null) + // pooledObject.AnimateRanged(animationTime, target, DelegateSupport.ConvertDelegate(weaponPrefabInfo.weaponPuffInfo!.animationDelegate!)); + // else + // pooledObject.AnimateRanged(animationTime, target); + // } + // else + // { + // pooledObject.AnimateCloseRangeAttack(0.2f); + // } + + // if (__instance.unitData.GetRange() < 2) + // { + // __instance.AnimateMeleeAttackMovement(targetTile, moveToTarget, onComplete); + // } + // else + // { + // GameManager.DelayCall((int)(animationTime * 1000f), onComplete); + // } + + // return false; + // } // [HarmonyPrefix] // testing....... // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index bbd854e..1b5ca10 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -40,78 +40,78 @@ public class ResourcePrefabInfo : BasePrefabInfo public ResourceData.Type? resourceType = null; } -public class WeaponPrefabInfo +internal class WeaponPrefabInfo { [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] - public UnitData.WeaponEnum? weaponEnum = null; + internal UnitData.WeaponEnum? weaponEnum = null; [JsonInclude] - public string spriteName = ""; + internal string spriteName = ""; [JsonInclude] [JsonConverter(typeof(EnumNameJson))] - public PathType pathType = PathType.CatmullRom; + internal PathType pathType = PathType.CatmullRom; [JsonInclude] [JsonConverter(typeof(EnumNameJson))] - public PathMode pathMode = PathMode.Sidescroller2D; + internal PathMode pathMode = PathMode.Sidescroller2D; [JsonInclude] - public int pathResolution = 10; + internal int pathResolution = 10; [JsonInclude] [JsonConverter(typeof(EnumNameJson))] - public Ease pathEase = Ease.Linear; + internal Ease pathEase = Ease.Linear; [JsonInclude] - public float lookAheadOffset = 0.01f; + internal float lookAheadOffset = 0.01f; [JsonInclude] - public float handleAngleOffset = 0.3f; + internal float handleAngleOffset = 0.3f; [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] - public SFXTypes sfxType = SFXTypes.None; + internal SFXTypes sfxType = SFXTypes.None; [JsonInclude] - public WeaponPuffInfo? weaponPuffInfo = null; + internal WeaponPuffInfo? weaponPuffInfo = null; [JsonInclude] - public WeaponRangedInfo? weaponRangedInfo = null; + internal WeaponRangedInfo? weaponRangedInfo = null; } -public class WeaponPuffInfo +internal class WeaponPuffInfo { [JsonInclude] - public bool sway = false; + internal bool sway = false; - public float animationMultiplier = 1f; + internal float animationMultiplier = 1f; - public Action? initialDelegate = null; + internal Action? initialDelegate = null; - public Action? animationDelegate = null; + internal Action? animationDelegate = null; // [JsonInclude] Nuh uh, I wont do ts // public List puffsToSpawn = new(); } -public class WeaponRangedInfo +internal class WeaponRangedInfo { [JsonInclude] - public float centerOffset = 0.15f; + internal float centerOffset = 0.15f; } -public class GFXPrefabInfo +internal class GFXPrefabInfo { [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] - public GFXType? gfxType = null; + internal GFXType? gfxType = null; } -public class UnitEffectPrefabInfo +internal class UnitEffectPrefabInfo { [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] - public UnitEffect? unitEffect = null; + internal UnitEffect? unitEffect = null; } \ No newline at end of file diff --git a/src/Prefabs/PrefabsInfo.cs b/src/Prefabs/PrefabsInfo.cs index 416985f..09c867e 100644 --- a/src/Prefabs/PrefabsInfo.cs +++ b/src/Prefabs/PrefabsInfo.cs @@ -14,6 +14,6 @@ public class PrefabsInfo [JsonInclude] public List resources = new(); - [JsonInclude] - public List weapons = new(); + // [JsonInclude] + private List weapons = new(); } \ No newline at end of file From 2da85e20c9548c46c3783b650daaabb185f38107 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 2 Nov 2026 19:50:18 +0100 Subject: [PATCH 26/42] rewrote checksums, added editorconfig for formatting, formatted every file --- .editorconfig | 42 +++ Directory.Build.props | 14 + resources/localization.json | 8 + src/Api/Config.cs | 214 +++++------ src/Api/GLDConfig.cs | 154 ++++---- src/Api/PolyScript.cs | 80 ++--- src/Json/EnumCacheJson.cs | 224 ++++++------ src/Json/EnumNameJson.cs | 30 +- src/Json/JsonMerger.cs | 188 +++++----- src/Json/Vector2Json.cs | 70 ++-- src/Json/VersionJson.cs | 42 +-- src/Loader.cs | 42 +-- src/Managers/Audio.cs | 180 +++++----- src/Managers/Compatibility.cs | 617 ++++++++++++++++++-------------- src/Managers/Hub.cs | 40 ++- src/Managers/Loc.cs | 318 ++++++++-------- src/Managers/Main.cs | 3 +- src/Managers/Prefabs.cs | 289 ++++++++------- src/Managers/TribePreviews.cs | 38 +- src/Managers/Visual.cs | 488 ++++++++++++------------- src/Mod.cs | 199 +++++----- src/NullableFix.cs | 82 ++--- src/Plugin.cs | 175 ++++----- src/Prefabs/OtherPrefabInfo.cs | 100 +++--- src/Prefabs/PrefabsInfo.cs | 18 +- src/Prefabs/SkinnedKey.cs | 74 ++-- src/Prefabs/VisualPartInfo.cs | 104 +++--- src/Registry.cs | 67 ++-- src/Util.cs | 240 +++++++------ tests/CheckDependenciesTests.cs | 94 ++--- tests/CompatibilityTests.cs | 134 +++++++ tests/LoaderTests.cs | 96 ++--- tests/ModFactory.cs | 18 +- tests/TestSetup.cs | 40 +-- tests/UtilTests.cs | 52 +-- tests/VersionJsonTests.cs | 16 +- 36 files changed, 2458 insertions(+), 2132 deletions(-) create mode 100644 .editorconfig create mode 100644 Directory.Build.props create mode 100644 tests/CompatibilityTests.cs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a62b01d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,42 @@ +root = true + +[*] +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{json,yml,yaml}] +indent_style = space +indent_size = 2 + +[*.cs] +indent_style = tab +tab_width = 4 +indent_size = 4 +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_style_var_when_type_is_apparent = true:suggestion +dotnet_style_qualification_for_field = false:warning +dotnet_style_qualification_for_property = false:warning +dotnet_style_qualification_for_method = false:warning +csharp_prefer_braces = when_multiline:suggestion +dotnet_diagnostic.IDE0005.severity = warning +dotnet_diagnostic.CS4014.severity = warning +dotnet_diagnostic.IDE0051.severity = none +dotnet_diagnostic.IDE0060.severity = none +dotnet_diagnostic.CA1707.severity = none +dotnet_diagnostic.CA1051.severity = none +dotnet_diagnostic.CA2211.severity = none +dotnet_diagnostic.CA1805.severity = suggestion +dotnet_diagnostic.CA1716.severity = none +dotnet_diagnostic.CA1708.severity = none +dotnet_diagnostic.CS1591.severity = none +dotnet_diagnostic.CS1573.severity = none diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..66f37af --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,14 @@ + + + + true + latest + Recommended + true + + + true + $(NoWarn);CS1591 + + + diff --git a/resources/localization.json b/resources/localization.json index 455c1ef..51fba0d 100644 --- a/resources/localization.json +++ b/resources/localization.json @@ -267,6 +267,14 @@ "English": "by {0}", "Russian": "от {0}" }, + "polymod_hub_mod_checksum": { + "English": "checksum {0}", + "Russian": "контрольная сумма {0}" + }, + "polymod_hub_checksum": { + "English": "Global checksum: {0}", + "Russian": "Общая контрольная сумма: {0}" + }, "polymod_hub_config_debug": { "English": "DEBUG", "Russian": "ОТЛАДКА" diff --git a/src/Api/Config.cs b/src/Api/Config.cs index f253bf8..3e6d2a2 100644 --- a/src/Api/Config.cs +++ b/src/Api/Config.cs @@ -8,113 +8,113 @@ namespace PolyMod.Api; /// public class Config where T : class { - private T? currentConfig; - private readonly string modName; - private readonly ConfigTypes configType; - private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string perModConfigPath; - private T? defaultConfig; - public Config(string modName, ConfigTypes configType) - { - this.modName = modName; - this.configType = configType; - perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); - Load(); - } + private T? currentConfig; + private readonly string modName; + private readonly ConfigTypes configType; + private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); + private readonly string perModConfigPath; + private T? defaultConfig; + public Config(string modName, ConfigTypes configType) + { + this.modName = modName; + this.configType = configType; + perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); + Load(); + } - internal void Load() // can be called internally if config changes; gui config not implemented yet - { - switch (configType) - { - case ConfigTypes.PerMod: - { - if (!File.Exists(perModConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(perModConfigPath); - currentConfig = JsonSerializer.Deserialize(jsonText); - break; - } - case ConfigTypes.Exposed: - { - if (!File.Exists(ExposedConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(ExposedConfigPath); - currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); - break; - } - default: - throw new ArgumentOutOfRangeException(); - } - } - /// - /// Sets the default if the config does not exist yet. Always call this before reading from the config. - /// - public void SetDefaultConfig(T defaultValue) - { - defaultConfig = defaultValue; - if (currentConfig is not null) return; - Write(defaultConfig); - SaveChanges(); - } + internal void Load() // can be called internally if config changes; gui config not implemented yet + { + switch (configType) + { + case ConfigTypes.PerMod: + { + if (!File.Exists(perModConfigPath)) + { + return; + } + var jsonText = File.ReadAllText(perModConfigPath); + currentConfig = JsonSerializer.Deserialize(jsonText); + break; + } + case ConfigTypes.Exposed: + { + if (!File.Exists(ExposedConfigPath)) + { + return; + } + var jsonText = File.ReadAllText(ExposedConfigPath); + currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); + break; + } + default: + throw new ArgumentOutOfRangeException(); + } + } + /// + /// Sets the default if the config does not exist yet. Always call this before reading from the config. + /// + public void SetDefaultConfig(T defaultValue) + { + defaultConfig = defaultValue; + if (currentConfig is not null) return; + Write(defaultConfig); + SaveChanges(); + } - /// - /// Writes the **entire** config. Usage not recommended, use Edit() instead - /// - public void Write(T config) - { - currentConfig = config; - } - /// - /// Gets the config. Should only be called after setting a default. - /// - public T Get() - { - return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); - } - /// - /// Edits the config. Should only be called after setting a default. - /// - /// Call SaveChanges after editing - public void Edit(Action editor) - { - editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Gets part of the config. Should only be called after setting a default - /// - public TResult Get(Func getter) - { - return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Writes the config to disk - /// - public void SaveChanges() - { - switch (configType) - { - case ConfigTypes.PerMod: - var perModJson = JsonSerializer.Serialize(currentConfig, new JsonSerializerOptions { WriteIndented = true }); - File.WriteAllText(perModConfigPath, perModJson); - break; - case ConfigTypes.Exposed: - var modsConfigText = File.ReadAllText(ExposedConfigPath); - var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); - modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); - File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); - break; - default: - throw new ArgumentOutOfRangeException(); - } - } + /// + /// Writes the **entire** config. Usage not recommended, use Edit() instead + /// + public void Write(T config) + { + currentConfig = config; + } + /// + /// Gets the config. Should only be called after setting a default. + /// + public T Get() + { + return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); + } + /// + /// Edits the config. Should only be called after setting a default. + /// + /// Call SaveChanges after editing + public void Edit(Action editor) + { + editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); + } + /// + /// Gets part of the config. Should only be called after setting a default + /// + public TResult Get(Func getter) + { + return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); + } + /// + /// Writes the config to disk + /// + public void SaveChanges() + { + switch (configType) + { + case ConfigTypes.PerMod: + var perModJson = JsonSerializer.Serialize(currentConfig, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(perModConfigPath, perModJson); + break; + case ConfigTypes.Exposed: + var modsConfigText = File.ReadAllText(ExposedConfigPath); + var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); + modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); + File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } - public enum ConfigTypes - { - PerMod, - Exposed - } -} \ No newline at end of file + public enum ConfigTypes + { + PerMod, + Exposed + } +} diff --git a/src/Api/GLDConfig.cs b/src/Api/GLDConfig.cs index ecda511..8ff0e62 100644 --- a/src/Api/GLDConfig.cs +++ b/src/Api/GLDConfig.cs @@ -7,88 +7,88 @@ namespace PolyMod.Api; public class GldConfigTemplate { - private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); + private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string templateText; - private JsonObject currentConfig = new(); - private string modName; + private readonly string templateText; + private JsonObject currentConfig = new(); + private string modName; - public GldConfigTemplate(string templateText, string modName) - { - this.templateText = templateText; - this.modName = modName; - Load(); - } - private void Load() - { - if (File.Exists(ConfigPath)) - { - var json = File.ReadAllText(ConfigPath); - if (JsonNode.Parse(json) is JsonObject modsConfig - && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) - && modConfigNode is JsonObject modConfig) - { - currentConfig = modConfig; - return; - } - } - currentConfig = new JsonObject(); - } + public GldConfigTemplate(string templateText, string modName) + { + this.templateText = templateText; + this.modName = modName; + Load(); + } + private void Load() + { + if (File.Exists(ConfigPath)) + { + var json = File.ReadAllText(ConfigPath); + if (JsonNode.Parse(json) is JsonObject modsConfig + && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) + && modConfigNode is JsonObject modConfig) + { + currentConfig = modConfig; + return; + } + } + currentConfig = new JsonObject(); + } - public string? Render() - { - if (!templateText.Contains("{{")) return templateText; - var template = Template.Parse(templateText); - var context = new TemplateContext(); - var scriptObject = new ScriptObject(); + public string? Render() + { + if (!templateText.Contains("{{")) return templateText; + var template = Template.Parse(templateText); + var context = new TemplateContext(); + var scriptObject = new ScriptObject(); - bool changedConfig = false; - scriptObject.Import("config", - new Func((key, defaultValue) => - { - if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) - { - return token.ToString(); - } + bool changedConfig = false; + scriptObject.Import("config", + new Func((key, defaultValue) => + { + if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) + { + return token.ToString(); + } - changedConfig = true; - currentConfig[key] = defaultValue; + changedConfig = true; + currentConfig[key] = defaultValue; - return defaultValue; - }) - ); - context.PushGlobal(scriptObject); - string? result; - try - { - result = template.Render(context); - } - catch (Exception e) - { - Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); - result = null; - } - if (changedConfig) - { - SaveChanges(); - } - return result; - } + return defaultValue; + }) + ); + context.PushGlobal(scriptObject); + string? result; + try + { + result = template.Render(context); + } + catch (Exception e) + { + Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); + result = null; + } + if (changedConfig) + { + SaveChanges(); + } + return result; + } - public void SaveChanges() - { - JsonObject modsConfigJson; - if (File.Exists(ConfigPath)) - { - var modsConfigText = File.ReadAllText(ConfigPath); - modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); - } - else - { - modsConfigJson = new JsonObject(); - } + public void SaveChanges() + { + JsonObject modsConfigJson; + if (File.Exists(ConfigPath)) + { + var modsConfigText = File.ReadAllText(ConfigPath); + modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); + } + else + { + modsConfigJson = new JsonObject(); + } - modsConfigJson[modName] = currentConfig; - File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); - } -} \ No newline at end of file + modsConfigJson[modName] = currentConfig; + File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + } +} diff --git a/src/Api/PolyScript.cs b/src/Api/PolyScript.cs index 09fd36e..6dd697e 100644 --- a/src/Api/PolyScript.cs +++ b/src/Api/PolyScript.cs @@ -5,50 +5,50 @@ namespace PolyMod.Api; public abstract class PolyScriptBase { - /// - /// Initializes the PolyScript with the given mod and logger. - /// - /// The mod instance. - /// The logger instance. - internal abstract void Initialize(Mod mod, ManualLogSource logger); - - /// > - /// Called when the mod is loaded. - /// - public abstract void Load(); - - /// - /// Called when the mod is unloaded. - /// - public abstract void Unload(); - - internal PolyScriptBase() - { - } + /// + /// Initializes the PolyScript with the given mod and logger. + /// + /// The mod instance. + /// The logger instance. + internal abstract void Initialize(Mod mod, ManualLogSource logger); + + /// > + /// Called when the mod is loaded. + /// + public abstract void Load(); + + /// + /// Called when the mod is unloaded. + /// + public abstract void Unload(); + + internal PolyScriptBase() + { + } } public abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class { - internal override void Initialize(Mod mod, ManualLogSource logger) - { - Mod = mod; - Config = new Config(mod.id, Config.ConfigTypes.PerMod); - ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); - Logger = logger; - } - - internal byte[]? GetFile(string fileName) - { - return Registry.mods[Mod.id].files.FirstOrDefault(f => f.name == fileName)?.bytes; - } - - public override void Unload() { } - - public Mod Mod { get; private set; } = null!; - protected Config Config { get; private set; } = null!; - protected Config ExposedConfig { get; private set; } = null!; - protected ManualLogSource Logger { get; private set; } = null!; + internal override void Initialize(Mod mod, ManualLogSource logger) + { + Mod = mod; + Config = new Config(mod.id, Config.ConfigTypes.PerMod); + ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); + Logger = logger; + } + + internal byte[]? GetFile(string fileName) + { + return Registry.mods[Mod.id].files.FirstOrDefault(f => f.name == fileName)?.bytes; + } + + public override void Unload() { } + + public Mod Mod { get; private set; } = null!; + protected Config Config { get; private set; } = null!; + protected Config ExposedConfig { get; private set; } = null!; + protected ManualLogSource Logger { get; private set; } = null!; } public abstract class PolyScript : PolyScript { -} \ No newline at end of file +} diff --git a/src/Json/EnumCacheJson.cs b/src/Json/EnumCacheJson.cs index 5f561c6..b0545f8 100644 --- a/src/Json/EnumCacheJson.cs +++ b/src/Json/EnumCacheJson.cs @@ -11,70 +11,70 @@ namespace PolyMod.Json; /// The enum type being converted. public class EnumCacheJson : JsonConverter where T : struct, Enum { - /// - /// Determines whether the converter can handle the given type. - /// Supports both the enum type and . - /// - /// The type to check for compatibility. - /// True if the type can be converted; otherwise false. - public override bool CanConvert(Type typeToConvert) - { - return typeToConvert == typeof(T) || typeToConvert == typeof(List); - } - - /// - /// Reads a JSON string and converts it into the corresponding enum value - /// using the EnumCache lookup. - /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// The enum value represented by the JSON string. - /// Thrown if the type is not supported. - public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (typeToConvert == typeof(T)) - { - return EnumCache.GetType(reader.GetString()); - } - - throw new NotSupportedException("EnumCacheJson does not support reading this type directly."); - } - - - /// - /// Writes the enum value as its cached string representation. - /// - /// The JSON writer. - /// The enum value to write. - /// Serialization options. - public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) - { - writer.WriteStringValue(EnumCache.GetName(value)); - } - - /// - /// Reads a JSON property name and converts it into the corresponding enum value. - /// - /// The JSON reader. - /// The target type. - /// Serialization options. - /// The enum value represented by the property name. - public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return Read(ref reader, typeToConvert, options); - } - - /// - /// Writes the enum value as a property name using its cached string representation. - /// - /// The JSON writer. - /// The enum value to write. - /// Serialization options. - public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options) - { - writer.WritePropertyName(EnumCache.GetName(value)); - } + /// + /// Determines whether the converter can handle the given type. + /// Supports both the enum type and . + /// + /// The type to check for compatibility. + /// True if the type can be converted; otherwise false. + public override bool CanConvert(Type typeToConvert) + { + return typeToConvert == typeof(T) || typeToConvert == typeof(List); + } + + /// + /// Reads a JSON string and converts it into the corresponding enum value + /// using the EnumCache lookup. + /// + /// The JSON reader. + /// The type to convert into. + /// Serialization options. + /// The enum value represented by the JSON string. + /// Thrown if the type is not supported. + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (typeToConvert == typeof(T)) + { + return EnumCache.GetType(reader.GetString()); + } + + throw new NotSupportedException("EnumCacheJson does not support reading this type directly."); + } + + + /// + /// Writes the enum value as its cached string representation. + /// + /// The JSON writer. + /// The enum value to write. + /// Serialization options. + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + writer.WriteStringValue(EnumCache.GetName(value)); + } + + /// + /// Reads a JSON property name and converts it into the corresponding enum value. + /// + /// The JSON reader. + /// The target type. + /// Serialization options. + /// The enum value represented by the property name. + public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return Read(ref reader, typeToConvert, options); + } + + /// + /// Writes the enum value as a property name using its cached string representation. + /// + /// The JSON writer. + /// The enum value to write. + /// Serialization options. + public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + writer.WritePropertyName(EnumCache.GetName(value)); + } } /// @@ -84,52 +84,52 @@ public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSer /// The enum type being converted. public class EnumCacheListJson : JsonConverter> where T : struct, Enum { - /// - /// Inner converter used to handle individual enum values. - /// - private readonly EnumCacheJson _inner = new(); - - /// - /// Reads a JSON array of enum string values and converts them into a list of enum values. - /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// A list of enum values. - /// Thrown if the JSON is not an array. - public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var list = new List(); - - if (reader.TokenType != JsonTokenType.StartArray) - throw new JsonException("Expected StartArray token for enum list"); - - while (reader.Read()) - { - if (reader.TokenType == JsonTokenType.EndArray) - break; - - list.Add(_inner.Read(ref reader, typeof(T), options)); - } - - return list; - } - - /// - /// Writes a list of enum values as a JSON array of strings. - /// - /// The JSON writer. - /// The list of enum values to write. - /// Serialization options. - public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) - { - writer.WriteStartArray(); - - foreach (var item in value) - { - _inner.Write(writer, item, options); - } - - writer.WriteEndArray(); - } + /// + /// Inner converter used to handle individual enum values. + /// + private readonly EnumCacheJson _inner = new(); + + /// + /// Reads a JSON array of enum string values and converts them into a list of enum values. + /// + /// The JSON reader. + /// The type to convert into. + /// Serialization options. + /// A list of enum values. + /// Thrown if the JSON is not an array. + public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var list = new List(); + + if (reader.TokenType != JsonTokenType.StartArray) + throw new JsonException("Expected StartArray token for enum list"); + + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndArray) + break; + + list.Add(_inner.Read(ref reader, typeof(T), options)); + } + + return list; + } + + /// + /// Writes a list of enum values as a JSON array of strings. + /// + /// The JSON writer. + /// The list of enum values to write. + /// Serialization options. + public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) + { + writer.WriteStartArray(); + + foreach (var item in value) + { + _inner.Write(writer, item, options); + } + + writer.WriteEndArray(); + } } diff --git a/src/Json/EnumNameJson.cs b/src/Json/EnumNameJson.cs index 953ec68..71c3012 100644 --- a/src/Json/EnumNameJson.cs +++ b/src/Json/EnumNameJson.cs @@ -9,21 +9,21 @@ namespace PolyMod.Json; /// public class EnumNameJson : JsonConverter where EnumType : struct, Enum { - public override EnumType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - string? enumName = reader.GetString(); + public override EnumType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? enumName = reader.GetString(); - if (enumName != null && Enum.TryParse(enumName, true, out EnumType parsedValue)) - { - return parsedValue; - } + if (enumName != null && Enum.TryParse(enumName, true, out EnumType parsedValue)) + { + return parsedValue; + } - string validNames = string.Join(", ", Enum.GetNames(typeof(EnumType))); - throw new JsonException($"Unknown {typeof(EnumType).Name} value '{enumName}'. Valid values: {validNames}"); - } + string validNames = string.Join(", ", Enum.GetNames(typeof(EnumType))); + throw new JsonException($"Unknown {typeof(EnumType).Name} value '{enumName}'. Valid values: {validNames}"); + } - public override void Write(Utf8JsonWriter writer, EnumType value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } -} \ No newline at end of file + public override void Write(Utf8JsonWriter writer, EnumType value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } +} diff --git a/src/Json/JsonMerger.cs b/src/Json/JsonMerger.cs index 44eb212..a556202 100644 --- a/src/Json/JsonMerger.cs +++ b/src/Json/JsonMerger.cs @@ -8,107 +8,107 @@ namespace PolyMod.Json; /// public static class JsonMerger { - /// - /// Merges a patch JObject into an original JObject. - /// - /// The original JObject. - /// The patch JObject to merge. - /// The merged JObject. - public static JObject Merge(JObject original, JObject patch) - { - patch = MergeRecursive(original, patch); - original.Merge(patch, new() { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); - return original; - } + /// + /// Merges a patch JObject into an original JObject. + /// + /// The original JObject. + /// The patch JObject to merge. + /// The merged JObject. + public static JObject Merge(JObject original, JObject patch) + { + patch = MergeRecursive(original, patch); + original.Merge(patch, new() { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); + return original; + } - /// - /// Recursively applies custom merging logic to arrays. - /// - /// - /// - /// - private static JObject MergeRecursive(JObject original, JObject patch) - { - foreach (var property in patch.Properties().ToArray().ToList()) - { - if (property == null || property.Name == null) - continue; + /// + /// Recursively applies custom merging logic to arrays. + /// + /// + /// + /// + private static JObject MergeRecursive(JObject original, JObject patch) + { + foreach (var property in patch.Properties().ToArray().ToList()) + { + if (property == null || property.Name == null) + continue; - string propName = property.Name; - JToken? originalValue = original[propName]; - JToken patchValue = property.Value; + string propName = property.Name; + JToken? originalValue = original[propName]; + JToken patchValue = property.Value; - if (patchValue.Type == JTokenType.Array) - { - if (originalValue == null) - originalValue = new JArray(); + if (patchValue.Type == JTokenType.Array) + { + if (originalValue == null) + originalValue = new JArray(); - JArray originalArr = originalValue.Cast(); - JArray patchArr = patchValue.Cast(); - bool isSkins = propName.Equals("skins", StringComparison.OrdinalIgnoreCase); - JArray merged = MergeArrays(originalArr, patchArr, isSkins); - patch[propName] = merged; - } - else if (patchValue.Type == JTokenType.Object) - { - if (originalValue == null || originalValue.Type != JTokenType.Object) - originalValue = new JObject(); + JArray originalArr = originalValue.Cast(); + JArray patchArr = patchValue.Cast(); + bool isSkins = propName.Equals("skins", StringComparison.OrdinalIgnoreCase); + JArray merged = MergeArrays(originalArr, patchArr, isSkins); + patch[propName] = merged; + } + else if (patchValue.Type == JTokenType.Object) + { + if (originalValue == null || originalValue.Type != JTokenType.Object) + originalValue = new JObject(); - MergeRecursive(originalValue.Cast(), patchValue.Cast()); - } - } - return patch; - } + MergeRecursive(originalValue.Cast(), patchValue.Cast()); + } + } + return patch; + } - /// - /// Merges two JArrays, with special handling for adding and removing elements. - /// - /// The original JArray. - /// The patch JArray to merge. - /// A flag to indicate if the array is a 'skins' array, which has special merging logic. - /// The merged JArray. - private static JArray MergeArrays(JArray original, JArray patch, bool isSkins) - { - var result = new JArray(original); - var patchList = patch._values.ToArray().ToList(); + /// + /// Merges two JArrays, with special handling for adding and removing elements. + /// + /// The original JArray. + /// The patch JArray to merge. + /// A flag to indicate if the array is a 'skins' array, which has special merging logic. + /// The merged JArray. + private static JArray MergeArrays(JArray original, JArray patch, bool isSkins) + { + var result = new JArray(original); + var patchList = patch._values.ToArray().ToList(); - bool hasCustomValues = false; - foreach (var token in patchList) - { - if (token.Type != JTokenType.String) - { - result.Add(token); - continue; - } + bool hasCustomValues = false; + foreach (var token in patchList) + { + if (token.Type != JTokenType.String) + { + result.Add(token); + continue; + } - string str = token.ToString(); + string str = token.ToString(); - if (str.StartsWith("+")) - { - string value = str.Substring(1); - result.Add(value); - hasCustomValues = true; - } - else if (str.StartsWith("-")) - { - string value = str.Substring(1); - var toRemove = result._values.ToArray() - .Where(t => t.Type == JTokenType.String && t.ToString() == value) - .ToList(); - foreach (var rem in toRemove) - result.Remove(rem); - hasCustomValues = true; - } - else if (isSkins) - { - result.Add(str); - hasCustomValues = true; - } - } - if (!hasCustomValues) - { - result = new JArray(patch); - } - return result; - } + if (str.StartsWith('+')) + { + string value = str.Substring(1); + result.Add(value); + hasCustomValues = true; + } + else if (str.StartsWith('-')) + { + string value = str.Substring(1); + var toRemove = result._values.ToArray() + .Where(t => t.Type == JTokenType.String && t.ToString() == value) + .ToList(); + foreach (var rem in toRemove) + result.Remove(rem); + hasCustomValues = true; + } + else if (isSkins) + { + result.Add(str); + hasCustomValues = true; + } + } + if (!hasCustomValues) + { + result = new JArray(patch); + } + return result; + } } diff --git a/src/Json/Vector2Json.cs b/src/Json/Vector2Json.cs index 1957c4d..a36e5df 100644 --- a/src/Json/Vector2Json.cs +++ b/src/Json/Vector2Json.cs @@ -9,40 +9,40 @@ namespace PolyMod.Json; /// public class Vector2Json : JsonConverter { - /// - /// Reads and converts the JSON to a . - /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. - public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - List values = new(); - if (reader.TokenType == JsonTokenType.StartArray) - { - while (reader.Read()) - { - if (reader.TokenType == JsonTokenType.EndArray) break; - if (reader.TokenType != JsonTokenType.Number) throw new JsonException(); - values.Add(reader.GetSingle()); - } - } - if (values.Count != 2) throw new JsonException(); - return new(values[0], values[1]); - } + /// + /// Reads and converts the JSON to a . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + List values = new(); + if (reader.TokenType == JsonTokenType.StartArray) + { + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndArray) break; + if (reader.TokenType != JsonTokenType.Number) throw new JsonException(); + values.Add(reader.GetSingle()); + } + } + if (values.Count != 2) throw new JsonException(); + return new(values[0], values[1]); + } - /// - /// Writes a specified value as JSON. - /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. - public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) - { - writer.WriteStartArray(); - writer.WriteNumberValue(value.x); - writer.WriteNumberValue(value.y); - writer.WriteEndArray(); - } + /// + /// Writes a specified value as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) + { + writer.WriteStartArray(); + writer.WriteNumberValue(value.x); + writer.WriteNumberValue(value.y); + writer.WriteEndArray(); + } } diff --git a/src/Json/VersionJson.cs b/src/Json/VersionJson.cs index 21c6c81..47b9067 100644 --- a/src/Json/VersionJson.cs +++ b/src/Json/VersionJson.cs @@ -8,26 +8,26 @@ namespace PolyMod.Json; /// public class VersionJson : JsonConverter { - /// - /// Reads and converts the JSON to a . - /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. - public override Version? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(reader.GetString()!); - } + /// + /// Reads and converts the JSON to a . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override Version? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(reader.GetString()!); + } - /// - /// Writes a specified value as JSON. - /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. - public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } + /// + /// Writes a specified value as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } } diff --git a/src/Loader.cs b/src/Loader.cs index 218357a..467f3d2 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -10,7 +10,6 @@ using System.Diagnostics; using System.IO.Compression; using System.Reflection; -using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using UnityEngine; @@ -99,7 +98,7 @@ out TribeAbility.Type tribeAbilityType string tileEffectId = skinId.ToLowerInvariant() + "_flood"; EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); - Visual.customFloodingSkins.Add((TileData.EffectType)Registry.autoidx, skinValue); + Visual.customFloodingSkins.Add((TileData.EffectType)Registry.autoidx, skinValue); Plugin.logger.LogInfo("Created mapping for tileEffect with id " + tileEffectId + " and index " + Registry.autoidx); Registry.autoidx++; } @@ -231,7 +230,7 @@ public static void AddGameMode(string id, UIButtonBase.ButtonAction action, bool { EnumCache.AddMapping(id, (GameMode)Registry.gameModesAutoidx); EnumCache.AddMapping(id, (GameMode)Registry.gameModesAutoidx); - if(shouldShowInMenu) + if (shouldShowInMenu) gamemodes.Add(new GameModeButtonsInformation(Registry.gameModesAutoidx, action, null, sprite, spriteName)); Registry.gameModesAutoidx++; } @@ -256,14 +255,14 @@ public static void AddPatchDataType(string typeId, Type type, bool shouldCreateC public static void AddTypeHandler(Type type, Action handler) { string typeString = type.ToString(); - if(!typeMappings.ContainsValue(new TypeMapping(type, true)) && !typeMappings.ContainsValue(new TypeMapping(type, false))) + if (!typeMappings.ContainsValue(new TypeMapping(type, true)) && !typeMappings.ContainsValue(new TypeMapping(type, false))) { Plugin.logger.LogWarning($"Tried adding TypeHandler for type: {typeString} with missing TypeMapping. Please, add TypeMapping first."); return; } - if(!typeHandlers.ContainsKey(type)) + if (!typeHandlers.ContainsKey(type)) typeHandlers[type] = new(); - + typeHandlers[type].Add(handler); Plugin.logger.LogInfo($"Added TypeHandler for type: {typeString}."); @@ -379,13 +378,11 @@ internal static void LoadMods(Dictionary mods, out bool dependencyC dependencyCycle = !SortMods(Registry.mods); if (dependencyCycle) return; - StringBuilder checksumString = new(); foreach (var (id, mod) in Registry.mods) { if (mod.status != Mod.Status.Success) continue; foreach (var file in mod.files) { - checksumString.Append(JsonSerializer.Serialize(file)); if (Path.GetExtension(file.name) == ".dll") { LoadAssemblyFile(mod, file); @@ -406,13 +403,8 @@ internal static void LoadMods(Dictionary mods, out bool dependencyC ); } } - if (!mod.client && id != "polytopia") - { - checksumString.Append(id); - checksumString.Append(mod.version.ToString()); - } } - Compatibility.HashSignatures(checksumString); + Compatibility.ComputeChecksums(Registry.mods); } internal static void CheckDependencies(Dictionary mods) @@ -530,11 +522,11 @@ public static void LoadAssemblyFile(Mod mod, Mod.File file) { Assembly assembly = Assembly.Load(file.bytes); if (assembly - .GetTypes() - .FirstOrDefault(t => t.IsSubclassOf(typeof(Api.PolyScriptBase))) - is { } modType) + .GetTypes() + .FirstOrDefault(t => t.IsSubclassOf(typeof(Api.PolyScriptBase))) + is { } modType) { - var modInstance = (Api.PolyScriptBase) Activator.CreateInstance(modType)!; + var modInstance = (Api.PolyScriptBase)Activator.CreateInstance(modType)!; modInstance.Initialize(mod, BepInEx.Logging.Logger.CreateLogSource($"PolyMod] [{mod.id}")); modInstance.Load(); return; @@ -592,7 +584,7 @@ public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) try { var dict = JsonSerializer.Deserialize>(file.bytes); - if(dict != null) + if (dict != null) { Loc.languagesToAdd.Add(languageName, dict); Plugin.logger.LogInfo($"Registered language from {mod.id} mod"); @@ -827,7 +819,7 @@ internal static void ProcessCustomTribes() { foreach (var tribe in Registry.customTribes) { - if(!GameLogicData.legacyTribeTypesOrder.Contains(tribe)) + if (!GameLogicData.legacyTribeTypesOrder.Contains(tribe)) { GameLogicData.legacyTribeTypesOrder.Add(tribe); } @@ -862,18 +854,18 @@ internal static void CreateMappings(JObject rootObject) string id = Util.GetJTokenName(token); - if((int)token["idx"] == -1) + if ((int)token["idx"] == -1) { token["idx"] = Registry.autoidx; Registry.autoidx++; } - else if(Plugin.config.allowUnsafeIndexes) + else if (Plugin.config.allowUnsafeIndexes) { Array values = Enum.GetValues(targetType); var maxValue = values.Cast().Max(); - if(maxValue >= (int)token["idx"]) + if (maxValue >= (int)token["idx"]) { continue; } @@ -895,7 +887,7 @@ internal static void CreateMappings(JObject rootObject) if (typeHandlers.TryGetValue(targetType, out var handlers)) { - foreach(var handler in handlers) + foreach (var handler in handlers) { handler(token, true); } @@ -912,7 +904,7 @@ internal static void CreateMappings(JObject rootObject) { if (typeHandlers.TryGetValue(typeMapping.type, out var handlers)) { - foreach(var handler in handlers) + foreach (var handler in handlers) { handler(token, false); } diff --git a/src/Managers/Audio.cs b/src/Managers/Audio.cs index aefd86c..fa629a0 100644 --- a/src/Managers/Audio.cs +++ b/src/Managers/Audio.cs @@ -9,101 +9,101 @@ namespace PolyMod.Managers; /// public static class Audio { - /// - /// Patches the music data to get custom nature audio clips. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetNatureAudioClip))] - private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) - { - AudioClip? audioClip = Registry.GetAudioClip("nature", type, skinType); - if (audioClip != null) - { - __result = audioClip; - return false; - } - return true; - } + /// + /// Patches the music data to get custom nature audio clips. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetNatureAudioClip))] + private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) + { + AudioClip? audioClip = Registry.GetAudioClip("nature", type, skinType); + if (audioClip != null) + { + __result = audioClip; + return false; + } + return true; + } - /// - /// Patches the music data to get custom music audio clips. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetMusicAudioClip))] - private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) - { - AudioClip? audioClip = Registry.GetAudioClip("music", type, skinType); - if (audioClip != null) - { - __result = audioClip; - return false; - } - return true; - } + /// + /// Patches the music data to get custom music audio clips. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetMusicAudioClip))] + private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) + { + AudioClip? audioClip = Registry.GetAudioClip("music", type, skinType); + if (audioClip != null) + { + __result = audioClip; + return false; + } + return true; + } - /// - /// Patches the audio SFX data to get custom sound effect clips. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(AudioSFXData), nameof(AudioSFXData.GetClip))] - private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, SkinType skinType) - { - AudioClip? audioClip = Registry.GetAudioClip( - EnumCache.GetName(id), - skin: skinType - ); - if (audioClip != null) - { - __result = audioClip; - return false; - } - return true; - } + /// + /// Patches the audio SFX data to get custom sound effect clips. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(AudioSFXData), nameof(AudioSFXData.GetClip))] + private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, SkinType skinType) + { + AudioClip? audioClip = Registry.GetAudioClip( + EnumCache.GetName(id), + skin: skinType + ); + if (audioClip != null) + { + __result = audioClip; + return false; + } + return true; + } - private const string CLIP_CREATION_UNAVAILABLE = - "this game build cannot create audio clips at runtime." - + " AudioClip.Create marshals its arguments as spans, and" - + " Il2CppSystem.ReadOnlySpan.GetPinnableReference() is missing from its IL2CPP build." - + " Custom audio stays disabled until the game ships calling AudioClip.Create and SetData"; + private const string CLIP_CREATION_UNAVAILABLE = + "this game build cannot create audio clips at runtime." + + " AudioClip.Create marshals its arguments as spans, and" + + " Il2CppSystem.ReadOnlySpan.GetPinnableReference() is missing from its IL2CPP build." + + " Custom audio stays disabled until the game ships calling AudioClip.Create and SetData"; - private static bool clipCreationUnavailable = false; + private static bool clipCreationUnavailable = false; - /// - /// Builds an audio clip from raw byte data. - /// - /// The byte data of the audio file, which has to be a WAVE file. - /// The name to give the clip inside Unity. - /// The created audio clip. - /// The data is not a WAVE file that can be decoded. - /// The game build cannot create audio clips. - public static AudioClip BuildAudioClip(byte[] data, string name = "polymod_audio") - { - WavDecoder.WavData wav = WavDecoder.Decode(data); - if (clipCreationUnavailable) - throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}."); + /// + /// Builds an audio clip from raw byte data. + /// + /// The byte data of the audio file, which has to be a WAVE file. + /// The name to give the clip inside Unity. + /// The created audio clip. + /// The data is not a WAVE file that can be decoded. + /// The game build cannot create audio clips. + public static AudioClip BuildAudioClip(byte[] data, string name = "polymod_audio") + { + WavDecoder.WavData wav = WavDecoder.Decode(data); + if (clipCreationUnavailable) + throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}."); - try - { - AudioClip clip = AudioClip.Create(name, wav.lengthSamples, wav.channels, wav.frequency, false); - if (clip == null) - throw new InvalidOperationException($"Unity returned no audio clip for {name}."); - if (!clip.SetData(wav.samples, 0)) - throw new InvalidOperationException($"Unity rejected the samples for {name}."); - return clip; - } - catch (MissingMethodException exception) - { - // Remembered so that a mod shipping many files reports this once rather than per file. - clipCreationUnavailable = true; - throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}.", exception); - } - } + try + { + AudioClip clip = AudioClip.Create(name, wav.lengthSamples, wav.channels, wav.frequency, false); + if (clip == null) + throw new InvalidOperationException($"Unity returned no audio clip for {name}."); + if (!clip.SetData(wav.samples, 0)) + throw new InvalidOperationException($"Unity rejected the samples for {name}."); + return clip; + } + catch (MissingMethodException exception) + { + // Remembered so that a mod shipping many files reports this once rather than per file. + clipCreationUnavailable = true; + throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}.", exception); + } + } - /// - /// Initializes the Audio manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Audio)); - } + /// + /// Initializes the Audio manager by patching the necessary methods. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Audio)); + } } diff --git a/src/Managers/Compatibility.cs b/src/Managers/Compatibility.cs index c2d2498..8083f05 100644 --- a/src/Managers/Compatibility.cs +++ b/src/Managers/Compatibility.cs @@ -1,8 +1,6 @@ using HarmonyLib; using Il2CppInterop.Runtime; -using System.Text; using UnityEngine; -using UnityEngine.EventSystems; namespace PolyMod.Managers; @@ -11,263 +9,360 @@ namespace PolyMod.Managers; /// internal static class Compatibility { - /// - /// The checksum of all loaded mods. - /// - internal static string checksum = string.Empty; - - /// - /// Whether the game settings should be reset due to a change in mods. - /// - internal static bool shouldResetSettings = false; - private static bool sawSignatureWarning; - private const string downloadLink = "https://polymod.dev/download/"; - - // TODO: rewrite all of this bullshit! each mod should have a checksum. and then using per mod checksum, we should calculate overall checksum - // why? launcher will let you install a mod if u dont have it. if u have a mod with this id, but it doesnt match any checksum of any ver of - // this mod on polymod.dev, then we just leave it as "install". if there is a new ver, we can simply put "update" - // also add a client mod check or whatever - - /// - /// Hashes the signatures of all loaded mods to create a checksum. - /// - /// A string builder containing the signatures to hash. - public static void HashSignatures(StringBuilder checksumString) - { - checksum = Util.Hash(checksumString); - } - - /// - /// Checks the signature of a saved game to ensure it is compatible with the current mods. - /// - /// True if the signatures match or if the check is ignored, false otherwise. - private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) - { - if (sawSignatureWarning) - { - sawSignatureWarning = false; - return true; - } - - string stateChecksum = string.Empty; - try - { - Plugin.logger.LogInfo($"Getting checksum for state {gameId}"); - stateChecksum = File.ReadAllText(Path.Combine(Application.persistentDataPath, $"{gameId}.signatures")); - Plugin.logger.LogInfo($"Checksum found."); - } - catch - { - Plugin.logger.LogInfo($"Failed to get checksum."); - } - if (stateChecksum == string.Empty) - { - Plugin.logger.LogInfo($"State checksum is empty, ignoring."); - return true; - } - bool doChecksumsMatch = stateChecksum == checksum; - Plugin.logger.LogInfo($"State checksum: '{stateChecksum}', global checksum: '{checksum}', comparison result : {doChecksumsMatch}"); - if (Plugin.config.debug) - { - Plugin.logger.LogInfo($"Debug detected, ignoring."); - return true; - } - if (!doChecksumsMatch) - { - PopupManager.GetBasicPopupWithData(new( - Localization.Get("polymod.signature.mismatch"), - Localization.Get("polymod.signature.incompatible"), - new(new PopupBase.PopupButtonData[] { - new("OK") - }) - )).Show(); - - return false; - } - return true; - } - - /// - /// Performs compatibility checks when the start screen is shown. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] - private static void StartScreen_UI2_OnShow() - { - if(!Plugin.ValidLaunch && Application.platform != RuntimePlatform.Android) - { - PopupManager.GetBasicPopupWithData( - new( - Localization.Get("polymod.title.invalid"), - Localization.Get("polymod.description.invalid"), - new PopupBase.PopupButtonData[] { - new( - "buttons.exitgame", - PopupBase.PopupButtonData.States.None, - callback: (Il2CppSystem.Action)Application.Quit, - closesPopup: false - ), - new( - "buttons.download.launcher", - PopupBase.PopupButtonData.States.None, - callback: DelegateSupport.ConvertDelegate(OpenSite), - closesPopup: false - ) - } - ) - ).Show(); - - void OpenSite() - { - NativeHelpers.OpenURL(downloadLink, false); - Application.Quit(); - } - return; - } - string lastChecksum = checksum; - try - { - lastChecksum = new(File.ReadAllText(Plugin.CHECKSUM_PATH)); - } - catch (FileNotFoundException) { } - - File.WriteAllText( - Plugin.CHECKSUM_PATH, - checksum - ); - if (lastChecksum != checksum) - { - shouldResetSettings = true; - } - - Version incompatibilityWarningLastVersion = new(PlayerPrefs.GetString( - Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, - Plugin.POLYTOPIA_VERSION.CutRevision().ToString() - )); - if (VersionManager.SemanticVersion.Cast().CutRevision() > incompatibilityWarningLastVersion) - { - PlayerPrefs.SetString( - Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, - VersionManager.SemanticVersion.Cast().CutRevision().ToString() - ); - PlayerPrefs.Save(); - PopupManager.GetBasicPopupWithData( - new( - Localization.Get("polymod.version.mismatch"), - Localization.Get("polymod.version.mismatch.description"), - new PopupBase.PopupButtonData[] { - new("buttons.stay", customColorStates: ColorConstants.redButtonColorStates), - new( - "buttons.exitgame", - PopupBase.PopupButtonData.States.None, - (Il2CppSystem.Action)Application.Quit, - closesPopup: false - ) - } - ) - ).Show(); - } - } - - /// - /// Checks the signature of a pass-and-play game before loading it. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.OnMainButtonClicked))] - private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) - { - return CheckSignatures(__instance.OnMainButtonClicked, __instance.gameId); - } - - /// - /// Checks the signature of a single-player game before resuming it. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnResumeButtonLongPress))] - private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) - { - return CheckSignatures(__instance.OnResumeButtonLongPress, LocalSaveFileUtils.GetSaveFiles(PolytopiaBackendBase.Game.GameType.SinglePlayer)[0]); - } - - /// - /// Deletes the signature file of a pass-and-play game when it is deleted. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.DeletePaPGame))] - private static void GameInfoPopup_DeletePaPGame(GameInfoPopup __instance) - { - File.Delete(Path.Combine(Application.persistentDataPath, $"{__instance.gameId}.signatures")); - } - - /// - /// Deletes the signature file of all singleplayer games when they are deleted. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteAllSaveFilesOfType))] - private static void LocalSaveFileUtils_DeleteAllSaveFilesOfType(PolytopiaBackendBase.Game.GameType gameType, bool localOnly) - { - if (gameType == PolytopiaBackendBase.Game.GameType.SinglePlayer) - { - foreach (var gameId in LocalSaveFileUtils.GetSaveFiles(PolytopiaBackendBase.Game.GameType.SinglePlayer)) - { - File.Delete(Path.Combine(Application.persistentDataPath, $"{gameId}.signatures")); - } - } - } - - /// - /// Deletes the signature file of a game when the match ends. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GameManager), nameof(GameManager.MatchEnded))] - private static void GameManager_MatchEnded(bool localPlayerIsWinner, ScoreDetails scoreDetails, byte winnerId) - { - File.Delete(Path.Combine(Application.persistentDataPath, $"{GameManager.Client.gameId}.signatures")); - } - - /// - /// Creates a signature file when a new game session is created. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(ClientBase), nameof(ClientBase.CreateSession), typeof(GameSettings), typeof(Il2CppSystem.Guid))] - private static void ClientBase_CreateSession(GameSettings settings, Il2CppSystem.Guid gameId) - { - File.WriteAllTextAsync( - Path.Combine(Application.persistentDataPath, $"{gameId}.signatures"), - checksum - ); - } - - /// - /// Resets game settings if necessary when the tribe selector screen is shown. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(TribeSelectorScreen), nameof(TribeSelectorScreen.Show))] - private static bool TribeSelectorScreen_Show(bool instant = false) - { - if (shouldResetSettings) - { - RestorePreliminaryGameSettings(); - shouldResetSettings = false; - } - return true; - } - - /// - /// Restores the preliminary game settings to their default values. - /// - internal static void RestorePreliminaryGameSettings() - { - GameManager.PreliminaryGameSettings.disabledTribes.Clear(); - GameManager.PreliminaryGameSettings.selectedSkins.Clear(); - GameManager.PreliminaryGameSettings.SaveToDisk(); - } - - /// - /// Initializes the Compatibility manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Compatibility)); - } + /// + /// The checksum of all loaded mods. + /// + internal static string checksum = string.Empty; + + /// + /// Whether the game settings should be reset due to a change in mods. + /// + internal static bool shouldResetSettings = false; + private static bool sawSignatureWarning; + private const string downloadLink = "https://polymod.dev/download/"; + + public static void ComputeChecksums(Dictionary mods) + { + foreach (var (_, mod) in mods) + { + mod.checksum = ComputeModChecksum(mod); + } + + List signatures = new(); + foreach (var (id, mod) in mods) + { + if (mod.status != Mod.Status.Success) continue; + if (mod.client || id == "polytopia") continue; + + signatures.Add($"{id}:{mod.checksum}"); + } + signatures.Sort(StringComparer.Ordinal); + + checksum = Util.Hash(string.Join("\n", signatures)); + } + + public static string ComputeModChecksum(Mod mod) + { + List entries = new(); + foreach (Mod.File file in mod.files) + { + string name = file.name.Replace('\\', '/'); + if (name.EndsWith('/')) continue; + + entries.Add($"{name}:{Util.HashBytes(file.bytes)}"); + } + entries.Sort(StringComparer.Ordinal); + + return Util.Hash($"{mod.id}:{mod.version}\n{string.Join("\n", entries)}"); + } + + /// + /// Gets the player prefs key holding the checksum a saved game was created with. + /// + /// The id of the saved game. + /// The player prefs key. + private static string StateChecksumKey(object gameId) + { + return Plugin.STATE_CHECKSUM_KEY_PREFIX + NormalizeGameId(gameId); + } + + /// + /// Normalizes a game id so that the same save always maps to one key. The game hands ids over + /// as a Guid in some places and as a string in others, and those do not always match in case + /// or in whether they are wrapped in braces. + /// + /// The id of the saved game, as a Guid or a string. + /// The normalized id. + internal static string NormalizeGameId(object gameId) + { + return gameId.ToString()!.Trim('{', '}').ToLowerInvariant(); + } + + /// + /// Gets the path of the signature file older versions wrote for a saved game. + /// + /// The id of the saved game. + /// The path of the legacy signature file. + private static string LegacyStateChecksumPath(object gameId) + { + return Path.Combine(Application.persistentDataPath, $"{NormalizeGameId(gameId)}.signatures"); + } + + /// + /// Stores the current mod checksum for a saved game. + /// + /// The id of the saved game. + internal static void SaveStateChecksum(object gameId) + { + PlayerPrefs.SetString(StateChecksumKey(gameId), checksum); + PlayerPrefs.Save(); + } + + /// + /// Reads the mod checksum a saved game was created with, migrating it out of the + /// signature file older versions used. + /// + /// The id of the saved game. + /// The stored checksum, or an empty string when there is none. + internal static string ReadStateChecksum(object gameId) + { + string key = StateChecksumKey(gameId); + if (PlayerPrefs.HasKey(key)) + return PlayerPrefs.GetString(key); + + string legacyPath = LegacyStateChecksumPath(gameId); + if (!File.Exists(legacyPath)) + return string.Empty; + + string legacyChecksum = File.ReadAllText(legacyPath); + PlayerPrefs.SetString(key, legacyChecksum); + PlayerPrefs.Save(); + File.Delete(legacyPath); + return legacyChecksum; + } + + internal static void DeleteStateChecksum(object gameId) + { + PlayerPrefs.DeleteKey(StateChecksumKey(gameId)); + PlayerPrefs.Save(); + + string legacyPath = LegacyStateChecksumPath(gameId); + if (File.Exists(legacyPath)) + File.Delete(legacyPath); + } + + /// + /// Checks the signature of a saved game to ensure it is compatible with the current mods. + /// + /// True if the signatures match or if the check is ignored, false otherwise. + private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) + { + if (sawSignatureWarning) + { + sawSignatureWarning = false; + return true; + } + + string stateChecksum = string.Empty; + try + { + Plugin.logger.LogInfo($"Getting checksum for state {gameId}"); + stateChecksum = ReadStateChecksum(gameId); + Plugin.logger.LogInfo($"Checksum found."); + } + catch + { + Plugin.logger.LogInfo($"Failed to get checksum."); + } + if (stateChecksum == string.Empty) + { + Plugin.logger.LogInfo($"State checksum is empty, ignoring."); + return true; + } + bool doChecksumsMatch = stateChecksum == checksum; + Plugin.logger.LogInfo($"State checksum: '{stateChecksum}', global checksum: '{checksum}', comparison result : {doChecksumsMatch}"); + if (Plugin.config.debug) + { + Plugin.logger.LogInfo($"Debug detected, ignoring."); + return true; + } + if (!doChecksumsMatch) + { + PopupManager.GetBasicPopupWithData(new( + Localization.Get("polymod.signature.mismatch"), + Localization.Get("polymod.signature.incompatible"), + new(new PopupBase.PopupButtonData[] { + new("OK") + }) + )).Show(); + + return false; + } + return true; + } + + /// + /// Performs compatibility checks when the start screen is shown. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] + private static void StartScreen_UI2_OnShow() + { + if (!Plugin.ValidLaunch && Application.platform != RuntimePlatform.Android) + { + PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.title.invalid"), + Localization.Get("polymod.description.invalid"), + new PopupBase.PopupButtonData[] { + new( + "buttons.exitgame", + PopupBase.PopupButtonData.States.None, + callback: (Il2CppSystem.Action)Application.Quit, + closesPopup: false + ), + new( + "buttons.download.launcher", + PopupBase.PopupButtonData.States.None, + callback: DelegateSupport.ConvertDelegate(OpenSite), + closesPopup: false + ) + } + ) + ).Show(); + + void OpenSite() + { + NativeHelpers.OpenURL(downloadLink, false); + Application.Quit(); + } + return; + } + string lastChecksum = checksum; + try + { + lastChecksum = new(File.ReadAllText(Plugin.CHECKSUM_PATH)); + } + catch (FileNotFoundException) { } + + File.WriteAllText( + Plugin.CHECKSUM_PATH, + checksum + ); + if (lastChecksum != checksum) + { + shouldResetSettings = true; + } + + Version incompatibilityWarningLastVersion = new(PlayerPrefs.GetString( + Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, + Plugin.POLYTOPIA_VERSION.CutRevision().ToString() + )); + if (VersionManager.SemanticVersion.Cast().CutRevision() > incompatibilityWarningLastVersion) + { + PlayerPrefs.SetString( + Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, + VersionManager.SemanticVersion.Cast().CutRevision().ToString() + ); + PlayerPrefs.Save(); + PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.version.mismatch"), + Localization.Get("polymod.version.mismatch.description"), + new PopupBase.PopupButtonData[] { + new("buttons.stay", customColorStates: ColorConstants.redButtonColorStates), + new( + "buttons.exitgame", + PopupBase.PopupButtonData.States.None, + (Il2CppSystem.Action)Application.Quit, + closesPopup: false + ) + } + ) + ).Show(); + } + } + + /// + /// Checks the signature of a pass-and-play game before loading it. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.OnMainButtonClicked))] + private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) + { + return CheckSignatures(__instance.OnMainButtonClicked, __instance.gameId); + } + + /// + /// Checks the signature of a single-player game before resuming it. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnResumeButtonLongPress))] + private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) + { + return CheckSignatures(__instance.OnResumeButtonLongPress, LocalSaveFileUtils.GetSaveFiles(PolytopiaBackendBase.Game.GameType.SinglePlayer)[0]); + } + + /// + /// Deletes the stored checksum of a pass-and-play game when it is deleted. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.DeletePaPGame))] + private static void GameInfoPopup_DeletePaPGame(GameInfoPopup __instance) + { + DeleteStateChecksum(__instance.gameId); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteSaveFile))] + private static void LocalSaveFileUtils_DeleteSaveFile(PolytopiaBackendBase.Game.GameType gameType, string gameId, bool localOnly) + { + DeleteStateChecksum(gameId); + } + + /// + /// Deletes the stored checksums of all saved games of a type when they are deleted. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteAllSaveFilesOfType))] + private static void LocalSaveFileUtils_DeleteAllSaveFilesOfType(PolytopiaBackendBase.Game.GameType gameType, bool localOnly) + { + foreach (var gameId in LocalSaveFileUtils.GetSaveFiles(gameType)) + { + DeleteStateChecksum(gameId); + } + } + + /// + /// Deletes the stored checksum of a game when the match ends. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(GameManager), nameof(GameManager.MatchEnded))] + private static void GameManager_MatchEnded(bool localPlayerIsWinner, ScoreDetails scoreDetails, byte winnerId) + { + DeleteStateChecksum(GameManager.Client.gameId); + } + + /// + /// Stores the current mod checksum when a new game session is created. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(ClientBase), nameof(ClientBase.CreateSession), typeof(GameSettings), typeof(Il2CppSystem.Guid))] + private static void ClientBase_CreateSession(GameSettings settings, Il2CppSystem.Guid gameId) + { + SaveStateChecksum(gameId); + } + + /// + /// Resets game settings if necessary when the tribe selector screen is shown. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(TribeSelectorScreen), nameof(TribeSelectorScreen.Show))] + private static bool TribeSelectorScreen_Show(bool instant = false) + { + if (shouldResetSettings) + { + RestorePreliminaryGameSettings(); + shouldResetSettings = false; + } + return true; + } + + /// + /// Restores the preliminary game settings to their default values. + /// + internal static void RestorePreliminaryGameSettings() + { + GameManager.PreliminaryGameSettings.disabledTribes.Clear(); + GameManager.PreliminaryGameSettings.selectedSkins.Clear(); + GameManager.PreliminaryGameSettings.SaveToDisk(); + } + + /// + /// Initializes the Compatibility manager by patching the necessary methods. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Compatibility)); + } } diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 99db641..305581f 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -23,6 +23,7 @@ Action toggle private const string COLOR_ENABLED = "#4CC76A"; private const string COLOR_DISABLED = "#E36A5B"; private const string COLOR_WARNING = "#E0A52E"; + private const int CHECKSUM_LENGTH = 12; private const float HUB_POPUP_WIDTH_SHARE = 0.78f; private const float HUB_POPUP_MAX_WIDTH = 1400f; private const float SETTINGS_POPUP_WIDTH_SHARE = 0.5f; @@ -76,7 +77,7 @@ public static bool IsPopupOpen { if (openPopup.IsShowing()) return true; } - catch (Exception) {} + catch (Exception) { } openPopup = null; } return false; @@ -296,13 +297,16 @@ private static string BuildModList() if (mod.status == Mod.Status.Success) loaded++; } - List blocks = new() - { - Muted(Localization.Get( - "polymod.hub.summary", - Args(loaded.ToString(), Registry.mods.Count.ToString()) - )), - }; + string summary = Localization.Get( + "polymod.hub.summary", + Args(loaded.ToString(), Registry.mods.Count.ToString()) + ); + summary += " " + Localization.Get( + "polymod.hub.checksum", + Args(ShortChecksum(Compatibility.checksum)) + ); + + List blocks = new() { Muted(summary) }; foreach (Mod mod in Registry.mods.Values) { blocks.Add(BuildModEntry(mod)); @@ -310,6 +314,18 @@ private static string BuildModList() return string.Join("\n\n", blocks); } + /// + /// Shortens a checksum to the leading characters shown in the hub. + /// + /// The full checksum. + /// The shortened checksum. + private static string ShortChecksum(string checksum) + { + if (string.IsNullOrEmpty(checksum)) return "-"; + + return checksum.Length <= CHECKSUM_LENGTH ? checksum : checksum.Substring(0, CHECKSUM_LENGTH); + } + private static string BuildModEntry(Mod mod) { string status = Localization.Get( @@ -325,6 +341,14 @@ private static string BuildModEntry(Mod mod) ); meta += " " + Muted($"{authors}"); } + if (!string.IsNullOrEmpty(mod.checksum)) + { + string modChecksum = Localization.Get( + "polymod.hub.mod.checksum", + Args(ShortChecksum(mod.checksum)) + ); + meta += " " + Muted($"{modChecksum}"); + } List lines = new() { title, meta }; if (!string.IsNullOrWhiteSpace(mod.description)) diff --git a/src/Managers/Loc.cs b/src/Managers/Loc.cs index b3b7d17..d4d6938 100644 --- a/src/Managers/Loc.cs +++ b/src/Managers/Loc.cs @@ -13,163 +13,163 @@ namespace PolyMod.Managers; /// public static class Loc { - internal static Dictionary> languagesToAdd = new(); - internal static Dictionary buildingsInfoOverrides = new(); - - /// - /// Patches the localization getter to handle custom enum values. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(Localization), nameof(Localization.Get), typeof(string), typeof(Il2CppReferenceArray))] - private static bool Localization_Get(ref string key, Il2CppReferenceArray args) - { - List keys = key.Split('.').ToList(); - int? idx = null; - string? name = null; - - // Find any custom enum indices in the localization key - foreach (string item in keys) - { - if (int.TryParse(item, out int parsedIdx)) - { - if (parsedIdx >= Plugin.AUTOIDX_STARTS_FROM) - { - idx = parsedIdx; - } - } - } - - // If a custom enum index is found, try to resolve its name - if (idx != null) - { - foreach (var typeMapping in Loader.typeMappings.Values) - { - if (!typeMapping.shouldCreateCache) - continue; - - MethodInfo? methodInfo = typeof(EnumCache<>).MakeGenericType(typeMapping.type).GetMethod("TryGetName"); - if (methodInfo != null) - { - object?[] parameters = { idx, null }; - object? methodInvokeResult = methodInfo.Invoke(null, parameters); - if (methodInvokeResult != null) - { - if ((bool)methodInvokeResult) - { - name = (string?)parameters[1]; - } - } - } - } - - // If the name was resolved, replace the index with the name in the key - if (name != null && idx != null) - { - int index = keys.IndexOf(idx.ToString()!); - keys[index] = name; - key = string.Join(".", keys); - } - } - return true; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(Localization), nameof(Localization.Init))] - private static bool Localization_Init() - { - if (Localization.initialized) - return true; - - if (LocalizationManager.Sources.Count == 0) - LocalizationManager.UpdateSources(); - - LanguageSourceData source = LocalizationManager.Sources[0]; - - // Elyrion has no language code. I am almost completely sure it is a bug, by looking at the code. - LanguageData elyrionLanguage = source.GetLanguageData("Elyrion"); - elyrionLanguage.Code = Localization.LANG_CODE_ELYRION; - - foreach (var languageCode in languagesToAdd.Keys) - { - Dictionary terms = languagesToAdd[languageCode]; - - int languageIndex = source.GetLanguageIndexFromCode(languageCode); - string languageName = terms["language"]; - if (languageIndex == -1) - { - source.AddLanguage(languageName, languageCode); - languageIndex = source.GetLanguageIndex(languageName); - } - - foreach (var kvp in terms) - { - TermData term = source.GetTermData(kvp.Key); - if (term == null) - { - source.AddTerm(kvp.Key); - term = source.GetTermData(kvp.Key); - } - - term.Languages[languageIndex] = kvp.Value; - } - - LocalizationManager.UpdateSources(); - - Plugin.logger.LogInfo($"{languageCode} language terms added."); - } - return true; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(BuildingUtils), nameof(BuildingUtils.GetInfo))] - private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCurrentLocalPlayer, - ImprovementData improvementData, ImprovementState improvementState, PlayerState owner, TileData tileData) - { - TribeType tribe = TribeType.None; - if (owner != null) - tribe = owner.tribe; - - string key = EnumCache.GetName(improvementData.type); - if (buildingsInfoOverrides.ContainsKey(key)) - { - __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingsInfoOverrides[key]); - return false; - } - - return true; - } - - /// - /// Builds and loads localization data from a dictionary. - /// - /// A dictionary containing the localization data. - internal static void BuildAndLoadLocalization(Dictionary> localization) - { - foreach (var (key, data) in localization) - { - string name = ReplaceDashesWithDots(key); - if (name.StartsWith("tribeskins")) name = "TribeSkins/" + name; - TermData term = LocalizationManager.Sources[0].AddTerm(name); - List strings = new(); - foreach (string language in LocalizationManager.GetAllLanguages(false)) - { - strings.Add(data.GetOrDefault(language, data.GetOrDefault("English", term.Term))!); - } - term.Languages = new Il2CppStringArray(strings.ToArray()); - } - } - - internal static string ReplaceDashesWithDots(string key) - { - string name = key.Replace("_", "."); - return name.Replace("..", "_"); - } - - /// - /// Initializes the Loc manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Loc)); - } + internal static Dictionary> languagesToAdd = new(); + internal static Dictionary buildingsInfoOverrides = new(); + + /// + /// Patches the localization getter to handle custom enum values. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(Localization), nameof(Localization.Get), typeof(string), typeof(Il2CppReferenceArray))] + private static bool Localization_Get(ref string key, Il2CppReferenceArray args) + { + List keys = key.Split('.').ToList(); + int? idx = null; + string? name = null; + + // Find any custom enum indices in the localization key + foreach (string item in keys) + { + if (int.TryParse(item, out int parsedIdx)) + { + if (parsedIdx >= Plugin.AUTOIDX_STARTS_FROM) + { + idx = parsedIdx; + } + } + } + + // If a custom enum index is found, try to resolve its name + if (idx != null) + { + foreach (var typeMapping in Loader.typeMappings.Values) + { + if (!typeMapping.shouldCreateCache) + continue; + + MethodInfo? methodInfo = typeof(EnumCache<>).MakeGenericType(typeMapping.type).GetMethod("TryGetName"); + if (methodInfo != null) + { + object?[] parameters = { idx, null }; + object? methodInvokeResult = methodInfo.Invoke(null, parameters); + if (methodInvokeResult != null) + { + if ((bool)methodInvokeResult) + { + name = (string?)parameters[1]; + } + } + } + } + + // If the name was resolved, replace the index with the name in the key + if (name != null && idx != null) + { + int index = keys.IndexOf(idx.ToString()!); + keys[index] = name; + key = string.Join(".", keys); + } + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(Localization), nameof(Localization.Init))] + private static bool Localization_Init() + { + if (Localization.initialized) + return true; + + if (LocalizationManager.Sources.Count == 0) + LocalizationManager.UpdateSources(); + + LanguageSourceData source = LocalizationManager.Sources[0]; + + // Elyrion has no language code. I am almost completely sure it is a bug, by looking at the code. + LanguageData elyrionLanguage = source.GetLanguageData("Elyrion"); + elyrionLanguage.Code = Localization.LANG_CODE_ELYRION; + + foreach (var languageCode in languagesToAdd.Keys) + { + Dictionary terms = languagesToAdd[languageCode]; + + int languageIndex = source.GetLanguageIndexFromCode(languageCode); + string languageName = terms["language"]; + if (languageIndex == -1) + { + source.AddLanguage(languageName, languageCode); + languageIndex = source.GetLanguageIndex(languageName); + } + + foreach (var kvp in terms) + { + TermData term = source.GetTermData(kvp.Key); + if (term == null) + { + source.AddTerm(kvp.Key); + term = source.GetTermData(kvp.Key); + } + + term.Languages[languageIndex] = kvp.Value; + } + + LocalizationManager.UpdateSources(); + + Plugin.logger.LogInfo($"{languageCode} language terms added."); + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(BuildingUtils), nameof(BuildingUtils.GetInfo))] + private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCurrentLocalPlayer, + ImprovementData improvementData, ImprovementState improvementState, PlayerState owner, TileData tileData) + { + TribeType tribe = TribeType.None; + if (owner != null) + tribe = owner.tribe; + + string key = EnumCache.GetName(improvementData.type); + if (buildingsInfoOverrides.ContainsKey(key)) + { + __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingsInfoOverrides[key]); + return false; + } + + return true; + } + + /// + /// Builds and loads localization data from a dictionary. + /// + /// A dictionary containing the localization data. + internal static void BuildAndLoadLocalization(Dictionary> localization) + { + foreach (var (key, data) in localization) + { + string name = ReplaceDashesWithDots(key); + if (name.StartsWith("tribeskins", StringComparison.Ordinal)) name = "TribeSkins/" + name; + TermData term = LocalizationManager.Sources[0].AddTerm(name); + List strings = new(); + foreach (string language in LocalizationManager.GetAllLanguages(false)) + { + strings.Add(data.GetOrDefault(language, data.GetOrDefault("English", term.Term))!); + } + term.Languages = new Il2CppStringArray(strings.ToArray()); + } + } + + internal static string ReplaceDashesWithDots(string key) + { + string name = key.Replace("_", "."); + return name.Replace("..", "_"); + } + + /// + /// Initializes the Loc manager by patching the necessary methods. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Loc)); + } } diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 188544b..f154d42 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -33,7 +33,7 @@ public static class Main /// Whether the mod has been fully initialized. /// internal static bool fullyInitialized; - + /// /// A dictionary mapping unit IDs to the IDs of the units they embark into. /// @@ -390,7 +390,6 @@ internal static void Init() /// /// Loads all mod content. /// - /// The game logic data to patch. /// The JSON object representing the game logic data. internal static void Load(GameLogicData gameLogicData, JObject json) { diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index 3295f59..a226835 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -1,5 +1,4 @@ using HarmonyLib; -using Il2CppInterop.Runtime; using Polytopia.Data; using PolytopiaBackendBase.Common; using UnityEngine; @@ -10,9 +9,9 @@ namespace PolyMod.Managers; public static class Prefabs { - internal static Dictionary unitsNew = new(); - internal static Dictionary> unitOverridesNew = new(); // maybe in the future will implement - internal static Dictionary unitUIOverridesNew = new(); + internal static Dictionary unitsNew = new(); + internal static Dictionary> unitOverridesNew = new(); // maybe in the future will implement + internal static Dictionary unitUIOverridesNew = new(); internal static Material? cachedUnitMaterial; internal static Material? cachedSharedMaterial; @@ -39,94 +38,94 @@ public static class Prefabs {UnitData.WeaponEnum.Water, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnPuff(); }; - [HarmonyPostfix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] - private static void PrefabManager_Awake_Postfix(PrefabManager __instance) - { - unitsNew.Clear(); - unitOverridesNew.Clear(); - unitUIOverridesNew.Clear(); - - foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) - { - if(cachedUnitMaterial == null) - { - SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); - if (skinVisualsReference != null && skinVisualsReference.visualParts != null) - { - foreach (VisualPart currentPart in skinVisualsReference.visualParts) - { - if (currentPart.visualPart == null) - { - continue; - } - - SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); - if (headSpriteRenderer != null) - { - cachedUnitMaterial = headSpriteRenderer.sharedMaterial; - break; - } - } - } - } - unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; - } - - foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) - { - if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) - { - overridesForCondition = new Dictionary(); - unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; - } - overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; - } - - foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) - { - unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; - } - - Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] - public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) - { - __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] - public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) - { - if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) - { - __result = uiOverridePrefab; - } - else - { - __result = ResolveUnitPrefab(unitType, tribe, skin); - } - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] - public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) - { - __result = ResolveUnitPrefab(type, tribe, skin); - return false; - } - - [HarmonyPostfix] // prolly remove later - [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] - public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) - { - bool flag = false; + [HarmonyPostfix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] + private static void PrefabManager_Awake_Postfix(PrefabManager __instance) + { + unitsNew.Clear(); + unitOverridesNew.Clear(); + unitUIOverridesNew.Clear(); + + foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) + { + if (cachedUnitMaterial == null) + { + SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); + if (skinVisualsReference != null && skinVisualsReference.visualParts != null) + { + foreach (VisualPart currentPart in skinVisualsReference.visualParts) + { + if (currentPart.visualPart == null) + { + continue; + } + + SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); + if (headSpriteRenderer != null) + { + cachedUnitMaterial = headSpriteRenderer.sharedMaterial; + break; + } + } + } + } + unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; + } + + foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) + { + if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) + { + overridesForCondition = new Dictionary(); + unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; + } + overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; + } + + foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) + { + unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; + } + + Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] + public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] + public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) + { + __result = uiOverridePrefab; + } + else + { + __result = ResolveUnitPrefab(unitType, tribe, skin); + } + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] + public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) + { + __result = ResolveUnitPrefab(type, tribe, skin); + return false; + } + + [HarmonyPostfix] // prolly remove later + [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] + public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) + { + bool flag = false; flag = visualSetting.outline != null && visualSetting.outline.transform.parent == visualSetting.visualPart.transform; if (!flag && visualSetting.visualPart.transform.childCount > 0) { @@ -143,10 +142,10 @@ public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovem } } visualSetting.hasValidOutline = flag2; - } + } - // [HarmonyPrefix] // overrides again....... - // [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] // private static bool Unit_IsProjectile(ref bool __result, UnitData.WeaponEnum weapon) // { // if(!weaponProjectilesCache.ContainsKey(weapon)) @@ -156,8 +155,8 @@ public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovem // return false; // } - // [HarmonyPrefix] // overrides again....... - // [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] // private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Action onComplete) // { // UnitData.WeaponEnum weaponEnum = __instance.unitData.weapon; @@ -213,57 +212,57 @@ public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovem // return false; // } - // [HarmonyPrefix] // testing....... - // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] // public static bool WeaponGFX_AnimateCloseRangeAttack(ref float animTime, Action onComplete) // { // animTime = 100000f; // return true; // } - // [HarmonyPrefix] // testing....... - // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] // public static bool WeaponGFX_AnimateRanged(ref float animTime, WorldCoordinates to, Action onComplete) // { // animTime = 100000f; // return true; // } - private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) - { - if (SeasonManager.IsChristmas() - && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) - && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) - && christmasPrefab != null) - { - return christmasPrefab; - } - - SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); - if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) - { - return exactPrefab; - } - - if (skinType != SkinType.Default || tribeType != TribeType.None) - { - SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); - SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); - SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); - - if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) - || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) - || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) - { - unitsNew[exactKey] = fallbackPrefab; - return fallbackPrefab; - } - } - - Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); - unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); - return lastResortPrefab!; - } + private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + if (SeasonManager.IsChristmas() + && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) + && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) + && christmasPrefab != null) + { + return christmasPrefab; + } + + SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); + if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) + { + return exactPrefab; + } + + if (skinType != SkinType.Default || tribeType != TribeType.None) + { + SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); + SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); + SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); + + if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) + || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) + || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) + { + unitsNew[exactKey] = fallbackPrefab; + return fallbackPrefab; + } + } + + Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); + unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); + return lastResortPrefab!; + } internal static void CreatePrefabs() { @@ -273,7 +272,7 @@ internal static void CreatePrefabs() { // Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); - if(loadedMaterial.name == CACHED_SHARED_MATERIAL_NAME) + if (loadedMaterial.name == CACHED_SHARED_MATERIAL_NAME) { cachedSharedMaterial = loadedMaterial; GameObject.DontDestroyOnLoad(cachedSharedMaterial); @@ -373,7 +372,7 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) GameObject.DontDestroyOnLoad(unitInstance.gameObject); - if(unitPrefabInfo.uiOverride) + if (unitPrefabInfo.uiOverride) { unitUIOverridesNew[unitPrefabInfo.skinnedKey] = unitInstance; return; @@ -398,7 +397,7 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) foreach (var info in newVisualInfo) { parts.Add(CreateUnitVisualPart(info, spriteContainer, info.sortingOrderOverride ?? nextPartSortingOrder, info.outlineSortingOrderOverride ?? nextOutlineSortingOrder)); - if(nextOutlineSortingOrder < -1) + if (nextOutlineSortingOrder < -1) { nextOutlineSortingOrder++; } @@ -450,7 +449,7 @@ private static SkinVisualsReference.VisualPart CreateUnitVisualPart( #region Improvements internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvementPrefabInfo) { - if(improvementPrefabInfo.improvementType == null) + if (improvementPrefabInfo.improvementType == null) return; var baseBuilding = PrefabManager.GetPrefab(ImprovementData.Type.LumberHut); @@ -492,7 +491,7 @@ internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvem foreach (var info in visualPartInfos) { parts.Add(CreateBuildingVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder, improvementPrefabInfo.needsOutlines)); - if(nextOutlineSortingOrder < -1) + if (nextOutlineSortingOrder < -1) { nextOutlineSortingOrder++; } @@ -527,7 +526,7 @@ private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; - if(needsOutline) + if (needsOutline) { var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; @@ -563,7 +562,7 @@ private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject tar internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefabInfo) { - if(resourcePrefabInfo.resourceType == null) + if (resourcePrefabInfo.resourceType == null) return; var baseResource = PrefabManager.GetPrefab(ResourceData.Type.Game); @@ -605,7 +604,7 @@ internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefab foreach (var info in visualPartInfos) { parts.Add(CreateResourceVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); - if(nextOutlineSortingOrder < -1) + if (nextOutlineSortingOrder < -1) { nextOutlineSortingOrder++; } @@ -651,4 +650,4 @@ internal static void Init() { Harmony.CreateAndPatchAll(typeof(Prefabs)); } -} \ No newline at end of file +} diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index b0c41fd..fe82fb6 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -10,7 +10,7 @@ namespace PolyMod.Managers; public static class TribePreviews { - /// + /// /// Represents a tile in a tribe preview. /// public class PreviewTile @@ -43,7 +43,7 @@ public class PreviewTile public List tileEffects = new(); } - public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); + public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); [HarmonyPostfix] [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] @@ -52,7 +52,7 @@ public static void PreloadTribePreviews() Dictionary previewSaveStateDatas = new(); SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; - foreach(string tribe in Registry.tribePreviews.Keys) + foreach (string tribe in Registry.tribePreviews.Keys) { string previewId = "worldpreview_" + tribe; PreviewTile[] customPreview = Registry.tribePreviews[tribe]; @@ -62,7 +62,7 @@ public static void PreloadTribePreviews() for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) { SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; - if(previewSaveStateDatas.ContainsKey(saveStateData.name)) + if (previewSaveStateDatas.ContainsKey(saveStateData.name)) { previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, previewSaveStateDatas[saveStateData.name].customPreview); } @@ -72,10 +72,10 @@ public static void PreloadTribePreviews() { var data = previewSaveStateDatas[previewId]; SaveStateData? customSaveStateData = ApplyCustomPreview(previewId, data.saveStateData, data.customPreview); - if(customSaveStateData == null) + if (customSaveStateData == null) continue; - if(data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) + if (data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) { List saveStateDatas = TribePreviewRegistry.saveStateDatas.ToList(); saveStateDatas.Add(customSaveStateData); @@ -97,32 +97,32 @@ public static void PreloadTribePreviews() GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); foreach (var previewTile in preview) { - if(previewTile.x == null || previewTile.y == null) + if (previewTile.x == null || previewTile.y == null) continue; WorldCoordinates coordinates = new((int)previewTile.x, (int)previewTile.y); TileData? tileData = currentGameState.Map.GetTile(coordinates); - if(tileData == null) + if (tileData == null) continue; - if(previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) + if (previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) tileData.terrain = previewTile.terrainType; - if(previewTile.resourceType != null) + if (previewTile.resourceType != null) { ResourceState? resourceState = null; ResourceData.Type resourceType = (ResourceData.Type)previewTile.resourceType; - if(resourceType != ResourceData.Type.None) + if (resourceType != ResourceData.Type.None) { resourceState = new ResourceState { type = resourceType }; } tileData.resource = resourceState; } - if(previewTile.unitType != null) + if (previewTile.unitType != null) { tileData.unit = null; - if(previewTile.unitType != Polytopia.Data.UnitData.Type.None && + if (previewTile.unitType != Polytopia.Data.UnitData.Type.None && currentGameState.TryGetPlayer(currentGameState.CurrentPlayer, out PlayerState playerState) && currentGameState.GameLogicData.TryGetData((UnitData.Type)previewTile.unitType, out UnitData unitData)) { @@ -133,11 +133,11 @@ public static void PreloadTribePreviews() } - if(previewTile.improvementType != null) + if (previewTile.improvementType != null) { tileData.improvement = null; ImprovementData.Type improvementType = (ImprovementData.Type)previewTile.improvementType; - if( + if ( previewTile.improvementType != ImprovementData.Type.None && currentGameState.GameLogicData.TryGetData( improvementType, @@ -158,7 +158,7 @@ public static void PreloadTribePreviews() } } - if(previewTile.tileEffects.Count > 0) + if (previewTile.tileEffects.Count > 0) tileData.effects = new(); foreach (TileData.EffectType tileEffect in previewTile.tileEffects) @@ -179,7 +179,7 @@ public static void PreloadTribePreviews() [HarmonyPatch(typeof(SelectTribePopup), nameof(SelectTribePopup.SetBackground))] private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) { - if(!Plugin.config.showCoordinates) + if (!Plugin.config.showCoordinates) return; try @@ -200,7 +200,7 @@ private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) tribeType, __instance.SkinType ); - + var instance = SpriteCamera.instance; float baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; @@ -231,4 +231,4 @@ internal static void Init() { Harmony.CreateAndPatchAll(typeof(TribePreviews)); } -} \ No newline at end of file +} diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 82acd4d..26a5c59 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -59,8 +59,8 @@ public enum OriginType Inner // Inner means sprite is to be fetched from game's files } - /// Represents information about a custom skin. - public record SkinInfo(int idx, string id, SkinData? skinData); + /// Represents information about a custom skin. + public record SkinInfo(int idx, string id, SkinData? skinData); /// A dictionary of custom widths for basic popups. public static Dictionary basicPopupWidths = new(); @@ -83,61 +83,61 @@ public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); internal static Dictionary customFloodingSkins = new(); private static bool seenWarningWCPopup = false; - private static Dictionary? cachedSpriteDataReverse = null; + private static Dictionary? cachedSpriteDataReverse = null; private static Dictionary cachedReversedNames = new(); - #region General + #region General - /// A placeholder patch for the TechItem.SetupComplete method. - [HarmonyPostfix] - [HarmonyPatch(typeof(TechItem), nameof(TechItem.SetupComplete))] - private static void TechItem_SetupComplete() - { - } + /// A placeholder patch for the TechItem.SetupComplete method. + [HarmonyPostfix] + [HarmonyPatch(typeof(TechItem), nameof(TechItem.SetupComplete))] + private static void TechItem_SetupComplete() + { + } /// Patches the sprite atlas manager to look up custom sprites. internal static void CacheSpriteNames() { cachedSpriteDataReverse = new(); foreach (Polytopia.Data.TerrainData.Type terrainType in Enum.GetValues()) - { - string result = SpriteData.TerrainToString(terrainType); - if(terrainType == Polytopia.Data.TerrainData.Type.Wetland) - { - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(Polytopia.Data.TerrainData.Type.Field) + "_flooded"); - continue; - } - - if(result == SpriteData.TILE_UNKNOWN) - continue; - - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(terrainType)); - } - - foreach (ResourceData.Type resourceType in Enum.GetValues()) - { - string result = SpriteData.ResourceToString(resourceType); - if(result == SpriteData.IMPROVEMENT_PLACEHOLDER) - continue; - - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(resourceType)); - } - - foreach (ImprovementData.Type improvementType in Enum.GetValues()) - { - string result = SpriteData.ImprovementToString(improvementType); - if(result == SpriteData.IMPROVEMENT_PLACEHOLDER) - continue; - - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(improvementType)); - } - } - internal static string FormatSpriteName(string baseName) - { - if(cachedSpriteDataReverse == null) + { + string result = SpriteData.TerrainToString(terrainType); + if (terrainType == Polytopia.Data.TerrainData.Type.Wetland) + { + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(Polytopia.Data.TerrainData.Type.Field) + "_flooded"); + continue; + } + + if (result == SpriteData.TILE_UNKNOWN) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(terrainType)); + } + + foreach (ResourceData.Type resourceType in Enum.GetValues()) + { + string result = SpriteData.ResourceToString(resourceType); + if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(resourceType)); + } + + foreach (ImprovementData.Type improvementType in Enum.GetValues()) + { + string result = SpriteData.ImprovementToString(improvementType); + if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(improvementType)); + } + } + internal static string FormatSpriteName(string baseName) + { + if (cachedSpriteDataReverse == null) CacheSpriteNames(); - if(cachedReversedNames.ContainsKey(baseName)) + if (cachedReversedNames.ContainsKey(baseName)) return cachedReversedNames[baseName]; string formattedName = baseName; @@ -146,8 +146,8 @@ internal static string FormatSpriteName(string baseName) formattedName = formattedName.Replace(valuePair.Key, valuePair.Value); } cachedReversedNames[baseName] = formattedName; - return formattedName; - } + return formattedName; + } [HarmonyPostfix] [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.TrySolveSpriteNameForLevelSprites))] @@ -156,7 +156,7 @@ private static void SpriteAtlasManager_TrySolveSpriteNameForLevelSprites( SpriteAtlasManager __instance, Il2CppInterop.Runtime.InteropTypes.Arrays.Il2CppStringArray spriteNameVariants, int level, ref string result) { - if(!__result) __result = true; // will crash original lookup if false.... + if (!__result) __result = true; // will crash original lookup if false.... } [HarmonyPostfix] @@ -189,8 +189,8 @@ private static void ApplyRegisteredSprites( } [HarmonyPrefix] // its obsolete so may be removed soon by midjiwan - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[]{ typeof(string), typeof(string), typeof(SpriteCallback) })] - private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[] { typeof(string), typeof(string), typeof(SpriteCallback) })] + private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) { string formattedName = FormatSpriteName(sprite); @@ -214,7 +214,7 @@ private static bool LoadSprite(string atlas, string sprite, SpriteCallback compl [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) { - if((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) + if ((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) __result = EnumCache.GetName(terrain); } @@ -222,7 +222,7 @@ private static void SpriteData_TerrainToString(ref string __result, Polytopia.Da [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) { - if((int)resource >= Plugin.AUTOIDX_STARTS_FROM) + if ((int)resource >= Plugin.AUTOIDX_STARTS_FROM) __result = EnumCache.GetName(resource); } @@ -230,18 +230,18 @@ private static void SpriteData_ResourceToString(ref string __result, ResourceDat [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) { - if((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) + if ((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) __result = EnumCache.GetName(improvement); } - #endregion - #region Level + #endregion + #region Level [HarmonyPostfix] [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] public static void Tile_RenderDebug(Tile __instance) { - if(!Plugin.config.showCoordinates) + if (!Plugin.config.showCoordinates) return; GameObject textObj = new GameObject("CoordinateText"); @@ -294,8 +294,8 @@ private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, T { Polytopia.Data.TerrainData.Type.Water => __instance.waterSprites.GetSpriteName(tile), Polytopia.Data.TerrainData.Type.Ocean => __instance.oceanSprites.GetSpriteName(tile), - Polytopia.Data.TerrainData.Type.Ice => __instance.iceSprites.GetSpriteName(tile), - _ => GetLandSpriteName(tile.Data), + Polytopia.Data.TerrainData.Type.Ice => __instance.iceSprites.GetSpriteName(tile), + _ => GetLandSpriteName(tile.Data), }; SpriteAtlasManager.SpriteLookupResult spriteLookupResult = GameManager.GetSpriteAtlasManager().DoSpriteLookup(spriteName, climate, skin); @@ -312,33 +312,33 @@ private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, T return false; } - /// Adds custom flood tile effect when tile is flooded for custom aqua skins. - [HarmonyPostfix] - [HarmonyPatch(typeof(TileData), nameof(TileData.Flood))] - private static void TileData_Flood(TileData __instance, PlayerState playerState) - { - if (customFloodingSkins.ContainsValue(playerState.skinType)) - { - TileData.EffectType effectType = customFloodingSkins.FirstOrDefault(x => x.Value == playerState.skinType).Key; - __instance.AddEffect(effectType); - } - } - - /// Removes custom flood effect loc from tile tip header. - [HarmonyPostfix] - [HarmonyPatch(typeof(TileTipGenerator), nameof(TileTipGenerator.GetTileTipHeader))] - public static void GetTileTipHeader(ref string __result, TileData tileData, SkinType skin, - PlayerState playerState, GameState gameState, GameLogicData gameLogicData) - { - foreach (var effect in tileData.effects) - { - if (customFloodingSkins.ContainsKey(effect)) - { - string localizedEffect = Localization.GetSkinned(skin, playerState.tribe, $"tile.effect.{effect.GetName()}"); - __result = __result.Replace($", {localizedEffect}", string.Empty); - } - } - } + /// Adds custom flood tile effect when tile is flooded for custom aqua skins. + [HarmonyPostfix] + [HarmonyPatch(typeof(TileData), nameof(TileData.Flood))] + private static void TileData_Flood(TileData __instance, PlayerState playerState) + { + if (customFloodingSkins.ContainsValue(playerState.skinType)) + { + TileData.EffectType effectType = customFloodingSkins.FirstOrDefault(x => x.Value == playerState.skinType).Key; + __instance.AddEffect(effectType); + } + } + + /// Removes custom flood effect loc from tile tip header. + [HarmonyPostfix] + [HarmonyPatch(typeof(TileTipGenerator), nameof(TileTipGenerator.GetTileTipHeader))] + public static void GetTileTipHeader(ref string __result, TileData tileData, SkinType skin, + PlayerState playerState, GameState gameState, GameLogicData gameLogicData) + { + foreach (var effect in tileData.effects) + { + if (customFloodingSkins.ContainsKey(effect)) + { + string localizedEffect = Localization.GetSkinned(skin, playerState.tribe, $"tile.effect.{effect.GetName()}"); + __result = __result.Replace($", {localizedEffect}", string.Empty); + } + } + } /// Forces an update of the mesh for a PolytopiaSpriteRenderer with a custom sprite. [HarmonyPostfix] @@ -354,16 +354,16 @@ private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRende __instance.meshRenderer.SetPropertyBlock(materialPropertyBlock); } - #endregion - #region Popups + #endregion + #region Popups - /// Updates the width of a basic popup if a custom width is set. - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines))] - private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(PopupBase __instance) - { - UpdateWidth(__instance); - } + /// Updates the width of a basic popup if a custom width is set. + [HarmonyPostfix] + [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines))] + private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(PopupBase __instance) + { + UpdateWidth(__instance); + } private static void UpdateWidth(PopupBase popup) { @@ -501,51 +501,51 @@ private static void PlaceButtonRow(List row, float offsetY) } } - /// Removes a popup's custom width when it is hidden. - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] - private static void PopupBase_Hide(PopupBase __instance) - { - basicPopupWidths.Remove(__instance.GetInstanceID()); - } + /// Removes a popup's custom width when it is hidden. + [HarmonyPostfix] + [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] + private static void PopupBase_Hide(PopupBase __instance) + { + basicPopupWidths.Remove(__instance.GetInstanceID()); + } - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] - private static void StartScreen_UI2_OnShow() - { - CreateInnerOriginSprites(); + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] + private static void StartScreen_UI2_OnShow() + { + CreateInnerOriginSprites(); } [HarmonyPrefix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] private static bool StartScreen_OnWeeklyChallengeClicked(StartScreen_UI2 __instance) { - if(seenWarningWCPopup) + if (seenWarningWCPopup) return true; - BasicPopup popup = PopupManager.GetBasicPopup(); - popup.Header = Localization.Get("polymod.hub"); - popup.Description = Localization.Get("polymod.wc.warning", new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", new Il2CppSystem.Object[] { }) }); - - void WCProceed() - { - seenWarningWCPopup = true; - __instance.OnWeeklyChallengeClicked(); - } - List popupButtons = new() - { - new("buttons.back"), - new( - "polymod.wc.proceed", - PopupBase.PopupButtonData.States.None, - callback: DelegateSupport.ConvertDelegate(WCProceed), - customColorStates: ColorConstants.redButtonColorStates - ) - }; - popup.buttonData = popupButtons.ToArray(); - popup.Show(); - return false; - } + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = Localization.Get("polymod.wc.warning", new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", new Il2CppSystem.Object[] { }) }); + + void WCProceed() + { + seenWarningWCPopup = true; + __instance.OnWeeklyChallengeClicked(); + } + List popupButtons = new() + { + new("buttons.back"), + new( + "polymod.wc.proceed", + PopupBase.PopupButtonData.States.None, + callback: DelegateSupport.ConvertDelegate(WCProceed), + customColorStates: ColorConstants.redButtonColorStates + ) + }; + popup.buttonData = popupButtons.ToArray(); + popup.Show(); + return false; + } /// Shows a basic popup with a custom width. public static void ShowSetWidth(this BasicPopupLegacy self, int width) @@ -561,21 +561,21 @@ public static void ShowSetWidth(this BasicPopupLegacy self, float share, float m self.Show(); } - #endregion + #endregion - internal static BasicPopupLegacy GetBasicPopupLegacy() - { - WhatsNewPopup whatsNewPopup = PopupManager.GetWhatsNewPopup(); - BasicPopupLegacy original = PopupManager.instance.popupPrefabs[BASIC_POPUP_LEGACY_ID].Cast(); - BasicPopupLegacy basicPopupLegacy = UnityEngine.Object.Instantiate(original, PopupManager.instance.transform); - basicPopupLegacy.buttonContainer = GameObject.Instantiate(whatsNewPopup.buttonContainer, basicPopupLegacy.transform); - basicPopupLegacy.popupId = "basicPopupLegacy"; - basicPopupLegacy.popupManager = PopupManager.instance; - basicPopupLegacy.Init(); - basicPopupLegacy.identifier = null; - basicPopupLegacy.rectTransform.SetAsLastSibling(); - return basicPopupLegacy; - } + internal static BasicPopupLegacy GetBasicPopupLegacy() + { + WhatsNewPopup whatsNewPopup = PopupManager.GetWhatsNewPopup(); + BasicPopupLegacy original = PopupManager.instance.popupPrefabs[BASIC_POPUP_LEGACY_ID].Cast(); + BasicPopupLegacy basicPopupLegacy = UnityEngine.Object.Instantiate(original, PopupManager.instance.transform); + basicPopupLegacy.buttonContainer = GameObject.Instantiate(whatsNewPopup.buttonContainer, basicPopupLegacy.transform); + basicPopupLegacy.popupId = "basicPopupLegacy"; + basicPopupLegacy.popupManager = PopupManager.instance; + basicPopupLegacy.Init(); + basicPopupLegacy.identifier = null; + basicPopupLegacy.rectTransform.SetAsLastSibling(); + return basicPopupLegacy; + } public static Texture2D BuildTexture(byte[] data) { @@ -603,65 +603,65 @@ public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixel /// The created sprite. public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) { - if(transformToOutline) texture = TransformToOutline(texture); + if (transformToOutline) texture = TransformToOutline(texture); - if(gaussianBlurRadius != null) texture = ApplyGaussianBlur(texture, gaussianBlurRadius.Value); + if (gaussianBlurRadius != null) texture = ApplyGaussianBlur(texture, gaussianBlurRadius.Value); return Sprite.Create( texture, new(0, 0, texture.width, texture.height), pivot ?? new(0.5f, 0.5f), pixelsPerUnit ?? 2112f - );; + ); ; } - public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSizeInPixels = 8, Color? color = null) - { + public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSizeInPixels = 8, Color? color = null) + { Plugin.logger.LogInfo("Transforming texture to outline..."); - if(color == null) + if (color == null) color = Color.white; - int sourceWidthInPixels = sourceTexture.width; - int sourceHeightInPixels = sourceTexture.height; - int outputWidthInPixels = sourceWidthInPixels + borderSizeInPixels * 2; - int outputHeightInPixels = sourceHeightInPixels + borderSizeInPixels * 2; - - Color[] sourcePixels = sourceTexture.GetPixels(); - bool[] filledMask = new bool[outputWidthInPixels * outputHeightInPixels]; - int borderSquared = borderSizeInPixels * borderSizeInPixels; - - for (int pixelY = 0; pixelY < sourceHeightInPixels; pixelY++) - { - for (int pixelX = 0; pixelX < sourceWidthInPixels; pixelX++) - { - if (sourcePixels[pixelY * sourceWidthInPixels + pixelX].a <= 0.01f) continue; - - int centerX = pixelX + borderSizeInPixels; - int centerY = pixelY + borderSizeInPixels; - - for (int offsetY = -borderSizeInPixels; offsetY <= borderSizeInPixels; offsetY++) - { - for (int offsetX = -borderSizeInPixels; offsetX <= borderSizeInPixels; offsetX++) - { - if (offsetX * offsetX + offsetY * offsetY > borderSquared) continue; - - filledMask[(centerY + offsetY) * outputWidthInPixels + (centerX + offsetX)] = true; - } - } - } - } - - Color[] outputPixels = new Color[filledMask.Length]; - for (int pixelIndex = 0; pixelIndex < outputPixels.Length; pixelIndex++) - { - outputPixels[pixelIndex] = filledMask[pixelIndex] ? color.Value : Color.clear; - } - - Texture2D whiteSilhouetteTexture = new Texture2D(outputWidthInPixels, outputHeightInPixels, TextureFormat.RGBA32, false); - whiteSilhouetteTexture.SetPixels(outputPixels); - whiteSilhouetteTexture.Apply(); - return whiteSilhouetteTexture; - } + int sourceWidthInPixels = sourceTexture.width; + int sourceHeightInPixels = sourceTexture.height; + int outputWidthInPixels = sourceWidthInPixels + borderSizeInPixels * 2; + int outputHeightInPixels = sourceHeightInPixels + borderSizeInPixels * 2; + + Color[] sourcePixels = sourceTexture.GetPixels(); + bool[] filledMask = new bool[outputWidthInPixels * outputHeightInPixels]; + int borderSquared = borderSizeInPixels * borderSizeInPixels; + + for (int pixelY = 0; pixelY < sourceHeightInPixels; pixelY++) + { + for (int pixelX = 0; pixelX < sourceWidthInPixels; pixelX++) + { + if (sourcePixels[pixelY * sourceWidthInPixels + pixelX].a <= 0.01f) continue; + + int centerX = pixelX + borderSizeInPixels; + int centerY = pixelY + borderSizeInPixels; + + for (int offsetY = -borderSizeInPixels; offsetY <= borderSizeInPixels; offsetY++) + { + for (int offsetX = -borderSizeInPixels; offsetX <= borderSizeInPixels; offsetX++) + { + if (offsetX * offsetX + offsetY * offsetY > borderSquared) continue; + + filledMask[(centerY + offsetY) * outputWidthInPixels + (centerX + offsetX)] = true; + } + } + } + } + + Color[] outputPixels = new Color[filledMask.Length]; + for (int pixelIndex = 0; pixelIndex < outputPixels.Length; pixelIndex++) + { + outputPixels[pixelIndex] = filledMask[pixelIndex] ? color.Value : Color.clear; + } + + Texture2D whiteSilhouetteTexture = new Texture2D(outputWidthInPixels, outputHeightInPixels, TextureFormat.RGBA32, false); + whiteSilhouetteTexture.SetPixels(outputPixels); + whiteSilhouetteTexture.Apply(); + return whiteSilhouetteTexture; + } private static float[] BuildGaussianKernelWeights(float sigma, int kernelRadiusInPixels) { @@ -877,58 +877,58 @@ private static Vector2 GetNormalizedPivot(Sprite sourceSprite) ); } - private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) - { - Texture2D atlasTexture = sourceSprite.texture; - int spriteWidth = (int)sourceSprite.rect.width; - int spriteHeight = (int)sourceSprite.rect.height; - float sourcePixelsPerUnit = sourceSprite.pixelsPerUnit; - Vector2 sourcePivotInPixels = sourceSprite.pivot; - - var meshVertices = sourceSprite.vertices; - var meshUvs = sourceSprite.uv; - var meshTriangles = sourceSprite.triangles; - - RenderTexture renderTexture = RenderTexture.GetTemporary( - spriteWidth, spriteHeight, 0, - RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); - RenderTexture previousActiveRenderTexture = RenderTexture.active; - RenderTexture.active = renderTexture; - GL.Clear(true, true, Color.clear); - - Material spriteMaterial = new Material(Shader.Find("Sprites/Default")); - spriteMaterial.mainTexture = atlasTexture; - spriteMaterial.SetPass(0); - - GL.PushMatrix(); - GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); - GL.Begin(GL.TRIANGLES); - for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) - { - int vertexIndex = meshTriangles[triangleCornerIndex]; - Vector2 uv = meshUvs[vertexIndex]; - Vector2 vertex = meshVertices[vertexIndex]; - - GL.TexCoord(new Vector3(uv.x, uv.y, 0)); - GL.Vertex3( - vertex.x * sourcePixelsPerUnit + sourcePivotInPixels.x, - vertex.y * sourcePixelsPerUnit + sourcePivotInPixels.y, - 0); - } - GL.End(); - GL.PopMatrix(); - - Texture2D bakedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); - bakedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); - bakedTexture.Apply(); - bakedTexture.wrapMode = TextureWrapMode.Clamp; - - RenderTexture.active = previousActiveRenderTexture; - RenderTexture.ReleaseTemporary(renderTexture); - UnityEngine.Object.Destroy(spriteMaterial); - - return bakedTexture; - } + private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) + { + Texture2D atlasTexture = sourceSprite.texture; + int spriteWidth = (int)sourceSprite.rect.width; + int spriteHeight = (int)sourceSprite.rect.height; + float sourcePixelsPerUnit = sourceSprite.pixelsPerUnit; + Vector2 sourcePivotInPixels = sourceSprite.pivot; + + var meshVertices = sourceSprite.vertices; + var meshUvs = sourceSprite.uv; + var meshTriangles = sourceSprite.triangles; + + RenderTexture renderTexture = RenderTexture.GetTemporary( + spriteWidth, spriteHeight, 0, + RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); + RenderTexture previousActiveRenderTexture = RenderTexture.active; + RenderTexture.active = renderTexture; + GL.Clear(true, true, Color.clear); + + Material spriteMaterial = new Material(Shader.Find("Sprites/Default")); + spriteMaterial.mainTexture = atlasTexture; + spriteMaterial.SetPass(0); + + GL.PushMatrix(); + GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); + GL.Begin(GL.TRIANGLES); + for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) + { + int vertexIndex = meshTriangles[triangleCornerIndex]; + Vector2 uv = meshUvs[vertexIndex]; + Vector2 vertex = meshVertices[vertexIndex]; + + GL.TexCoord(new Vector3(uv.x, uv.y, 0)); + GL.Vertex3( + vertex.x * sourcePixelsPerUnit + sourcePivotInPixels.x, + vertex.y * sourcePixelsPerUnit + sourcePivotInPixels.y, + 0); + } + GL.End(); + GL.PopMatrix(); + + Texture2D bakedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); + bakedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); + bakedTexture.Apply(); + bakedTexture.wrapMode = TextureWrapMode.Clamp; + + RenderTexture.active = previousActiveRenderTexture; + RenderTexture.ReleaseTemporary(renderTexture); + UnityEngine.Object.Destroy(spriteMaterial); + + return bakedTexture; + } public static void CreateInnerOriginSprites() { diff --git a/src/Mod.cs b/src/Mod.cs index 5c5de5b..684d035 100644 --- a/src/Mod.cs +++ b/src/Mod.cs @@ -5,114 +5,119 @@ namespace PolyMod; /// public class Mod { - /// - /// Represents a dependency of a mod. - /// - /// The unique identifier of the dependency. - /// The minimum compatible version of the dependency, or null for no minimum. - /// The maximum compatible version of the dependency, or null for no maximum. - /// Whether the dependency is required for the mod to function. - public record Dependency(string id, Version? min, Version? max, bool required = true); + /// + /// Represents a dependency of a mod. + /// + /// The unique identifier of the dependency. + /// The minimum compatible version of the dependency, or null for no minimum. + /// The maximum compatible version of the dependency, or null for no maximum. + /// Whether the dependency is required for the mod to function. + public record Dependency(string id, Version? min, Version? max, bool required = true); - /// - /// Represents the manifest of a mod, containing metadata. - /// - /// The unique identifier of the mod. - /// The name of the mod. - /// A description of the mod. - /// The version of the mod. - /// The authors of the mod. - /// The dependencies of the mod. - /// Whether the mod is client-side only. - public record Manifest(string id, string? name, string? description, Version version, string[] authors, Dependency[]? dependencies, bool client = false); + /// + /// Represents the manifest of a mod, containing metadata. + /// + /// The unique identifier of the mod. + /// The name of the mod. + /// A description of the mod. + /// The version of the mod. + /// The authors of the mod. + /// The dependencies of the mod. + /// Whether the mod is client-side only. + public record Manifest(string id, string? name, string? description, Version version, string[] authors, Dependency[]? dependencies, bool client = false); - /// - /// Represents a file included in a mod. - /// - /// The name of the file. - /// The content of the file as a byte array. - public record File(string name, byte[] bytes); + /// + /// Represents a file included in a mod. + /// + /// The name of the file. + /// The content of the file as a byte array. + public record File(string name, byte[] bytes); - /// - /// Represents the loading status of a mod. - /// - public enum Status - { - /// - /// The mod was loaded successfully. - /// - Success, - /// - /// An error occurred while loading the mod. - /// - Error, - /// - /// The mod's dependencies were not satisfied. - /// - DependenciesUnsatisfied, - } + /// + /// Represents the loading status of a mod. + /// + public enum Status + { + /// + /// The mod was loaded successfully. + /// + Success, + /// + /// An error occurred while loading the mod. + /// + Error, + /// + /// The mod's dependencies were not satisfied. + /// + DependenciesUnsatisfied, + } - /// - /// The unique identifier of the mod. - /// - public string id; + /// + /// The unique identifier of the mod. + /// + public string id; - /// - /// The name of the mod. - /// - public string? name; + /// + /// The name of the mod. + /// + public string? name; - /// - /// A description of the mod. - /// - public string? description; + /// + /// A description of the mod. + /// + public string? description; - /// - /// The version of the mod. - /// - public Version version; + /// + /// The version of the mod. + /// + public Version version; - /// - /// The authors of the mod. - /// - public string[] authors; + /// + /// The authors of the mod. + /// + public string[] authors; - /// - /// The dependencies of the mod. - /// - public Dependency[]? dependencies; + /// + /// The dependencies of the mod. + /// + public Dependency[]? dependencies; - /// - /// Whether the mod is client-side only. - /// - public bool client; + /// + /// Whether the mod is client-side only. + /// + public bool client; - /// - /// The loading status of the mod. - /// - public Status status; + /// + /// The loading status of the mod. + /// + public Status status; - /// - /// The files included in the mod. - /// - public List files; + /// + /// The files included in the mod. + /// + public List files; - /// - /// Initializes a new instance of the class. - /// - /// The manifest of the mod. - /// The loading status of the mod. - /// The files included in the mod. - public Mod(Manifest manifest, Status status, List files) - { - id = manifest.id; - name = manifest.name ?? manifest.id; - description = manifest.description; - version = manifest.version; - authors = manifest.authors; - dependencies = manifest.dependencies; - client = manifest.client; - this.status = status; - this.files = files; - } + /// + /// The checksum of the mod, derived from its id, version and file contents. + /// + public string checksum = string.Empty; + + /// + /// Initializes a new instance of the class. + /// + /// The manifest of the mod. + /// The loading status of the mod. + /// The files included in the mod. + public Mod(Manifest manifest, Status status, List files) + { + id = manifest.id; + name = manifest.name ?? manifest.id; + description = manifest.description; + version = manifest.version; + authors = manifest.authors; + dependencies = manifest.dependencies; + client = manifest.client; + this.status = status; + this.files = files; + } } diff --git a/src/NullableFix.cs b/src/NullableFix.cs index 1c7e549..6048dd2 100644 --- a/src/NullableFix.cs +++ b/src/NullableFix.cs @@ -2,48 +2,48 @@ // verify whether it is needed at all bruv, i tested one time quickly and it easily compiled namespace System.Runtime.CompilerServices { - /// - /// A polyfill for the Nullable attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] - public sealed class NullableAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The nullable flags. - public NullableAttribute(byte b) { } + /// + /// A polyfill for the Nullable attribute, which is used by the compiler for nullable reference type analysis. + /// + [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] + public sealed class NullableAttribute : System.Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The nullable flags. + public NullableAttribute(byte b) { } - /// - /// Initializes a new instance of the class. - /// - /// The nullable flags. - public NullableAttribute(byte[] b) { } - } + /// + /// Initializes a new instance of the class. + /// + /// The nullable flags. + public NullableAttribute(byte[] b) { } + } - /// - /// A polyfill for the NullableContext attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false)] - public sealed class NullableContextAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The nullable context flags. - public NullableContextAttribute(byte b) { } - } + /// + /// A polyfill for the NullableContext attribute, which is used by the compiler for nullable reference type analysis. + /// + [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false)] + public sealed class NullableContextAttribute : System.Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The nullable context flags. + public NullableContextAttribute(byte b) { } + } - /// - /// A polyfill for the NullablePublicOnly attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.Module)] - public sealed class NullablePublicOnlyAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// Whether to apply nullable analysis to public members only. - public NullablePublicOnlyAttribute(bool b) { } - } + /// + /// A polyfill for the NullablePublicOnly attribute, which is used by the compiler for nullable reference type analysis. + /// + [System.AttributeUsage(System.AttributeTargets.Module)] + public sealed class NullablePublicOnlyAttribute : System.Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// Whether to apply nullable analysis to public members only. + public NullablePublicOnlyAttribute(bool b) { } + } } diff --git a/src/Plugin.cs b/src/Plugin.cs index 6fdfc0e..1c64fc4 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -1,4 +1,4 @@ -using System.IO.Pipes; +using System.IO.Pipes; using System.Reflection; using System.Text.Json; using BepInEx; @@ -14,7 +14,7 @@ namespace PolyMod; [BepInPlugin("com.polymod", "PolyMod", VERSION)] public partial class Plugin : BepInEx.Unity.IL2CPP.BasePlugin { - internal static string? Token { get; set; } + internal static string? Token { get; set; } internal static bool ValidLaunch { get; set; } = false; internal static bool Disabled { get; set; } = false; @@ -29,19 +29,24 @@ internal record PolyConfig( string overrideDeviceId = "" ) { - public List disabledMods { get; init; } = new(); + public List disabledMods { get; init; } = new(); }; - /// - /// The starting index for automatically assigned IDs. - /// - internal const int AUTOIDX_STARTS_FROM = 1000; + /// + /// The starting index for automatically assigned IDs. + /// + internal const int AUTOIDX_STARTS_FROM = 1000; - /// - /// The key used to store the last version for which the incompatibility warning was shown. - /// - internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY - = "INCOMPATIBILITY_WARNING_LAST_VERSION"; + /// + /// The key used to store the last version for which the incompatibility warning was shown. + /// + internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY + = "INCOMPATIBILITY_WARNING_LAST_VERSION"; + + /// + /// The prefix of the player prefs keys holding the mod checksum a saved game was created with. + /// + internal const string STATE_CHECKSUM_KEY_PREFIX = "POLYMOD_STATE_CHECKSUM_"; internal const int LAUNCH_DATA_TIMEOUT = 2000; @@ -50,25 +55,25 @@ internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY /// public static readonly string BASE_PATH = Path.Combine(BepInEx.Paths.BepInExRootPath, ".."); - /// - /// The path to the mods directory. - /// - public static readonly string MODS_PATH = Path.Combine(BASE_PATH, "Mods"); + /// + /// The path to the mods directory. + /// + public static readonly string MODS_PATH = Path.Combine(BASE_PATH, "Mods"); - /// - /// The path to the directory where game data is dumped. - /// - public static readonly string DUMPED_DATA_PATH = Path.Combine(BASE_PATH, "DumpedData"); + /// + /// The path to the directory where game data is dumped. + /// + public static readonly string DUMPED_DATA_PATH = Path.Combine(BASE_PATH, "DumpedData"); - /// - /// The path to the directory where localization is dumped. - /// - public static readonly string LOGIC_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Logic"); + /// + /// The path to the directory where localization is dumped. + /// + public static readonly string LOGIC_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Logic"); - /// - /// The path to the directory where gameLogicData and avatarData are dumped. - /// - public static readonly string LOCALIZATION_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Localization"); + /// + /// The path to the directory where gameLogicData and avatarData are dumped. + /// + public static readonly string LOCALIZATION_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Localization"); /// /// The path to the directory where sprites and sprite infos are dumped. @@ -85,66 +90,66 @@ internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY /// internal static readonly string CONFIG_PATH = Path.Combine(BASE_PATH, "PolyMod.json"); - /// - /// The path to the checksum file. - /// - internal static readonly string CHECKSUM_PATH - = Path.Combine(BASE_PATH, "CHECKSUM"); - - /// - /// The link to the PolyMod Discord server. - /// - internal static readonly string DISCORD_LINK = "https://discord.gg/eWPdhWtfVy"; - - /// - /// A list of log messages to ignore. - /// - internal static readonly List LOG_MESSAGES_IGNORE = new() - { - "Failed to find atlas", - "Could not find sprite", - "Couldn't find prefab for type", - "MARKET: id:", - "Missing name for value", - }; + /// + /// The path to the checksum file. + /// + internal static readonly string CHECKSUM_PATH + = Path.Combine(BASE_PATH, "CHECKSUM"); + + /// + /// The link to the PolyMod Discord server. + /// + internal static readonly string DISCORD_LINK = "https://discord.gg/eWPdhWtfVy"; + + /// + /// A list of log messages to ignore. + /// + internal static readonly List LOG_MESSAGES_IGNORE = new() + { + "Failed to find atlas", + "Could not find sprite", + "Couldn't find prefab for type", + "MARKET: id:", + "Missing name for value", + }; #pragma warning disable CS8618 - /// - /// The PolyMod configuration. - /// - internal static PolyConfig config; - - /// - /// The logger instance for PolyMod. - /// - internal static ManualLogSource logger; + /// + /// The PolyMod configuration. + /// + internal static PolyConfig config; + + /// + /// The logger instance for PolyMod. + /// + internal static ManualLogSource logger; #pragma warning restore CS8618 - /// - /// The entry point for the plugin. - /// - public override void Load() - { - try - { - config = JsonSerializer.Deserialize(File.ReadAllText(CONFIG_PATH))!; - } - catch - { - config = new(); - } - WriteConfig(); - UpdateConsole(); - logger = Log; - ConfigFile.CoreConfig[new("Logging.Disk", "WriteUnityLog")].BoxedValue = true; + /// + /// The entry point for the plugin. + /// + public override void Load() + { + try + { + config = JsonSerializer.Deserialize(File.ReadAllText(CONFIG_PATH))!; + } + catch + { + config = new(); + } + WriteConfig(); + UpdateConsole(); + logger = Log; + ConfigFile.CoreConfig[new("Logging.Disk", "WriteUnityLog")].BoxedValue = true; CaptureLaunchData(); - if(Disabled) + if (Disabled) return; - Compatibility.Init(); + Compatibility.Init(); Audio.Init(); Loc.Init(); @@ -194,13 +199,13 @@ internal static Stream GetResource(string id) )!; } - /// - /// Writes the configuration to disk. - /// - internal static void WriteConfig() - { - File.WriteAllText(CONFIG_PATH, JsonSerializer.Serialize(config)); - } + /// + /// Writes the configuration to disk. + /// + internal static void WriteConfig() + { + File.WriteAllText(CONFIG_PATH, JsonSerializer.Serialize(config)); + } /// /// Updates the console based on the debug configuration. diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index 1b5ca10..a0eee86 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -8,110 +8,110 @@ namespace PolyMod; public class BasePrefabInfo { - [JsonInclude] - public List visualParts = new(); + [JsonInclude] + public List visualParts = new(); } public class UnitPrefabInfo : BasePrefabInfo { - [JsonInclude] - public SkinnedKey skinnedKey; + [JsonInclude] + public SkinnedKey skinnedKey; - [JsonInclude] - public string headPositionMarker = ""; + [JsonInclude] + public string headPositionMarker = ""; - [JsonInclude] - public bool uiOverride = false; + [JsonInclude] + public bool uiOverride = false; } public class ImprovementPrefabInfo : BasePrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ImprovementData.Type? improvementType = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; - [JsonInclude] - public bool needsOutlines = false; + [JsonInclude] + public bool needsOutlines = false; } public class ResourcePrefabInfo : BasePrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ResourceData.Type? resourceType = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; } internal class WeaponPrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - internal UnitData.WeaponEnum? weaponEnum = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal UnitData.WeaponEnum? weaponEnum = null; - [JsonInclude] - internal string spriteName = ""; + [JsonInclude] + internal string spriteName = ""; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] internal PathType pathType = PathType.CatmullRom; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] internal PathMode pathMode = PathMode.Sidescroller2D; - [JsonInclude] + [JsonInclude] internal int pathResolution = 10; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] internal Ease pathEase = Ease.Linear; - [JsonInclude] + [JsonInclude] internal float lookAheadOffset = 0.01f; - [JsonInclude] + [JsonInclude] internal float handleAngleOffset = 0.3f; - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] internal SFXTypes sfxType = SFXTypes.None; - [JsonInclude] - internal WeaponPuffInfo? weaponPuffInfo = null; + [JsonInclude] + internal WeaponPuffInfo? weaponPuffInfo = null; - [JsonInclude] + [JsonInclude] internal WeaponRangedInfo? weaponRangedInfo = null; } internal class WeaponPuffInfo { - [JsonInclude] - internal bool sway = false; + [JsonInclude] + internal bool sway = false; - internal float animationMultiplier = 1f; + internal float animationMultiplier = 1f; - internal Action? initialDelegate = null; + internal Action? initialDelegate = null; - internal Action? animationDelegate = null; + internal Action? animationDelegate = null; - // [JsonInclude] Nuh uh, I wont do ts - // public List puffsToSpawn = new(); + // [JsonInclude] Nuh uh, I wont do ts + // public List puffsToSpawn = new(); } internal class WeaponRangedInfo { - [JsonInclude] + [JsonInclude] internal float centerOffset = 0.15f; } internal class GFXPrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - internal GFXType? gfxType = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal GFXType? gfxType = null; } internal class UnitEffectPrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - internal UnitEffect? unitEffect = null; -} \ No newline at end of file + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal UnitEffect? unitEffect = null; +} diff --git a/src/Prefabs/PrefabsInfo.cs b/src/Prefabs/PrefabsInfo.cs index 09c867e..5da59c4 100644 --- a/src/Prefabs/PrefabsInfo.cs +++ b/src/Prefabs/PrefabsInfo.cs @@ -5,15 +5,15 @@ namespace PolyMod; public class PrefabsInfo { - [JsonInclude] - public List units = new(); + [JsonInclude] + public List units = new(); - [JsonInclude] - public List improvements = new(); + [JsonInclude] + public List improvements = new(); - [JsonInclude] - public List resources = new(); + [JsonInclude] + public List resources = new(); - // [JsonInclude] - private List weapons = new(); -} \ No newline at end of file + // [JsonInclude] + private List weapons = new(); +} diff --git a/src/Prefabs/SkinnedKey.cs b/src/Prefabs/SkinnedKey.cs index 080b6df..a4bbb79 100644 --- a/src/Prefabs/SkinnedKey.cs +++ b/src/Prefabs/SkinnedKey.cs @@ -7,40 +7,40 @@ namespace PolyMod; public readonly struct SkinnedKey : IEquatable { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public UnitData.Type unitType { get; } - - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public TribeType tribeType { get; } - - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public SkinType skinType { get; } - - [JsonConstructor] - public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) - { - this.unitType = unitType; - this.tribeType = tribeType; - this.skinType = skinType; - } - - public bool Equals(SkinnedKey other) - { - return unitType == other.unitType - && tribeType == other.tribeType - && skinType == other.skinType; - } - - public override bool Equals(object? other) - { - return other is SkinnedKey otherKey && Equals(otherKey); - } - - public override int GetHashCode() - { - return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); - } -} \ No newline at end of file + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.Type unitType { get; } + + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public TribeType tribeType { get; } + + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public SkinType skinType { get; } + + [JsonConstructor] + public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + this.unitType = unitType; + this.tribeType = tribeType; + this.skinType = skinType; + } + + public bool Equals(SkinnedKey other) + { + return unitType == other.unitType + && tribeType == other.tribeType + && skinType == other.skinType; + } + + public override bool Equals(object? other) + { + return other is SkinnedKey otherKey && Equals(otherKey); + } + + public override int GetHashCode() + { + return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); + } +} diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs index 27105a2..329b3ef 100644 --- a/src/Prefabs/VisualPartInfo.cs +++ b/src/Prefabs/VisualPartInfo.cs @@ -6,38 +6,38 @@ namespace PolyMod; public class VisualPartInfo { - [JsonInclude] - public string? defaultSpriteName; + [JsonInclude] + public string? defaultSpriteName; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific - [JsonInclude] - public Vector2 coordinates = new Vector2(0, 0); + [JsonInclude] + public Vector2 coordinates = new Vector2(0, 0); - [JsonInclude] - public float rotation = 0f; + [JsonInclude] + public float rotation = 0f; - [JsonInclude] - public bool tintable = false; + [JsonInclude] + public bool tintable = false; - [JsonInclude] - public bool levels = false; // improvement specific + [JsonInclude] + public bool levels = false; // improvement specific - [JsonInclude] - public int? sortingOrderOverride = null; + [JsonInclude] + public int? sortingOrderOverride = null; - [JsonInclude] - public int? outlineSortingOrderOverride = null; + [JsonInclude] + public int? outlineSortingOrderOverride = null; - public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) - { - return new SkinVisualsReference.VisualPart + public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) + { + return new SkinVisualsReference.VisualPart { DefaultSpriteName = defaultSpriteName, tintable = tintable, @@ -46,36 +46,36 @@ public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) levels = levels, isImprovement = isImprovement, }; - } + } - public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) - { - int? sortingOrderOverride = null; - SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); - if (spriteRenderer != null) - { - sortingOrderOverride = spriteRenderer.sortingOrder; - } + public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) + { + int? sortingOrderOverride = null; + SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); + if (spriteRenderer != null) + { + sortingOrderOverride = spriteRenderer.sortingOrder; + } - int? outlineSortingOrderOverride = null; + int? outlineSortingOrderOverride = null; - if (visualPart.outline != null) - { - spriteRenderer = visualPart.outline.GetComponent(); - if (spriteRenderer != null) - { - outlineSortingOrderOverride = spriteRenderer.sortingOrder; - } - } + if (visualPart.outline != null) + { + spriteRenderer = visualPart.outline.GetComponent(); + if (spriteRenderer != null) + { + outlineSortingOrderOverride = spriteRenderer.sortingOrder; + } + } - coordinates = visualPart.visualPart.transform.position; - rotation = visualPart.visualPart.transform.rotation.z; - defaultSpriteName = visualPart.DefaultSpriteName; - tintable = visualPart.tintable; - skinningLogic = visualPart.skinLogic; - improvementSkinningLogic = visualPart.improvementSkinLogic; - levels = visualPart.levels; - this.sortingOrderOverride = sortingOrderOverride; - this.outlineSortingOrderOverride = outlineSortingOrderOverride; - } -} \ No newline at end of file + coordinates = visualPart.visualPart.transform.position; + rotation = visualPart.visualPart.transform.rotation.z; + defaultSpriteName = visualPart.DefaultSpriteName; + tintable = visualPart.tintable; + skinningLogic = visualPart.skinLogic; + improvementSkinningLogic = visualPart.improvementSkinLogic; + levels = visualPart.levels; + this.sortingOrderOverride = sortingOrderOverride; + this.outlineSortingOrderOverride = outlineSortingOrderOverride; + } +} diff --git a/src/Registry.cs b/src/Registry.cs index e8a5527..0016d8a 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -11,15 +11,15 @@ namespace PolyMod; /// public static class Registry { - /// - /// The next available index for automatically assigned IDs. - /// - public static int autoidx = Plugin.AUTOIDX_STARTS_FROM; + /// + /// The next available index for automatically assigned IDs. + /// + public static int autoidx = Plugin.AUTOIDX_STARTS_FROM; - /// - /// A dictionary of all loaded sprites, keyed by their name. - /// - public static Dictionary sprites = new(); + /// + /// A dictionary of all loaded sprites, keyed by their name. + /// + public static Dictionary sprites = new(); public static Dictionary> textures = new(); // string = texture name, bool, whether texture was processed or not. reviwers, pls tell me how to improve @@ -28,45 +28,45 @@ public static class Registry /// public static Dictionary audioClips = new(); - /// - /// A dictionary of all loaded mods, keyed by their ID. - /// - public static Dictionary mods = new(); + /// + /// A dictionary of all loaded mods, keyed by their ID. + /// + public static Dictionary mods = new(); /// /// A dictionary of tribe previews, keyed by tribe name. /// public static Dictionary tribePreviews = new(); - /// - /// A dictionary of sprite information, keyed by sprite name. - /// - public static Dictionary spriteInfos = new(); + /// + /// A dictionary of sprite information, keyed by sprite name. + /// + public static Dictionary spriteInfos = new(); /// /// A dictionary of loaded asset bundles, keyed by their name. /// public static Dictionary assetBundles = new(); - /// - /// A list of custom tribes. - /// - public static List customTribes = new(); + /// + /// A list of custom tribes. + /// + public static List customTribes = new(); - /// - /// A list of custom skin information. - /// - public static List skinInfo = new(); + /// + /// A list of custom skin information. + /// + public static List skinInfo = new(); - /// - /// The next available index for climate styles. - /// - public static int climateAutoidx = (int)Enum.GetValues(typeof(TribeType)).Cast().Last(); + /// + /// The next available index for climate styles. + /// + public static int climateAutoidx = (int)Enum.GetValues(typeof(TribeType)).Cast().Last(); - /// - /// The next available index for game modes. - /// - public static int gameModesAutoidx = Enum.GetValues(typeof(GameMode)).Length; + /// + /// The next available index for game modes. + /// + public static int gameModesAutoidx = Enum.GetValues(typeof(GameMode)).Length; public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it @@ -97,7 +97,7 @@ public static class Registry spriteNameVariants.Add(baseName + "_" + skinText); spriteNameVariants.Add(baseName + "_" + tribeText + "_" + skinText); - foreach(string spriteName in spriteNameVariants) + foreach (string spriteName in spriteNameVariants) { sprite = sprites.GetOrDefault(outline ? spriteName + "_outline" : spriteName, sprite); } @@ -109,7 +109,6 @@ public static class Registry /// Gets an audio clip from the registry. /// /// The name of the audio clip. - /// The style of the audio clip. /// The requested audio clip, or null if not found. public static AudioClip? GetAudioClip(string name, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default) { diff --git a/src/Util.cs b/src/Util.cs index 9c84c41..ca4bf36 100644 --- a/src/Util.cs +++ b/src/Util.cs @@ -11,131 +11,141 @@ namespace PolyMod; /// internal static class Util { - /// - /// Wraps a managed type for use in the Il2Cpp runtime. - /// - /// The type to wrap. - /// The Il2Cpp representation of the type. - internal static Il2CppSystem.Type WrapType() where T : class - { - if (!ClassInjector.IsTypeRegisteredInIl2Cpp()) - ClassInjector.RegisterTypeInIl2Cpp(); - return Il2CppType.From(typeof(T)); - } + /// + /// Wraps a managed type for use in the Il2Cpp runtime. + /// + /// The type to wrap. + /// The Il2Cpp representation of the type. + internal static Il2CppSystem.Type WrapType() where T : class + { + if (!ClassInjector.IsTypeRegisteredInIl2Cpp()) + ClassInjector.RegisterTypeInIl2Cpp(); + return Il2CppType.From(typeof(T)); + } - /// - /// Computes the SHA256 hash of an object's string representation. - /// - /// The object to hash. - /// The hexadecimal string representation of the hash. - internal static string Hash(object data) - { - return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(data.ToString()!))); - } + /// + /// Computes the SHA256 hash of an object's string representation. + /// + /// The object to hash. + /// The hexadecimal string representation of the hash. + internal static string Hash(object data) + { + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(data.ToString()!))); + } - /// - /// Gets the name of a JToken from its path. - /// - /// The JToken. - /// The part of the path to retrieve, from the end. - /// The name of the JToken. - internal static string GetJTokenName(JToken token, int n = 1) - { - return token.Path.Split('.')[^n]; - } + /// + /// Computes the SHA256 hash of raw bytes. + /// + /// The bytes to hash. + /// The hexadecimal string representation of the hash. + internal static string HashBytes(byte[] data) + { + return Convert.ToHexString(SHA256.HashData(data)); + } - /// - /// Converts an Il2CppSystem.Version to a System.Version. - /// - /// The Il2CppSystem.Version to convert. - /// The equivalent System.Version. - internal static Version Cast(this Il2CppSystem.Version self) - { - return new(self.ToString()); - } + /// + /// Gets the name of a JToken from its path. + /// + /// The JToken. + /// The part of the path to retrieve, from the end. + /// The name of the JToken. + internal static string GetJTokenName(JToken token, int n = 1) + { + return token.Path.Split('.')[^n]; + } - /// - /// Synchronously unwraps the result of a Task. - /// - /// The result type of the Task. - /// The Task to unwrap. - /// The result of the Task. - internal static T UnwrapAsync(this Task self) - { - return self.GetAwaiter().GetResult(); - } + /// + /// Converts an Il2CppSystem.Version to a System.Version. + /// + /// The Il2CppSystem.Version to convert. + /// The equivalent System.Version. + internal static Version Cast(this Il2CppSystem.Version self) + { + return new(self.ToString()); + } - /// - /// Removes the revision component from a Version. - /// - /// The Version to modify. - /// A new Version with the revision set to -1. - internal static Version CutRevision(this Version self) - { - return new(self.Major, self.Minor, self.Build); - } + /// + /// Synchronously unwraps the result of a Task. + /// + /// The result type of the Task. + /// The Task to unwrap. + /// The result of the Task. + internal static T UnwrapAsync(this Task self) + { + return self.GetAwaiter().GetResult(); + } - /// - /// Compares two version strings to see if the first is older or equal to the second. - /// Pre-release tags follow semantic-version rules: the part after the first dash is - /// split on dots, purely numeric identifiers compare numerically and sort before - /// alphanumeric ones, and a longer identifier list is newer. A version with a - /// pre-release tag is always older than the same version without one. - /// - /// The first version string. - /// The second version string. - /// True if version1 is older or equal to version2, false otherwise. - internal static bool IsVersionOlderOrEqual(this string version1, string version2) - { - Version core1 = ParseVersion(version1, out string? pre1); - Version core2 = ParseVersion(version2, out string? pre2); + /// + /// Removes the revision component from a Version. + /// + /// The Version to modify. + /// A new Version with the revision set to -1. + internal static Version CutRevision(this Version self) + { + return new(self.Major, self.Minor, self.Build); + } - if (core1 != core2) - return core1 < core2; + /// + /// Compares two version strings to see if the first is older or equal to the second. + /// Pre-release tags follow semantic-version rules: the part after the first dash is + /// split on dots, purely numeric identifiers compare numerically and sort before + /// alphanumeric ones, and a longer identifier list is newer. A version with a + /// pre-release tag is always older than the same version without one. + /// + /// The first version string. + /// The second version string. + /// True if version1 is older or equal to version2, false otherwise. + internal static bool IsVersionOlderOrEqual(this string version1, string version2) + { + Version core1 = ParseVersion(version1, out string? pre1); + Version core2 = ParseVersion(version2, out string? pre2); - return ComparePreRelease(pre1, pre2) <= 0; - } + if (core1 != core2) + return core1 < core2; - private static Version ParseVersion(string version, out string? preRelease) - { - int dash = version.IndexOf('-'); - if (dash < 0) - { - preRelease = null; - return new Version(version); - } - preRelease = version[(dash + 1)..]; - if (preRelease.Length == 0) - preRelease = null; - return new Version(version[..dash]); - } + return ComparePreRelease(pre1, pre2) <= 0; + } - private static int ComparePreRelease(string? left, string? right) - { - if (left == null && right == null) return 0; - if (left == null) return 1; - if (right == null) return -1; + private static Version ParseVersion(string version, out string? preRelease) + { + int dash = version.IndexOf('-'); + if (dash < 0) + { + preRelease = null; + return new Version(version); + } + preRelease = version[(dash + 1)..]; + if (preRelease.Length == 0) + preRelease = null; + return new Version(version[..dash]); + } - string[] leftIds = left.Split('.'); - string[] rightIds = right.Split('.'); - int shared = Math.Min(leftIds.Length, rightIds.Length); - for (int i = 0; i < shared; i++) - { - int comparison = CompareIdentifier(leftIds[i], rightIds[i]); - if (comparison != 0) - return comparison; - } - return leftIds.Length.CompareTo(rightIds.Length); - } + private static int ComparePreRelease(string? left, string? right) + { + if (left == null && right == null) return 0; + if (left == null) return 1; + if (right == null) return -1; - private static int CompareIdentifier(string left, string right) - { - bool leftNumeric = left.Length > 0 && left.All(char.IsDigit); - bool rightNumeric = right.Length > 0 && right.All(char.IsDigit); - if (leftNumeric && rightNumeric) - return long.Parse(left).CompareTo(long.Parse(right)); - if (leftNumeric) return -1; - if (rightNumeric) return 1; - return string.Compare(left, right, StringComparison.Ordinal); - } + string[] leftIds = left.Split('.'); + string[] rightIds = right.Split('.'); + int shared = Math.Min(leftIds.Length, rightIds.Length); + for (int i = 0; i < shared; i++) + { + int comparison = CompareIdentifier(leftIds[i], rightIds[i]); + if (comparison != 0) + return comparison; + } + return leftIds.Length.CompareTo(rightIds.Length); + } + + private static int CompareIdentifier(string left, string right) + { + bool leftNumeric = left.Length > 0 && left.All(char.IsDigit); + bool rightNumeric = right.Length > 0 && right.All(char.IsDigit); + if (leftNumeric && rightNumeric) + return long.Parse(left).CompareTo(long.Parse(right)); + if (leftNumeric) return -1; + if (rightNumeric) return 1; + return string.Compare(left, right, StringComparison.Ordinal); + } } diff --git a/tests/CheckDependenciesTests.cs b/tests/CheckDependenciesTests.cs index b297606..95276d0 100644 --- a/tests/CheckDependenciesTests.cs +++ b/tests/CheckDependenciesTests.cs @@ -4,56 +4,56 @@ namespace Tests; public class CheckDependenciesTests { - [Fact] - public void MissingRequiredDependencyMarksModUnsatisfied() - { - var mod = ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); - Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); - } + [Fact] + public void MissingRequiredDependencyMarksModUnsatisfied() + { + var mod = ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); + Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); + } - [Fact] - public void VersionBelowMinimumMarksModUnsatisfied() - { - var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: null); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); - Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); - } + [Fact] + public void VersionBelowMinimumMarksModUnsatisfied() + { + var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: null); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); + Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); + } - [Fact] - public void VersionAboveMaximumMarksModUnsatisfied() - { - var dep = new Mod.Dependency("a", min: null, max: new Version(1, 0, 0)); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); - Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); - } + [Fact] + public void VersionAboveMaximumMarksModUnsatisfied() + { + var dep = new Mod.Dependency("a", min: null, max: new Version(1, 0, 0)); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); + Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); + } - [Fact] - public void VersionEqualToBoundsIsAllowed() - { - var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: new Version(2, 0, 0)); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); - Assert.Equal(Mod.Status.Success, mod.status); - } + [Fact] + public void VersionEqualToBoundsIsAllowed() + { + var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: new Version(2, 0, 0)); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); + Assert.Equal(Mod.Status.Success, mod.status); + } - [Fact] - public void SatisfiedDependencyKeepsModSuccessful() - { - var dep = new Mod.Dependency("a", min: new Version(1, 0, 0), max: new Version(2, 0, 0)); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); - Assert.Equal(Mod.Status.Success, mod.status); - } + [Fact] + public void SatisfiedDependencyKeepsModSuccessful() + { + var dep = new Mod.Dependency("a", min: new Version(1, 0, 0), max: new Version(2, 0, 0)); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); + Assert.Equal(Mod.Status.Success, mod.status); + } - [Fact] - public void MissingOptionalDependencyOnlyWarns() - { - var dep = new Mod.Dependency("ghost", null, null, required: false); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(mod)); - Assert.Equal(Mod.Status.Success, mod.status); - } + [Fact] + public void MissingOptionalDependencyOnlyWarns() + { + var dep = new Mod.Dependency("ghost", null, null, required: false); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(mod)); + Assert.Equal(Mod.Status.Success, mod.status); + } } diff --git a/tests/CompatibilityTests.cs b/tests/CompatibilityTests.cs new file mode 100644 index 0000000..30ffe8e --- /dev/null +++ b/tests/CompatibilityTests.cs @@ -0,0 +1,134 @@ +using System.Text; +using PolyMod; +using PolyMod.Managers; + +namespace Tests; + +public class CompatibilityTests +{ + private static Mod MakeModWithFiles(string id, Version version, params (string Name, string Content)[] files) + { + List modFiles = new(); + foreach ((string name, string content) in files) + modFiles.Add(new Mod.File(name, Encoding.UTF8.GetBytes(content))); + + Mod.Manifest manifest = new(id, null, null, version, new[] { "author" }, null); + return new Mod(manifest, Mod.Status.Success, modFiles); + } + + // The launcher computes this same value from the mod's .polymod archive. If this literal has to + // change, PolyModLauncher's ModChecksum must change with it or multiplayer checks will disagree. + [Fact] + public void ModChecksumMatchesTheLauncher() + { + Mod mod = MakeModWithFiles( + "testmod", + new Version(1, 2, 3), + ("sprites.json", "{\"a\":1}"), + ("nested/thing.txt", "hello world"), + ("code.dll", "not really a dll")); + + Assert.Equal( + "34A44D3156F856C4A6CACB16379B529E797230E7F1DB9A32E1E3682D416405AC", + Compatibility.ComputeModChecksum(mod)); + } + + [Fact] + public void ModChecksumIgnoresFileOrder() + { + Mod ordered = MakeModWithFiles( + "testmod", + new Version(1, 0, 0), + ("a.txt", "first"), + ("b.txt", "second")); + Mod reversed = MakeModWithFiles( + "testmod", + new Version(1, 0, 0), + ("b.txt", "second"), + ("a.txt", "first")); + + Assert.Equal( + Compatibility.ComputeModChecksum(ordered), + Compatibility.ComputeModChecksum(reversed)); + } + + [Fact] + public void ModChecksumChangesWithFileContents() + { + Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); + Mod edited = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "firsT")); + + Assert.NotEqual( + Compatibility.ComputeModChecksum(original), + Compatibility.ComputeModChecksum(edited)); + } + + [Fact] + public void ModChecksumChangesWithVersion() + { + Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); + Mod bumped = MakeModWithFiles("testmod", new Version(1, 0, 1), ("a.txt", "first")); + + Assert.NotEqual( + Compatibility.ComputeModChecksum(original), + Compatibility.ComputeModChecksum(bumped)); + } + + [Fact] + public void GlobalChecksumIgnoresClientOnlyMods() + { + Mod shared = MakeModWithFiles("sharedmod", new Version(1, 0, 0), ("a.txt", "first")); + + Dictionary withoutClient = new() { { shared.id, shared } }; + Compatibility.ComputeChecksums(withoutClient); + string before = Compatibility.checksum; + + Mod clientOnly = MakeModWithFiles("clientmod", new Version(1, 0, 0), ("b.txt", "second")); + clientOnly.client = true; + + Dictionary withClient = new() + { + { shared.id, shared }, + { clientOnly.id, clientOnly }, + }; + Compatibility.ComputeChecksums(withClient); + + Assert.Equal(before, Compatibility.checksum); + } + + // The game deletes saves through APIs that hand the id over as a Guid in some places and as a + // string in others. If those produced different keys the stored checksum would never be purged. + [Fact] + public void GameIdNormalizesAcrossTheFormsTheGameUses() + { + Guid gameId = Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301"); + string expected = "3f2504e0-4f89-11d3-9a0c-0305e82c3301"; + + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId)); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString())); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString().ToUpperInvariant())); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString("B"))); + } + + [Fact] + public void GlobalChecksumIgnoresModOrder() + { + Mod first = MakeModWithFiles("alpha", new Version(1, 0, 0), ("a.txt", "first")); + Mod second = MakeModWithFiles("beta", new Version(1, 0, 0), ("b.txt", "second")); + + Compatibility.ComputeChecksums(new Dictionary + { + { first.id, first }, + { second.id, second }, + }); + string ordered = Compatibility.checksum; + + Compatibility.ComputeChecksums(new Dictionary + { + { second.id, second }, + { first.id, first }, + }); + + Assert.Equal(ordered, Compatibility.checksum); + } +} diff --git a/tests/LoaderTests.cs b/tests/LoaderTests.cs index f7aae24..e056664 100644 --- a/tests/LoaderTests.cs +++ b/tests/LoaderTests.cs @@ -4,57 +4,57 @@ namespace Tests; public class LoaderTests { - private static string[] Ids(Dictionary mods) => - mods.Select(kv => kv.Key).ToArray(); + private static string[] Ids(Dictionary mods) => + mods.Select(kv => kv.Key).ToArray(); - [Fact] - public void DependencyLoadsBeforeDependent() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), - ModFactory.MakeMod("a")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(new[] { "a", "b" }, Ids(mods)); - } + [Fact] + public void DependencyLoadsBeforeDependent() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), + ModFactory.MakeMod("a")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(new[] { "a", "b" }, Ids(mods)); + } - [Fact] - public void TransitiveChainSortsDeepestFirst() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("c", dependencies: new Mod.Dependency("b", null, null)), - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), - ModFactory.MakeMod("a")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(new[] { "a", "b", "c" }, Ids(mods)); - } + [Fact] + public void TransitiveChainSortsDeepestFirst() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("c", dependencies: new Mod.Dependency("b", null, null)), + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), + ModFactory.MakeMod("a")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(new[] { "a", "b", "c" }, Ids(mods)); + } - [Fact] - public void DependencyCycleReturnsFalseAndLeavesDictionaryUntouched() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("a", dependencies: new Mod.Dependency("b", null, null)), - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null))); - Assert.False(Loader.SortMods(mods)); - Assert.Equal(new[] { "a", "b" }, Ids(mods)); - } + [Fact] + public void DependencyCycleReturnsFalseAndLeavesDictionaryUntouched() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("a", dependencies: new Mod.Dependency("b", null, null)), + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null))); + Assert.False(Loader.SortMods(mods)); + Assert.Equal(new[] { "a", "b" }, Ids(mods)); + } - [Fact] - public void DependencyOnMissingModDoesNotBlockSorting() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)), - ModFactory.MakeMod("a")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(2, mods.Count); - } + [Fact] + public void DependencyOnMissingModDoesNotBlockSorting() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)), + ModFactory.MakeMod("a")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(2, mods.Count); + } - [Fact] - public void FailedModsSinkToEnd() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("bad", Mod.Status.Error), - ModFactory.MakeMod("good")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(new[] { "good", "bad" }, Ids(mods)); - } + [Fact] + public void FailedModsSinkToEnd() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("bad", Mod.Status.Error), + ModFactory.MakeMod("good")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(new[] { "good", "bad" }, Ids(mods)); + } } diff --git a/tests/ModFactory.cs b/tests/ModFactory.cs index 1a78280..2e2c9a1 100644 --- a/tests/ModFactory.cs +++ b/tests/ModFactory.cs @@ -4,14 +4,14 @@ namespace Tests; internal static class ModFactory { - internal static Mod MakeMod( - string id, - Mod.Status status = Mod.Status.Success, - Version? version = null, - params Mod.Dependency[] dependencies) => - new(new Mod.Manifest(id, null, null, version ?? new Version(1, 0, 0), new[] { "author" }, dependencies), - status, new()); + internal static Mod MakeMod( + string id, + Mod.Status status = Mod.Status.Success, + Version? version = null, + params Mod.Dependency[] dependencies) => + new(new Mod.Manifest(id, null, null, version ?? new Version(1, 0, 0), new[] { "author" }, dependencies), + status, new()); - internal static Dictionary Mods(params Mod[] mods) => - mods.ToDictionary(mod => mod.id); + internal static Dictionary Mods(params Mod[] mods) => + mods.ToDictionary(mod => mod.id); } diff --git a/tests/TestSetup.cs b/tests/TestSetup.cs index 87f54f1..4e8e3b2 100644 --- a/tests/TestSetup.cs +++ b/tests/TestSetup.cs @@ -7,24 +7,24 @@ namespace Tests; internal static class TestSetup { - [ModuleInitializer] - internal static void Init() - { - var root = AppContext.BaseDirectory; - var prop = typeof(BepInEx.Paths).GetProperty( - nameof(BepInEx.Paths.BepInExRootPath), - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); - try - { - prop?.SetValue(null, root); - } - catch (ArgumentException) - { - var field = typeof(BepInEx.Paths) - .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) - .FirstOrDefault(f => f.Name.Contains("BepInExRootPath", StringComparison.Ordinal)); - field?.SetValue(null, root); - } - Plugin.logger ??= new ManualLogSource("tests"); - } + [ModuleInitializer] + internal static void Init() + { + var root = AppContext.BaseDirectory; + var prop = typeof(BepInEx.Paths).GetProperty( + nameof(BepInEx.Paths.BepInExRootPath), + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + try + { + prop?.SetValue(null, root); + } + catch (ArgumentException) + { + var field = typeof(BepInEx.Paths) + .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) + .FirstOrDefault(f => f.Name.Contains("BepInExRootPath", StringComparison.Ordinal)); + field?.SetValue(null, root); + } + Plugin.logger ??= new ManualLogSource("tests"); + } } diff --git a/tests/UtilTests.cs b/tests/UtilTests.cs index 2bb4799..7b42ad1 100644 --- a/tests/UtilTests.cs +++ b/tests/UtilTests.cs @@ -4,31 +4,31 @@ namespace Tests; public class UtilTests { - [Theory] - [InlineData("1.0.0", "2.0.0", true)] // older core - [InlineData("2.0.0", "1.0.0", false)] // newer core - [InlineData("2.0.0", "2.0.0", true)] // equal - [InlineData("2.0", "2.0.0", true)] // shorter version sorts first - [InlineData("2.0.0.1", "2.0.0", false)] // revision makes it newer - [InlineData("2.0.0", "2.0.0-beta", false)] // release is newer than its pre-release - [InlineData("2.0.0-beta", "2.0.0", true)] - [InlineData("2.0.0-alpha", "2.0.0-beta", true)] // alphanumeric identifiers compare lexically - [InlineData("2.0.0-rc.9", "2.0.0-rc.10", true)] // numeric identifiers compare numerically - [InlineData("2.0.0-rc.10", "2.0.0-rc.9", false)] - [InlineData("2.0.0-9", "2.0.0-10", true)] - [InlineData("2.0.0-1", "2.0.0-alpha", true)] // numeric sorts before alphanumeric - [InlineData("2.0.0-pre", "2.0.0-pre.1", true)] // more identifiers mean a newer pre-release - [InlineData("2.0.0-pre.1", "2.0.0-pre", false)] - [InlineData("2.0.0-alpha-1", "2.0.0-alpha-2", true)] // everything after the first dash is the tag - [InlineData("2.0.0-alpha-2", "2.0.0-alpha-1", false)] - public void VersionComparisons(string version, string other, bool expected) => - Assert.Equal(expected, version.IsVersionOlderOrEqual(other)); + [Theory] + [InlineData("1.0.0", "2.0.0", true)] // older core + [InlineData("2.0.0", "1.0.0", false)] // newer core + [InlineData("2.0.0", "2.0.0", true)] // equal + [InlineData("2.0", "2.0.0", true)] // shorter version sorts first + [InlineData("2.0.0.1", "2.0.0", false)] // revision makes it newer + [InlineData("2.0.0", "2.0.0-beta", false)] // release is newer than its pre-release + [InlineData("2.0.0-beta", "2.0.0", true)] + [InlineData("2.0.0-alpha", "2.0.0-beta", true)] // alphanumeric identifiers compare lexically + [InlineData("2.0.0-rc.9", "2.0.0-rc.10", true)] // numeric identifiers compare numerically + [InlineData("2.0.0-rc.10", "2.0.0-rc.9", false)] + [InlineData("2.0.0-9", "2.0.0-10", true)] + [InlineData("2.0.0-1", "2.0.0-alpha", true)] // numeric sorts before alphanumeric + [InlineData("2.0.0-pre", "2.0.0-pre.1", true)] // more identifiers mean a newer pre-release + [InlineData("2.0.0-pre.1", "2.0.0-pre", false)] + [InlineData("2.0.0-alpha-1", "2.0.0-alpha-2", true)] // everything after the first dash is the tag + [InlineData("2.0.0-alpha-2", "2.0.0-alpha-1", false)] + public void VersionComparisons(string version, string other, bool expected) => + Assert.Equal(expected, version.IsVersionOlderOrEqual(other)); - [Fact] - public void HashProducesUppercaseSha256Hex() - { - Assert.Equal( - "9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08", - Util.Hash("test")); - } + [Fact] + public void HashProducesUppercaseSha256Hex() + { + Assert.Equal( + "9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08", + Util.Hash("test")); + } } diff --git a/tests/VersionJsonTests.cs b/tests/VersionJsonTests.cs index f85fe15..d080b15 100644 --- a/tests/VersionJsonTests.cs +++ b/tests/VersionJsonTests.cs @@ -5,13 +5,13 @@ namespace Tests; public class VersionJsonTests { - private static readonly JsonSerializerOptions options = new() { Converters = { new VersionJson() } }; + private static readonly JsonSerializerOptions options = new() { Converters = { new VersionJson() } }; - [Fact] - public void VersionRoundTripsThroughString() - { - var json = JsonSerializer.Serialize(new Version(1, 2, 3), options); - Assert.Equal("\"1.2.3\"", json); - Assert.Equal(new Version(1, 2, 3), JsonSerializer.Deserialize(json, options)); - } + [Fact] + public void VersionRoundTripsThroughString() + { + var json = JsonSerializer.Serialize(new Version(1, 2, 3), options); + Assert.Equal("\"1.2.3\"", json); + Assert.Equal(new Version(1, 2, 3), JsonSerializer.Deserialize(json, options)); + } } From ecfa1d9e357991e1f4cfa665a6ad2a46deaad70b Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 2 Nov 2026 20:24:18 +0100 Subject: [PATCH 27/42] fixed formatting --- .editorconfig | 3 ++ src/Api/Config.cs | 3 +- src/Json/EnumNameJson.cs | 12 +++---- src/Loader.cs | 61 ++++++++++++++++------------------- src/Managers/Hub.cs | 3 +- src/Managers/Loc.cs | 7 ++-- src/Managers/Main.cs | 6 ++-- src/Managers/TribePreviews.cs | 4 +-- src/Managers/Visual.cs | 6 ++-- src/Prefabs/SkinnedKey.cs | 14 ++++++-- src/Registry.cs | 19 +++++------ src/Util.cs | 3 +- 12 files changed, 78 insertions(+), 63 deletions(-) diff --git a/.editorconfig b/.editorconfig index a62b01d..bca1bc2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -40,3 +40,6 @@ dotnet_diagnostic.CA1716.severity = none dotnet_diagnostic.CA1708.severity = none dotnet_diagnostic.CS1591.severity = none dotnet_diagnostic.CS1573.severity = none + +[tests/**.cs] +dotnet_diagnostic.CA1861.severity = none diff --git a/src/Api/Config.cs b/src/Api/Config.cs index 3e6d2a2..4cd3a19 100644 --- a/src/Api/Config.cs +++ b/src/Api/Config.cs @@ -8,6 +8,7 @@ namespace PolyMod.Api; /// public class Config where T : class { + private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; private T? currentConfig; private readonly string modName; private readonly ConfigTypes configType; @@ -98,7 +99,7 @@ public void SaveChanges() switch (configType) { case ConfigTypes.PerMod: - var perModJson = JsonSerializer.Serialize(currentConfig, new JsonSerializerOptions { WriteIndented = true }); + var perModJson = JsonSerializer.Serialize(currentConfig, indentedJsonOptions); File.WriteAllText(perModConfigPath, perModJson); break; case ConfigTypes.Exposed: diff --git a/src/Json/EnumNameJson.cs b/src/Json/EnumNameJson.cs index 71c3012..cbf157b 100644 --- a/src/Json/EnumNameJson.cs +++ b/src/Json/EnumNameJson.cs @@ -7,22 +7,22 @@ namespace PolyMod.Json; /// Converts fixed (non-extensible) enums to and from their plain string names. /// Use this for enums that are not registered in EnumCache. /// -public class EnumNameJson : JsonConverter where EnumType : struct, Enum +public class EnumNameJson : JsonConverter where TEnum : struct, Enum { - public override EnumType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { string? enumName = reader.GetString(); - if (enumName != null && Enum.TryParse(enumName, true, out EnumType parsedValue)) + if (enumName != null && Enum.TryParse(enumName, true, out TEnum parsedValue)) { return parsedValue; } - string validNames = string.Join(", ", Enum.GetNames(typeof(EnumType))); - throw new JsonException($"Unknown {typeof(EnumType).Name} value '{enumName}'. Valid values: {validNames}"); + string validNames = string.Join(", ", Enum.GetNames()); + throw new JsonException($"Unknown {typeof(TEnum).Name} value '{enumName}'. Valid values: {validNames}"); } - public override void Write(Utf8JsonWriter writer, EnumType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); } diff --git a/src/Loader.cs b/src/Loader.cs index 467f3d2..1c99191 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -1,3 +1,4 @@ +using System.Globalization; using BepInEx.Logging; using Cpp2IL.Core.Extensions; using Il2CppSystem.Linq; @@ -22,6 +23,22 @@ namespace PolyMod; /// public static class Loader { + private static readonly JsonSerializerOptions manifestJsonOptions = new() + { + Converters = { new VersionJson() }, + }; + + private static readonly JsonSerializerOptions spriteInfoJsonOptions = new() + { + Converters = { new Vector2Json() }, + }; + + private static readonly JsonSerializerOptions prefabJsonOptions = new() + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }; + internal record TypeMapping(Type type, bool shouldCreateCache = true); /// @@ -112,7 +129,7 @@ out TribeAbility.Type tribeAbilityType if (modifiedSkins.Contains(skin.id)) { modifiedSkins.Remove(skin.id); - modifiedSkins.Add(skin.idx.ToString()); + modifiedSkins.Add(skin.idx.ToString(CultureInfo.InvariantCulture)); } } JArray newSkins = new JArray(); @@ -203,7 +220,7 @@ out TribeAbility.Type tribeAbilityType new((token, duringEnumCacheCreation) => { var prop = token.Parent.Cast(); - prop.Replace(new JProperty(prop.Name.ToLower(), prop.Value)); + prop.Replace(new JProperty(prop.Name.ToLowerInvariant(), prop.Value)); }) }, }; @@ -363,10 +380,7 @@ private static void ProcessModFile(string fullName, byte[] bytes, List { manifest = JsonSerializer.Deserialize( bytes, - new JsonSerializerOptions() - { - Converters = { new VersionJson() }, - } + manifestJsonOptions ); return; } @@ -414,13 +428,13 @@ internal static void CheckDependencies(Dictionary mods) foreach (var dependency in mod.dependencies ?? Array.Empty()) { string? message = null; - if (!mods.ContainsKey(dependency.id)) + if (!mods.TryGetValue(dependency.id, out Mod? dependencyMod)) { message = $"Dependency {dependency.id} not found"; } else { - Version version = mods[dependency.id].version; + Version version = dependencyMod.version; if ( (dependency.min != null && version < dependency.min) || @@ -620,10 +634,7 @@ public static void LoadTextureFile(Mod mod, Mod.File file) { var deserialized = JsonSerializer.Deserialize>( file.bytes, - new JsonSerializerOptions() - { - Converters = { new Vector2Json() }, - } + spriteInfoJsonOptions ); if (deserialized != null) @@ -651,7 +662,7 @@ public static void LoadTextureFile(Mod mod, Mod.File file) /// The audio file to load. public static void LoadAudioFile(Mod mod, Mod.File file) { - string name = Path.GetFileNameWithoutExtension(file.name).ToLower(); + string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); try { AudioClip clip = Managers.Audio.BuildAudioClip(file.bytes, name); @@ -675,11 +686,7 @@ public static void LoadPrefabsFile(Mod mod, Mod.File file) { try { - var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); + var prefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); if (prefab == null) return; @@ -699,11 +706,7 @@ public static void LoadUnitPrefabFile(Mod mod, Mod.File file) { try { - var unitPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); + var unitPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); if (unitPrefab == null) return; @@ -721,11 +724,7 @@ public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) { try { - var improvementPrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); + var improvementPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); if (improvementPrefab == null) return; @@ -743,11 +742,7 @@ public static void LoadResourcePrefabFile(Mod mod, Mod.File file) { try { - var resourcePrefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); + var resourcePrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); if (resourcePrefab == null) return; diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 305581f..e28648e 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Cpp2IL.Core.Extensions; using HarmonyLib; using Il2CppInterop.Runtime; @@ -299,7 +300,7 @@ private static string BuildModList() string summary = Localization.Get( "polymod.hub.summary", - Args(loaded.ToString(), Registry.mods.Count.ToString()) + Args(loaded.ToString(CultureInfo.InvariantCulture), Registry.mods.Count.ToString(CultureInfo.InvariantCulture)) ); summary += " " + Localization.Get( "polymod.hub.checksum", diff --git a/src/Managers/Loc.cs b/src/Managers/Loc.cs index d4d6938..239b4be 100644 --- a/src/Managers/Loc.cs +++ b/src/Managers/Loc.cs @@ -1,3 +1,4 @@ +using System.Globalization; using HarmonyLib; using I2.Loc; using Il2CppInterop.Runtime.InteropTypes.Arrays; @@ -65,7 +66,7 @@ private static bool Localization_Get(ref string key, Il2CppReferenceArray.GetName(improvementData.type); - if (buildingsInfoOverrides.ContainsKey(key)) + if (buildingsInfoOverrides.TryGetValue(key, out string? buildingInfoOverride)) { - __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingsInfoOverrides[key]); + __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingInfoOverride); return false; } diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index f154d42..346b7d9 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -17,6 +17,8 @@ namespace PolyMod.Managers; /// public static class Main { + private static readonly string[] polytopiaAuthors = { "Midjiwan AB" }; + internal static bool dependencyCycle; /// @@ -184,7 +186,7 @@ private static void GameModeScreen_Init(GameModeScreen __instance) var newData = button.gamemodeData.ToList(); foreach (var info in Loader.gamemodes) { - string id = EnumCache.GetName((GameMode)info.gameModeIndex).ToLower(); + string id = EnumCache.GetName((GameMode)info.gameModeIndex).ToLowerInvariant(); newData.Add(new GamemodeButton.GamemodeButtonData() { gameMode = (GameMode)info.gameModeIndex, @@ -377,7 +379,7 @@ internal static void Init() "The Battle of Polytopia", null, new(Application.version.ToString()), - new string[] { "Midjiwan AB" }, + polytopiaAuthors, Array.Empty() ); Registry.mods.Add(polytopia.id, new(polytopia, Mod.Status.Success, new())); diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index fe82fb6..f545572 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -62,9 +62,9 @@ public static void PreloadTribePreviews() for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) { SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; - if (previewSaveStateDatas.ContainsKey(saveStateData.name)) + if (previewSaveStateDatas.TryGetValue(saveStateData.name, out PreviewInfo? existingPreview)) { - previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, previewSaveStateDatas[saveStateData.name].customPreview); + previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, existingPreview.customPreview); } } diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 26a5c59..7f7223d 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -137,8 +137,8 @@ internal static string FormatSpriteName(string baseName) if (cachedSpriteDataReverse == null) CacheSpriteNames(); - if (cachedReversedNames.ContainsKey(baseName)) - return cachedReversedNames[baseName]; + if (cachedReversedNames.TryGetValue(baseName, out string? cachedReversedName)) + return cachedReversedName; string formattedName = baseName; foreach (var valuePair in cachedSpriteDataReverse!) @@ -525,7 +525,7 @@ private static bool StartScreen_OnWeeklyChallengeClicked(StartScreen_UI2 __insta BasicPopup popup = PopupManager.GetBasicPopup(); popup.Header = Localization.Get("polymod.hub"); - popup.Description = Localization.Get("polymod.wc.warning", new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", new Il2CppSystem.Object[] { }) }); + popup.Description = Localization.Get("polymod.wc.warning", new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", Array.Empty()) }); void WCProceed() { diff --git a/src/Prefabs/SkinnedKey.cs b/src/Prefabs/SkinnedKey.cs index a4bbb79..53cfa52 100644 --- a/src/Prefabs/SkinnedKey.cs +++ b/src/Prefabs/SkinnedKey.cs @@ -34,13 +34,23 @@ public bool Equals(SkinnedKey other) && skinType == other.skinType; } - public override bool Equals(object? other) + public override bool Equals(object? obj) { - return other is SkinnedKey otherKey && Equals(otherKey); + return obj is SkinnedKey otherKey && Equals(otherKey); } public override int GetHashCode() { return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); } + + public static bool operator ==(SkinnedKey left, SkinnedKey right) + { + return left.Equals(right); + } + + public static bool operator !=(SkinnedKey left, SkinnedKey right) + { + return !left.Equals(right); + } } diff --git a/src/Registry.cs b/src/Registry.cs index 0016d8a..8944632 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -1,3 +1,4 @@ +using System.Globalization; using LibCpp2IL; using PolyMod.Managers; using PolytopiaBackendBase.Game; @@ -61,12 +62,12 @@ public static class Registry /// /// The next available index for climate styles. /// - public static int climateAutoidx = (int)Enum.GetValues(typeof(TribeType)).Cast().Last(); + public static int climateAutoidx = (int)Enum.GetValues().Last(); /// /// The next available index for game modes. /// - public static int gameModesAutoidx = Enum.GetValues(typeof(GameMode)).Length; + public static int gameModesAutoidx = Enum.GetValues().Length; public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it @@ -74,7 +75,7 @@ public static class Registry { string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); - string levelText = (level == -1) ? "" : level.ToString(); + string levelText = (level == -1) ? "" : level.ToString(CultureInfo.InvariantCulture); return GetSpriteByText(baseName, tribeText, skinText, levelText, outline); } /// @@ -83,9 +84,9 @@ public static class Registry public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", string levelText = "", bool outline = false) { Sprite? sprite = null; - baseName = baseName.ToLower(); - tribeText = tribeText.ToLower(); - skinText = skinText.ToLower(); + baseName = baseName.ToLowerInvariant(); + tribeText = tribeText.ToLowerInvariant(); + skinText = skinText.ToLowerInvariant(); List spriteNameVariants = new(); @@ -123,9 +124,9 @@ public static class Registry public static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") { AudioSource? audioSource = null; - baseName = baseName.ToLower(); - tribeText = tribeText.ToLower(); - skinText = skinText.ToLower(); + baseName = baseName.ToLowerInvariant(); + tribeText = tribeText.ToLowerInvariant(); + skinText = skinText.ToLowerInvariant(); List audioNameVariants = new() { diff --git a/src/Util.cs b/src/Util.cs index ca4bf36..cae4707 100644 --- a/src/Util.cs +++ b/src/Util.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Security.Cryptography; using System.Text; using Il2CppInterop.Runtime; @@ -143,7 +144,7 @@ private static int CompareIdentifier(string left, string right) bool leftNumeric = left.Length > 0 && left.All(char.IsDigit); bool rightNumeric = right.Length > 0 && right.All(char.IsDigit); if (leftNumeric && rightNumeric) - return long.Parse(left).CompareTo(long.Parse(right)); + return long.Parse(left, CultureInfo.InvariantCulture).CompareTo(long.Parse(right, CultureInfo.InvariantCulture)); if (leftNumeric) return -1; if (rightNumeric) return 1; return string.Compare(left, right, StringComparison.Ordinal); From 8aae0b49fe59eea6905b490b4d759e87dce904da Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 2 Nov 2026 23:15:31 +0100 Subject: [PATCH 28/42] Seperated PolyMod Persistent Data from original Polytopia one --- src/Managers/Main.cs | 7 +++++++ src/Plugin.cs | 2 ++ 2 files changed, 9 insertions(+) diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 346b7d9..a2483ad 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -389,6 +389,13 @@ internal static void Init() stopwatch.Stop(); } + [HarmonyPostfix] + [HarmonyPatch(typeof(UnityEngine.Application), nameof(UnityEngine.Application.persistentDataPath), MethodType.Getter)] + private static void Application_persistentDataPath_get(ref string __result) + { + __result = Plugin.PERSISTENT_DATA_PATH; + } + /// /// Loads all mod content. /// diff --git a/src/Plugin.cs b/src/Plugin.cs index 1c64fc4..74f7813 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -96,6 +96,8 @@ internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY internal static readonly string CHECKSUM_PATH = Path.Combine(BASE_PATH, "CHECKSUM"); + internal static readonly string PERSISTENT_DATA_PATH = Path.Combine(BASE_PATH, "PersistentData"); + /// /// The link to the PolyMod Discord server. /// From 4bb50028ae9cfc76737567df270874547b8f2333 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 2 Nov 2026 23:37:22 +0100 Subject: [PATCH 29/42] disabled weekly challenges --- resources/localization.json | 12 +++------- src/Managers/Visual.cs | 47 ++++++++++++++++++------------------- 2 files changed, 26 insertions(+), 33 deletions(-) diff --git a/resources/localization.json b/resources/localization.json index 51fba0d..1a97e23 100644 --- a/resources/localization.json +++ b/resources/localization.json @@ -233,15 +233,9 @@ "Russian": "Данные спрайтов не найдены!", "Elyrion": "ŋȱ ȓπriŦ∑ iŋ₼ȱȓ ~∑r∑ ₼ȱ₺ŋΔ!" }, - "polymod_wc_warning": { - "English": "{0} may not work correctly due to PolyMod. Do you wish to proceed?", - "Russian": "{0} может работать некорректно из-за PolyMod'а. Вы уверены что хотите продолжить?", - "Elyrion": "{0} maỹ ŋȱŦ ~ȱr§ #ȱrr∑#Ŧ∫ỹ Δ₺∑ Ŧȱ πȱ∫ỹmȱΔ. Δȱ ỹȱ₺ ~iȓţ Ŧȱ πrȱ#∑∑Δ?" - }, - "polymod_wc_proceed": { - "English": "PROCEED", - "Russian": "ПРОДОЛЖИТЬ", - "Elyrion": "πrȱ#∑∑Δ" + "polymod_wc_vanillaonly": { + "English": "{0} is only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", + "Russian": "{0} доступен только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера." }, "polymod_title_invalid": { "English": "Invalid Launch", diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 7f7223d..05249ec 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -3,7 +3,6 @@ using UnityEngine; using Il2CppSystem.Linq; using PolytopiaBackendBase.Common; -using Il2CppInterop.Runtime; using System.Text.Json.Serialization; using PolyMod.Json; using TMPro; @@ -81,7 +80,8 @@ public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. /// internal static Dictionary customFloodingSkins = new(); - private static bool seenWarningWCPopup = false; + + private static readonly Color WEEKLY_CHALLENGE_DISABLED_COLOR = new(0.42f, 0.42f, 0.42f, 1f); private static Dictionary? cachedSpriteDataReverse = null; private static Dictionary cachedReversedNames = new(); @@ -518,35 +518,34 @@ private static void StartScreen_UI2_OnShow() [HarmonyPrefix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] - private static bool StartScreen_OnWeeklyChallengeClicked(StartScreen_UI2 __instance) + private static bool StartScreen_OnWeeklyChallengeClicked() { - if (seenWarningWCPopup) - return true; - BasicPopup popup = PopupManager.GetBasicPopup(); popup.Header = Localization.Get("polymod.hub"); - popup.Description = Localization.Get("polymod.wc.warning", new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", Array.Empty()) }); - - void WCProceed() - { - seenWarningWCPopup = true; - __instance.OnWeeklyChallengeClicked(); - } - List popupButtons = new() - { - new("buttons.back"), - new( - "polymod.wc.proceed", - PopupBase.PopupButtonData.States.None, - callback: DelegateSupport.ConvertDelegate(WCProceed), - customColorStates: ColorConstants.redButtonColorStates - ) - }; - popup.buttonData = popupButtons.ToArray(); + popup.Description = Localization.Get( + "polymod.wc.vanillaonly", + new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", Array.Empty()) } + ); + popup.buttonData = new PopupBase.PopupButtonData[] { new("buttons.ok") }; popup.Show(); return false; } + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RefreshWeeklyChallengeButton))] + private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __instance) + { + WeeklyChallengesButton weeklyChallengeButton = __instance.weeklyChallengeButton; + if (weeklyChallengeButton == null) + return; + + weeklyChallengeButton.SetColors( + WEEKLY_CHALLENGE_DISABLED_COLOR, + WEEKLY_CHALLENGE_DISABLED_COLOR, + WEEKLY_CHALLENGE_DISABLED_COLOR + ); + } + /// Shows a basic popup with a custom width. public static void ShowSetWidth(this BasicPopupLegacy self, int width) { From d1ed3eb2d7e8ad977ff1fa7819644c238bec7481 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 5 Nov 2026 21:48:37 +0100 Subject: [PATCH 30/42] minor fixes --- src/Managers/Compatibility.cs | 8 ++------ src/Managers/Hub.cs | 6 +++++- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Managers/Compatibility.cs b/src/Managers/Compatibility.cs index 8083f05..e79d647 100644 --- a/src/Managers/Compatibility.cs +++ b/src/Managers/Compatibility.cs @@ -23,17 +23,13 @@ internal static class Compatibility public static void ComputeChecksums(Dictionary mods) { - foreach (var (_, mod) in mods) - { - mod.checksum = ComputeModChecksum(mod); - } - List signatures = new(); foreach (var (id, mod) in mods) { if (mod.status != Mod.Status.Success) continue; if (mod.client || id == "polytopia") continue; - + + mod.checksum = ComputeModChecksum(mod); signatures.Add($"{id}:{mod.checksum}"); } signatures.Sort(StringComparer.Ordinal); diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index e28648e..9047320 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -34,6 +34,7 @@ Action toggle private const float VERSION_LABEL_GAP = 10f; /// Margin the game keeps between the safe area and its own corner widgets. private const float VERSION_LABEL_MARGIN = 15f; + private const float ROUND_BUTTON_TITLE_GAP = 10f; private const string INTRO = "intro.mp4"; private const KeyCode HOTKEY_MODIFIER = KeyCode.LeftControl; @@ -138,9 +139,12 @@ private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, Screen polyModButton.bg.color = Color.white; // Setting the text re-runs the button's own layout, which also repositions the badge. polyModButton.Text = Localization.Get("polymod.hub"); + float titleDrop = polyModButton.titleTextField == null + ? 0f + : (polyModButton.titleTextField.GetHeight() + ROUND_BUTTON_TITLE_GAP) / 2f; polyModButton.SetPosition( screenSize.safeRect.Right - START_SCREEN_MARGIN * 2.5f, - screenSize.safeRect.Top - START_SCREEN_MARGIN + screenSize.safeRect.Top - START_SCREEN_MARGIN - titleDrop ); brokenModsBadge?.SetValue(CountBrokenMods()); From 4c1e011f0f71163a100f00e1a6bdc29d4cd19c50 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Fri, 6 Nov 2026 18:46:31 +0100 Subject: [PATCH 31/42] fixed black outlines around sprites --- src/Loader.cs | 6 ++- src/Managers/Visual.cs | 94 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 2 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index 1c99191..0ce89e0 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -617,7 +617,7 @@ public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) /// The sprite file to load. public static void LoadTextureFile(Mod mod, Mod.File file) { - string name = Path.GetFileNameWithoutExtension(file.name); + string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); Texture2D texture2D = Visual.BuildTexture(file.bytes); Registry.textures[name] = new KeyValuePair(texture2D, false); } @@ -641,7 +641,9 @@ public static void LoadTextureFile(Mod mod, Mod.File file) { foreach (var kvp in deserialized) { - Registry.spriteInfos[kvp.Key] = kvp.Value; + if (kvp.Value.spriteOrigin?.name != null) + kvp.Value.spriteOrigin.name = kvp.Value.spriteOrigin.name.ToLowerInvariant(); + Registry.spriteInfos[kvp.Key.ToLowerInvariant()] = kvp.Value; } } diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index fcb6450..44de3a4 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -76,6 +76,12 @@ public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); /// Vertical gap between two rows of popup buttons. private const float POPUP_BUTTON_ROW_GAP = 10f; + + private const byte INVISIBLE_ALPHA = 2; + private const int ALPHA_BLEED_RINGS = 16; + private const int PREMULTIPLIED_MIN_EDGE_PIXELS = 64; + private const float PREMULTIPLIED_MAX_OUTLIER_SHARE = 0.005f; + /// /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. /// @@ -591,11 +597,93 @@ public static Texture2D BuildTexture(byte[] data) { Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); texture.LoadImage(data); + Color32[] pixels = texture.GetPixels32(); + if (LooksPremultiplied(pixels)) + Unpremultiply(pixels); + BleedAlphaEdges(pixels, texture.width, texture.height); + texture.SetPixels32(pixels); texture.filterMode = FilterMode.Trilinear; + texture.wrapMode = TextureWrapMode.Clamp; texture.Apply(); return texture; } + internal static bool LooksPremultiplied(Color32[] pixels) + { + int edge = 0; + int brighterThanAlpha = 0; + foreach (Color32 pixel in pixels) + { + if (pixel.a == 0 || pixel.a == 255) continue; + edge++; + if (Math.Max(pixel.r, Math.Max(pixel.g, pixel.b)) > pixel.a) + brighterThanAlpha++; + } + return edge >= PREMULTIPLIED_MIN_EDGE_PIXELS + && brighterThanAlpha <= edge * PREMULTIPLIED_MAX_OUTLIER_SHARE; + } + + internal static void Unpremultiply(Color32[] pixels) + { + for (int i = 0; i < pixels.Length; i++) + { + byte alpha = pixels[i].a; + if (alpha == 0 || alpha == byte.MaxValue) continue; + pixels[i] = new Color32( + (byte)Math.Min(byte.MaxValue, pixels[i].r * byte.MaxValue / alpha), + (byte)Math.Min(byte.MaxValue, pixels[i].g * byte.MaxValue / alpha), + (byte)Math.Min(byte.MaxValue, pixels[i].b * byte.MaxValue / alpha), + alpha + ); + } + } + + internal static void BleedAlphaEdges(Color32[] pixels, int width, int height) + { + bool[] hasColour = new bool[pixels.Length]; + List frontier = new(); + for (int i = 0; i < pixels.Length; i++) + { + if (pixels[i].a <= INVISIBLE_ALPHA) continue; + hasColour[i] = true; + frontier.Add(i); + } + if (frontier.Count == 0 || frontier.Count == pixels.Length) return; + + for (int ring = 0; ring < ALPHA_BLEED_RINGS && frontier.Count > 0; ring++) + { + List nextFrontier = new(); + foreach (int index in frontier) + { + int x = index % width; + int y = index / width; + Color32 source = pixels[index]; + + for (int offsetY = -1; offsetY <= 1; offsetY++) + { + int neighbourY = y + offsetY; + if (neighbourY < 0 || neighbourY >= height) continue; + + for (int offsetX = -1; offsetX <= 1; offsetX++) + { + int neighbourX = x + offsetX; + if (neighbourX < 0 || neighbourX >= width) continue; + + int neighbour = neighbourY * width + neighbourX; + if (hasColour[neighbour]) continue; + + hasColour[neighbour] = true; + pixels[neighbour] = new Color32( + source.r, source.g, source.b, pixels[neighbour].a + ); + nextFrontier.Add(neighbour); + } + } + } + frontier = nextFrontier; + } + } + /// Builds a sprite from raw byte data. /// The raw byte data of the image. /// The pivot point of the sprite. @@ -930,6 +1018,12 @@ private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) Texture2D bakedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); bakedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); + + Color32[] bakedPixels = bakedTexture.GetPixels32(); + Unpremultiply(bakedPixels); + BleedAlphaEdges(bakedPixels, spriteWidth, spriteHeight); + bakedTexture.SetPixels32(bakedPixels); + bakedTexture.Apply(); bakedTexture.wrapMode = TextureWrapMode.Clamp; From 819fa8c41b70a1a42dbd6d19fb1db58df0662c48 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Sun, 8 Nov 2026 22:13:27 +0100 Subject: [PATCH 32/42] removed wav decoder, fixed some sprites not being fetched, changed editorconfig and formatting so it would much previous one --- .editorconfig | 4 +- src/Api/Config.cs | 214 +-- src/Api/GLDConfig.cs | 152 +-- src/Api/PolyScript.cs | 78 +- src/Dumper.cs | 492 +++---- src/Json/EnumCacheJson.cs | 224 ++-- src/Json/EnumNameJson.cs | 28 +- src/Json/JsonMerger.cs | 188 +-- src/Json/Vector2Json.cs | 70 +- src/Json/VersionJson.cs | 42 +- src/Loader.cs | 1951 ++++++++++++++------------- src/Managers/Audio.cs | 160 +-- src/Managers/Compatibility.cs | 704 +++++----- src/Managers/Hub.cs | 810 ++++++------ src/Managers/Loc.cs | 318 ++--- src/Managers/Main.cs | 917 +++++++------ src/Managers/Prefabs.cs | 1282 +++++++++--------- src/Managers/TribePreviews.cs | 442 +++---- src/Managers/Visual.cs | 2169 ++++++++++++++++--------------- src/Mod.cs | 202 +-- src/NullableFix.cs | 82 +- src/Plugin.cs | 410 +++--- src/Prefabs/OtherPrefabInfo.cs | 116 +- src/Prefabs/PrefabsInfo.cs | 16 +- src/Prefabs/SkinnedKey.cs | 92 +- src/Prefabs/VisualPartInfo.cs | 118 +- src/Registry.cs | 260 ++-- src/Util.cs | 248 ++-- src/WavDecoder.cs | 157 --- tests/CheckDependenciesTests.cs | 94 +- tests/CompatibilityTests.cs | 250 ++-- tests/LoaderTests.cs | 96 +- tests/ModFactory.cs | 18 +- tests/TestSetup.cs | 40 +- tests/UtilTests.cs | 52 +- tests/VersionJsonTests.cs | 16 +- 36 files changed, 6146 insertions(+), 6366 deletions(-) delete mode 100644 src/WavDecoder.cs diff --git a/.editorconfig b/.editorconfig index bca1bc2..bf10af8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,10 +7,10 @@ trim_trailing_whitespace = true [*.{json,yml,yaml}] indent_style = space -indent_size = 2 +indent_size = 4 [*.cs] -indent_style = tab +indent_style = space tab_width = 4 indent_size = 4 csharp_new_line_before_open_brace = all diff --git a/src/Api/Config.cs b/src/Api/Config.cs index 4cd3a19..88b8045 100644 --- a/src/Api/Config.cs +++ b/src/Api/Config.cs @@ -8,114 +8,114 @@ namespace PolyMod.Api; /// public class Config where T : class { - private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; - private T? currentConfig; - private readonly string modName; - private readonly ConfigTypes configType; - private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string perModConfigPath; - private T? defaultConfig; - public Config(string modName, ConfigTypes configType) - { - this.modName = modName; - this.configType = configType; - perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); - Load(); - } + private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; + private T? currentConfig; + private readonly string modName; + private readonly ConfigTypes configType; + private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); + private readonly string perModConfigPath; + private T? defaultConfig; + public Config(string modName, ConfigTypes configType) + { + this.modName = modName; + this.configType = configType; + perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); + Load(); + } - internal void Load() // can be called internally if config changes; gui config not implemented yet - { - switch (configType) - { - case ConfigTypes.PerMod: - { - if (!File.Exists(perModConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(perModConfigPath); - currentConfig = JsonSerializer.Deserialize(jsonText); - break; - } - case ConfigTypes.Exposed: - { - if (!File.Exists(ExposedConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(ExposedConfigPath); - currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); - break; - } - default: - throw new ArgumentOutOfRangeException(); - } - } - /// - /// Sets the default if the config does not exist yet. Always call this before reading from the config. - /// - public void SetDefaultConfig(T defaultValue) - { - defaultConfig = defaultValue; - if (currentConfig is not null) return; - Write(defaultConfig); - SaveChanges(); - } + internal void Load() // can be called internally if config changes; gui config not implemented yet + { + switch (configType) + { + case ConfigTypes.PerMod: + { + if (!File.Exists(perModConfigPath)) + { + return; + } + var jsonText = File.ReadAllText(perModConfigPath); + currentConfig = JsonSerializer.Deserialize(jsonText); + break; + } + case ConfigTypes.Exposed: + { + if (!File.Exists(ExposedConfigPath)) + { + return; + } + var jsonText = File.ReadAllText(ExposedConfigPath); + currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); + break; + } + default: + throw new ArgumentOutOfRangeException(); + } + } + /// + /// Sets the default if the config does not exist yet. Always call this before reading from the config. + /// + public void SetDefaultConfig(T defaultValue) + { + defaultConfig = defaultValue; + if (currentConfig is not null) return; + Write(defaultConfig); + SaveChanges(); + } - /// - /// Writes the **entire** config. Usage not recommended, use Edit() instead - /// - public void Write(T config) - { - currentConfig = config; - } - /// - /// Gets the config. Should only be called after setting a default. - /// - public T Get() - { - return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); - } - /// - /// Edits the config. Should only be called after setting a default. - /// - /// Call SaveChanges after editing - public void Edit(Action editor) - { - editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Gets part of the config. Should only be called after setting a default - /// - public TResult Get(Func getter) - { - return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Writes the config to disk - /// - public void SaveChanges() - { - switch (configType) - { - case ConfigTypes.PerMod: - var perModJson = JsonSerializer.Serialize(currentConfig, indentedJsonOptions); - File.WriteAllText(perModConfigPath, perModJson); - break; - case ConfigTypes.Exposed: - var modsConfigText = File.ReadAllText(ExposedConfigPath); - var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); - modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); - File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); - break; - default: - throw new ArgumentOutOfRangeException(); - } - } + /// + /// Writes the **entire** config. Usage not recommended, use Edit() instead + /// + public void Write(T config) + { + currentConfig = config; + } + /// + /// Gets the config. Should only be called after setting a default. + /// + public T Get() + { + return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); + } + /// + /// Edits the config. Should only be called after setting a default. + /// + /// Call SaveChanges after editing + public void Edit(Action editor) + { + editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); + } + /// + /// Gets part of the config. Should only be called after setting a default + /// + public TResult Get(Func getter) + { + return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); + } + /// + /// Writes the config to disk + /// + public void SaveChanges() + { + switch (configType) + { + case ConfigTypes.PerMod: + var perModJson = JsonSerializer.Serialize(currentConfig, indentedJsonOptions); + File.WriteAllText(perModConfigPath, perModJson); + break; + case ConfigTypes.Exposed: + var modsConfigText = File.ReadAllText(ExposedConfigPath); + var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); + modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); + File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } - public enum ConfigTypes - { - PerMod, - Exposed - } + public enum ConfigTypes + { + PerMod, + Exposed + } } diff --git a/src/Api/GLDConfig.cs b/src/Api/GLDConfig.cs index 8ff0e62..758d60b 100644 --- a/src/Api/GLDConfig.cs +++ b/src/Api/GLDConfig.cs @@ -7,88 +7,88 @@ namespace PolyMod.Api; public class GldConfigTemplate { - private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); + private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string templateText; - private JsonObject currentConfig = new(); - private string modName; + private readonly string templateText; + private JsonObject currentConfig = new(); + private string modName; - public GldConfigTemplate(string templateText, string modName) - { - this.templateText = templateText; - this.modName = modName; - Load(); - } - private void Load() - { - if (File.Exists(ConfigPath)) - { - var json = File.ReadAllText(ConfigPath); - if (JsonNode.Parse(json) is JsonObject modsConfig - && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) - && modConfigNode is JsonObject modConfig) - { - currentConfig = modConfig; - return; - } - } - currentConfig = new JsonObject(); - } + public GldConfigTemplate(string templateText, string modName) + { + this.templateText = templateText; + this.modName = modName; + Load(); + } + private void Load() + { + if (File.Exists(ConfigPath)) + { + var json = File.ReadAllText(ConfigPath); + if (JsonNode.Parse(json) is JsonObject modsConfig + && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) + && modConfigNode is JsonObject modConfig) + { + currentConfig = modConfig; + return; + } + } + currentConfig = new JsonObject(); + } - public string? Render() - { - if (!templateText.Contains("{{")) return templateText; - var template = Template.Parse(templateText); - var context = new TemplateContext(); - var scriptObject = new ScriptObject(); + public string? Render() + { + if (!templateText.Contains("{{")) return templateText; + var template = Template.Parse(templateText); + var context = new TemplateContext(); + var scriptObject = new ScriptObject(); - bool changedConfig = false; - scriptObject.Import("config", - new Func((key, defaultValue) => - { - if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) - { - return token.ToString(); - } + bool changedConfig = false; + scriptObject.Import("config", + new Func((key, defaultValue) => + { + if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) + { + return token.ToString(); + } - changedConfig = true; - currentConfig[key] = defaultValue; + changedConfig = true; + currentConfig[key] = defaultValue; - return defaultValue; - }) - ); - context.PushGlobal(scriptObject); - string? result; - try - { - result = template.Render(context); - } - catch (Exception e) - { - Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); - result = null; - } - if (changedConfig) - { - SaveChanges(); - } - return result; - } + return defaultValue; + }) + ); + context.PushGlobal(scriptObject); + string? result; + try + { + result = template.Render(context); + } + catch (Exception e) + { + Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); + result = null; + } + if (changedConfig) + { + SaveChanges(); + } + return result; + } - public void SaveChanges() - { - JsonObject modsConfigJson; - if (File.Exists(ConfigPath)) - { - var modsConfigText = File.ReadAllText(ConfigPath); - modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); - } - else - { - modsConfigJson = new JsonObject(); - } + public void SaveChanges() + { + JsonObject modsConfigJson; + if (File.Exists(ConfigPath)) + { + var modsConfigText = File.ReadAllText(ConfigPath); + modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); + } + else + { + modsConfigJson = new JsonObject(); + } - modsConfigJson[modName] = currentConfig; - File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); - } + modsConfigJson[modName] = currentConfig; + File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + } } diff --git a/src/Api/PolyScript.cs b/src/Api/PolyScript.cs index 6dd697e..cb2383a 100644 --- a/src/Api/PolyScript.cs +++ b/src/Api/PolyScript.cs @@ -5,48 +5,48 @@ namespace PolyMod.Api; public abstract class PolyScriptBase { - /// - /// Initializes the PolyScript with the given mod and logger. - /// - /// The mod instance. - /// The logger instance. - internal abstract void Initialize(Mod mod, ManualLogSource logger); - - /// > - /// Called when the mod is loaded. - /// - public abstract void Load(); - - /// - /// Called when the mod is unloaded. - /// - public abstract void Unload(); - - internal PolyScriptBase() - { - } + /// + /// Initializes the PolyScript with the given mod and logger. + /// + /// The mod instance. + /// The logger instance. + internal abstract void Initialize(Mod mod, ManualLogSource logger); + + /// > + /// Called when the mod is loaded. + /// + public abstract void Load(); + + /// + /// Called when the mod is unloaded. + /// + public abstract void Unload(); + + internal PolyScriptBase() + { + } } public abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class { - internal override void Initialize(Mod mod, ManualLogSource logger) - { - Mod = mod; - Config = new Config(mod.id, Config.ConfigTypes.PerMod); - ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); - Logger = logger; - } - - internal byte[]? GetFile(string fileName) - { - return Registry.mods[Mod.id].files.FirstOrDefault(f => f.name == fileName)?.bytes; - } - - public override void Unload() { } - - public Mod Mod { get; private set; } = null!; - protected Config Config { get; private set; } = null!; - protected Config ExposedConfig { get; private set; } = null!; - protected ManualLogSource Logger { get; private set; } = null!; + internal override void Initialize(Mod mod, ManualLogSource logger) + { + Mod = mod; + Config = new Config(mod.id, Config.ConfigTypes.PerMod); + ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); + Logger = logger; + } + + internal byte[]? GetFile(string fileName) + { + return Registry.mods[Mod.id].files.FirstOrDefault(f => f.name == fileName)?.bytes; + } + + public override void Unload() { } + + public Mod Mod { get; private set; } = null!; + protected Config Config { get; private set; } = null!; + protected Config ExposedConfig { get; private set; } = null!; + protected ManualLogSource Logger { get; private set; } = null!; } public abstract class PolyScript : PolyScript diff --git a/src/Dumper.cs b/src/Dumper.cs index 0bd3c20..343044a 100644 --- a/src/Dumper.cs +++ b/src/Dumper.cs @@ -13,279 +13,279 @@ namespace PolyMod.Managers; /// internal static class Dumper { - private static readonly JsonSerializerOptions INDENTED = new() - { - WriteIndented = true, - }; + private static readonly JsonSerializerOptions INDENTED = new() + { + WriteIndented = true, + }; - private static readonly JsonSerializerOptions INDENTED_WITH_VECTORS = new() - { - WriteIndented = true, - Converters = { new Vector2Json() }, - }; + private static readonly JsonSerializerOptions INDENTED_WITH_VECTORS = new() + { + WriteIndented = true, + Converters = { new Vector2Json() }, + }; - private static readonly JsonSerializerOptions LOCALIZATION = new() - { - WriteIndented = true, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - }; + private static readonly JsonSerializerOptions LOCALIZATION = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; - internal static string RootPath => Path.GetFullPath(Plugin.DUMPED_DATA_PATH); + internal static string RootPath => Path.GetFullPath(Plugin.DUMPED_DATA_PATH); - internal static void DumpAll() - { - Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); - DumpLogic(); - DumpLocalization(); - DumpSprites(); - DumpTribePreviews(); - DumpPrefabs(); - } + internal static void DumpAll() + { + Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); + DumpLogic(); + DumpLocalization(); + DumpSprites(); + DumpTribePreviews(); + DumpPrefabs(); + } - /// - /// Dumps every version of the game logic and avatar data. - /// - internal static void DumpLogic() - { - try - { - Directory.CreateDirectory(Plugin.LOGIC_DUMP_PATH); - for (int version = 1; version <= VersionManager.GameLogicDataVersion; version++) - { - File.WriteAllText( - Path.Combine(Plugin.LOGIC_DUMP_PATH, $"GameLogicData{version}.json"), - PolytopiaDataManager.provider.LoadGameLogicData(version) - ); - } - for (int version = 1; version <= VersionManager.AvatarDataVersion; version++) - { - File.WriteAllText( - Path.Combine(Plugin.LOGIC_DUMP_PATH, $"AvatarData{version}.json"), - PolytopiaDataManager.provider.LoadAvatarData(version) - ); - } - } - catch (Exception exception) - { - Plugin.logger.LogError($"Dumping logic failed: {exception}"); - } - } + /// + /// Dumps every version of the game logic and avatar data. + /// + internal static void DumpLogic() + { + try + { + Directory.CreateDirectory(Plugin.LOGIC_DUMP_PATH); + for (int version = 1; version <= VersionManager.GameLogicDataVersion; version++) + { + File.WriteAllText( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"GameLogicData{version}.json"), + PolytopiaDataManager.provider.LoadGameLogicData(version) + ); + } + for (int version = 1; version <= VersionManager.AvatarDataVersion; version++) + { + File.WriteAllText( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"AvatarData{version}.json"), + PolytopiaDataManager.provider.LoadAvatarData(version) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping logic failed: {exception}"); + } + } - internal static void DumpLocalization() - { - try - { - Directory.CreateDirectory(Plugin.LOCALIZATION_DUMP_PATH); - var source = I2.Loc.LocalizationManager.Sources[0]; + internal static void DumpLocalization() + { + try + { + Directory.CreateDirectory(Plugin.LOCALIZATION_DUMP_PATH); + var source = I2.Loc.LocalizationManager.Sources[0]; - foreach (var language in source.GetLanguages()) - { - int languageIndex = source.GetLanguageIndex(language); - Dictionary translations = new(); - foreach (var term in source.mTerms) - { - string translation = term.GetTranslation(languageIndex); - if (!string.IsNullOrEmpty(translation)) - translations[term.Term] = translation; - } - File.WriteAllText( - Path.Combine( - Plugin.LOCALIZATION_DUMP_PATH, - $"language_{source.mLanguages[languageIndex].Code}.json" - ), - JsonSerializer.Serialize(translations, LOCALIZATION) - ); - } + foreach (var language in source.GetLanguages()) + { + int languageIndex = source.GetLanguageIndex(language); + Dictionary translations = new(); + foreach (var term in source.mTerms) + { + string translation = term.GetTranslation(languageIndex); + if (!string.IsNullOrEmpty(translation)) + translations[term.Term] = translation; + } + File.WriteAllText( + Path.Combine( + Plugin.LOCALIZATION_DUMP_PATH, + $"language_{source.mLanguages[languageIndex].Code}.json" + ), + JsonSerializer.Serialize(translations, LOCALIZATION) + ); + } - foreach (var category in source.GetCategories()) - { - File.WriteAllText( - Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"localization_{category}.csv"), - source.Export_CSV(category) - ); - } - } - catch (Exception exception) - { - Plugin.logger.LogError($"Dumping localization failed: {exception}"); - } - } + foreach (var category in source.GetCategories()) + { + File.WriteAllText( + Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"localization_{category}.csv"), + source.Export_CSV(category) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping localization failed: {exception}"); + } + } - internal static void DumpSprites() - { - try - { - Directory.CreateDirectory(Plugin.SPRITES_DUMP_PATH); - SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + internal static void DumpSprites() + { + try + { + Directory.CreateDirectory(Plugin.SPRITES_DUMP_PATH); + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); - for (int i = 0; i < AtlasData.raw.Count; i++) - { - if (spriteAtlasManager.loadedAtlases[i] == null) continue; + for (int i = 0; i < AtlasData.raw.Count; i++) + { + if (spriteAtlasManager.loadedAtlases[i] == null) continue; - string[] row = AtlasData.raw[i]; - string atlasName = row[0]; - string directory = Path.Combine(Plugin.SPRITES_DUMP_PATH, atlasName); - Directory.CreateDirectory(directory); + string[] row = AtlasData.raw[i]; + string atlasName = row[0]; + string directory = Path.Combine(Plugin.SPRITES_DUMP_PATH, atlasName); + Directory.CreateDirectory(directory); - Dictionary atlasSpriteInfo = new(); - for (int j = 1; j < row.Length; j++) - { - string spriteName = row[j]; - Sprite sprite = spriteAtlasManager.GetSprite(spriteName, atlasName); - if (sprite == null) continue; + Dictionary atlasSpriteInfo = new(); + for (int j = 1; j < row.Length; j++) + { + string spriteName = row[j]; + Sprite sprite = spriteAtlasManager.GetSprite(spriteName, atlasName); + if (sprite == null) continue; - (byte[] bytes, Visual.SpriteInfo spriteInfo) = Visual.SpriteToPng(sprite); - File.WriteAllBytes(Path.Combine(directory, $"{spriteName}.png"), bytes); - atlasSpriteInfo[spriteName] = spriteInfo; - } - File.WriteAllText( - Path.Combine(directory, $"sprites_{atlasName}.json"), - JsonSerializer.Serialize(atlasSpriteInfo, INDENTED_WITH_VECTORS) - ); - } - } - catch (Exception exception) - { - Plugin.logger.LogError($"Dumping sprites failed: {exception}"); - } - } + (byte[] bytes, Visual.SpriteInfo spriteInfo) = Visual.SpriteToPng(sprite); + File.WriteAllBytes(Path.Combine(directory, $"{spriteName}.png"), bytes); + atlasSpriteInfo[spriteName] = spriteInfo; + } + File.WriteAllText( + Path.Combine(directory, $"sprites_{atlasName}.json"), + JsonSerializer.Serialize(atlasSpriteInfo, INDENTED_WITH_VECTORS) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping sprites failed: {exception}"); + } + } - internal static void DumpTribePreviews() - { - try - { - foreach (TribeType type in Enum.GetValues()) - { - SaveStateData saveStateData = TribePreviewRegistry.GetTribePreviewData(type, SkinType.Default); // TODO: skins - if (saveStateData == null) continue; + internal static void DumpTribePreviews() + { + try + { + foreach (TribeType type in Enum.GetValues()) + { + SaveStateData saveStateData = TribePreviewRegistry.GetTribePreviewData(type, SkinType.Default); // TODO: skins + if (saveStateData == null) continue; - if (!DiskSerializationHelpers.FromLZ4CompressedByteArray( - saveStateData.byteArray, out ClientSerializationWrapper wrapper, out int _)) - { - Plugin.logger.LogWarning($"Dump skipped preview of {type}: save state could not be read"); - continue; - } + if (!DiskSerializationHelpers.FromLZ4CompressedByteArray( + saveStateData.byteArray, out ClientSerializationWrapper wrapper, out int _)) + { + Plugin.logger.LogWarning($"Dump skipped preview of {type}: save state could not be read"); + continue; + } - List previewTiles = new(); - foreach (var tileData in wrapper.GetCurrentGameState().Map.Tiles) - { - previewTiles.Add(new TribePreviews.PreviewTile - { - x = tileData.coordinates.x, - y = tileData.coordinates.y, - terrainType = tileData.terrain, - resourceType = tileData.resource != null ? tileData.resource.type : null, - unitType = tileData.unit != null ? tileData.unit.type : null, - improvementType = tileData.improvement != null ? tileData.improvement.type : null, - tileEffects = tileData.effects.ToArray().ToList(), - }); - } + List previewTiles = new(); + foreach (var tileData in wrapper.GetCurrentGameState().Map.Tiles) + { + previewTiles.Add(new TribePreviews.PreviewTile + { + x = tileData.coordinates.x, + y = tileData.coordinates.y, + terrainType = tileData.terrain, + resourceType = tileData.resource != null ? tileData.resource.type : null, + unitType = tileData.unit != null ? tileData.unit.type : null, + improvementType = tileData.improvement != null ? tileData.improvement.type : null, + tileEffects = tileData.effects.ToArray().ToList(), + }); + } - File.WriteAllText( - Path.Combine(Plugin.DUMPED_DATA_PATH, $"preview_{type}.json"), - JsonSerializer.Serialize(previewTiles, INDENTED) - ); - } - } - catch (Exception exception) - { - Plugin.logger.LogError($"Dumping tribe previews failed: {exception}"); - } - } + File.WriteAllText( + Path.Combine(Plugin.DUMPED_DATA_PATH, $"preview_{type}.json"), + JsonSerializer.Serialize(previewTiles, INDENTED) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping tribe previews failed: {exception}"); + } + } - internal static void DumpPrefabs() - { - try - { - Directory.CreateDirectory(Plugin.PREFABS_DUMP_PATH); - PrefabsInfo prefabsInfo = new(); + internal static void DumpPrefabs() + { + try + { + Directory.CreateDirectory(Plugin.PREFABS_DUMP_PATH); + PrefabsInfo prefabsInfo = new(); - foreach (var entry in Prefabs.unitsNew) - { - List? visualParts = CollectVisualParts(entry.Value, entry.Key.unitType); - if (visualParts == null) continue; + foreach (var entry in Prefabs.unitsNew) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key.unitType); + if (visualParts == null) continue; - prefabsInfo.units.Add(new UnitPrefabInfo - { - headPositionMarker = entry.Value.headPositionMarker.gameObject.name, - skinnedKey = entry.Key, - visualParts = visualParts, - }); - } + prefabsInfo.units.Add(new UnitPrefabInfo + { + headPositionMarker = entry.Value.headPositionMarker.gameObject.name, + skinnedKey = entry.Key, + visualParts = visualParts, + }); + } - foreach (var entry in PrefabManager.improvements) - { - List? visualParts = CollectVisualParts(entry.Value, entry.Key); - if (visualParts == null) continue; + foreach (var entry in PrefabManager.improvements) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key); + if (visualParts == null) continue; - prefabsInfo.improvements.Add(new ImprovementPrefabInfo - { - improvementType = entry.Key, - visualParts = visualParts, - }); - } + prefabsInfo.improvements.Add(new ImprovementPrefabInfo + { + improvementType = entry.Key, + visualParts = visualParts, + }); + } - foreach (var entry in PrefabManager.resources) - { - List? visualParts = CollectVisualParts(entry.Value, entry.Key); - if (visualParts == null) continue; + foreach (var entry in PrefabManager.resources) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key); + if (visualParts == null) continue; - prefabsInfo.resources.Add(new ResourcePrefabInfo - { - resourceType = entry.Key, - visualParts = visualParts, - }); - } + prefabsInfo.resources.Add(new ResourcePrefabInfo + { + resourceType = entry.Key, + visualParts = visualParts, + }); + } - // TODO - // foreach (var entry in PrefabManager.weapons) - // { - // WeaponGFX weaponGFX = entry.Value; - // prefabsInfo.weapons.Add(new WeaponPrefabInfo - // { - // weaponEnum = entry.Key, - // spriteName = weaponGFX.defaultSprite.name, - // pathType = weaponGFX.pathType, - // pathMode = weaponGFX.pathMode, - // pathResolution = weaponGFX.pathResolution, - // pathEase = weaponGFX.pathEase, - // lookAheadOffset = weaponGFX.lookAheadOffset, - // handleAngleOffset = weaponGFX.handleAngleOffset, - // sfxType = SFXTypes.None, //TODO - // weaponPuffInfo = null, //TODO - // weaponRangedInfo = null //TODO - // }); - // } + // TODO + // foreach (var entry in PrefabManager.weapons) + // { + // WeaponGFX weaponGFX = entry.Value; + // prefabsInfo.weapons.Add(new WeaponPrefabInfo + // { + // weaponEnum = entry.Key, + // spriteName = weaponGFX.defaultSprite.name, + // pathType = weaponGFX.pathType, + // pathMode = weaponGFX.pathMode, + // pathResolution = weaponGFX.pathResolution, + // pathEase = weaponGFX.pathEase, + // lookAheadOffset = weaponGFX.lookAheadOffset, + // handleAngleOffset = weaponGFX.handleAngleOffset, + // sfxType = SFXTypes.None, //TODO + // weaponPuffInfo = null, //TODO + // weaponRangedInfo = null //TODO + // }); + // } - File.WriteAllText( - Path.Combine(Plugin.PREFABS_DUMP_PATH, "prefabs.json"), - JsonSerializer.Serialize(prefabsInfo, INDENTED_WITH_VECTORS) - ); - } - catch (Exception exception) - { - Plugin.logger.LogError($"Dumping prefabs failed: {exception}"); - } - } + File.WriteAllText( + Path.Combine(Plugin.PREFABS_DUMP_PATH, "prefabs.json"), + JsonSerializer.Serialize(prefabsInfo, INDENTED_WITH_VECTORS) + ); + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping prefabs failed: {exception}"); + } + } - private static List? CollectVisualParts(Component prefab, object key) - { - SkinVisualsReference skinVisualsReference = prefab.GetComponent(); - if (skinVisualsReference == null || skinVisualsReference.visualParts == null) - { - Plugin.logger.LogWarning($"Dump skipped {key}: no SkinVisualsReference"); - return null; - } + private static List? CollectVisualParts(Component prefab, object key) + { + SkinVisualsReference skinVisualsReference = prefab.GetComponent(); + if (skinVisualsReference == null || skinVisualsReference.visualParts == null) + { + Plugin.logger.LogWarning($"Dump skipped {key}: no SkinVisualsReference"); + return null; + } - List visualParts = new(); - foreach (var visualPart in skinVisualsReference.visualParts) - { - if (visualPart == null || visualPart.visualPart == null) continue; + List visualParts = new(); + foreach (var visualPart in skinVisualsReference.visualParts) + { + if (visualPart == null || visualPart.visualPart == null) continue; - VisualPartInfo visualPartInfo = new(); - visualPartInfo.CopyFromVisualPart(visualPart); - visualParts.Add(visualPartInfo); - } - return visualParts; - } + VisualPartInfo visualPartInfo = new(); + visualPartInfo.CopyFromVisualPart(visualPart); + visualParts.Add(visualPartInfo); + } + return visualParts; + } } diff --git a/src/Json/EnumCacheJson.cs b/src/Json/EnumCacheJson.cs index b0545f8..5f561c6 100644 --- a/src/Json/EnumCacheJson.cs +++ b/src/Json/EnumCacheJson.cs @@ -11,70 +11,70 @@ namespace PolyMod.Json; /// The enum type being converted. public class EnumCacheJson : JsonConverter where T : struct, Enum { - /// - /// Determines whether the converter can handle the given type. - /// Supports both the enum type and . - /// - /// The type to check for compatibility. - /// True if the type can be converted; otherwise false. - public override bool CanConvert(Type typeToConvert) - { - return typeToConvert == typeof(T) || typeToConvert == typeof(List); - } - - /// - /// Reads a JSON string and converts it into the corresponding enum value - /// using the EnumCache lookup. - /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// The enum value represented by the JSON string. - /// Thrown if the type is not supported. - public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (typeToConvert == typeof(T)) - { - return EnumCache.GetType(reader.GetString()); - } - - throw new NotSupportedException("EnumCacheJson does not support reading this type directly."); - } - - - /// - /// Writes the enum value as its cached string representation. - /// - /// The JSON writer. - /// The enum value to write. - /// Serialization options. - public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) - { - writer.WriteStringValue(EnumCache.GetName(value)); - } - - /// - /// Reads a JSON property name and converts it into the corresponding enum value. - /// - /// The JSON reader. - /// The target type. - /// Serialization options. - /// The enum value represented by the property name. - public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return Read(ref reader, typeToConvert, options); - } - - /// - /// Writes the enum value as a property name using its cached string representation. - /// - /// The JSON writer. - /// The enum value to write. - /// Serialization options. - public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options) - { - writer.WritePropertyName(EnumCache.GetName(value)); - } + /// + /// Determines whether the converter can handle the given type. + /// Supports both the enum type and . + /// + /// The type to check for compatibility. + /// True if the type can be converted; otherwise false. + public override bool CanConvert(Type typeToConvert) + { + return typeToConvert == typeof(T) || typeToConvert == typeof(List); + } + + /// + /// Reads a JSON string and converts it into the corresponding enum value + /// using the EnumCache lookup. + /// + /// The JSON reader. + /// The type to convert into. + /// Serialization options. + /// The enum value represented by the JSON string. + /// Thrown if the type is not supported. + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (typeToConvert == typeof(T)) + { + return EnumCache.GetType(reader.GetString()); + } + + throw new NotSupportedException("EnumCacheJson does not support reading this type directly."); + } + + + /// + /// Writes the enum value as its cached string representation. + /// + /// The JSON writer. + /// The enum value to write. + /// Serialization options. + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + writer.WriteStringValue(EnumCache.GetName(value)); + } + + /// + /// Reads a JSON property name and converts it into the corresponding enum value. + /// + /// The JSON reader. + /// The target type. + /// Serialization options. + /// The enum value represented by the property name. + public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return Read(ref reader, typeToConvert, options); + } + + /// + /// Writes the enum value as a property name using its cached string representation. + /// + /// The JSON writer. + /// The enum value to write. + /// Serialization options. + public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + writer.WritePropertyName(EnumCache.GetName(value)); + } } /// @@ -84,52 +84,52 @@ public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSer /// The enum type being converted. public class EnumCacheListJson : JsonConverter> where T : struct, Enum { - /// - /// Inner converter used to handle individual enum values. - /// - private readonly EnumCacheJson _inner = new(); - - /// - /// Reads a JSON array of enum string values and converts them into a list of enum values. - /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// A list of enum values. - /// Thrown if the JSON is not an array. - public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - var list = new List(); - - if (reader.TokenType != JsonTokenType.StartArray) - throw new JsonException("Expected StartArray token for enum list"); - - while (reader.Read()) - { - if (reader.TokenType == JsonTokenType.EndArray) - break; - - list.Add(_inner.Read(ref reader, typeof(T), options)); - } - - return list; - } - - /// - /// Writes a list of enum values as a JSON array of strings. - /// - /// The JSON writer. - /// The list of enum values to write. - /// Serialization options. - public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) - { - writer.WriteStartArray(); - - foreach (var item in value) - { - _inner.Write(writer, item, options); - } - - writer.WriteEndArray(); - } + /// + /// Inner converter used to handle individual enum values. + /// + private readonly EnumCacheJson _inner = new(); + + /// + /// Reads a JSON array of enum string values and converts them into a list of enum values. + /// + /// The JSON reader. + /// The type to convert into. + /// Serialization options. + /// A list of enum values. + /// Thrown if the JSON is not an array. + public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var list = new List(); + + if (reader.TokenType != JsonTokenType.StartArray) + throw new JsonException("Expected StartArray token for enum list"); + + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndArray) + break; + + list.Add(_inner.Read(ref reader, typeof(T), options)); + } + + return list; + } + + /// + /// Writes a list of enum values as a JSON array of strings. + /// + /// The JSON writer. + /// The list of enum values to write. + /// Serialization options. + public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) + { + writer.WriteStartArray(); + + foreach (var item in value) + { + _inner.Write(writer, item, options); + } + + writer.WriteEndArray(); + } } diff --git a/src/Json/EnumNameJson.cs b/src/Json/EnumNameJson.cs index cbf157b..f4e7231 100644 --- a/src/Json/EnumNameJson.cs +++ b/src/Json/EnumNameJson.cs @@ -9,21 +9,21 @@ namespace PolyMod.Json; /// public class EnumNameJson : JsonConverter where TEnum : struct, Enum { - public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - string? enumName = reader.GetString(); + public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? enumName = reader.GetString(); - if (enumName != null && Enum.TryParse(enumName, true, out TEnum parsedValue)) - { - return parsedValue; - } + if (enumName != null && Enum.TryParse(enumName, true, out TEnum parsedValue)) + { + return parsedValue; + } - string validNames = string.Join(", ", Enum.GetNames()); - throw new JsonException($"Unknown {typeof(TEnum).Name} value '{enumName}'. Valid values: {validNames}"); - } + string validNames = string.Join(", ", Enum.GetNames()); + throw new JsonException($"Unknown {typeof(TEnum).Name} value '{enumName}'. Valid values: {validNames}"); + } - public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } + public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } } diff --git a/src/Json/JsonMerger.cs b/src/Json/JsonMerger.cs index a556202..4b6d8c3 100644 --- a/src/Json/JsonMerger.cs +++ b/src/Json/JsonMerger.cs @@ -8,107 +8,107 @@ namespace PolyMod.Json; /// public static class JsonMerger { - /// - /// Merges a patch JObject into an original JObject. - /// - /// The original JObject. - /// The patch JObject to merge. - /// The merged JObject. - public static JObject Merge(JObject original, JObject patch) - { - patch = MergeRecursive(original, patch); - original.Merge(patch, new() { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); - return original; - } + /// + /// Merges a patch JObject into an original JObject. + /// + /// The original JObject. + /// The patch JObject to merge. + /// The merged JObject. + public static JObject Merge(JObject original, JObject patch) + { + patch = MergeRecursive(original, patch); + original.Merge(patch, new() { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }); + return original; + } - /// - /// Recursively applies custom merging logic to arrays. - /// - /// - /// - /// - private static JObject MergeRecursive(JObject original, JObject patch) - { - foreach (var property in patch.Properties().ToArray().ToList()) - { - if (property == null || property.Name == null) - continue; + /// + /// Recursively applies custom merging logic to arrays. + /// + /// + /// + /// + private static JObject MergeRecursive(JObject original, JObject patch) + { + foreach (var property in patch.Properties().ToArray().ToList()) + { + if (property == null || property.Name == null) + continue; - string propName = property.Name; - JToken? originalValue = original[propName]; - JToken patchValue = property.Value; + string propName = property.Name; + JToken? originalValue = original[propName]; + JToken patchValue = property.Value; - if (patchValue.Type == JTokenType.Array) - { - if (originalValue == null) - originalValue = new JArray(); + if (patchValue.Type == JTokenType.Array) + { + if (originalValue == null) + originalValue = new JArray(); - JArray originalArr = originalValue.Cast(); - JArray patchArr = patchValue.Cast(); - bool isSkins = propName.Equals("skins", StringComparison.OrdinalIgnoreCase); - JArray merged = MergeArrays(originalArr, patchArr, isSkins); - patch[propName] = merged; - } - else if (patchValue.Type == JTokenType.Object) - { - if (originalValue == null || originalValue.Type != JTokenType.Object) - originalValue = new JObject(); + JArray originalArr = originalValue.Cast(); + JArray patchArr = patchValue.Cast(); + bool isSkins = propName.Equals("skins", StringComparison.OrdinalIgnoreCase); + JArray merged = MergeArrays(originalArr, patchArr, isSkins); + patch[propName] = merged; + } + else if (patchValue.Type == JTokenType.Object) + { + if (originalValue == null || originalValue.Type != JTokenType.Object) + originalValue = new JObject(); - MergeRecursive(originalValue.Cast(), patchValue.Cast()); - } - } - return patch; - } + MergeRecursive(originalValue.Cast(), patchValue.Cast()); + } + } + return patch; + } - /// - /// Merges two JArrays, with special handling for adding and removing elements. - /// - /// The original JArray. - /// The patch JArray to merge. - /// A flag to indicate if the array is a 'skins' array, which has special merging logic. - /// The merged JArray. - private static JArray MergeArrays(JArray original, JArray patch, bool isSkins) - { - var result = new JArray(original); - var patchList = patch._values.ToArray().ToList(); + /// + /// Merges two JArrays, with special handling for adding and removing elements. + /// + /// The original JArray. + /// The patch JArray to merge. + /// A flag to indicate if the array is a 'skins' array, which has special merging logic. + /// The merged JArray. + private static JArray MergeArrays(JArray original, JArray patch, bool isSkins) + { + var result = new JArray(original); + var patchList = patch._values.ToArray().ToList(); - bool hasCustomValues = false; - foreach (var token in patchList) - { - if (token.Type != JTokenType.String) - { - result.Add(token); - continue; - } + bool hasCustomValues = false; + foreach (var token in patchList) + { + if (token.Type != JTokenType.String) + { + result.Add(token); + continue; + } - string str = token.ToString(); + string str = token.ToString(); - if (str.StartsWith('+')) - { - string value = str.Substring(1); - result.Add(value); - hasCustomValues = true; - } - else if (str.StartsWith('-')) - { - string value = str.Substring(1); - var toRemove = result._values.ToArray() - .Where(t => t.Type == JTokenType.String && t.ToString() == value) - .ToList(); - foreach (var rem in toRemove) - result.Remove(rem); - hasCustomValues = true; - } - else if (isSkins) - { - result.Add(str); - hasCustomValues = true; - } - } - if (!hasCustomValues) - { - result = new JArray(patch); - } - return result; - } + if (str.StartsWith('+')) + { + string value = str.Substring(1); + result.Add(value); + hasCustomValues = true; + } + else if (str.StartsWith('-')) + { + string value = str.Substring(1); + var toRemove = result._values.ToArray() + .Where(t => t.Type == JTokenType.String && t.ToString() == value) + .ToList(); + foreach (var rem in toRemove) + result.Remove(rem); + hasCustomValues = true; + } + else if (isSkins) + { + result.Add(str); + hasCustomValues = true; + } + } + if (!hasCustomValues) + { + result = new JArray(patch); + } + return result; + } } diff --git a/src/Json/Vector2Json.cs b/src/Json/Vector2Json.cs index a36e5df..1957c4d 100644 --- a/src/Json/Vector2Json.cs +++ b/src/Json/Vector2Json.cs @@ -9,40 +9,40 @@ namespace PolyMod.Json; /// public class Vector2Json : JsonConverter { - /// - /// Reads and converts the JSON to a . - /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. - public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - List values = new(); - if (reader.TokenType == JsonTokenType.StartArray) - { - while (reader.Read()) - { - if (reader.TokenType == JsonTokenType.EndArray) break; - if (reader.TokenType != JsonTokenType.Number) throw new JsonException(); - values.Add(reader.GetSingle()); - } - } - if (values.Count != 2) throw new JsonException(); - return new(values[0], values[1]); - } + /// + /// Reads and converts the JSON to a . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + List values = new(); + if (reader.TokenType == JsonTokenType.StartArray) + { + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndArray) break; + if (reader.TokenType != JsonTokenType.Number) throw new JsonException(); + values.Add(reader.GetSingle()); + } + } + if (values.Count != 2) throw new JsonException(); + return new(values[0], values[1]); + } - /// - /// Writes a specified value as JSON. - /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. - public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) - { - writer.WriteStartArray(); - writer.WriteNumberValue(value.x); - writer.WriteNumberValue(value.y); - writer.WriteEndArray(); - } + /// + /// Writes a specified value as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) + { + writer.WriteStartArray(); + writer.WriteNumberValue(value.x); + writer.WriteNumberValue(value.y); + writer.WriteEndArray(); + } } diff --git a/src/Json/VersionJson.cs b/src/Json/VersionJson.cs index 47b9067..21c6c81 100644 --- a/src/Json/VersionJson.cs +++ b/src/Json/VersionJson.cs @@ -8,26 +8,26 @@ namespace PolyMod.Json; /// public class VersionJson : JsonConverter { - /// - /// Reads and converts the JSON to a . - /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. - public override Version? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(reader.GetString()!); - } + /// + /// Reads and converts the JSON to a . + /// + /// The reader. + /// The type to convert. + /// An object that specifies serialization options to use. + /// The converted value. + public override Version? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(reader.GetString()!); + } - /// - /// Writes a specified value as JSON. - /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. - public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) - { - writer.WriteStringValue(value.ToString()); - } + /// + /// Writes a specified value as JSON. + /// + /// The writer to write to. + /// The value to convert to JSON. + /// An object that specifies serialization options to use. + public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } } diff --git a/src/Loader.cs b/src/Loader.cs index 0ce89e0..7a18e3a 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -7,7 +7,6 @@ using PolyMod.Json; using PolyMod.Managers; using Polytopia.Data; -using PolytopiaBackendBase.Game; using System.Diagnostics; using System.IO.Compression; using System.Reflection; @@ -21,996 +20,964 @@ namespace PolyMod; /// /// Handles loading of mods and their assets. /// -public static class Loader +internal static class Loader { - private static readonly JsonSerializerOptions manifestJsonOptions = new() - { - Converters = { new VersionJson() }, - }; - - private static readonly JsonSerializerOptions spriteInfoJsonOptions = new() - { - Converters = { new Vector2Json() }, - }; - - private static readonly JsonSerializerOptions prefabJsonOptions = new() - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }; - - internal record TypeMapping(Type type, bool shouldCreateCache = true); - - /// - /// Mappings from JSON data types to their corresponding C# types. - /// - internal static Dictionary typeMappings = new() - { - { "tribeData", new TypeMapping(typeof(TribeType)) }, - { "techData", new TypeMapping(typeof(TechData.Type)) }, - { "unitData", new TypeMapping(typeof(UnitData.Type)) }, - { "improvementData", new TypeMapping(typeof(ImprovementData.Type)) }, - { "terrainData", new TypeMapping(typeof(Polytopia.Data.TerrainData.Type)) }, - { "resourceData", new TypeMapping(typeof(ResourceData.Type)) }, - { "taskData", new TypeMapping(typeof(TaskData.Type)) }, - { "tribeAbility", new TypeMapping(typeof(TribeAbility.Type)) }, - { "unitAbility", new TypeMapping(typeof(UnitAbility.Type)) }, - { "improvementAbility", new TypeMapping(typeof(ImprovementAbility.Type)) }, - { "playerAbility", new TypeMapping(typeof(PlayerAbility.Type)) }, - { "weaponData", new TypeMapping(typeof(UnitData.WeaponEnum)) }, - { "skinData", new TypeMapping(typeof(SkinData), false) } - }; - - /// - /// List of custom game modes to be added. - /// - internal static List gamemodes = new(); - - /// - /// Handlers for processing specific data types during mod loading. - /// - internal static readonly Dictionary>> typeHandlers = new() - { - [typeof(TribeType)] = new List>() { - new((token, duringEnumCacheCreation) => - { - if (duringEnumCacheCreation) - { - Registry.customTribes.Add((TribeType)(int)token["idx"]); - token["style"] = Registry.climateAutoidx; - token["climate"] = Registry.climateAutoidx; - Registry.climateAutoidx++; - } - else - { - if (token["skins"] != null) - { - JArray skins = token["skins"].Cast(); - List skinValues = skins._values.ToArray().ToList(); - foreach (var skin in skinValues) - { - string skinId = skin.ToString(); - if (!Enum.TryParse(skinId, ignoreCase: true, out _)) - { - SkinType skinValue = (SkinType)Registry.autoidx; - EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); - EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); - Registry.skinInfo.Add(new Visual.SkinInfo(Registry.autoidx, skinId, null)); - Plugin.logger.LogInfo("Created mapping for skinType with id " + skinId + " and index " + Registry.autoidx); - Registry.autoidx++; - if(token["tribeAbilities"] != null) - { - JArray tribeAbilities = token["tribeAbilities"].Cast(); - List tribeAbilitiesValues = tribeAbilities._values.ToArray().ToList(); - - foreach(JToken ability in tribeAbilitiesValues) - { - string abilityValue = ability.ToString(); - - if (Enum.TryParse( - abilityValue, ignoreCase: true, - out TribeAbility.Type tribeAbilityType - ) && tribeAbilityType == TribeAbility.Type.Flooded) - { - string tileEffectId = skinId.ToLowerInvariant() + "_flood"; - EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); - EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); - Visual.customFloodingSkins.Add((TileData.EffectType)Registry.autoidx, skinValue); - Plugin.logger.LogInfo("Created mapping for tileEffect with id " + tileEffectId + " and index " + Registry.autoidx); - Registry.autoidx++; - } - } - } - } - } - Il2CppSystem.Collections.Generic.List modifiedSkins = skins._values; - foreach (var skin in Registry.skinInfo) - { - if (modifiedSkins.Contains(skin.id)) - { - modifiedSkins.Remove(skin.id); - modifiedSkins.Add(skin.idx.ToString(CultureInfo.InvariantCulture)); - } - } - JArray newSkins = new JArray(); - foreach (var item in modifiedSkins) - { - newSkins.Add(item); - } - token["skins"] = newSkins; - } - if (token["preview"] != null) - { - TribePreviews.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; - Registry.tribePreviews[Util.GetJTokenName(token)] = preview; - } - } - }) - }, - [typeof(UnitData.Type)] = new List>() { - new((token, duringEnumCacheCreation) => - { - if(!duringEnumCacheCreation) - { - if (token["embarksTo"] != null) - { - string unitId = Util.GetJTokenName(token); - string embarkUnitId = token["embarksTo"].ToString(); - Main.embarkNames[unitId] = embarkUnitId; - } - if (token["weapon"] != null) - { - string weaponString = token["weapon"].ToString(); - if (EnumCache.TryGetType(weaponString, out UnitData.WeaponEnum type)) - { - token["weapon"] = (int)type; - } - } - } - }) - }, - - [typeof(ImprovementData.Type)] = new List>() { - new((token, duringEnumCacheCreation) => - { - if (duringEnumCacheCreation) - return; - - if (token["prefab"] != null && (bool)token["prefab"]) - { - bool levels = false; - if(token["maxLevel"] != null && (int)token["maxLevel"] > 0) - { - levels = true; - } - Prefabs.improvementPrefabInfosToCreate[(ImprovementData.Type)(int)token["idx"]] = levels; - } - string improvementId = Util.GetJTokenName(token); - if (token["attractsResource"] != null) - { - string attractsId = token["attractsResource"].ToString(); - Main.attractsResourceNames[improvementId] = attractsId; - } - if (token["attractsToTerrain"] != null) - { - string attractsId = token["attractsToTerrain"].ToString(); - Main.attractsTerrainNames[improvementId] = attractsId; - } - if(token["infoOverride"] != null) - { - Loc.buildingsInfoOverrides[improvementId] = Loc.ReplaceDashesWithDots(token["infoOverride"].ToString()); - } - }) - }, - - [typeof(ResourceData.Type)] = new List>() { - new((token, duringEnumCacheCreation) => - { - if (duringEnumCacheCreation) - return; - - if (token["prefab"] != null && (bool)token["prefab"]) - { - Prefabs.resourcePrefabsInfosToCreate.Add((ResourceData.Type)(int)token["idx"]); - } - }) - }, - - [typeof(SkinData)] = new List>() { - new((token, duringEnumCacheCreation) => - { - var prop = token.Parent.Cast(); - prop.Replace(new JProperty(prop.Name.ToLowerInvariant(), prop.Value)); - }) - }, - }; - - /// - /// Represents information for a custom game mode button. - /// - /// The index of the game mode. - /// The action to perform when the button is clicked. - /// The index of the button in the UI. - /// The sprite for the button. - /// The name of the sprite for the button. - public record GameModeButtonsInformation(int gameModeIndex, UIButtonBase.ButtonAction action, int? buttonIndex, Sprite? sprite, string? spriteName); - - /// - /// Adds a new game mode button. - /// - /// The unique identifier for the game mode. - /// The action to perform when the button is clicked. - /// The boolean which decides if GameMode should appear in the menu. - /// The sprite for the button. - /// The name of the sprite for the button. - public static void AddGameMode(string id, UIButtonBase.ButtonAction action, bool shouldShowInMenu = true, Sprite? sprite = null, string? spriteName = null) - { - EnumCache.AddMapping(id, (GameMode)Registry.gameModesAutoidx); - EnumCache.AddMapping(id, (GameMode)Registry.gameModesAutoidx); - if (shouldShowInMenu) - gamemodes.Add(new GameModeButtonsInformation(Registry.gameModesAutoidx, action, null, sprite, spriteName)); - Registry.gameModesAutoidx++; - } - - /// - /// Adds a new data type for patching. - /// - /// The identifier for the data type in JSON. - /// "The C# type corresponding to the identifier. - public static void AddPatchDataType(string typeId, Type type) - { - if (!typeMappings.ContainsKey(typeId)) - typeMappings.Add(typeId, new TypeMapping(type)); - } - - public static void AddPatchDataType(string typeId, Type type, bool shouldCreateCache) - { - if (!typeMappings.ContainsKey(typeId)) - typeMappings.Add(typeId, new TypeMapping(type, shouldCreateCache)); - } - - public static void AddTypeHandler(Type type, Action handler) - { - string typeString = type.ToString(); - if (!typeMappings.ContainsValue(new TypeMapping(type, true)) && !typeMappings.ContainsValue(new TypeMapping(type, false))) - { - Plugin.logger.LogWarning($"Tried adding TypeHandler for type: {typeString} with missing TypeMapping. Please, add TypeMapping first."); - return; - } - if (!typeHandlers.ContainsKey(type)) - typeHandlers[type] = new(); - - typeHandlers[type].Add(handler); - - Plugin.logger.LogInfo($"Added TypeHandler for type: {typeString}."); - } - - /// - /// Loads all mods from the mods directory. - /// - /// A dictionary to populate with the loaded mods. - internal static void RegisterMods(Dictionary mods) - { - Directory.CreateDirectory(Plugin.MODS_PATH); - string[] modContainers = Directory.GetDirectories(Plugin.MODS_PATH) - .Union(Directory.GetFiles(Plugin.MODS_PATH, "*.polymod")) - .Union(Directory.GetFiles(Plugin.MODS_PATH, "*.zip")) - .ToArray(); - foreach (var modContainer in modContainers) - { - Mod.Manifest? manifest = null; - List files = new(); - - // Load mod from directory or zip archive - if (Directory.Exists(modContainer)) - { - foreach (var file in Directory.GetFiles(modContainer, "*", SearchOption.AllDirectories)) - { - ProcessModFile( - Path.GetRelativePath(modContainer, file), - File.ReadAllBytes(file), - files, - ref manifest - ); - } - } - else - { - foreach (var entry in new ZipArchive(File.OpenRead(modContainer)).Entries) - { - ProcessModFile( - entry.FullName, - entry.ReadBytes(), - files, - ref manifest - ); - } - } - #region ValidateManifest() - if (manifest == null) - { - Plugin.logger.LogError($"Mod manifest not found in {modContainer}"); - continue; - } - if (manifest.id == null) - { - Plugin.logger.LogError($"Mod id not found in {modContainer}"); - continue; - } - if (!Regex.IsMatch(manifest.id, @"^(?!polytopia$)[a-z_]+$")) - { - Plugin.logger.LogError($"Mod id {manifest.id} is invalid in {modContainer}"); - continue; - } - if (Plugin.config.disabledMods.Contains(manifest.id)) - { - Plugin.logger.LogError($"Mod {manifest.id} is disabled, skipping"); - continue; - } - if (manifest.version == null) - { - Plugin.logger.LogError($"Mod version not found in {modContainer}"); - continue; - } - if (manifest.authors == null || manifest.authors.Length == 0) - { - Plugin.logger.LogError($"Mod authors not found in {modContainer}"); - continue; - } - if (mods.ContainsKey(manifest.id)) - { - Plugin.logger.LogError($"Mod {manifest.id} already exists"); - continue; - } - #endregion - mods.Add(manifest.id, new( - manifest, - Mod.Status.Success, - files - )); - Plugin.logger.LogInfo($"Registered mod {manifest.id}"); - } - - CheckDependencies(mods); - } - - private static void ProcessModFile(string fullName, byte[] bytes, List files, ref Mod.Manifest? manifest) - { - if (fullName == "manifest.json") - { - manifest = JsonSerializer.Deserialize( - bytes, - manifestJsonOptions - ); - return; - } - files.Add(new(fullName, bytes)); - } - - internal static void LoadMods(Dictionary mods, out bool dependencyCycle) - { - dependencyCycle = !SortMods(Registry.mods); - if (dependencyCycle) return; - - foreach (var (id, mod) in Registry.mods) - { - if (mod.status != Mod.Status.Success) continue; - foreach (var file in mod.files) - { - if (Path.GetExtension(file.name) == ".dll") - { - LoadAssemblyFile(mod, file); - } - Match spritesMatch = Regex.Match(Path.GetFileName(file.name), @"^sprites(?:_(.*))?\.json$"); - if (spritesMatch.Success) - { - LoadSpriteInfoFile(mod, file); - } - Match languageMatch = Regex.Match(Path.GetFileName(file.name), @"^language(?:_(.*))?\.json$"); - if (languageMatch.Success) - { - string languageName = languageMatch.Groups[1].Value; - LoadLanguageFile( - mod, - file, - languageName - ); - } - } - } - Compatibility.ComputeChecksums(Registry.mods); - } - - internal static void CheckDependencies(Dictionary mods) - { - foreach (var (id, mod) in mods) - { - foreach (var dependency in mod.dependencies ?? Array.Empty()) - { - string? message = null; - if (!mods.TryGetValue(dependency.id, out Mod? dependencyMod)) - { - message = $"Dependency {dependency.id} not found"; - } - else - { - Version version = dependencyMod.version; - if ( - (dependency.min != null && version < dependency.min) - || - (dependency.max != null && version > dependency.max) - ) - { - message = $"Need dependency {dependency.id} version {dependency.min} - {dependency.max} found {version}"; - } - } - if (message != null) - { - if (dependency.required) - { - Plugin.logger.LogError(message); - mod.status = Mod.Status.DependenciesUnsatisfied; - } - else - { - Plugin.logger.LogWarning(message); - } - } - } - } - } - - /// - /// Sorts mods based on their dependencies using a topological sort. - /// - /// The dictionary of mods to sort. - /// True if the mods could be sorted (no circular dependencies), false otherwise. - internal static bool SortMods(Dictionary mods) - { - Stopwatch s = new(); - Dictionary> graph = new(); - Dictionary inDegree = new(); - Dictionary successfulMods = new(); - Dictionary unsuccessfulMods = new(); - foreach (var (id, mod) in mods) - { - if (mod.status == Mod.Status.Success) successfulMods.Add(id, mod); - else unsuccessfulMods.Add(id, mod); - } - foreach (var (id, _) in successfulMods) - { - graph[id] = new(); - inDegree[id] = 0; - } - foreach (var (id, mod) in successfulMods) - { - foreach (var dependency in mod.dependencies ?? Array.Empty()) - { - if (!graph.ContainsKey(dependency.id)) continue; - graph[dependency.id].Add(id); - inDegree[id]++; - } - } - Queue queue = new(); - foreach (var (id, _) in successfulMods) - { - if (inDegree[id] == 0) - { - queue.Enqueue(id); - } - } - Dictionary sorted = new(); - while (queue.Count > 0) - { - var id = queue.Dequeue(); - var mod = successfulMods[id]; - sorted.Add(id, mod); - foreach (var neighbor in graph[id]) - { - inDegree[neighbor]--; - if (inDegree[neighbor] == 0) - { - queue.Enqueue(neighbor); - } - } - } - if (sorted.Count != successfulMods.Count) - { - return false; - } - mods.Clear(); - mods.AddRange(sorted); - mods.AddRange(unsuccessfulMods); - - return true; - } - - /// - /// Loads an assembly file from a mod. - /// - /// The mod the assembly belongs to. - /// The assembly file to load. - public static void LoadAssemblyFile(Mod mod, Mod.File file) - { - try - { - Assembly assembly = Assembly.Load(file.bytes); - if (assembly - .GetTypes() - .FirstOrDefault(t => t.IsSubclassOf(typeof(Api.PolyScriptBase))) - is { } modType) - { - var modInstance = (Api.PolyScriptBase)Activator.CreateInstance(modType)!; - modInstance.Initialize(mod, BepInEx.Logging.Logger.CreateLogSource($"PolyMod] [{mod.id}")); - modInstance.Load(); - return; - } - foreach (Type type in assembly.GetTypes()) - { - MethodInfo? loadWithLogger = type.GetMethod("Load", new Type[] { typeof(ManualLogSource) }); - if (loadWithLogger != null) - { - loadWithLogger.Invoke(null, new object[] - { - BepInEx.Logging.Logger.CreateLogSource($"PolyMod] [{mod.id}") - }); - Plugin.logger.LogInfo($"Invoked Load method with logger from {type.FullName} from {mod.id} mod"); - } - MethodInfo? load = type.GetMethod("Load", Array.Empty()); - if (load != null) - { - load.Invoke(null, null); - Plugin.logger.LogInfo($"Invoked Load method from {type.FullName} from {mod.id} mod"); - } - } - } - catch (TargetInvocationException exception) - { - if (exception.InnerException != null) - { - Plugin.logger.LogError($"Error on loading assembly from {mod.id} mod: {exception.InnerException.Message}"); - mod.status = Mod.Status.Error; - } - } - } - - /// - /// Loads a localization file from a mod. - /// - /// The mod the localization file belongs to. - /// The localization file to load. - public static void LoadLocalizationFile(Mod mod, Mod.File file) - { - try - { - Loc.BuildAndLoadLocalization(JsonSerializer - .Deserialize>>(file.bytes)!); - Plugin.logger.LogInfo($"Registered localization from {mod.id} mod"); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading locatization from {mod.id} mod: {e.StackTrace}"); - } - } - - public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) - { - try - { - var dict = JsonSerializer.Deserialize>(file.bytes); - if (dict != null) - { - Loc.languagesToAdd.Add(languageName, dict); - Plugin.logger.LogInfo($"Registered language from {mod.id} mod"); - } - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading language file from {mod.id} mod: {e.StackTrace}"); - } - } - - /// - /// Loads a sprite file from a mod. - /// - /// The mod the sprite file belongs to. - /// The sprite file to load. - public static void LoadTextureFile(Mod mod, Mod.File file) - { - string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); - Texture2D texture2D = Visual.BuildTexture(file.bytes); - Registry.textures[name] = new KeyValuePair(texture2D, false); - } - - /// - /// Loads a sprite info file from a mod. - /// - /// The mod the sprite info file belongs to. - /// The sprite info file to load. - /// A dictionary of sprite information, or null if an error occurred. - public static Dictionary? LoadSpriteInfoFile(Mod mod, Mod.File file) - { - try - { - var deserialized = JsonSerializer.Deserialize>( - file.bytes, - spriteInfoJsonOptions - ); - - if (deserialized != null) - { - foreach (var kvp in deserialized) - { - if (kvp.Value.spriteOrigin?.name != null) - kvp.Value.spriteOrigin.name = kvp.Value.spriteOrigin.name.ToLowerInvariant(); - Registry.spriteInfos[kvp.Key.ToLowerInvariant()] = kvp.Value; - } - } - - Plugin.logger.LogInfo($"Registered sprite data from {mod.id} mod"); - return deserialized; - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading sprite data from {mod.id} mod: {e.StackTrace}"); - return null; - } - } - - /// - /// Loads an audio file from a mod. - /// - /// The mod the audio file belongs to. - /// The audio file to load. - public static void LoadAudioFile(Mod mod, Mod.File file) - { - string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); - try - { - AudioClip clip = Managers.Audio.BuildAudioClip(file.bytes, name); - AudioSource audioSource = new GameObject($"PolyModAudio_{name}").AddComponent(); - UnityEngine.Object.DontDestroyOnLoad(audioSource.gameObject); - audioSource.clip = clip; - Registry.audioClips[name] = audioSource; - - Plugin.logger.LogInfo( - $"Registered audio {name} file from {mod.id} mod" - + $" ({clip.channels}ch {clip.frequency}Hz {clip.length:F2}s)." - ); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading audio {name} file from {mod.id} mod: {e.Message}"); - } - } - - public static void LoadPrefabsFile(Mod mod, Mod.File file) - { - try - { - var prefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); - if (prefab == null) - return; - - Prefabs.unitInfos.AddRange(prefab.units); - Prefabs.improvementInfos.AddRange(prefab.improvements); - Prefabs.resourceInfos.AddRange(prefab.resources); - - Plugin.logger.LogInfo($"Registered prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); - } - } - - public static void LoadUnitPrefabFile(Mod mod, Mod.File file) - { - try - { - var unitPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); - if (unitPrefab == null) - return; - - Prefabs.unitInfos.Add(unitPrefab); - - Plugin.logger.LogInfo($"Registered unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); - } - } - - public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) - { - try - { - var improvementPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); - if (improvementPrefab == null) - return; - - Prefabs.improvementInfos.Add(improvementPrefab); - - Plugin.logger.LogInfo($"Registered improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); - } - } - - public static void LoadResourcePrefabFile(Mod mod, Mod.File file) - { - try - { - var resourcePrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); - if (resourcePrefab == null) - return; - - Prefabs.resourceInfos.Add(resourcePrefab); - - Plugin.logger.LogInfo($"Registered resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); - } - } - - /// - /// Loads and applies a game logic data patch from a mod. - /// - /// The mod the patch belongs to. - /// The original game logic data. - /// The patch to apply. - public static void LoadGameLogicDataPatch(Mod mod, JObject gld, JObject patch) - { - try - { - // Merge the patch into the game logic data - gld = JsonMerger.Merge(gld, patch); - Plugin.logger.LogInfo($"Registered patch from {mod.id} mod"); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on loading patch from {mod.id} mod: {e.StackTrace}"); - mod.status = Mod.Status.Error; - } - } - - /// - /// Loads an asset bundle from a mod. - /// - /// The mod the asset bundle belongs to. - /// The asset bundle file to load. - public static void LoadAssetBundle(Mod mod, Mod.File file) - { - Registry.assetBundles.Add( - Path.GetFileNameWithoutExtension(file.name), - AssetBundle.LoadFromMemory(file.bytes) - ); - } - - /// - /// Processes the merged game logic data after all mods have been loaded and patched. - /// - /// The game logic data object to populate. - /// The root JObject of the merged game logic data. - internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject rootObject) - { - try - { - CreateMappings(rootObject); - ProcessCustomTribes(); - ProcessEmbarkOverrides(); - ProcessAttractOverrides(); - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on processing modified game logic data : {e.StackTrace}"); - } - } - - internal static void ProcessCustomTribes() - { - foreach (var tribe in Registry.customTribes) - { - if (!GameLogicData.legacyTribeTypesOrder.Contains(tribe)) - { - GameLogicData.legacyTribeTypesOrder.Add(tribe); - } - } - } - - /// - /// Creates EnumCache mappings for custom enum values and invokes type handlers. - /// - /// - internal static void CreateMappings(JObject rootObject) - { - foreach (JToken jtoken in rootObject.SelectTokens("$.*.*").ToArray()) - { - JObject? token = jtoken.TryCast(); - if (token == null) - continue; - - string dataType = Util.GetJTokenName(token, 2); - if (!typeMappings.TryGetValue(dataType, out TypeMapping? typeMapping)) - continue; - - if (token["idx"] == null || !typeMapping.shouldCreateCache) - continue; - - Type targetType = typeMapping.type; - if (!targetType.IsEnum) - { - Plugin.logger.LogWarning($"Type {targetType.FullName} is not an enum, skipping!"); - continue; - } - - string id = Util.GetJTokenName(token); - - if ((int)token["idx"] == -1) - { - token["idx"] = Registry.autoidx; - Registry.autoidx++; - } - else if (Plugin.config.allowUnsafeIndexes) - { - Array values = Enum.GetValues(targetType); - - var maxValue = values.Cast().Max(); - - if (maxValue >= (int)token["idx"]) - { - continue; - } - } - else - { - continue; - } - - MethodInfo? methodInfo = typeof(EnumCache<>).MakeGenericType(targetType).GetMethod("AddMapping"); - if (methodInfo == null) - { - Plugin.logger.LogWarning($"Missing AddMapping method for {targetType.FullName}"); - continue; - } - - methodInfo.Invoke(null, new object[] { id, (int)token["idx"] }); - methodInfo.Invoke(null, new object[] { id, (int)token["idx"] }); - - if (typeHandlers.TryGetValue(targetType, out var handlers)) - { - foreach (var handler in handlers) - { - handler(token, true); - } - } - Plugin.logger.LogInfo("Created mapping for " + targetType.ToString() + " with id " + id + " and index " + (int)token["idx"]); - } - foreach (JToken jtoken in rootObject.SelectTokens("$.*.*").ToArray()) - { - JObject? token = jtoken.TryCast(); - if (token != null) - { - string dataType = Util.GetJTokenName(token, 2); - if (typeMappings.TryGetValue(dataType, out TypeMapping? typeMapping)) - { - if (typeHandlers.TryGetValue(typeMapping.type, out var handlers)) - { - foreach (var handler in handlers) - { - handler(token, false); - } - } - } - } - } - } - - /// - /// Processes the prefab registry and populates the PrefabManager with custom prefabs. - /// - internal static void ProcessFilesQueue() - { - try - { - foreach (KeyValuePair keyValuePair in Registry.filesQueueToBeProcessedAfterGLDMerge) - { - Mod mod = keyValuePair.Key; - Mod.File file = keyValuePair.Value; - Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); - if (prefabsMatch.Success) - { - LoadPrefabsFile(mod, file); - continue; - } - - Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); - if (unitPrefabMatch.Success) - { - LoadUnitPrefabFile(mod, file); - continue; - } - - Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); - if (improvementPrefabMatch.Success) - { - LoadImprovementPrefabFile(mod, file); - continue; - } - - Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); - if (resourcePrefabMatch.Success) - { - LoadResourcePrefabFile(mod, file); - continue; - } - - } - } - catch (Exception e) - { - Plugin.logger.LogError($"Error on processing post gld merge files queue : {e.StackTrace}"); - } - } - - /// - /// Processes embark overrides by mapping original embark unit types to configured overrides. - /// - internal static void ProcessEmbarkOverrides() - { - foreach (KeyValuePair entry in Main.embarkNames) - { - try - { - UnitData.Type unit = EnumCache.GetType(entry.Key); - UnitData.Type newUnit = EnumCache.GetType(entry.Value); - Main.embarkOverrides[unit] = newUnit; - Plugin.logger.LogInfo($"Embark unit type for {entry.Key} is now {entry.Value}"); - } - catch - { - Plugin.logger.LogError($"Embark unit type for {entry.Key} is not valid: {entry.Value}"); - } - } - } - - /// - /// Processes attract overrides by mapping improvements to resources and terrain types based on configured overrides. - /// - internal static void ProcessAttractOverrides() - { - foreach (KeyValuePair entry in Main.attractsResourceNames) - { - try - { - ImprovementData.Type improvement = EnumCache.GetType(entry.Key); - ResourceData.Type resource = EnumCache.GetType(entry.Value); - Main.attractsResourceOverrides[improvement] = resource; - Plugin.logger.LogInfo($"Improvement {entry.Key} now attracts {entry.Value}"); - } - catch - { - Plugin.logger.LogError($"Improvement {entry.Key} resource type is not valid: {entry.Value}"); - } - } - foreach (KeyValuePair entry in Main.attractsTerrainNames) - { - try - { - ImprovementData.Type improvement = EnumCache.GetType(entry.Key); - Polytopia.Data.TerrainData.Type terrain = EnumCache.GetType(entry.Value); - Main.attractsTerrainOverrides[improvement] = terrain; - Plugin.logger.LogInfo($"Improvement {entry.Key} now attracts on {entry.Value}"); - } - catch - { - Plugin.logger.LogError($"Improvement {entry.Key} terrain type is not valid: {entry.Value}"); - } - } - } + private static readonly JsonSerializerOptions manifestJsonOptions = new() + { + Converters = { new VersionJson() }, + }; + + private static readonly JsonSerializerOptions spriteInfoJsonOptions = new() + { + Converters = { new Vector2Json() }, + }; + + private static readonly JsonSerializerOptions prefabJsonOptions = new() + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }; + + internal record TypeMapping(Type type, bool shouldCreateCache = true); + + /// + /// Mappings from JSON data types to their corresponding C# types. + /// + internal static Dictionary typeMappings = new() + { + { "tribeData", new TypeMapping(typeof(TribeType)) }, + { "techData", new TypeMapping(typeof(TechData.Type)) }, + { "unitData", new TypeMapping(typeof(UnitData.Type)) }, + { "improvementData", new TypeMapping(typeof(ImprovementData.Type)) }, + { "terrainData", new TypeMapping(typeof(Polytopia.Data.TerrainData.Type)) }, + { "resourceData", new TypeMapping(typeof(ResourceData.Type)) }, + { "taskData", new TypeMapping(typeof(TaskData.Type)) }, + { "tribeAbility", new TypeMapping(typeof(TribeAbility.Type)) }, + { "unitAbility", new TypeMapping(typeof(UnitAbility.Type)) }, + { "improvementAbility", new TypeMapping(typeof(ImprovementAbility.Type)) }, + { "playerAbility", new TypeMapping(typeof(PlayerAbility.Type)) }, + { "weaponData", new TypeMapping(typeof(UnitData.WeaponEnum)) }, + { "skinData", new TypeMapping(typeof(SkinData), false) } + }; + + /// + /// Handlers for processing specific data types during mod loading. + /// + internal static readonly Dictionary>> typeHandlers = new() + { + [typeof(TribeType)] = new List>() { + new((token, duringEnumCacheCreation) => + { + if (duringEnumCacheCreation) + { + Registry.customTribes.Add((TribeType)(int)token["idx"]); + token["style"] = Registry.climateAutoidx; + token["climate"] = Registry.climateAutoidx; + Registry.climateAutoidx++; + } + else + { + if (token["skins"] != null) + { + JArray skins = token["skins"].Cast(); + List skinValues = skins._values.ToArray().ToList(); + foreach (var skin in skinValues) + { + string skinId = skin.ToString(); + if (!Enum.TryParse(skinId, ignoreCase: true, out _)) + { + SkinType skinValue = (SkinType)Registry.autoidx; + EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); + EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); + Registry.skinInfo.Add(new Visual.SkinInfo(Registry.autoidx, skinId, null)); + Plugin.logger.LogInfo("Created mapping for skinType with id " + skinId + " and index " + Registry.autoidx); + Registry.autoidx++; + if(token["tribeAbilities"] != null) + { + JArray tribeAbilities = token["tribeAbilities"].Cast(); + List tribeAbilitiesValues = tribeAbilities._values.ToArray().ToList(); + + foreach(JToken ability in tribeAbilitiesValues) + { + string abilityValue = ability.ToString(); + + if (Enum.TryParse( + abilityValue, ignoreCase: true, + out TribeAbility.Type tribeAbilityType + ) && tribeAbilityType == TribeAbility.Type.Flooded) + { + string tileEffectId = skinId.ToLowerInvariant() + "_flood"; + EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); + EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); + Visual.customFloodingSkins.Add((TileData.EffectType)Registry.autoidx, skinValue); + Plugin.logger.LogInfo("Created mapping for tileEffect with id " + tileEffectId + " and index " + Registry.autoidx); + Registry.autoidx++; + } + } + } + } + } + Il2CppSystem.Collections.Generic.List modifiedSkins = skins._values; + foreach (var skin in Registry.skinInfo) + { + if (modifiedSkins.Contains(skin.id)) + { + modifiedSkins.Remove(skin.id); + modifiedSkins.Add(skin.idx.ToString(CultureInfo.InvariantCulture)); + } + } + JArray newSkins = new JArray(); + foreach (var item in modifiedSkins) + { + newSkins.Add(item); + } + token["skins"] = newSkins; + } + if (token["preview"] != null) + { + TribePreviews.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; + Registry.tribePreviews[Util.GetJTokenName(token)] = preview; + } + } + }) + }, + [typeof(UnitData.Type)] = new List>() { + new((token, duringEnumCacheCreation) => + { + if(!duringEnumCacheCreation) + { + if (token["embarksTo"] != null) + { + string unitId = Util.GetJTokenName(token); + string embarkUnitId = token["embarksTo"].ToString(); + Main.embarkNames[unitId] = embarkUnitId; + } + if (token["weapon"] != null) + { + string weaponString = token["weapon"].ToString(); + if (EnumCache.TryGetType(weaponString, out UnitData.WeaponEnum type)) + { + token["weapon"] = (int)type; + } + } + } + }) + }, + + [typeof(ImprovementData.Type)] = new List>() { + new((token, duringEnumCacheCreation) => + { + if (duringEnumCacheCreation) + return; + + if (token["prefab"] != null && (bool)token["prefab"]) + { + bool levels = false; + if(token["maxLevel"] != null && (int)token["maxLevel"] > 0) + { + levels = true; + } + Prefabs.improvementPrefabInfosToCreate[(ImprovementData.Type)(int)token["idx"]] = levels; + } + string improvementId = Util.GetJTokenName(token); + if (token["attractsResource"] != null) + { + string attractsId = token["attractsResource"].ToString(); + Main.attractsResourceNames[improvementId] = attractsId; + } + if (token["attractsToTerrain"] != null) + { + string attractsId = token["attractsToTerrain"].ToString(); + Main.attractsTerrainNames[improvementId] = attractsId; + } + if(token["infoOverride"] != null) + { + Loc.buildingsInfoOverrides[improvementId] = Loc.ReplaceDashesWithDots(token["infoOverride"].ToString()); + } + }) + }, + + [typeof(ResourceData.Type)] = new List>() { + new((token, duringEnumCacheCreation) => + { + if (duringEnumCacheCreation) + return; + + if (token["prefab"] != null && (bool)token["prefab"]) + { + Prefabs.resourcePrefabsInfosToCreate.Add((ResourceData.Type)(int)token["idx"]); + } + }) + }, + + [typeof(SkinData)] = new List>() { + new((token, duringEnumCacheCreation) => + { + var prop = token.Parent.Cast(); + prop.Replace(new JProperty(prop.Name.ToLowerInvariant(), prop.Value)); + }) + }, + }; + + /// + /// Adds a new data type for patching. + /// + /// The identifier for the data type in JSON. + /// "The C# type corresponding to the identifier. + public static void AddPatchDataType(string typeId, Type type) + { + if (!typeMappings.ContainsKey(typeId)) + typeMappings.Add(typeId, new TypeMapping(type)); + } + + public static void AddPatchDataType(string typeId, Type type, bool shouldCreateCache) + { + if (!typeMappings.ContainsKey(typeId)) + typeMappings.Add(typeId, new TypeMapping(type, shouldCreateCache)); + } + + public static void AddTypeHandler(Type type, Action handler) + { + string typeString = type.ToString(); + if (!typeMappings.ContainsValue(new TypeMapping(type, true)) && !typeMappings.ContainsValue(new TypeMapping(type, false))) + { + Plugin.logger.LogWarning($"Tried adding TypeHandler for type: {typeString} with missing TypeMapping. Please, add TypeMapping first."); + return; + } + if (!typeHandlers.ContainsKey(type)) + typeHandlers[type] = new(); + + typeHandlers[type].Add(handler); + + Plugin.logger.LogInfo($"Added TypeHandler for type: {typeString}."); + } + + /// + /// Loads all mods from the mods directory. + /// + /// A dictionary to populate with the loaded mods. + internal static void RegisterMods(Dictionary mods) + { + Directory.CreateDirectory(Plugin.MODS_PATH); + string[] modContainers = Directory.GetDirectories(Plugin.MODS_PATH) + .Union(Directory.GetFiles(Plugin.MODS_PATH, "*.polymod")) + .Union(Directory.GetFiles(Plugin.MODS_PATH, "*.zip")) + .ToArray(); + foreach (var modContainer in modContainers) + { + Mod.Manifest? manifest = null; + List files = new(); + + // Load mod from directory or zip archive + if (Directory.Exists(modContainer)) + { + foreach (var file in Directory.GetFiles(modContainer, "*", SearchOption.AllDirectories)) + { + ProcessModFile( + Path.GetRelativePath(modContainer, file), + File.ReadAllBytes(file), + files, + ref manifest + ); + } + } + else + { + foreach (var entry in new ZipArchive(File.OpenRead(modContainer)).Entries) + { + ProcessModFile( + entry.FullName, + entry.ReadBytes(), + files, + ref manifest + ); + } + } + #region ValidateManifest() + if (manifest == null) + { + Plugin.logger.LogError($"Mod manifest not found in {modContainer}"); + continue; + } + if (manifest.id == null) + { + Plugin.logger.LogError($"Mod id not found in {modContainer}"); + continue; + } + if (!Regex.IsMatch(manifest.id, @"^(?!polytopia$)[a-z_]+$")) + { + Plugin.logger.LogError($"Mod id {manifest.id} is invalid in {modContainer}"); + continue; + } + if (Plugin.config.disabledMods.Contains(manifest.id)) + { + Plugin.logger.LogError($"Mod {manifest.id} is disabled, skipping"); + continue; + } + if (manifest.version == null) + { + Plugin.logger.LogError($"Mod version not found in {modContainer}"); + continue; + } + if (manifest.authors == null || manifest.authors.Length == 0) + { + Plugin.logger.LogError($"Mod authors not found in {modContainer}"); + continue; + } + if (mods.ContainsKey(manifest.id)) + { + Plugin.logger.LogError($"Mod {manifest.id} already exists"); + continue; + } + #endregion + mods.Add(manifest.id, new( + manifest, + Mod.Status.Success, + files + )); + Plugin.logger.LogInfo($"Registered mod {manifest.id}"); + } + + CheckDependencies(mods); + } + + private static void ProcessModFile(string fullName, byte[] bytes, List files, ref Mod.Manifest? manifest) + { + if (fullName == "manifest.json") + { + manifest = JsonSerializer.Deserialize( + bytes, + manifestJsonOptions + ); + return; + } + files.Add(new(fullName, bytes)); + } + + internal static void LoadMods(Dictionary mods, out bool dependencyCycle) + { + dependencyCycle = !SortMods(Registry.mods); + if (dependencyCycle) return; + + foreach (var (id, mod) in Registry.mods) + { + if (mod.status != Mod.Status.Success) continue; + foreach (var file in mod.files) + { + if (Path.GetExtension(file.name) == ".dll") + { + LoadAssemblyFile(mod, file); + } + Match spritesMatch = Regex.Match(Path.GetFileName(file.name), @"^sprites(?:_(.*))?\.json$"); + if (spritesMatch.Success) + { + LoadSpriteInfoFile(mod, file); + } + Match languageMatch = Regex.Match(Path.GetFileName(file.name), @"^language(?:_(.*))?\.json$"); + if (languageMatch.Success) + { + string languageName = languageMatch.Groups[1].Value; + LoadLanguageFile( + mod, + file, + languageName + ); + } + } + } + Compatibility.ComputeChecksums(Registry.mods); + } + + internal static void CheckDependencies(Dictionary mods) + { + foreach (var (id, mod) in mods) + { + foreach (var dependency in mod.dependencies ?? Array.Empty()) + { + string? message = null; + if (!mods.TryGetValue(dependency.id, out Mod? dependencyMod)) + { + message = $"Dependency {dependency.id} not found"; + } + else + { + Version version = dependencyMod.version; + if ( + (dependency.min != null && version < dependency.min) + || + (dependency.max != null && version > dependency.max) + ) + { + message = $"Need dependency {dependency.id} version {dependency.min} - {dependency.max} found {version}"; + } + } + if (message != null) + { + if (dependency.required) + { + Plugin.logger.LogError(message); + mod.status = Mod.Status.DependenciesUnsatisfied; + } + else + { + Plugin.logger.LogWarning(message); + } + } + } + } + } + + /// + /// Sorts mods based on their dependencies using a topological sort. + /// + /// The dictionary of mods to sort. + /// True if the mods could be sorted (no circular dependencies), false otherwise. + internal static bool SortMods(Dictionary mods) + { + Stopwatch s = new(); + Dictionary> graph = new(); + Dictionary inDegree = new(); + Dictionary successfulMods = new(); + Dictionary unsuccessfulMods = new(); + foreach (var (id, mod) in mods) + { + if (mod.status == Mod.Status.Success) successfulMods.Add(id, mod); + else unsuccessfulMods.Add(id, mod); + } + foreach (var (id, _) in successfulMods) + { + graph[id] = new(); + inDegree[id] = 0; + } + foreach (var (id, mod) in successfulMods) + { + foreach (var dependency in mod.dependencies ?? Array.Empty()) + { + if (!graph.ContainsKey(dependency.id)) continue; + graph[dependency.id].Add(id); + inDegree[id]++; + } + } + Queue queue = new(); + foreach (var (id, _) in successfulMods) + { + if (inDegree[id] == 0) + { + queue.Enqueue(id); + } + } + Dictionary sorted = new(); + while (queue.Count > 0) + { + var id = queue.Dequeue(); + var mod = successfulMods[id]; + sorted.Add(id, mod); + foreach (var neighbor in graph[id]) + { + inDegree[neighbor]--; + if (inDegree[neighbor] == 0) + { + queue.Enqueue(neighbor); + } + } + } + if (sorted.Count != successfulMods.Count) + { + return false; + } + mods.Clear(); + mods.AddRange(sorted); + mods.AddRange(unsuccessfulMods); + + return true; + } + + /// + /// Loads an assembly file from a mod. + /// + /// The mod the assembly belongs to. + /// The assembly file to load. + public static void LoadAssemblyFile(Mod mod, Mod.File file) + { + try + { + Assembly assembly = Assembly.Load(file.bytes); + if (assembly + .GetTypes() + .FirstOrDefault(t => t.IsSubclassOf(typeof(Api.PolyScriptBase))) + is { } modType) + { + var modInstance = (Api.PolyScriptBase)Activator.CreateInstance(modType)!; + modInstance.Initialize(mod, BepInEx.Logging.Logger.CreateLogSource($"PolyMod] [{mod.id}")); + modInstance.Load(); + return; + } + foreach (Type type in assembly.GetTypes()) + { + MethodInfo? loadWithLogger = type.GetMethod("Load", new Type[] { typeof(ManualLogSource) }); + if (loadWithLogger != null) + { + loadWithLogger.Invoke(null, new object[] + { + BepInEx.Logging.Logger.CreateLogSource($"PolyMod] [{mod.id}") + }); + Plugin.logger.LogInfo($"Invoked Load method with logger from {type.FullName} from {mod.id} mod"); + } + MethodInfo? load = type.GetMethod("Load", Array.Empty()); + if (load != null) + { + load.Invoke(null, null); + Plugin.logger.LogInfo($"Invoked Load method from {type.FullName} from {mod.id} mod"); + } + } + } + catch (TargetInvocationException exception) + { + if (exception.InnerException != null) + { + Plugin.logger.LogError($"Error on loading assembly from {mod.id} mod: {exception.InnerException.Message}"); + mod.status = Mod.Status.Error; + } + } + } + + /// + /// Loads a localization file from a mod. + /// + /// The mod the localization file belongs to. + /// The localization file to load. + public static void LoadLocalizationFile(Mod mod, Mod.File file) + { + try + { + Loc.BuildAndLoadLocalization(JsonSerializer + .Deserialize>>(file.bytes)!); + Plugin.logger.LogInfo($"Registered localization from {mod.id} mod"); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading locatization from {mod.id} mod: {e.StackTrace}"); + } + } + + public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) + { + try + { + var dict = JsonSerializer.Deserialize>(file.bytes); + if (dict != null) + { + Loc.languagesToAdd.Add(languageName, dict); + Plugin.logger.LogInfo($"Registered language from {mod.id} mod"); + } + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading language file from {mod.id} mod: {e.StackTrace}"); + } + } + + /// + /// Loads a sprite file from a mod. + /// + /// The mod the sprite file belongs to. + /// The sprite file to load. + public static void LoadTextureFile(Mod mod, Mod.File file) + { + string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); + Texture2D texture2D = Visual.BuildTexture(file.bytes); + Registry.textures[name] = new KeyValuePair(texture2D, false); + } + + /// + /// Loads a sprite info file from a mod. + /// + /// The mod the sprite info file belongs to. + /// The sprite info file to load. + /// A dictionary of sprite information, or null if an error occurred. + public static Dictionary? LoadSpriteInfoFile(Mod mod, Mod.File file) + { + try + { + var deserialized = JsonSerializer.Deserialize>( + file.bytes, + spriteInfoJsonOptions + ); + + if (deserialized != null) + { + foreach (var kvp in deserialized) + { + if (kvp.Value.spriteOrigin?.name != null) + kvp.Value.spriteOrigin.name = kvp.Value.spriteOrigin.name.ToLowerInvariant(); + Registry.spriteInfos[kvp.Key.ToLowerInvariant()] = kvp.Value; + } + } + + Plugin.logger.LogInfo($"Registered sprite data from {mod.id} mod"); + return deserialized; + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading sprite data from {mod.id} mod: {e.StackTrace}"); + return null; + } + } + + /// + /// Loads an audio file from a mod. + /// + /// The mod the audio file belongs to. + /// The audio file to load. + public static void LoadAudioFile(Mod mod, Mod.File file) + { + string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); + try + { + AudioClip clip = Managers.Audio.BuildAudioClip(file.bytes, name); + AudioSource audioSource = new GameObject($"PolyModAudio_{name}").AddComponent(); + UnityEngine.Object.DontDestroyOnLoad(audioSource.gameObject); + audioSource.clip = clip; + Registry.audioClips[name] = audioSource; + + Plugin.logger.LogInfo( + $"Registered audio {name} file from {mod.id} mod" + + $" ({clip.channels}ch {clip.frequency}Hz {clip.length:F2}s)." + ); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading audio {name} file from {mod.id} mod: {e.Message}"); + } + } + + public static void LoadPrefabsFile(Mod mod, Mod.File file) + { + try + { + var prefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (prefab == null) + return; + + Prefabs.unitInfos.AddRange(prefab.units); + Prefabs.improvementInfos.AddRange(prefab.improvements); + Prefabs.resourceInfos.AddRange(prefab.resources); + + Plugin.logger.LogInfo($"Registered prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } + + public static void LoadUnitPrefabFile(Mod mod, Mod.File file) + { + try + { + var unitPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (unitPrefab == null) + return; + + Prefabs.unitInfos.Add(unitPrefab); + + Plugin.logger.LogInfo($"Registered unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } + + public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) + { + try + { + var improvementPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (improvementPrefab == null) + return; + + Prefabs.improvementInfos.Add(improvementPrefab); + + Plugin.logger.LogInfo($"Registered improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } + + public static void LoadResourcePrefabFile(Mod mod, Mod.File file) + { + try + { + var resourcePrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (resourcePrefab == null) + return; + + Prefabs.resourceInfos.Add(resourcePrefab); + + Plugin.logger.LogInfo($"Registered resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } + } + + /// + /// Loads and applies a game logic data patch from a mod. + /// + /// The mod the patch belongs to. + /// The original game logic data. + /// The patch to apply. + public static void LoadGameLogicDataPatch(Mod mod, JObject gld, JObject patch) + { + try + { + // Merge the patch into the game logic data + gld = JsonMerger.Merge(gld, patch); + Plugin.logger.LogInfo($"Registered patch from {mod.id} mod"); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading patch from {mod.id} mod: {e.StackTrace}"); + mod.status = Mod.Status.Error; + } + } + + /// + /// Loads an asset bundle from a mod. + /// + /// The mod the asset bundle belongs to. + /// The asset bundle file to load. + public static void LoadAssetBundle(Mod mod, Mod.File file) + { + Registry.assetBundles.Add( + Path.GetFileNameWithoutExtension(file.name), + AssetBundle.LoadFromMemory(file.bytes) + ); + } + + /// + /// Processes the merged game logic data after all mods have been loaded and patched. + /// + /// The game logic data object to populate. + /// The root JObject of the merged game logic data. + internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject rootObject) + { + try + { + CreateMappings(rootObject); + ProcessCustomTribes(); + ProcessEmbarkOverrides(); + ProcessAttractOverrides(); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on processing modified game logic data : {e.StackTrace}"); + } + } + + internal static void ProcessCustomTribes() + { + foreach (var tribe in Registry.customTribes) + { + if (!GameLogicData.legacyTribeTypesOrder.Contains(tribe)) + { + GameLogicData.legacyTribeTypesOrder.Add(tribe); + } + } + } + + /// + /// Creates EnumCache mappings for custom enum values and invokes type handlers. + /// + /// + internal static void CreateMappings(JObject rootObject) + { + foreach (JToken jtoken in rootObject.SelectTokens("$.*.*").ToArray()) + { + JObject? token = jtoken.TryCast(); + if (token == null) + continue; + + string dataType = Util.GetJTokenName(token, 2); + if (!typeMappings.TryGetValue(dataType, out TypeMapping? typeMapping)) + continue; + + if (token["idx"] == null || !typeMapping.shouldCreateCache) + continue; + + Type targetType = typeMapping.type; + if (!targetType.IsEnum) + { + Plugin.logger.LogWarning($"Type {targetType.FullName} is not an enum, skipping!"); + continue; + } + + string id = Util.GetJTokenName(token); + + if ((int)token["idx"] == -1) + { + token["idx"] = Registry.autoidx; + Registry.autoidx++; + } + else if (Plugin.config.allowUnsafeIndexes) + { + Array values = Enum.GetValues(targetType); + + var maxValue = values.Cast().Max(); + + if (maxValue >= (int)token["idx"]) + { + continue; + } + } + else + { + continue; + } + + MethodInfo? methodInfo = typeof(EnumCache<>).MakeGenericType(targetType).GetMethod("AddMapping"); + if (methodInfo == null) + { + Plugin.logger.LogWarning($"Missing AddMapping method for {targetType.FullName}"); + continue; + } + + methodInfo.Invoke(null, new object[] { id, (int)token["idx"] }); + methodInfo.Invoke(null, new object[] { id, (int)token["idx"] }); + + if (typeHandlers.TryGetValue(targetType, out var handlers)) + { + foreach (var handler in handlers) + { + handler(token, true); + } + } + Plugin.logger.LogInfo("Created mapping for " + targetType.ToString() + " with id " + id + " and index " + (int)token["idx"]); + } + foreach (JToken jtoken in rootObject.SelectTokens("$.*.*").ToArray()) + { + JObject? token = jtoken.TryCast(); + if (token != null) + { + string dataType = Util.GetJTokenName(token, 2); + if (typeMappings.TryGetValue(dataType, out TypeMapping? typeMapping)) + { + if (typeHandlers.TryGetValue(typeMapping.type, out var handlers)) + { + foreach (var handler in handlers) + { + handler(token, false); + } + } + } + } + } + } + + /// + /// Processes the prefab registry and populates the PrefabManager with custom prefabs. + /// + internal static void ProcessFilesQueue() + { + try + { + foreach (KeyValuePair keyValuePair in Registry.filesQueueToBeProcessedAfterGLDMerge) + { + Mod mod = keyValuePair.Key; + Mod.File file = keyValuePair.Value; + Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); + if (prefabsMatch.Success) + { + LoadPrefabsFile(mod, file); + continue; + } + + Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); + if (unitPrefabMatch.Success) + { + LoadUnitPrefabFile(mod, file); + continue; + } + + Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); + if (improvementPrefabMatch.Success) + { + LoadImprovementPrefabFile(mod, file); + continue; + } + + Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); + if (resourcePrefabMatch.Success) + { + LoadResourcePrefabFile(mod, file); + continue; + } + + } + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on processing post gld merge files queue : {e.StackTrace}"); + } + } + + /// + /// Processes embark overrides by mapping original embark unit types to configured overrides. + /// + internal static void ProcessEmbarkOverrides() + { + foreach (KeyValuePair entry in Main.embarkNames) + { + try + { + UnitData.Type unit = EnumCache.GetType(entry.Key); + UnitData.Type newUnit = EnumCache.GetType(entry.Value); + Main.embarkOverrides[unit] = newUnit; + Plugin.logger.LogInfo($"Embark unit type for {entry.Key} is now {entry.Value}"); + } + catch + { + Plugin.logger.LogError($"Embark unit type for {entry.Key} is not valid: {entry.Value}"); + } + } + } + + /// + /// Processes attract overrides by mapping improvements to resources and terrain types based on configured overrides. + /// + internal static void ProcessAttractOverrides() + { + foreach (KeyValuePair entry in Main.attractsResourceNames) + { + try + { + ImprovementData.Type improvement = EnumCache.GetType(entry.Key); + ResourceData.Type resource = EnumCache.GetType(entry.Value); + Main.attractsResourceOverrides[improvement] = resource; + Plugin.logger.LogInfo($"Improvement {entry.Key} now attracts {entry.Value}"); + } + catch + { + Plugin.logger.LogError($"Improvement {entry.Key} resource type is not valid: {entry.Value}"); + } + } + foreach (KeyValuePair entry in Main.attractsTerrainNames) + { + try + { + ImprovementData.Type improvement = EnumCache.GetType(entry.Key); + Polytopia.Data.TerrainData.Type terrain = EnumCache.GetType(entry.Value); + Main.attractsTerrainOverrides[improvement] = terrain; + Plugin.logger.LogInfo($"Improvement {entry.Key} now attracts on {entry.Value}"); + } + catch + { + Plugin.logger.LogError($"Improvement {entry.Key} terrain type is not valid: {entry.Value}"); + } + } + } } diff --git a/src/Managers/Audio.cs b/src/Managers/Audio.cs index fa629a0..1fcceb2 100644 --- a/src/Managers/Audio.cs +++ b/src/Managers/Audio.cs @@ -9,101 +9,75 @@ namespace PolyMod.Managers; /// public static class Audio { - /// - /// Patches the music data to get custom nature audio clips. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetNatureAudioClip))] - private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) - { - AudioClip? audioClip = Registry.GetAudioClip("nature", type, skinType); - if (audioClip != null) - { - __result = audioClip; - return false; - } - return true; - } + /// + /// Patches the music data to get custom nature audio clips. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetNatureAudioClip))] + private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) + { + AudioClip? audioClip = Registry.GetAudioClip("nature", type, skinType); + if (audioClip != null) + { + __result = audioClip; + return false; + } + return true; + } - /// - /// Patches the music data to get custom music audio clips. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetMusicAudioClip))] - private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) - { - AudioClip? audioClip = Registry.GetAudioClip("music", type, skinType); - if (audioClip != null) - { - __result = audioClip; - return false; - } - return true; - } + /// + /// Patches the music data to get custom music audio clips. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetMusicAudioClip))] + private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) + { + AudioClip? audioClip = Registry.GetAudioClip("music", type, skinType); + if (audioClip != null) + { + __result = audioClip; + return false; + } + return true; + } - /// - /// Patches the audio SFX data to get custom sound effect clips. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(AudioSFXData), nameof(AudioSFXData.GetClip))] - private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, SkinType skinType) - { - AudioClip? audioClip = Registry.GetAudioClip( - EnumCache.GetName(id), - skin: skinType - ); - if (audioClip != null) - { - __result = audioClip; - return false; - } - return true; - } + /// + /// Patches the audio SFX data to get custom sound effect clips. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(AudioSFXData), nameof(AudioSFXData.GetClip))] + private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, SkinType skinType) + { + AudioClip? audioClip = Registry.GetAudioClip( + EnumCache.GetName(id), + skin: skinType + ); + if (audioClip != null) + { + __result = audioClip; + return false; + } + return true; + } - private const string CLIP_CREATION_UNAVAILABLE = - "this game build cannot create audio clips at runtime." - + " AudioClip.Create marshals its arguments as spans, and" - + " Il2CppSystem.ReadOnlySpan.GetPinnableReference() is missing from its IL2CPP build." - + " Custom audio stays disabled until the game ships calling AudioClip.Create and SetData"; + /// + /// Builds an audio clip from raw byte data. + /// + /// The byte data of the audio file, which has to be a WAVE file. + /// The name to give the clip inside Unity. + /// The created audio clip. + /// The data is not a WAVE file that can be decoded. + /// The game build cannot create audio clips. + public static AudioClip BuildAudioClip(byte[] data, string name = "polymod_audio") + { + return new(); + } - private static bool clipCreationUnavailable = false; - - /// - /// Builds an audio clip from raw byte data. - /// - /// The byte data of the audio file, which has to be a WAVE file. - /// The name to give the clip inside Unity. - /// The created audio clip. - /// The data is not a WAVE file that can be decoded. - /// The game build cannot create audio clips. - public static AudioClip BuildAudioClip(byte[] data, string name = "polymod_audio") - { - WavDecoder.WavData wav = WavDecoder.Decode(data); - if (clipCreationUnavailable) - throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}."); - - try - { - AudioClip clip = AudioClip.Create(name, wav.lengthSamples, wav.channels, wav.frequency, false); - if (clip == null) - throw new InvalidOperationException($"Unity returned no audio clip for {name}."); - if (!clip.SetData(wav.samples, 0)) - throw new InvalidOperationException($"Unity rejected the samples for {name}."); - return clip; - } - catch (MissingMethodException exception) - { - // Remembered so that a mod shipping many files reports this once rather than per file. - clipCreationUnavailable = true; - throw new NotSupportedException($"Cannot build {name}, {CLIP_CREATION_UNAVAILABLE}.", exception); - } - } - - /// - /// Initializes the Audio manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Audio)); - } + /// + /// Initializes the Audio manager by patching the necessary methods. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Audio)); + } } diff --git a/src/Managers/Compatibility.cs b/src/Managers/Compatibility.cs index e79d647..55b2e28 100644 --- a/src/Managers/Compatibility.cs +++ b/src/Managers/Compatibility.cs @@ -9,356 +9,356 @@ namespace PolyMod.Managers; /// internal static class Compatibility { - /// - /// The checksum of all loaded mods. - /// - internal static string checksum = string.Empty; - - /// - /// Whether the game settings should be reset due to a change in mods. - /// - internal static bool shouldResetSettings = false; - private static bool sawSignatureWarning; - private const string downloadLink = "https://polymod.dev/download/"; - - public static void ComputeChecksums(Dictionary mods) - { - List signatures = new(); - foreach (var (id, mod) in mods) - { - if (mod.status != Mod.Status.Success) continue; - if (mod.client || id == "polytopia") continue; - - mod.checksum = ComputeModChecksum(mod); - signatures.Add($"{id}:{mod.checksum}"); - } - signatures.Sort(StringComparer.Ordinal); - - checksum = Util.Hash(string.Join("\n", signatures)); - } - - public static string ComputeModChecksum(Mod mod) - { - List entries = new(); - foreach (Mod.File file in mod.files) - { - string name = file.name.Replace('\\', '/'); - if (name.EndsWith('/')) continue; - - entries.Add($"{name}:{Util.HashBytes(file.bytes)}"); - } - entries.Sort(StringComparer.Ordinal); - - return Util.Hash($"{mod.id}:{mod.version}\n{string.Join("\n", entries)}"); - } - - /// - /// Gets the player prefs key holding the checksum a saved game was created with. - /// - /// The id of the saved game. - /// The player prefs key. - private static string StateChecksumKey(object gameId) - { - return Plugin.STATE_CHECKSUM_KEY_PREFIX + NormalizeGameId(gameId); - } - - /// - /// Normalizes a game id so that the same save always maps to one key. The game hands ids over - /// as a Guid in some places and as a string in others, and those do not always match in case - /// or in whether they are wrapped in braces. - /// - /// The id of the saved game, as a Guid or a string. - /// The normalized id. - internal static string NormalizeGameId(object gameId) - { - return gameId.ToString()!.Trim('{', '}').ToLowerInvariant(); - } - - /// - /// Gets the path of the signature file older versions wrote for a saved game. - /// - /// The id of the saved game. - /// The path of the legacy signature file. - private static string LegacyStateChecksumPath(object gameId) - { - return Path.Combine(Application.persistentDataPath, $"{NormalizeGameId(gameId)}.signatures"); - } - - /// - /// Stores the current mod checksum for a saved game. - /// - /// The id of the saved game. - internal static void SaveStateChecksum(object gameId) - { - PlayerPrefs.SetString(StateChecksumKey(gameId), checksum); - PlayerPrefs.Save(); - } - - /// - /// Reads the mod checksum a saved game was created with, migrating it out of the - /// signature file older versions used. - /// - /// The id of the saved game. - /// The stored checksum, or an empty string when there is none. - internal static string ReadStateChecksum(object gameId) - { - string key = StateChecksumKey(gameId); - if (PlayerPrefs.HasKey(key)) - return PlayerPrefs.GetString(key); - - string legacyPath = LegacyStateChecksumPath(gameId); - if (!File.Exists(legacyPath)) - return string.Empty; - - string legacyChecksum = File.ReadAllText(legacyPath); - PlayerPrefs.SetString(key, legacyChecksum); - PlayerPrefs.Save(); - File.Delete(legacyPath); - return legacyChecksum; - } - - internal static void DeleteStateChecksum(object gameId) - { - PlayerPrefs.DeleteKey(StateChecksumKey(gameId)); - PlayerPrefs.Save(); - - string legacyPath = LegacyStateChecksumPath(gameId); - if (File.Exists(legacyPath)) - File.Delete(legacyPath); - } - - /// - /// Checks the signature of a saved game to ensure it is compatible with the current mods. - /// - /// True if the signatures match or if the check is ignored, false otherwise. - private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) - { - if (sawSignatureWarning) - { - sawSignatureWarning = false; - return true; - } - - string stateChecksum = string.Empty; - try - { - Plugin.logger.LogInfo($"Getting checksum for state {gameId}"); - stateChecksum = ReadStateChecksum(gameId); - Plugin.logger.LogInfo($"Checksum found."); - } - catch - { - Plugin.logger.LogInfo($"Failed to get checksum."); - } - if (stateChecksum == string.Empty) - { - Plugin.logger.LogInfo($"State checksum is empty, ignoring."); - return true; - } - bool doChecksumsMatch = stateChecksum == checksum; - Plugin.logger.LogInfo($"State checksum: '{stateChecksum}', global checksum: '{checksum}', comparison result : {doChecksumsMatch}"); - if (Plugin.config.debug) - { - Plugin.logger.LogInfo($"Debug detected, ignoring."); - return true; - } - if (!doChecksumsMatch) - { - PopupManager.GetBasicPopupWithData(new( - Localization.Get("polymod.signature.mismatch"), - Localization.Get("polymod.signature.incompatible"), - new(new PopupBase.PopupButtonData[] { - new("OK") - }) - )).Show(); - - return false; - } - return true; - } - - /// - /// Performs compatibility checks when the start screen is shown. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] - private static void StartScreen_UI2_OnShow() - { - if (!Plugin.ValidLaunch && Application.platform != RuntimePlatform.Android) - { - PopupManager.GetBasicPopupWithData( - new( - Localization.Get("polymod.title.invalid"), - Localization.Get("polymod.description.invalid"), - new PopupBase.PopupButtonData[] { - new( - "buttons.exitgame", - PopupBase.PopupButtonData.States.None, - callback: (Il2CppSystem.Action)Application.Quit, - closesPopup: false - ), - new( - "buttons.download.launcher", - PopupBase.PopupButtonData.States.None, - callback: DelegateSupport.ConvertDelegate(OpenSite), - closesPopup: false - ) - } - ) - ).Show(); - - void OpenSite() - { - NativeHelpers.OpenURL(downloadLink, false); - Application.Quit(); - } - return; - } - string lastChecksum = checksum; - try - { - lastChecksum = new(File.ReadAllText(Plugin.CHECKSUM_PATH)); - } - catch (FileNotFoundException) { } - - File.WriteAllText( - Plugin.CHECKSUM_PATH, - checksum - ); - if (lastChecksum != checksum) - { - shouldResetSettings = true; - } - - Version incompatibilityWarningLastVersion = new(PlayerPrefs.GetString( - Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, - Plugin.POLYTOPIA_VERSION.CutRevision().ToString() - )); - if (VersionManager.SemanticVersion.Cast().CutRevision() > incompatibilityWarningLastVersion) - { - PlayerPrefs.SetString( - Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, - VersionManager.SemanticVersion.Cast().CutRevision().ToString() - ); - PlayerPrefs.Save(); - PopupManager.GetBasicPopupWithData( - new( - Localization.Get("polymod.version.mismatch"), - Localization.Get("polymod.version.mismatch.description"), - new PopupBase.PopupButtonData[] { - new("buttons.stay", customColorStates: ColorConstants.redButtonColorStates), - new( - "buttons.exitgame", - PopupBase.PopupButtonData.States.None, - (Il2CppSystem.Action)Application.Quit, - closesPopup: false - ) - } - ) - ).Show(); - } - } - - /// - /// Checks the signature of a pass-and-play game before loading it. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.OnMainButtonClicked))] - private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) - { - return CheckSignatures(__instance.OnMainButtonClicked, __instance.gameId); - } - - /// - /// Checks the signature of a single-player game before resuming it. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnResumeButtonLongPress))] - private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) - { - return CheckSignatures(__instance.OnResumeButtonLongPress, LocalSaveFileUtils.GetSaveFiles(PolytopiaBackendBase.Game.GameType.SinglePlayer)[0]); - } - - /// - /// Deletes the stored checksum of a pass-and-play game when it is deleted. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.DeletePaPGame))] - private static void GameInfoPopup_DeletePaPGame(GameInfoPopup __instance) - { - DeleteStateChecksum(__instance.gameId); - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteSaveFile))] - private static void LocalSaveFileUtils_DeleteSaveFile(PolytopiaBackendBase.Game.GameType gameType, string gameId, bool localOnly) - { - DeleteStateChecksum(gameId); - } - - /// - /// Deletes the stored checksums of all saved games of a type when they are deleted. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteAllSaveFilesOfType))] - private static void LocalSaveFileUtils_DeleteAllSaveFilesOfType(PolytopiaBackendBase.Game.GameType gameType, bool localOnly) - { - foreach (var gameId in LocalSaveFileUtils.GetSaveFiles(gameType)) - { - DeleteStateChecksum(gameId); - } - } - - /// - /// Deletes the stored checksum of a game when the match ends. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GameManager), nameof(GameManager.MatchEnded))] - private static void GameManager_MatchEnded(bool localPlayerIsWinner, ScoreDetails scoreDetails, byte winnerId) - { - DeleteStateChecksum(GameManager.Client.gameId); - } - - /// - /// Stores the current mod checksum when a new game session is created. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(ClientBase), nameof(ClientBase.CreateSession), typeof(GameSettings), typeof(Il2CppSystem.Guid))] - private static void ClientBase_CreateSession(GameSettings settings, Il2CppSystem.Guid gameId) - { - SaveStateChecksum(gameId); - } - - /// - /// Resets game settings if necessary when the tribe selector screen is shown. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(TribeSelectorScreen), nameof(TribeSelectorScreen.Show))] - private static bool TribeSelectorScreen_Show(bool instant = false) - { - if (shouldResetSettings) - { - RestorePreliminaryGameSettings(); - shouldResetSettings = false; - } - return true; - } - - /// - /// Restores the preliminary game settings to their default values. - /// - internal static void RestorePreliminaryGameSettings() - { - GameManager.PreliminaryGameSettings.disabledTribes.Clear(); - GameManager.PreliminaryGameSettings.selectedSkins.Clear(); - GameManager.PreliminaryGameSettings.SaveToDisk(); - } - - /// - /// Initializes the Compatibility manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Compatibility)); - } + /// + /// The checksum of all loaded mods. + /// + internal static string checksum = string.Empty; + + /// + /// Whether the game settings should be reset due to a change in mods. + /// + internal static bool shouldResetSettings = false; + private static bool sawSignatureWarning; + private const string downloadLink = "https://polymod.dev/download/"; + + public static void ComputeChecksums(Dictionary mods) + { + List signatures = new(); + foreach (var (id, mod) in mods) + { + if (mod.status != Mod.Status.Success) continue; + if (mod.client || id == "polytopia") continue; + + mod.checksum = ComputeModChecksum(mod); + signatures.Add($"{id}:{mod.checksum}"); + } + signatures.Sort(StringComparer.Ordinal); + + checksum = Util.Hash(string.Join("\n", signatures)); + } + + public static string ComputeModChecksum(Mod mod) + { + List entries = new(); + foreach (Mod.File file in mod.files) + { + string name = file.name.Replace('\\', '/'); + if (name.EndsWith('/')) continue; + + entries.Add($"{name}:{Util.HashBytes(file.bytes)}"); + } + entries.Sort(StringComparer.Ordinal); + + return Util.Hash($"{mod.id}:{mod.version}\n{string.Join("\n", entries)}"); + } + + /// + /// Gets the player prefs key holding the checksum a saved game was created with. + /// + /// The id of the saved game. + /// The player prefs key. + private static string StateChecksumKey(object gameId) + { + return Plugin.STATE_CHECKSUM_KEY_PREFIX + NormalizeGameId(gameId); + } + + /// + /// Normalizes a game id so that the same save always maps to one key. The game hands ids over + /// as a Guid in some places and as a string in others, and those do not always match in case + /// or in whether they are wrapped in braces. + /// + /// The id of the saved game, as a Guid or a string. + /// The normalized id. + internal static string NormalizeGameId(object gameId) + { + return gameId.ToString()!.Trim('{', '}').ToLowerInvariant(); + } + + /// + /// Gets the path of the signature file older versions wrote for a saved game. + /// + /// The id of the saved game. + /// The path of the legacy signature file. + private static string LegacyStateChecksumPath(object gameId) + { + return Path.Combine(Application.persistentDataPath, $"{NormalizeGameId(gameId)}.signatures"); + } + + /// + /// Stores the current mod checksum for a saved game. + /// + /// The id of the saved game. + internal static void SaveStateChecksum(object gameId) + { + PlayerPrefs.SetString(StateChecksumKey(gameId), checksum); + PlayerPrefs.Save(); + } + + /// + /// Reads the mod checksum a saved game was created with, migrating it out of the + /// signature file older versions used. + /// + /// The id of the saved game. + /// The stored checksum, or an empty string when there is none. + internal static string ReadStateChecksum(object gameId) + { + string key = StateChecksumKey(gameId); + if (PlayerPrefs.HasKey(key)) + return PlayerPrefs.GetString(key); + + string legacyPath = LegacyStateChecksumPath(gameId); + if (!File.Exists(legacyPath)) + return string.Empty; + + string legacyChecksum = File.ReadAllText(legacyPath); + PlayerPrefs.SetString(key, legacyChecksum); + PlayerPrefs.Save(); + File.Delete(legacyPath); + return legacyChecksum; + } + + internal static void DeleteStateChecksum(object gameId) + { + PlayerPrefs.DeleteKey(StateChecksumKey(gameId)); + PlayerPrefs.Save(); + + string legacyPath = LegacyStateChecksumPath(gameId); + if (File.Exists(legacyPath)) + File.Delete(legacyPath); + } + + /// + /// Checks the signature of a saved game to ensure it is compatible with the current mods. + /// + /// True if the signatures match or if the check is ignored, false otherwise. + private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) + { + if (sawSignatureWarning) + { + sawSignatureWarning = false; + return true; + } + + string stateChecksum = string.Empty; + try + { + Plugin.logger.LogInfo($"Getting checksum for state {gameId}"); + stateChecksum = ReadStateChecksum(gameId); + Plugin.logger.LogInfo($"Checksum found."); + } + catch + { + Plugin.logger.LogInfo($"Failed to get checksum."); + } + if (stateChecksum == string.Empty) + { + Plugin.logger.LogInfo($"State checksum is empty, ignoring."); + return true; + } + bool doChecksumsMatch = stateChecksum == checksum; + Plugin.logger.LogInfo($"State checksum: '{stateChecksum}', global checksum: '{checksum}', comparison result : {doChecksumsMatch}"); + if (Plugin.config.debug) + { + Plugin.logger.LogInfo($"Debug detected, ignoring."); + return true; + } + if (!doChecksumsMatch) + { + PopupManager.GetBasicPopupWithData(new( + Localization.Get("polymod.signature.mismatch"), + Localization.Get("polymod.signature.incompatible"), + new(new PopupBase.PopupButtonData[] { + new("OK") + }) + )).Show(); + + return false; + } + return true; + } + + /// + /// Performs compatibility checks when the start screen is shown. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] + private static void StartScreen_UI2_OnShow() + { + if (!Plugin.ValidLaunch && Application.platform != RuntimePlatform.Android) + { + PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.title.invalid"), + Localization.Get("polymod.description.invalid"), + new PopupBase.PopupButtonData[] { + new( + "buttons.exitgame", + PopupBase.PopupButtonData.States.None, + callback: (Il2CppSystem.Action)Application.Quit, + closesPopup: false + ), + new( + "buttons.download.launcher", + PopupBase.PopupButtonData.States.None, + callback: DelegateSupport.ConvertDelegate(OpenSite), + closesPopup: false + ) + } + ) + ).Show(); + + void OpenSite() + { + NativeHelpers.OpenURL(downloadLink, false); + Application.Quit(); + } + return; + } + string lastChecksum = checksum; + try + { + lastChecksum = new(File.ReadAllText(Plugin.CHECKSUM_PATH)); + } + catch (FileNotFoundException) { } + + File.WriteAllText( + Plugin.CHECKSUM_PATH, + checksum + ); + if (lastChecksum != checksum) + { + shouldResetSettings = true; + } + + Version incompatibilityWarningLastVersion = new(PlayerPrefs.GetString( + Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, + Plugin.POLYTOPIA_VERSION.CutRevision().ToString() + )); + if (VersionManager.SemanticVersion.Cast().CutRevision() > incompatibilityWarningLastVersion) + { + PlayerPrefs.SetString( + Plugin.INCOMPATIBILITY_WARNING_LAST_VERSION_KEY, + VersionManager.SemanticVersion.Cast().CutRevision().ToString() + ); + PlayerPrefs.Save(); + PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.version.mismatch"), + Localization.Get("polymod.version.mismatch.description"), + new PopupBase.PopupButtonData[] { + new("buttons.stay", customColorStates: ColorConstants.redButtonColorStates), + new( + "buttons.exitgame", + PopupBase.PopupButtonData.States.None, + (Il2CppSystem.Action)Application.Quit, + closesPopup: false + ) + } + ) + ).Show(); + } + } + + /// + /// Checks the signature of a pass-and-play game before loading it. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.OnMainButtonClicked))] + private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) + { + return CheckSignatures(__instance.OnMainButtonClicked, __instance.gameId); + } + + /// + /// Checks the signature of a single-player game before resuming it. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnResumeButtonLongPress))] + private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) + { + return CheckSignatures(__instance.OnResumeButtonLongPress, LocalSaveFileUtils.GetSaveFiles(PolytopiaBackendBase.Game.GameType.SinglePlayer)[0]); + } + + /// + /// Deletes the stored checksum of a pass-and-play game when it is deleted. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.DeletePaPGame))] + private static void GameInfoPopup_DeletePaPGame(GameInfoPopup __instance) + { + DeleteStateChecksum(__instance.gameId); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteSaveFile))] + private static void LocalSaveFileUtils_DeleteSaveFile(PolytopiaBackendBase.Game.GameType gameType, string gameId, bool localOnly) + { + DeleteStateChecksum(gameId); + } + + /// + /// Deletes the stored checksums of all saved games of a type when they are deleted. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteAllSaveFilesOfType))] + private static void LocalSaveFileUtils_DeleteAllSaveFilesOfType(PolytopiaBackendBase.Game.GameType gameType, bool localOnly) + { + foreach (var gameId in LocalSaveFileUtils.GetSaveFiles(gameType)) + { + DeleteStateChecksum(gameId); + } + } + + /// + /// Deletes the stored checksum of a game when the match ends. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(GameManager), nameof(GameManager.MatchEnded))] + private static void GameManager_MatchEnded(bool localPlayerIsWinner, ScoreDetails scoreDetails, byte winnerId) + { + DeleteStateChecksum(GameManager.Client.gameId); + } + + /// + /// Stores the current mod checksum when a new game session is created. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(ClientBase), nameof(ClientBase.CreateSession), typeof(GameSettings), typeof(Il2CppSystem.Guid))] + private static void ClientBase_CreateSession(GameSettings settings, Il2CppSystem.Guid gameId) + { + SaveStateChecksum(gameId); + } + + /// + /// Resets game settings if necessary when the tribe selector screen is shown. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(TribeSelectorScreen), nameof(TribeSelectorScreen.Show))] + private static bool TribeSelectorScreen_Show(bool instant = false) + { + if (shouldResetSettings) + { + RestorePreliminaryGameSettings(); + shouldResetSettings = false; + } + return true; + } + + /// + /// Restores the preliminary game settings to their default values. + /// + internal static void RestorePreliminaryGameSettings() + { + GameManager.PreliminaryGameSettings.disabledTribes.Clear(); + GameManager.PreliminaryGameSettings.selectedSkins.Clear(); + GameManager.PreliminaryGameSettings.SaveToDisk(); + } + + /// + /// Initializes the Compatibility manager by patching the necessary methods. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Compatibility)); + } } diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 9047320..728b650 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -9,409 +9,409 @@ namespace PolyMod.Managers; internal static class Hub { - private record Setting( - string buttonKey, - string nameKey, - string descriptionKey, - Func isEnabled, - Action toggle - ); - - private const string HEADER_PREFIX = ""; - private const string HEADER_POSTFIX = ""; - - private const string COLOR_MUTED = "#9AA0A6"; - private const string COLOR_ENABLED = "#4CC76A"; - private const string COLOR_DISABLED = "#E36A5B"; - private const string COLOR_WARNING = "#E0A52E"; - private const int CHECKSUM_LENGTH = 12; - private const float HUB_POPUP_WIDTH_SHARE = 0.78f; - private const float HUB_POPUP_MAX_WIDTH = 1400f; - private const float SETTINGS_POPUP_WIDTH_SHARE = 0.5f; - private const float SETTINGS_POPUP_MAX_WIDTH = 900f; - private const float START_SCREEN_MARGIN = 50f; - private const float VERSION_LABEL_FONT_SIZE = 18f; - private const float VERSION_LABEL_GAP = 10f; - /// Margin the game keeps between the safe area and its own corner widgets. - private const float VERSION_LABEL_MARGIN = 15f; - private const float ROUND_BUTTON_TITLE_GAP = 10f; - private const string INTRO = "intro.mp4"; - - private const KeyCode HOTKEY_MODIFIER = KeyCode.LeftControl; - private const KeyCode HOTKEY_MODIFIER_ALTERNATIVE = KeyCode.RightControl; - private const KeyCode HOTKEY = KeyCode.Tab; - - private static readonly Setting[] SETTINGS = new Setting[] - { - new( - "polymod.hub.config.debug", - "polymod.debug", - "polymod.debug.description", - () => Plugin.config.debug, - () => - { - Plugin.config = Plugin.config with { debug = !Plugin.config.debug }; - Plugin.UpdateConsole(); - } - ), - new( - "polymod.hub.config.coordinates", - "polymod.coordinates", - "polymod.coordinates.description", - () => Plugin.config.showCoordinates, - () => Plugin.config = Plugin.config with { showCoordinates = !Plugin.config.showCoordinates } - ), - }; - - private static UIRoundButton_UI2? polyModButton = null; - private static NotificationBadge? brokenModsBadge = null; - private static TextField_UI2? polyModVersion = null; - - private static PopupBase? openPopup = null; - - public static bool IsPopupOpen - { - get - { - if (openPopup != null) - { - try - { - if (openPopup.IsShowing()) return true; - } - catch (Exception) { } - openPopup = null; - } - return false; - } - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(SplashController), nameof(SplashController.LoadAndPlayClip))] - private static bool SplashController_LoadAndPlayClip(SplashController __instance) - { - string path = Path.Combine(Application.persistentDataPath, INTRO); - File.WriteAllBytesAsync(path, Plugin.GetResource(INTRO).ReadBytes()); - __instance.lastPlayTime = Time.realtimeSinceStartup; - __instance.videoPlayer.url = path; - __instance.videoPlayer.Play(); - return false; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.Init))] - private static void StartScreen_UI2_Init(RectTransform transform) - { - polyModButton = UILibrary.NewRoundButton(transform).SetStyle(UIButtonBase_UI2.ButtonStyle.Suggested); - polyModButton.bg.sprite = Visual.BuildSprite(Plugin.GetResource("polymod_icon.png").ReadBytes()); - polyModButton.OnClickedSignal.Add(Callback(ShowPolyModHub)); - - brokenModsBadge = UILibrary.NewNotificationBadge(polyModButton.rectTransform).SetValue(CountBrokenMods()); - polyModButton.SetOverlay(brokenModsBadge, UIButtonBase_UI2.OverlayPosition.TopRight); - - // NewHeaderTinyText is the prefab a round button builds its own title from, so the label - // keeps the game's header font rather than the lighter body font NewText would give it. - polyModVersion = UILibrary.NewHeaderTinyText(transform); - polyModVersion.gameObject.name = "PolyModVersion"; - polyModVersion.textField.fontSize = VERSION_LABEL_FONT_SIZE; - polyModVersion.textField.color = Color.white; - polyModVersion.Text = $"PolyMod {Plugin.VERSION}"; - - if (Main.dependencyCycle) - ShowDependencyCyclePopup(); - } - - /// - /// Patches the start screen layout to place the PolyMod hub button and the version label. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RunLayout))] - private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, ScreenBase_UI2.ScreenSize screenSize) - { - if (polyModButton == null || polyModVersion == null) - { - Plugin.logger.LogWarning("PolyMod start screen widgets are missing, skipping their layout."); - return; - } - - polyModButton.iconContainer.gameObject.SetActive(false); - polyModButton.outline.gameObject.SetActive(false); - polyModButton.bg.color = Color.white; - // Setting the text re-runs the button's own layout, which also repositions the badge. - polyModButton.Text = Localization.Get("polymod.hub"); - float titleDrop = polyModButton.titleTextField == null - ? 0f - : (polyModButton.titleTextField.GetHeight() + ROUND_BUTTON_TITLE_GAP) / 2f; - polyModButton.SetPosition( - screenSize.safeRect.Right - START_SCREEN_MARGIN * 2.5f, - screenSize.safeRect.Top - START_SCREEN_MARGIN - titleDrop - ); - brokenModsBadge?.SetValue(CountBrokenMods()); - - // Anchored by its edges, not its centre, so a longer version string cannot run off screen. - float versionX = screenSize.safeRect.Left + VERSION_LABEL_MARGIN + polyModVersion.GetHalfWidth(); - float versionY = screenSize.safeRect.Bottom + VERSION_LABEL_MARGIN + polyModVersion.GetHalfHeight(); - polyModVersion.SetPosition(versionX, versionY); - - // The bottom row of buttons is centred and of fixed width, so a narrow window walks it into - // the version label. The row is already laid out by now, so lift the label clear of it. - UIRoundButton_UI2 bottomRowStart = __instance.settingsButton; - if (bottomRowStart != null - && polyModVersion.GetRight() + VERSION_LABEL_GAP > bottomRowStart.GetLeft()) - { - polyModVersion.SetPosition( - versionX, - bottomRowStart.GetTop() + polyModVersion.GetHalfHeight() + VERSION_LABEL_GAP - ); - } - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(GameManager), nameof(GameManager.Update))] - private static void GameManager_Update() - { - bool modifierHeld = Input.GetKey(HOTKEY_MODIFIER) || Input.GetKey(HOTKEY_MODIFIER_ALTERNATIVE); - if (modifierHeld && Input.GetKeyDown(HOTKEY) && !IsPopupOpen) - ShowPolyModHub(); - } - - internal static void ShowPolyModHub() - { - BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); - popup.Header = Localization.Get("polymod.hub"); - popup.Description = string.Join( - "\n\n", - Localization.Get("polymod.hub.header", Args(HEADER_PREFIX, HEADER_POSTFIX)), - BuildModList(), - Localization.Get("polymod.hub.footer", Args(HEADER_PREFIX, HEADER_POSTFIX)) - ); - - void OpenDiscord() => NativeHelpers.OpenURL(Plugin.DISCORD_LINK, false); - - List buttons = new() - { - new("buttons.back"), - new("polymod.hub.discord", callback: Callback(OpenDiscord)), - new("polymod.hub.config", callback: Callback(ShowConfigPopup)), - }; - if (Plugin.config.debug) - { - buttons.Add(new("polymod.hub.dump", callback: Callback(DumpData), closesPopup: false)); - buttons.Add(new("polymod.hub.hotreload", callback: Callback(HotReload), closesPopup: false)); - } - - popup.buttonData = buttons.ToArray(); - openPopup = popup; - popup.ShowSetWidth(HUB_POPUP_WIDTH_SHARE, HUB_POPUP_MAX_WIDTH); - } - - internal static void ShowConfigPopup() - { - BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); - popup.Header = Localization.Get("polymod.hub.config"); - popup.Description = BuildSettingsList(); - - List buttons = new() - { - new("buttons.back", callback: Callback(ShowPolyModHub)), - }; - foreach (Setting setting in SETTINGS) - { - void OnSettingClicked() - { - setting.toggle(); - Plugin.WriteConfig(); - popup.Description = BuildSettingsList(); - } - buttons.Add(new(setting.buttonKey, callback: Callback(OnSettingClicked), closesPopup: false)); - } - - popup.buttonData = buttons.ToArray(); - openPopup = popup; - popup.ShowSetWidth(SETTINGS_POPUP_WIDTH_SHARE, SETTINGS_POPUP_MAX_WIDTH); - } - - private static void ShowDependencyCyclePopup() - { - BasicPopup popup = PopupManager.GetBasicPopupWithData( - new( - Localization.Get("polymod.cycle"), - Localization.Get("polymod.cycle.description"), - new PopupButtonData[] - { - new( - "buttons.exitgame", - PopupButtonData.States.None, - (Il2CppSystem.Action)Application.Quit, - closesPopup: false, - customColorStates: ColorConstants.redButtonColorStates - ), - } - ) - ); - popup.IsUnskippable = true; - popup.Show(); - } - - private static void DumpData() - { - Dumper.DumpAll(); - string path = Dumper.RootPath; - - BasicPopup popup = PopupManager.GetBasicPopup(); - popup.Header = Localization.Get("polymod.hub.dump"); - popup.Description = Localization.Get("polymod.hub.dumped", Args(path)); - - void OpenDumpFolder() - { - try - { - Application.OpenURL(new Uri(path).AbsoluteUri); - } - catch (Exception exception) - { - Plugin.logger.LogError($"Could not open the dump folder at {path}: {exception}"); - } - } - - popup.buttonData = new PopupButtonData[] - { - new("polymod.hub.openfolder", callback: Callback(OpenDumpFolder)), - new("buttons.ok"), - }; - popup.Show(); - } - - private static void HotReload() - { - BasicPopup popup = PopupManager.GetBasicPopup(); - popup.Header = Localization.Get("polymod.hub.hotreload"); - popup.Description = Localization.Get("polymod.hotreload.unavailable"); - popup.SetDefaultOkbutton(); - popup.Show(); - } - - private static string BuildModList() - { - if (Registry.mods.Count == 0) - return Muted(Localization.Get("polymod.hub.mods.none")); - - int loaded = 0; - foreach (Mod mod in Registry.mods.Values) - { - if (mod.status == Mod.Status.Success) loaded++; - } - - string summary = Localization.Get( - "polymod.hub.summary", - Args(loaded.ToString(CultureInfo.InvariantCulture), Registry.mods.Count.ToString(CultureInfo.InvariantCulture)) - ); - summary += " " + Localization.Get( - "polymod.hub.checksum", - Args(ShortChecksum(Compatibility.checksum)) - ); - - List blocks = new() { Muted(summary) }; - foreach (Mod mod in Registry.mods.Values) - { - blocks.Add(BuildModEntry(mod)); - } - return string.Join("\n\n", blocks); - } - - /// - /// Shortens a checksum to the leading characters shown in the hub. - /// - /// The full checksum. - /// The shortened checksum. - private static string ShortChecksum(string checksum) - { - if (string.IsNullOrEmpty(checksum)) return "-"; - - return checksum.Length <= CHECKSUM_LENGTH ? checksum : checksum.Substring(0, CHECKSUM_LENGTH); - } - - private static string BuildModEntry(Mod mod) - { - string status = Localization.Get( - "polymod.hub.mod.status." + Enum.GetName(mod.status)!.ToLowerInvariant() - ); - string title = $"{mod.name} " + Muted($"v{mod.version}"); - string meta = $"{status}"; - if (mod.authors.Length > 0) - { - string authors = Localization.Get( - "polymod.hub.mod.authors", - Args(string.Join(", ", mod.authors)) - ); - meta += " " + Muted($"{authors}"); - } - if (!string.IsNullOrEmpty(mod.checksum)) - { - string modChecksum = Localization.Get( - "polymod.hub.mod.checksum", - Args(ShortChecksum(mod.checksum)) - ); - meta += " " + Muted($"{modChecksum}"); - } - - List lines = new() { title, meta }; - if (!string.IsNullOrWhiteSpace(mod.description)) - lines.Add($"{mod.description}"); - - return string.Join("\n", lines); - } - - private static string BuildSettingsList() - { - List blocks = new(); - foreach (Setting setting in SETTINGS) - { - bool enabled = setting.isEnabled(); - string state = Localization.Get(enabled ? "polymod.on" : "polymod.off"); - string color = enabled ? COLOR_ENABLED : COLOR_DISABLED; - blocks.Add( - $"{Localization.Get(setting.nameKey)} {state}\n" - + Muted($"{Localization.Get(setting.descriptionKey)}") - ); - } - return string.Join("\n\n", blocks); - } - - private static string Muted(string text) => $"{text}"; - - private static string StatusColor(Mod.Status status) => status switch - { - Mod.Status.Success => COLOR_ENABLED, - Mod.Status.DependenciesUnsatisfied => COLOR_WARNING, - _ => COLOR_DISABLED, - }; - - private static int CountBrokenMods() - { - int broken = 0; - foreach (Mod mod in Registry.mods.Values) - { - if (mod.status != Mod.Status.Success) broken++; - } - return broken; - } - - private static Il2CppSystem.Action Callback(Action callback) - => DelegateSupport.ConvertDelegate(callback)!; - - private static Il2CppSystem.Object[] Args(params string[] values) - { - Il2CppSystem.Object[] arguments = new Il2CppSystem.Object[values.Length]; - for (int i = 0; i < values.Length; i++) - { - arguments[i] = values[i]; - } - return arguments; - } - - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Hub)); - } + private record Setting( + string buttonKey, + string nameKey, + string descriptionKey, + Func isEnabled, + Action toggle + ); + + private const string HEADER_PREFIX = ""; + private const string HEADER_POSTFIX = ""; + + private const string COLOR_MUTED = "#9AA0A6"; + private const string COLOR_ENABLED = "#4CC76A"; + private const string COLOR_DISABLED = "#E36A5B"; + private const string COLOR_WARNING = "#E0A52E"; + private const int CHECKSUM_LENGTH = 12; + private const float HUB_POPUP_WIDTH_SHARE = 0.78f; + private const float HUB_POPUP_MAX_WIDTH = 1400f; + private const float SETTINGS_POPUP_WIDTH_SHARE = 0.5f; + private const float SETTINGS_POPUP_MAX_WIDTH = 900f; + private const float START_SCREEN_MARGIN = 50f; + private const float VERSION_LABEL_FONT_SIZE = 18f; + private const float VERSION_LABEL_GAP = 10f; + /// Margin the game keeps between the safe area and its own corner widgets. + private const float VERSION_LABEL_MARGIN = 15f; + private const float ROUND_BUTTON_TITLE_GAP = 10f; + private const string INTRO = "intro.mp4"; + + private const KeyCode HOTKEY_MODIFIER = KeyCode.LeftControl; + private const KeyCode HOTKEY_MODIFIER_ALTERNATIVE = KeyCode.RightControl; + private const KeyCode HOTKEY = KeyCode.Tab; + + private static readonly Setting[] SETTINGS = new Setting[] + { + new( + "polymod.hub.config.debug", + "polymod.debug", + "polymod.debug.description", + () => Plugin.config.debug, + () => + { + Plugin.config = Plugin.config with { debug = !Plugin.config.debug }; + Plugin.UpdateConsole(); + } + ), + new( + "polymod.hub.config.coordinates", + "polymod.coordinates", + "polymod.coordinates.description", + () => Plugin.config.showCoordinates, + () => Plugin.config = Plugin.config with { showCoordinates = !Plugin.config.showCoordinates } + ), + }; + + private static UIRoundButton_UI2? polyModButton = null; + private static NotificationBadge? brokenModsBadge = null; + private static TextField_UI2? polyModVersion = null; + + private static PopupBase? openPopup = null; + + public static bool IsPopupOpen + { + get + { + if (openPopup != null) + { + try + { + if (openPopup.IsShowing()) return true; + } + catch (Exception) { } + openPopup = null; + } + return false; + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SplashController), nameof(SplashController.LoadAndPlayClip))] + private static bool SplashController_LoadAndPlayClip(SplashController __instance) + { + string path = Path.Combine(Application.persistentDataPath, INTRO); + File.WriteAllBytesAsync(path, Plugin.GetResource(INTRO).ReadBytes()); + __instance.lastPlayTime = Time.realtimeSinceStartup; + __instance.videoPlayer.url = path; + __instance.videoPlayer.Play(); + return false; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.Init))] + private static void StartScreen_UI2_Init(RectTransform transform) + { + polyModButton = UILibrary.NewRoundButton(transform).SetStyle(UIButtonBase_UI2.ButtonStyle.Suggested); + polyModButton.bg.sprite = Visual.BuildSprite(Plugin.GetResource("polymod_icon.png").ReadBytes()); + polyModButton.OnClickedSignal.Add(Callback(ShowPolyModHub)); + + brokenModsBadge = UILibrary.NewNotificationBadge(polyModButton.rectTransform).SetValue(CountBrokenMods()); + polyModButton.SetOverlay(brokenModsBadge, UIButtonBase_UI2.OverlayPosition.TopRight); + + // NewHeaderTinyText is the prefab a round button builds its own title from, so the label + // keeps the game's header font rather than the lighter body font NewText would give it. + polyModVersion = UILibrary.NewHeaderTinyText(transform); + polyModVersion.gameObject.name = "PolyModVersion"; + polyModVersion.textField.fontSize = VERSION_LABEL_FONT_SIZE; + polyModVersion.textField.color = Color.white; + polyModVersion.Text = $"PolyMod {Plugin.VERSION}"; + + if (Main.dependencyCycle) + ShowDependencyCyclePopup(); + } + + /// + /// Patches the start screen layout to place the PolyMod hub button and the version label. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RunLayout))] + private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, ScreenBase_UI2.ScreenSize screenSize) + { + if (polyModButton == null || polyModVersion == null) + { + Plugin.logger.LogWarning("PolyMod start screen widgets are missing, skipping their layout."); + return; + } + + polyModButton.iconContainer.gameObject.SetActive(false); + polyModButton.outline.gameObject.SetActive(false); + polyModButton.bg.color = Color.white; + // Setting the text re-runs the button's own layout, which also repositions the badge. + polyModButton.Text = Localization.Get("polymod.hub"); + float titleDrop = polyModButton.titleTextField == null + ? 0f + : (polyModButton.titleTextField.GetHeight() + ROUND_BUTTON_TITLE_GAP) / 2f; + polyModButton.SetPosition( + screenSize.safeRect.Right - START_SCREEN_MARGIN * 2.5f, + screenSize.safeRect.Top - START_SCREEN_MARGIN - titleDrop + ); + brokenModsBadge?.SetValue(CountBrokenMods()); + + // Anchored by its edges, not its centre, so a longer version string cannot run off screen. + float versionX = screenSize.safeRect.Left + VERSION_LABEL_MARGIN + polyModVersion.GetHalfWidth(); + float versionY = screenSize.safeRect.Bottom + VERSION_LABEL_MARGIN + polyModVersion.GetHalfHeight(); + polyModVersion.SetPosition(versionX, versionY); + + // The bottom row of buttons is centred and of fixed width, so a narrow window walks it into + // the version label. The row is already laid out by now, so lift the label clear of it. + UIRoundButton_UI2 bottomRowStart = __instance.settingsButton; + if (bottomRowStart != null + && polyModVersion.GetRight() + VERSION_LABEL_GAP > bottomRowStart.GetLeft()) + { + polyModVersion.SetPosition( + versionX, + bottomRowStart.GetTop() + polyModVersion.GetHalfHeight() + VERSION_LABEL_GAP + ); + } + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(GameManager), nameof(GameManager.Update))] + private static void GameManager_Update() + { + bool modifierHeld = Input.GetKey(HOTKEY_MODIFIER) || Input.GetKey(HOTKEY_MODIFIER_ALTERNATIVE); + if (modifierHeld && Input.GetKeyDown(HOTKEY) && !IsPopupOpen) + ShowPolyModHub(); + } + + internal static void ShowPolyModHub() + { + BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = string.Join( + "\n\n", + Localization.Get("polymod.hub.header", Args(HEADER_PREFIX, HEADER_POSTFIX)), + BuildModList(), + Localization.Get("polymod.hub.footer", Args(HEADER_PREFIX, HEADER_POSTFIX)) + ); + + void OpenDiscord() => NativeHelpers.OpenURL(Plugin.DISCORD_LINK, false); + + List buttons = new() + { + new("buttons.back"), + new("polymod.hub.discord", callback: Callback(OpenDiscord)), + new("polymod.hub.config", callback: Callback(ShowConfigPopup)), + }; + if (Plugin.config.debug) + { + buttons.Add(new("polymod.hub.dump", callback: Callback(DumpData), closesPopup: false)); + buttons.Add(new("polymod.hub.hotreload", callback: Callback(HotReload), closesPopup: false)); + } + + popup.buttonData = buttons.ToArray(); + openPopup = popup; + popup.ShowSetWidth(HUB_POPUP_WIDTH_SHARE, HUB_POPUP_MAX_WIDTH); + } + + internal static void ShowConfigPopup() + { + BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); + popup.Header = Localization.Get("polymod.hub.config"); + popup.Description = BuildSettingsList(); + + List buttons = new() + { + new("buttons.back", callback: Callback(ShowPolyModHub)), + }; + foreach (Setting setting in SETTINGS) + { + void OnSettingClicked() + { + setting.toggle(); + Plugin.WriteConfig(); + popup.Description = BuildSettingsList(); + } + buttons.Add(new(setting.buttonKey, callback: Callback(OnSettingClicked), closesPopup: false)); + } + + popup.buttonData = buttons.ToArray(); + openPopup = popup; + popup.ShowSetWidth(SETTINGS_POPUP_WIDTH_SHARE, SETTINGS_POPUP_MAX_WIDTH); + } + + private static void ShowDependencyCyclePopup() + { + BasicPopup popup = PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.cycle"), + Localization.Get("polymod.cycle.description"), + new PopupButtonData[] + { + new( + "buttons.exitgame", + PopupButtonData.States.None, + (Il2CppSystem.Action)Application.Quit, + closesPopup: false, + customColorStates: ColorConstants.redButtonColorStates + ), + } + ) + ); + popup.IsUnskippable = true; + popup.Show(); + } + + private static void DumpData() + { + Dumper.DumpAll(); + string path = Dumper.RootPath; + + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub.dump"); + popup.Description = Localization.Get("polymod.hub.dumped", Args(path)); + + void OpenDumpFolder() + { + try + { + Application.OpenURL(new Uri(path).AbsoluteUri); + } + catch (Exception exception) + { + Plugin.logger.LogError($"Could not open the dump folder at {path}: {exception}"); + } + } + + popup.buttonData = new PopupButtonData[] + { + new("polymod.hub.openfolder", callback: Callback(OpenDumpFolder)), + new("buttons.ok"), + }; + popup.Show(); + } + + private static void HotReload() + { + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub.hotreload"); + popup.Description = Localization.Get("polymod.hotreload.unavailable"); + popup.SetDefaultOkbutton(); + popup.Show(); + } + + private static string BuildModList() + { + if (Registry.mods.Count == 0) + return Muted(Localization.Get("polymod.hub.mods.none")); + + int loaded = 0; + foreach (Mod mod in Registry.mods.Values) + { + if (mod.status == Mod.Status.Success) loaded++; + } + + string summary = Localization.Get( + "polymod.hub.summary", + Args(loaded.ToString(CultureInfo.InvariantCulture), Registry.mods.Count.ToString(CultureInfo.InvariantCulture)) + ); + summary += " " + Localization.Get( + "polymod.hub.checksum", + Args(ShortChecksum(Compatibility.checksum)) + ); + + List blocks = new() { Muted(summary) }; + foreach (Mod mod in Registry.mods.Values) + { + blocks.Add(BuildModEntry(mod)); + } + return string.Join("\n\n", blocks); + } + + /// + /// Shortens a checksum to the leading characters shown in the hub. + /// + /// The full checksum. + /// The shortened checksum. + private static string ShortChecksum(string checksum) + { + if (string.IsNullOrEmpty(checksum)) return "-"; + + return checksum.Length <= CHECKSUM_LENGTH ? checksum : checksum.Substring(0, CHECKSUM_LENGTH); + } + + private static string BuildModEntry(Mod mod) + { + string status = Localization.Get( + "polymod.hub.mod.status." + Enum.GetName(mod.status)!.ToLowerInvariant() + ); + string title = $"{mod.name} " + Muted($"v{mod.version}"); + string meta = $"{status}"; + if (mod.authors.Length > 0) + { + string authors = Localization.Get( + "polymod.hub.mod.authors", + Args(string.Join(", ", mod.authors)) + ); + meta += " " + Muted($"{authors}"); + } + if (!string.IsNullOrEmpty(mod.checksum)) + { + string modChecksum = Localization.Get( + "polymod.hub.mod.checksum", + Args(ShortChecksum(mod.checksum)) + ); + meta += " " + Muted($"{modChecksum}"); + } + + List lines = new() { title, meta }; + if (!string.IsNullOrWhiteSpace(mod.description)) + lines.Add($"{mod.description}"); + + return string.Join("\n", lines); + } + + private static string BuildSettingsList() + { + List blocks = new(); + foreach (Setting setting in SETTINGS) + { + bool enabled = setting.isEnabled(); + string state = Localization.Get(enabled ? "polymod.on" : "polymod.off"); + string color = enabled ? COLOR_ENABLED : COLOR_DISABLED; + blocks.Add( + $"{Localization.Get(setting.nameKey)} {state}\n" + + Muted($"{Localization.Get(setting.descriptionKey)}") + ); + } + return string.Join("\n\n", blocks); + } + + private static string Muted(string text) => $"{text}"; + + private static string StatusColor(Mod.Status status) => status switch + { + Mod.Status.Success => COLOR_ENABLED, + Mod.Status.DependenciesUnsatisfied => COLOR_WARNING, + _ => COLOR_DISABLED, + }; + + private static int CountBrokenMods() + { + int broken = 0; + foreach (Mod mod in Registry.mods.Values) + { + if (mod.status != Mod.Status.Success) broken++; + } + return broken; + } + + private static Il2CppSystem.Action Callback(Action callback) + => DelegateSupport.ConvertDelegate(callback)!; + + private static Il2CppSystem.Object[] Args(params string[] values) + { + Il2CppSystem.Object[] arguments = new Il2CppSystem.Object[values.Length]; + for (int i = 0; i < values.Length; i++) + { + arguments[i] = values[i]; + } + return arguments; + } + + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Hub)); + } } diff --git a/src/Managers/Loc.cs b/src/Managers/Loc.cs index 239b4be..0c76da6 100644 --- a/src/Managers/Loc.cs +++ b/src/Managers/Loc.cs @@ -14,163 +14,163 @@ namespace PolyMod.Managers; /// public static class Loc { - internal static Dictionary> languagesToAdd = new(); - internal static Dictionary buildingsInfoOverrides = new(); - - /// - /// Patches the localization getter to handle custom enum values. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(Localization), nameof(Localization.Get), typeof(string), typeof(Il2CppReferenceArray))] - private static bool Localization_Get(ref string key, Il2CppReferenceArray args) - { - List keys = key.Split('.').ToList(); - int? idx = null; - string? name = null; - - // Find any custom enum indices in the localization key - foreach (string item in keys) - { - if (int.TryParse(item, out int parsedIdx)) - { - if (parsedIdx >= Plugin.AUTOIDX_STARTS_FROM) - { - idx = parsedIdx; - } - } - } - - // If a custom enum index is found, try to resolve its name - if (idx != null) - { - foreach (var typeMapping in Loader.typeMappings.Values) - { - if (!typeMapping.shouldCreateCache) - continue; - - MethodInfo? methodInfo = typeof(EnumCache<>).MakeGenericType(typeMapping.type).GetMethod("TryGetName"); - if (methodInfo != null) - { - object?[] parameters = { idx, null }; - object? methodInvokeResult = methodInfo.Invoke(null, parameters); - if (methodInvokeResult != null) - { - if ((bool)methodInvokeResult) - { - name = (string?)parameters[1]; - } - } - } - } - - // If the name was resolved, replace the index with the name in the key - if (name != null && idx != null) - { - int index = keys.IndexOf(idx.Value.ToString(CultureInfo.InvariantCulture)); - keys[index] = name; - key = string.Join(".", keys); - } - } - return true; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(Localization), nameof(Localization.Init))] - private static bool Localization_Init() - { - if (Localization.initialized) - return true; - - if (LocalizationManager.Sources.Count == 0) - LocalizationManager.UpdateSources(); - - LanguageSourceData source = LocalizationManager.Sources[0]; - - // Elyrion has no language code. I am almost completely sure it is a bug, by looking at the code. - LanguageData elyrionLanguage = source.GetLanguageData("Elyrion"); - elyrionLanguage.Code = Localization.LANG_CODE_ELYRION; - - foreach (var languageCode in languagesToAdd.Keys) - { - Dictionary terms = languagesToAdd[languageCode]; - - int languageIndex = source.GetLanguageIndexFromCode(languageCode); - string languageName = terms["language"]; - if (languageIndex == -1) - { - source.AddLanguage(languageName, languageCode); - languageIndex = source.GetLanguageIndex(languageName); - } - - foreach (var kvp in terms) - { - TermData term = source.GetTermData(kvp.Key); - if (term == null) - { - source.AddTerm(kvp.Key); - term = source.GetTermData(kvp.Key); - } - - term.Languages[languageIndex] = kvp.Value; - } - - LocalizationManager.UpdateSources(); - - Plugin.logger.LogInfo($"{languageCode} language terms added."); - } - return true; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(BuildingUtils), nameof(BuildingUtils.GetInfo))] - private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCurrentLocalPlayer, - ImprovementData improvementData, ImprovementState improvementState, PlayerState owner, TileData tileData) - { - TribeType tribe = TribeType.None; - if (owner != null) - tribe = owner.tribe; - - string key = EnumCache.GetName(improvementData.type); - if (buildingsInfoOverrides.TryGetValue(key, out string? buildingInfoOverride)) - { - __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingInfoOverride); - return false; - } - - return true; - } - - /// - /// Builds and loads localization data from a dictionary. - /// - /// A dictionary containing the localization data. - internal static void BuildAndLoadLocalization(Dictionary> localization) - { - foreach (var (key, data) in localization) - { - string name = ReplaceDashesWithDots(key); - if (name.StartsWith("tribeskins", StringComparison.Ordinal)) name = "TribeSkins/" + name; - TermData term = LocalizationManager.Sources[0].AddTerm(name); - List strings = new(); - foreach (string language in LocalizationManager.GetAllLanguages(false)) - { - strings.Add(data.GetOrDefault(language, data.GetOrDefault("English", term.Term))!); - } - term.Languages = new Il2CppStringArray(strings.ToArray()); - } - } - - internal static string ReplaceDashesWithDots(string key) - { - string name = key.Replace("_", "."); - return name.Replace("..", "_"); - } - - /// - /// Initializes the Loc manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Loc)); - } + internal static Dictionary> languagesToAdd = new(); + internal static Dictionary buildingsInfoOverrides = new(); + + /// + /// Patches the localization getter to handle custom enum values. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(Localization), nameof(Localization.Get), typeof(string), typeof(Il2CppReferenceArray))] + private static bool Localization_Get(ref string key, Il2CppReferenceArray args) + { + List keys = key.Split('.').ToList(); + int? idx = null; + string? name = null; + + // Find any custom enum indices in the localization key + foreach (string item in keys) + { + if (int.TryParse(item, out int parsedIdx)) + { + if (parsedIdx >= Plugin.AUTOIDX_STARTS_FROM) + { + idx = parsedIdx; + } + } + } + + // If a custom enum index is found, try to resolve its name + if (idx != null) + { + foreach (var typeMapping in Loader.typeMappings.Values) + { + if (!typeMapping.shouldCreateCache) + continue; + + MethodInfo? methodInfo = typeof(EnumCache<>).MakeGenericType(typeMapping.type).GetMethod("TryGetName"); + if (methodInfo != null) + { + object?[] parameters = { idx, null }; + object? methodInvokeResult = methodInfo.Invoke(null, parameters); + if (methodInvokeResult != null) + { + if ((bool)methodInvokeResult) + { + name = (string?)parameters[1]; + } + } + } + } + + // If the name was resolved, replace the index with the name in the key + if (name != null && idx != null) + { + int index = keys.IndexOf(idx.Value.ToString(CultureInfo.InvariantCulture)); + keys[index] = name; + key = string.Join(".", keys); + } + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(Localization), nameof(Localization.Init))] + private static bool Localization_Init() + { + if (Localization.initialized) + return true; + + if (LocalizationManager.Sources.Count == 0) + LocalizationManager.UpdateSources(); + + LanguageSourceData source = LocalizationManager.Sources[0]; + + // Elyrion has no language code. I am almost completely sure it is a bug, by looking at the code. + LanguageData elyrionLanguage = source.GetLanguageData("Elyrion"); + elyrionLanguage.Code = Localization.LANG_CODE_ELYRION; + + foreach (var languageCode in languagesToAdd.Keys) + { + Dictionary terms = languagesToAdd[languageCode]; + + int languageIndex = source.GetLanguageIndexFromCode(languageCode); + string languageName = terms["language"]; + if (languageIndex == -1) + { + source.AddLanguage(languageName, languageCode); + languageIndex = source.GetLanguageIndex(languageName); + } + + foreach (var kvp in terms) + { + TermData term = source.GetTermData(kvp.Key); + if (term == null) + { + source.AddTerm(kvp.Key); + term = source.GetTermData(kvp.Key); + } + + term.Languages[languageIndex] = kvp.Value; + } + + LocalizationManager.UpdateSources(); + + Plugin.logger.LogInfo($"{languageCode} language terms added."); + } + return true; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(BuildingUtils), nameof(BuildingUtils.GetInfo))] + private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCurrentLocalPlayer, + ImprovementData improvementData, ImprovementState improvementState, PlayerState owner, TileData tileData) + { + TribeType tribe = TribeType.None; + if (owner != null) + tribe = owner.tribe; + + string key = EnumCache.GetName(improvementData.type); + if (buildingsInfoOverrides.TryGetValue(key, out string? buildingInfoOverride)) + { + __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingInfoOverride); + return false; + } + + return true; + } + + /// + /// Builds and loads localization data from a dictionary. + /// + /// A dictionary containing the localization data. + internal static void BuildAndLoadLocalization(Dictionary> localization) + { + foreach (var (key, data) in localization) + { + string name = ReplaceDashesWithDots(key); + if (name.StartsWith("tribeskins", StringComparison.Ordinal)) name = "TribeSkins/" + name; + TermData term = LocalizationManager.Sources[0].AddTerm(name); + List strings = new(); + foreach (string language in LocalizationManager.GetAllLanguages(false)) + { + strings.Add(data.GetOrDefault(language, data.GetOrDefault("English", term.Term))!); + } + term.Languages = new Il2CppStringArray(strings.ToArray()); + } + } + + internal static string ReplaceDashesWithDots(string key) + { + string name = key.Replace("_", "."); + return name.Replace("..", "_"); + } + + /// + /// Initializes the Loc manager by patching the necessary methods. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Loc)); + } } diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index a2483ad..d288783 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -1,14 +1,13 @@ using BepInEx.Unity.IL2CPP.Logging; using HarmonyLib; -using Il2CppSystem.Linq; using Newtonsoft.Json.Linq; using Polytopia.Data; -using PolytopiaBackendBase.Game; using System.Diagnostics; using System.Text.Json; using System.Text.RegularExpressions; using UnityEngine; using PolytopiaBackendBase.Common; +using Steamworks; namespace PolyMod.Managers; @@ -17,482 +16,440 @@ namespace PolyMod.Managers; /// public static class Main { - private static readonly string[] polytopiaAuthors = { "Midjiwan AB" }; - - internal static bool dependencyCycle; - - /// - /// The maximum tier for technology, used to extend the tech tree. - /// - internal const int MAX_TECH_TIER = 100; - - /// - /// A stopwatch to measure the time taken to load mods. - /// - internal static readonly Stopwatch stopwatch = new(); - - /// - /// Whether the mod has been fully initialized. - /// - internal static bool fullyInitialized; - - /// - /// A dictionary mapping unit IDs to the IDs of the units they embark into. - /// - internal static Dictionary embarkNames = new(); - - /// - /// A dictionary mapping unit types to the types of the units they embark into. - /// - internal static Dictionary embarkOverrides = new(); - - /// - /// Whether an embark action is currently being executed. - /// - internal static bool currentlyEmbarking = false; - - /// - /// A dictionary mapping improvement IDs to the IDs of the resources they attract. - /// - internal static Dictionary attractsResourceNames = new(); - - /// - /// A dictionary mapping improvement IDs to the IDs of the terrain types they attract resources on. - /// - internal static Dictionary attractsTerrainNames = new(); - - /// - /// A dictionary mapping improvement types to the types of the resources they attract. - /// - internal static Dictionary attractsResourceOverrides = new(); - - /// - /// A dictionary mapping improvement types to the types of the terrain they attract resources on. - /// - internal static Dictionary attractsTerrainOverrides = new(); - - /// - /// Patches the game logic data parsing to load PolyMod content. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GameLogicData), nameof(GameLogicData.AddGameLogicPlaceholders))] - private static void GameLogicData_AddGameLogicPlaceholders(GameLogicData __instance, ref JObject rootObject) - { - if (!fullyInitialized) - { - Load(__instance, rootObject); - fullyInitialized = true; - } - } - - /// - /// Patches the purchase manager to unlock custom skins. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsSkinUnlocked))] - private static bool PurchaseManager_IsSkinUnlockedInternal(ref bool __result, SkinType skinType) - { - __result = (int)skinType >= Plugin.AUTOIDX_STARTS_FROM && skinType != SkinType.Test; - return !__result; - } - - /// - /// Patches the purchase manager to unlock custom tribes. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsTribeUnlocked))] - private static void PurchaseManager_IsTribeUnlocked(ref bool __result, TribeType type) - { - __result = (int)type >= Plugin.AUTOIDX_STARTS_FROM || __result; - } - - /// - /// Patches the steam purchase manager to unlock custom content. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(SteamPlatformPurchaseManager), nameof(SteamPlatformPurchaseManager.IsProductUnlocked))] - private static bool SteamPlatformPurchaseManager_IsProductUnlocked(ref bool __result, IAPProduct iapProduct) - { - __result = iapProduct == null; - return iapProduct != null; - } - - /// - /// Patches the purchase manager to add custom tribes to the list of unlocked tribes. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.GetUnlockedTribes))] - private static void PurchaseManager_GetUnlockedTribes( - ref Il2CppSystem.Collections.Generic.List __result, - bool forceUpdate = false - ) - { - foreach (var tribe in Registry.customTribes) __result.Add(tribe); - } - - /// - /// Patches the Unity log callback to filter out spammy messages. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(IL2CPPUnityLogSource), nameof(IL2CPPUnityLogSource.UnityLogCallback))] - private static bool IL2CPPUnityLogSource_UnityLogCallback(string logLine, string exception, LogType type) - { - foreach (string stringToIgnore in Plugin.LOG_MESSAGES_IGNORE) - { - if (logLine.Contains(stringToIgnore)) - return false; - } - return true; - } - - /// - /// Patches the game mode screen to add custom game modes. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GameModeScreen), nameof(GameModeScreen.Init))] - private static void GameModeScreen_Init(GameModeScreen __instance) - { - List list = __instance.buttons.ToList(); - for (int i = 0; i < Loader.gamemodes.Count; i++) - { - var item = Loader.gamemodes[i]; - var button = GameObject.Instantiate(__instance.buttons[2]); - list.Add(button); - Sprite? sprite = item.sprite; - if (item.sprite == null && item.spriteName != null) - { - sprite = Registry.GetSprite(item.spriteName); - } - Loader.gamemodes[i] = new Loader.GameModeButtonsInformation(item.gameModeIndex, item.action, __instance.buttons.Length, sprite, item.spriteName); - } - - var newArray = list.ToArray(); - for (int i = 0; i < __instance.buttons.Length; i++) - { - if (newArray[i] != null) newArray[i].OnClicked = __instance.buttons[i].OnClicked; - } - - for (int i = 0; i < Loader.gamemodes.Count; i++) - { - if (Loader.gamemodes[i].buttonIndex != null) - newArray[Loader.gamemodes[i].buttonIndex!.Value].OnClicked = Loader.gamemodes[i].action; - } - - __instance.buttons = newArray; - - for (int i = 0; i < __instance.buttons.Length; i++) - { - GamemodeButton button = __instance.buttons[i]; - var newData = button.gamemodeData.ToList(); - foreach (var info in Loader.gamemodes) - { - string id = EnumCache.GetName((GameMode)info.gameModeIndex).ToLowerInvariant(); - newData.Add(new GamemodeButton.GamemodeButtonData() - { - gameMode = (GameMode)info.gameModeIndex, - id = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id), - descriptionKey = "gamemode." + id + ".description.button", - headerKey = "gamemode." + id + ".caps", - icon = info.sprite - }); - } - button.gamemodeData = newData.ToArray(); - - for (int j = 0; j < Loader.gamemodes.Count; j++) - { - Loader.GameModeButtonsInformation info = Loader.gamemodes[j]; - - if (info.buttonIndex == i) - { - button.SetGamemode(info.buttonIndex.Value); - } - } - } - } - - /// - /// Patches the tech view to correctly display the tech tree with custom technologies. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(TechView), nameof(TechView.CreateNode))] - public static bool TechView_CreateNode(TechView __instance, TechData data, TechItem parentItem, float angle) - { - // This patch is a reimplementation of the original CreateNode method to fix layout issues with custom techs. - // It recalculates the angles for each node to ensure they are displayed correctly. - GameLogicData gameLogicData = GameManager.GameState.GameLogicData; - TribeData tribeData = gameLogicData.GetTribeData(GameManager.LocalPlayer.tribe); - float baseAngle = 360 / gameLogicData.GetOverride(gameLogicData.GetTechData(TechData.Type.Basic), tribeData).techUnlocks.Count; - float childAngle = 0f; - if (parentItem != null) - childAngle = angle + baseAngle * (data.techUnlocks.Count - 1) / 2f; - foreach (var techData in data.techUnlocks) - { - if (gameLogicData.TryGetData(techData.type, out TechData techData2)) - { - TechData @override = gameLogicData.GetOverride(techData, tribeData); - TechItem techItem = __instance.CreateTechItem(@override, parentItem, childAngle); - __instance.currTechIdx++; - if (@override.techUnlocks != null && @override.techUnlocks.Count > 0) - __instance.CreateNode(@override, techItem, childAngle); - childAngle -= baseAngle; - } - } - Il2CppSystem.Action onItemsRefreshed = __instance.OnItemsRefreshed; - if (onItemsRefreshed == null) - { - return false; - } - onItemsRefreshed.Invoke(__instance); - return false; - } - - /// - /// Patches the embark action to set a flag indicating that an embark is in progress. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(EmbarkAction), nameof(EmbarkAction.Execute))] - private static bool EmbarkAction_Execute_Prefix(EmbarkAction __instance, GameState gameState) - { - currentlyEmbarking = true; - return true; - } - - /// - /// Patches the unit training method to handle custom embark units. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(ActionUtils), nameof(ActionUtils.TrainUnit))] - private static bool ActionUtils_TrainUnit(ref UnitState __result, GameState gameState, PlayerState playerState, TileData tile, ref UnitData unitData) - { - if (tile == null || tile.unit == null) - { - return true; - } - - if (currentlyEmbarking) - { - if (embarkOverrides.TryGetValue(tile.unit.type, out UnitData.Type newType)) - { - gameState.GameLogicData.TryGetData(newType, out unitData); - } - currentlyEmbarking = false; - } - return true; - } - - /// - /// Patches the start turn action to handle the 'Attract' ability for custom improvements. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(StartTurnAction), nameof(StartTurnAction.Execute))] - private static void StartTurnAction_Execute(StartTurnAction __instance, GameState state) - { - // Clear any existing CreateResource actions to prevent duplicates. - for (int i = state.ActionStack.Count - 1; i >= 0; i--) - { - if (state.ActionStack[i].GetActionType() == ActionType.CreateResource) - { - state.ActionStack.RemoveAt(i); - } - } - - // Iterate through all tiles owned by the current player. - for (int i = 0; i < state.Map.Tiles.Length; i++) - { - TileData tileData = state.Map.Tiles[i]; - if (tileData.owner == __instance.PlayerId && tileData.improvement != null && state.CurrentTurn > 0U) - { - ImprovementData improvementData; - state.GameLogicData.TryGetData(tileData.improvement.type, out improvementData); - if (improvementData != null) - { - // If the improvement has the 'Attract' ability and is ready to spawn a resource. - if (improvementData.HasAbility(ImprovementAbility.Type.Attract) && tileData.improvement.GetAge(state) % improvementData.growthRate == 0) - { - ResourceData.Type resourceType = ResourceData.Type.Game; - if (attractsResourceOverrides.TryGetValue(tileData.improvement.type, out ResourceData.Type newType)) - { - resourceType = newType; - } - Polytopia.Data.TerrainData.Type targetTerrain = Polytopia.Data.TerrainData.Type.Forest; - if (attractsTerrainOverrides.TryGetValue(tileData.improvement.type, out Polytopia.Data.TerrainData.Type newTerrain)) - { - targetTerrain = newTerrain; - } - - // Find a valid tile to spawn the resource on. - foreach (TileData tileData2 in state.Map.GetArea(tileData.coordinates, 1, true, false)) - { - if (tileData2.owner == __instance.PlayerId && tileData2.improvement == null && tileData2.resource == null && tileData2.terrain == targetTerrain) - { - state.ActionStack.Add(new CreateResourceAction(__instance.PlayerId, resourceType, tileData2.coordinates, CreateResourceAction.CreateReason.Attract)); - break; - } - } - } - } - } - } - } - - /// - /// Serialization fixes for custom (modded) content. - /// GamePlayerSummary stores the tribe as a single byte, which custom tribe ids (>= 1000) overflow into garbage. - /// Instead the tribe is clamped to None before the untouched native serializer runs and menu summaries show a generic icon for custom tribes, nothing more. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GamePlayerSummary), nameof(GamePlayerSummary.Serialize))] - private static bool GamePlayerSummary_Serialize(GamePlayerSummary __instance) - { - if ((int)__instance.TribeType >= byte.MaxValue) - { - __instance.TribeType = TribeType.None; - } - - return true; - } - - /// - /// Serialization fixes for custom (modded) content. - /// PlayerState stores the play climate as a single byte, which custom climate ids (>= 1000) overflow into garbage. - /// Instead the climate is overriden by the tribe value, as those are effectively the same. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(PlayerState), nameof(PlayerState.Deserialize))] - private static void PlayerState_Deserialize(PlayerState __instance, Il2CppSystem.IO.BinaryReader reader, int version) - { - if ((int)__instance.tribe >= Plugin.AUTOIDX_STARTS_FROM) - { - __instance.climate = __instance.tribe; - } - } - - /// - /// Initializes the Main manager. - /// - internal static void Init() - { - stopwatch.Start(); - Harmony.CreateAndPatchAll(typeof(Main)); - Mod.Manifest polytopia = new( - "polytopia", - "The Battle of Polytopia", - null, - new(Application.version.ToString()), - polytopiaAuthors, - Array.Empty() - ); - Registry.mods.Add(polytopia.id, new(polytopia, Mod.Status.Success, new())); - Loader.RegisterMods(Registry.mods); - Loader.LoadMods(Registry.mods, out var cycle); - dependencyCycle = cycle; - stopwatch.Stop(); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(UnityEngine.Application), nameof(UnityEngine.Application.persistentDataPath), MethodType.Getter)] - private static void Application_persistentDataPath_get(ref string __result) - { - __result = Plugin.PERSISTENT_DATA_PATH; - } - - /// - /// Loads all mod content. - /// - /// The JSON object representing the game logic data. - internal static void Load(GameLogicData gameLogicData, JObject json) - { - stopwatch.Start(); - Loc.BuildAndLoadLocalization( - JsonSerializer.Deserialize>>( - Plugin.GetResource("localization.json") - )! - ); - if (dependencyCycle) return; - - foreach (var (id, mod) in Registry.mods) - { - if (mod.status != Mod.Status.Success) continue; - foreach (var file in mod.files) - { - if (mod.status != Mod.Status.Success) break; - Match localizationMatch = Regex.Match(Path.GetFileName(file.name), @"^localization(_.*)?\.json$"); - if (localizationMatch.Success) - { - Loader.LoadLocalizationFile(mod, file); - continue; - } - Match patchMatch = Regex.Match(Path.GetFileName(file.name), @"^patch(_.*)?\.json$"); - if (patchMatch.Success) - { - var patchText = new StreamReader(new MemoryStream(file.bytes)).ReadToEnd(); - var template = new Api.GldConfigTemplate(patchText, mod.id); - var text = template.Render(); - if (text is null) - { - mod.status = Mod.Status.Error; - continue; - } - Loader.LoadGameLogicDataPatch( - mod, - json, - JObject.Parse(text) - ); - continue; - } - - Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); - if (prefabsMatch.Success) - { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); - continue; - } - - Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); - if (unitPrefabMatch.Success) - { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); - continue; - } - - Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); - if (improvementPrefabMatch.Success) - { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); - continue; - } - - Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); - if (resourcePrefabMatch.Success) - { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); - continue; - } - - switch (Path.GetExtension(file.name)) - { - case ".png": - Loader.LoadTextureFile(mod, file); - break; - case ".wav": - Loader.LoadAudioFile(mod, file); - break; - case ".bundle": - Loader.LoadAssetBundle(mod, file); - break; - } - } - } - TechItem.techTierFirebaseId.Clear(); - for (int i = 0; i <= MAX_TECH_TIER; i++) - { - TechItem.techTierFirebaseId.Add($"tech_research_{i}"); - } - Loader.ProcessGameLogicData(gameLogicData, json); - Loader.ProcessFilesQueue(); - Visual.CreateSprites(); - Prefabs.CreatePrefabs(); - stopwatch.Stop(); - Plugin.logger.LogInfo($"Loaded all mods in {stopwatch.ElapsedMilliseconds}ms"); - } + private static readonly string[] polytopiaAuthors = { "Midjiwan AB" }; + + internal static bool dependencyCycle; + + /// + /// The maximum tier for technology, used to extend the tech tree. + /// + internal const int MAX_TECH_TIER = 100; + + /// + /// A stopwatch to measure the time taken to load mods. + /// + internal static readonly Stopwatch stopwatch = new(); + + /// + /// Whether the mod has been fully initialized. + /// + internal static bool fullyInitialized; + + /// + /// A dictionary mapping unit IDs to the IDs of the units they embark into. + /// + internal static Dictionary embarkNames = new(); + + /// + /// A dictionary mapping unit types to the types of the units they embark into. + /// + internal static Dictionary embarkOverrides = new(); + + /// + /// Whether an embark action is currently being executed. + /// + internal static bool currentlyEmbarking = false; + + /// + /// A dictionary mapping improvement IDs to the IDs of the resources they attract. + /// + internal static Dictionary attractsResourceNames = new(); + + /// + /// A dictionary mapping improvement IDs to the IDs of the terrain types they attract resources on. + /// + internal static Dictionary attractsTerrainNames = new(); + + /// + /// A dictionary mapping improvement types to the types of the resources they attract. + /// + internal static Dictionary attractsResourceOverrides = new(); + + /// + /// A dictionary mapping improvement types to the types of the terrain they attract resources on. + /// + internal static Dictionary attractsTerrainOverrides = new(); + + /// + /// Patches the game logic data parsing to load PolyMod content. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(GameLogicData), nameof(GameLogicData.AddGameLogicPlaceholders))] + private static void GameLogicData_AddGameLogicPlaceholders(GameLogicData __instance, ref JObject rootObject) + { + if (!fullyInitialized) + { + Load(__instance, rootObject); + fullyInitialized = true; + } + } + + /// + /// Patches the purchase manager to unlock custom skins. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsSkinUnlocked))] + private static bool PurchaseManager_IsSkinUnlockedInternal(ref bool __result, SkinType skinType) + { + __result = (int)skinType >= Plugin.AUTOIDX_STARTS_FROM && skinType != SkinType.Test; + return !__result; + } + + /// + /// Patches the purchase manager to unlock custom tribes. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsTribeUnlocked))] + private static void PurchaseManager_IsTribeUnlocked(ref bool __result, TribeType type) + { + __result = (int)type >= Plugin.AUTOIDX_STARTS_FROM || __result; + } + + /// + /// Patches the steam purchase manager to unlock custom content. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(SteamPlatformPurchaseManager), nameof(SteamPlatformPurchaseManager.IsProductUnlocked))] + private static bool SteamPlatformPurchaseManager_IsProductUnlocked(ref bool __result, IAPProduct iapProduct) + { + __result = iapProduct == null; + return iapProduct != null; + } + + /// + /// Patches the purchase manager to add custom tribes to the list of unlocked tribes. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.GetUnlockedTribes))] + private static void PurchaseManager_GetUnlockedTribes( + ref Il2CppSystem.Collections.Generic.List __result, + bool forceUpdate = false + ) + { + foreach (var tribe in Registry.customTribes) __result.Add(tribe); + } + + /// + /// Patches the Unity log callback to filter out spammy messages. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(IL2CPPUnityLogSource), nameof(IL2CPPUnityLogSource.UnityLogCallback))] + private static bool IL2CPPUnityLogSource_UnityLogCallback(string logLine, string exception, LogType type) + { + foreach (string stringToIgnore in Plugin.LOG_MESSAGES_IGNORE) + { + if (logLine.Contains(stringToIgnore)) + return false; + } + return true; + } + + /// + /// Patches the tech view to correctly display the tech tree with custom technologies. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(TechView), nameof(TechView.CreateNode))] + public static bool TechView_CreateNode(TechView __instance, TechData data, TechItem parentItem, float angle) + { + // This patch is a reimplementation of the original CreateNode method to fix layout issues with custom techs. + // It recalculates the angles for each node to ensure they are displayed correctly. + GameLogicData gameLogicData = GameManager.GameState.GameLogicData; + TribeData tribeData = gameLogicData.GetTribeData(GameManager.LocalPlayer.tribe); + float baseAngle = 360 / gameLogicData.GetOverride(gameLogicData.GetTechData(TechData.Type.Basic), tribeData).techUnlocks.Count; + float childAngle = 0f; + if (parentItem != null) + childAngle = angle + baseAngle * (data.techUnlocks.Count - 1) / 2f; + foreach (var techData in data.techUnlocks) + { + if (gameLogicData.TryGetData(techData.type, out TechData techData2)) + { + TechData @override = gameLogicData.GetOverride(techData, tribeData); + TechItem techItem = __instance.CreateTechItem(@override, parentItem, childAngle); + __instance.currTechIdx++; + if (@override.techUnlocks != null && @override.techUnlocks.Count > 0) + __instance.CreateNode(@override, techItem, childAngle); + childAngle -= baseAngle; + } + } + Il2CppSystem.Action onItemsRefreshed = __instance.OnItemsRefreshed; + if (onItemsRefreshed == null) + { + return false; + } + onItemsRefreshed.Invoke(__instance); + return false; + } + + /// + /// Patches the embark action to set a flag indicating that an embark is in progress. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(EmbarkAction), nameof(EmbarkAction.Execute))] + private static bool EmbarkAction_Execute_Prefix(EmbarkAction __instance, GameState gameState) + { + currentlyEmbarking = true; + return true; + } + + /// + /// Patches the unit training method to handle custom embark units. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(ActionUtils), nameof(ActionUtils.TrainUnit))] + private static bool ActionUtils_TrainUnit(ref UnitState __result, GameState gameState, PlayerState playerState, TileData tile, ref UnitData unitData) + { + if (tile == null || tile.unit == null) + { + return true; + } + + if (currentlyEmbarking) + { + if (embarkOverrides.TryGetValue(tile.unit.type, out UnitData.Type newType)) + { + gameState.GameLogicData.TryGetData(newType, out unitData); + } + currentlyEmbarking = false; + } + return true; + } + + /// + /// Patches the start turn action to handle the 'Attract' ability for custom improvements. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(StartTurnAction), nameof(StartTurnAction.Execute))] + private static void StartTurnAction_Execute(StartTurnAction __instance, GameState state) + { + // Clear any existing CreateResource actions to prevent duplicates. + for (int i = state.ActionStack.Count - 1; i >= 0; i--) + { + if (state.ActionStack[i].GetActionType() == ActionType.CreateResource) + { + state.ActionStack.RemoveAt(i); + } + } + + // Iterate through all tiles owned by the current player. + for (int i = 0; i < state.Map.Tiles.Length; i++) + { + TileData tileData = state.Map.Tiles[i]; + if (tileData.owner == __instance.PlayerId && tileData.improvement != null && state.CurrentTurn > 0U) + { + ImprovementData improvementData; + state.GameLogicData.TryGetData(tileData.improvement.type, out improvementData); + if (improvementData != null) + { + // If the improvement has the 'Attract' ability and is ready to spawn a resource. + if (improvementData.HasAbility(ImprovementAbility.Type.Attract) && tileData.improvement.GetAge(state) % improvementData.growthRate == 0) + { + ResourceData.Type resourceType = ResourceData.Type.Game; + if (attractsResourceOverrides.TryGetValue(tileData.improvement.type, out ResourceData.Type newType)) + { + resourceType = newType; + } + Polytopia.Data.TerrainData.Type targetTerrain = Polytopia.Data.TerrainData.Type.Forest; + if (attractsTerrainOverrides.TryGetValue(tileData.improvement.type, out Polytopia.Data.TerrainData.Type newTerrain)) + { + targetTerrain = newTerrain; + } + + // Find a valid tile to spawn the resource on. + foreach (TileData tileData2 in state.Map.GetArea(tileData.coordinates, 1, true, false)) + { + if (tileData2.owner == __instance.PlayerId && tileData2.improvement == null && tileData2.resource == null && tileData2.terrain == targetTerrain) + { + state.ActionStack.Add(new CreateResourceAction(__instance.PlayerId, resourceType, tileData2.coordinates, CreateResourceAction.CreateReason.Attract)); + break; + } + } + } + } + } + } + } + + /// + /// Serialization fixes for custom (modded) content. + /// GamePlayerSummary stores the tribe as a single byte, which custom tribe ids (>= 1000) overflow into garbage. + /// Instead the tribe is clamped to None before the untouched native serializer runs and menu summaries show a generic icon for custom tribes, nothing more. + /// + [HarmonyPrefix] + [HarmonyPatch(typeof(GamePlayerSummary), nameof(GamePlayerSummary.Serialize))] + private static bool GamePlayerSummary_Serialize(GamePlayerSummary __instance) + { + if ((int)__instance.TribeType >= byte.MaxValue) + { + __instance.TribeType = TribeType.None; + } + + return true; + } + + /// + /// Serialization fixes for custom (modded) content. + /// PlayerState stores the play climate as a single byte, which custom climate ids (>= 1000) overflow into garbage. + /// Instead the climate is overriden by the tribe value, as those are effectively the same. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(PlayerState), nameof(PlayerState.Deserialize))] + private static void PlayerState_Deserialize(PlayerState __instance, Il2CppSystem.IO.BinaryReader reader, int version) + { + if ((int)__instance.tribe >= Plugin.AUTOIDX_STARTS_FROM) + { + __instance.climate = __instance.tribe; + } + } + [HarmonyPrefix] + [HarmonyPatch(typeof(NativeHelpers), nameof(NativeHelpers.IsValidInstall))] + public static bool NativeHelpers_IsValidInstall(ref bool __result) + { + __result = true; + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SteamClient), nameof(SteamClient.IsValid), MethodType.Getter)] + public static bool SteamClient_IsValid(ref bool __result) + { + __result = true; + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(SteamClient), nameof(SteamClient.RestartAppIfNecessary))] + public static bool SteamClient_IsValid(ref bool __result, uint appid) + { + __result = false; + return false; + } + + /// + /// Initializes the Main manager. + /// + internal static void Init() + { + stopwatch.Start(); + Harmony.CreateAndPatchAll(typeof(Main)); + Mod.Manifest polytopia = new( + "polytopia", + "The Battle of Polytopia", + null, + new(Application.version.ToString()), + polytopiaAuthors, + Array.Empty() + ); + Registry.mods.Add(polytopia.id, new(polytopia, Mod.Status.Success, new())); + Loader.RegisterMods(Registry.mods); + Loader.LoadMods(Registry.mods, out var cycle); + dependencyCycle = cycle; + stopwatch.Stop(); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(UnityEngine.Application), nameof(UnityEngine.Application.persistentDataPath), MethodType.Getter)] + private static void Application_persistentDataPath_get(ref string __result) + { + __result = Plugin.PERSISTENT_DATA_PATH; + } + + /// + /// Loads all mod content. + /// + /// The JSON object representing the game logic data. + internal static void Load(GameLogicData gameLogicData, JObject json) + { + stopwatch.Start(); + Loc.BuildAndLoadLocalization( + JsonSerializer.Deserialize>>( + Plugin.GetResource("localization.json") + )! + ); + if (dependencyCycle) return; + + foreach (var (id, mod) in Registry.mods) + { + if (mod.status != Mod.Status.Success) continue; + foreach (var file in mod.files) + { + if (mod.status != Mod.Status.Success) break; + Match localizationMatch = Regex.Match(Path.GetFileName(file.name), @"^localization(_.*)?\.json$"); + if (localizationMatch.Success) + { + Loader.LoadLocalizationFile(mod, file); + continue; + } + Match patchMatch = Regex.Match(Path.GetFileName(file.name), @"^patch(_.*)?\.json$"); + if (patchMatch.Success) + { + var patchText = new StreamReader(new MemoryStream(file.bytes)).ReadToEnd(); + var template = new Api.GldConfigTemplate(patchText, mod.id); + var text = template.Render(); + if (text is null) + { + mod.status = Mod.Status.Error; + continue; + } + Loader.LoadGameLogicDataPatch( + mod, + json, + JObject.Parse(text) + ); + continue; + } + + Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); + if (prefabsMatch.Success) + { + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + continue; + } + + Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); + if (unitPrefabMatch.Success) + { + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + continue; + } + + Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); + if (improvementPrefabMatch.Success) + { + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + continue; + } + + Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); + if (resourcePrefabMatch.Success) + { + Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + continue; + } + + switch (Path.GetExtension(file.name)) + { + case ".png": + Loader.LoadTextureFile(mod, file); + break; + case ".wav": + Loader.LoadAudioFile(mod, file); + break; + case ".bundle": + Loader.LoadAssetBundle(mod, file); + break; + } + } + } + TechItem.techTierFirebaseId.Clear(); + for (int i = 0; i <= MAX_TECH_TIER; i++) + { + TechItem.techTierFirebaseId.Add($"tech_research_{i}"); + } + Loader.ProcessGameLogicData(gameLogicData, json); + Loader.ProcessFilesQueue(); + Visual.CreateSprites(); + Prefabs.CreatePrefabs(); + stopwatch.Stop(); + Plugin.logger.LogInfo($"Loaded all mods in {stopwatch.ElapsedMilliseconds}ms"); + } } diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index a226835..07d3a0e 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -9,645 +9,645 @@ namespace PolyMod.Managers; public static class Prefabs { - internal static Dictionary unitsNew = new(); - internal static Dictionary> unitOverridesNew = new(); // maybe in the future will implement - internal static Dictionary unitUIOverridesNew = new(); - - internal static Material? cachedUnitMaterial; - internal static Material? cachedSharedMaterial; - internal const string CACHED_SHARED_MATERIAL_NAME = "SpriteMaterial"; - - public static List unitInfos = new(); - - public static List resourceInfos = new(); - - public static List improvementInfos = new(); - internal static Dictionary improvementPrefabInfosToCreate = new(); - internal static List resourcePrefabsInfosToCreate = new(); - - private static List weaponInfos = new(); - private static Dictionary weaponProjectilesCache = new(); - private static Dictionary weaponAnimTimeCache = new() - { - {UnitData.WeaponEnum.Sting, 0.5f}, - {UnitData.WeaponEnum.IceArrow, 1f}, - {UnitData.WeaponEnum.Gun, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnDarkPuff(); - {UnitData.WeaponEnum.FireBlow, 2f}, // __instance.Tile.SpawnDarkPuff(); - {UnitData.WeaponEnum.Poison, 2f}, // __instance.Tile.SpawnPoison(__instance.Owner.GetVisualSkin()); - {UnitData.WeaponEnum.Pierce, 1f}, - {UnitData.WeaponEnum.Water, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnPuff(); - }; - - [HarmonyPostfix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] - private static void PrefabManager_Awake_Postfix(PrefabManager __instance) - { - unitsNew.Clear(); - unitOverridesNew.Clear(); - unitUIOverridesNew.Clear(); - - foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) - { - if (cachedUnitMaterial == null) - { - SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); - if (skinVisualsReference != null && skinVisualsReference.visualParts != null) - { - foreach (VisualPart currentPart in skinVisualsReference.visualParts) - { - if (currentPart.visualPart == null) - { - continue; - } - - SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); - if (headSpriteRenderer != null) - { - cachedUnitMaterial = headSpriteRenderer.sharedMaterial; - break; - } - } - } - } - unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; - } - - foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) - { - if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) - { - overridesForCondition = new Dictionary(); - unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; - } - overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; - } - - foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) - { - unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; - } - - Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] - public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) - { - __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] - public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) - { - if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) - { - __result = uiOverridePrefab; - } - else - { - __result = ResolveUnitPrefab(unitType, tribe, skin); - } - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] - public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) - { - __result = ResolveUnitPrefab(type, tribe, skin); - return false; - } - - [HarmonyPostfix] // prolly remove later - [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] - public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) - { - bool flag = false; - flag = visualSetting.outline != null && visualSetting.outline.transform.parent == visualSetting.visualPart.transform; - if (!flag && visualSetting.visualPart.transform.childCount > 0) - { - visualSetting.outline = visualSetting.visualPart.transform.GetChild(0).gameObject; - flag = true; - } - bool flag2 = false; - if (flag) - { - string defaultSpriteName = visualSetting.DefaultSpriteName; - if (visualSetting.outline != null && visualSetting.outline.name == defaultSpriteName + "_Outline") - { - flag2 = true; - } - } - visualSetting.hasValidOutline = flag2; - } - - // [HarmonyPrefix] // overrides again....... - // [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] - // private static bool Unit_IsProjectile(ref bool __result, UnitData.WeaponEnum weapon) - // { - // if(!weaponProjectilesCache.ContainsKey(weapon)) - // return true; - - // __result = weaponProjectilesCache[weapon]; - // return false; - // } - - // [HarmonyPrefix] // overrides again....... - // [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] - // private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Action onComplete) - // { - // UnitData.WeaponEnum weaponEnum = __instance.unitData.weapon; - // List weaponPrefabInfos = weaponInfos.Where(weaponInfo => weaponInfo.weaponEnum == weaponEnum).ToList(); - // if(weaponPrefabInfos.Count == 0) - // return true; - - // WeaponPrefabInfo weaponPrefabInfo = weaponPrefabInfos.Last(); - // float chebyshevDistance = MapDataExtensions.ChebyshevDistance(__instance.Tile.Coordinates, target); - - // float animationTime = 0.2f + chebyshevDistance * 0.05f; - // Tile targetTile = MapRenderer.Current.GetTileInstance(target); - - // WeaponGFX pooledObject = ObjectPool.GetPooledObject(GetPrefab(weaponEnum).gameObject); - // pooledObject.IsUsed = true; - // Vector3 center = SkinVisualsRenderer.GetSpriteBounds(__instance.skinVisuals).center; - // pooledObject.transform.position = __instance.transform.position + center; - // pooledObject.SetSkin(__instance.Owner.GetVisualSkin()); - - // if ((bool)targetTile.Unit) - // { - // targetTile.Unit.Flipped = targetTile.Unit.UnitState.flipped; - // } - // __instance.Flipped = __instance.UnitState.flipped; - - // if(weaponPrefabInfo.weaponPuffInfo != null) - // { - // animationTime *= weaponPrefabInfo.weaponPuffInfo.animationMultiplier; - // if(weaponPrefabInfo.weaponPuffInfo.sway) - // __instance.Sway(); - // } - // if (Unit.IsProjectile(weaponEnum)) - // { - // if(weaponPrefabInfo.weaponPuffInfo != null && weaponPrefabInfo.weaponPuffInfo!.animationDelegate != null) - // pooledObject.AnimateRanged(animationTime, target, DelegateSupport.ConvertDelegate(weaponPrefabInfo.weaponPuffInfo!.animationDelegate!)); - // else - // pooledObject.AnimateRanged(animationTime, target); - // } - // else - // { - // pooledObject.AnimateCloseRangeAttack(0.2f); - // } - - // if (__instance.unitData.GetRange() < 2) - // { - // __instance.AnimateMeleeAttackMovement(targetTile, moveToTarget, onComplete); - // } - // else - // { - // GameManager.DelayCall((int)(animationTime * 1000f), onComplete); - // } - - // return false; - // } - - // [HarmonyPrefix] // testing....... - // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] - // public static bool WeaponGFX_AnimateCloseRangeAttack(ref float animTime, Action onComplete) - // { - // animTime = 100000f; - // return true; - // } - - // [HarmonyPrefix] // testing....... - // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] - // public static bool WeaponGFX_AnimateRanged(ref float animTime, WorldCoordinates to, Action onComplete) - // { - // animTime = 100000f; - // return true; - // } - - private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) - { - if (SeasonManager.IsChristmas() - && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) - && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) - && christmasPrefab != null) - { - return christmasPrefab; - } - - SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); - if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) - { - return exactPrefab; - } - - if (skinType != SkinType.Default || tribeType != TribeType.None) - { - SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); - SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); - SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); - - if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) - || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) - || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) - { - unitsNew[exactKey] = fallbackPrefab; - return fallbackPrefab; - } - } - - Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); - unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); - return lastResortPrefab!; - } - - internal static void CreatePrefabs() - { - // get materials - Material[] allLoadedMaterials = Resources.FindObjectsOfTypeAll(); - foreach (Material loadedMaterial in allLoadedMaterials) - { - // Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); - - if (loadedMaterial.name == CACHED_SHARED_MATERIAL_NAME) - { - cachedSharedMaterial = loadedMaterial; - GameObject.DontDestroyOnLoad(cachedSharedMaterial); - break; - } - } - - // creates dummy improvements. those have one visual part, and default name is the enum cache name of the type - foreach (KeyValuePair improvementInfo in improvementPrefabInfosToCreate) - { - ImprovementData.Type improvementType = improvementInfo.Key; - improvementInfos.Add( - new ImprovementPrefabInfo() - { - improvementType = improvementType, - visualParts = new() - { - new() - { - defaultSpriteName = EnumCache.GetName(improvementType), - levels = improvementInfo.Value, - } - } - } - ); - } - - // creates dummy resources. those have one visual part, and default name is the enum cache name of the type - foreach (ResourceData.Type resourceType in resourcePrefabsInfosToCreate) - { - resourceInfos.Add( - new ResourcePrefabInfo() - { - resourceType = resourceType, - visualParts = new() - { - new() - { - defaultSpriteName = EnumCache.GetName(resourceType), - } - } - } - ); - } - - foreach (var unitPrefabInfo in unitInfos) - { - ProcessUnitPrefabInfo(unitPrefabInfo); - } - - foreach (var improvementPrefabInfo in improvementInfos) - { - ProcessImprovementPrefabInfo(improvementPrefabInfo); - } - - foreach (var resourcePrefabInfo in resourceInfos) - { - ProcessResourcePrefabInfo(resourcePrefabInfo); - } - } - - #region Units - internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) - { - // maybe just init new unit? hmmmmm will try later - var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); - if (baseUnit == null) - return; - - var unitInstance = GameObject.Instantiate(baseUnit); - if (unitInstance == null) - return; - - GameObject.Destroy(unitInstance.spriteContainer.gameObject); - - var spriteContainerObj = new GameObject("SpriteContainer"); - spriteContainerObj.transform.SetParent(unitInstance.transform, false); - var spriteContainer = spriteContainerObj.transform; - unitInstance.spriteContainer = spriteContainer; - - var visualParts = ApplyUnitVisualParts(unitPrefabInfo, spriteContainer); - - Transform? headPositionMarker = null; - foreach (var vp in visualParts) - { - if (vp.visualPart.gameObject.name == unitPrefabInfo.headPositionMarker) - { - headPositionMarker = vp.visualPart.gameObject.transform; - break; - } - } - - unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; - - var svr = unitInstance.GetComponent(); - svr.visualParts = visualParts.ToArray(); - - GameObject.DontDestroyOnLoad(unitInstance.gameObject); - - if (unitPrefabInfo.uiOverride) - { - unitUIOverridesNew[unitPrefabInfo.skinnedKey] = unitInstance; - return; - } - unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; - } - - private static List ApplyUnitVisualParts( - UnitPrefabInfo unitPrefabInfo, - Transform spriteContainer) - { - List parts = new(); - List visualPartInfos = unitPrefabInfo.visualParts; - - if (visualPartInfos.Count == 0) - return parts; - - int nextPartSortingOrder = 0; - int nextOutlineSortingOrder = -visualPartInfos.Count; - var newVisualInfo = visualPartInfos; - newVisualInfo.Reverse(); - foreach (var info in newVisualInfo) - { - parts.Add(CreateUnitVisualPart(info, spriteContainer, info.sortingOrderOverride ?? nextPartSortingOrder, info.outlineSortingOrderOverride ?? nextOutlineSortingOrder)); - if (nextOutlineSortingOrder < -1) - { - nextOutlineSortingOrder++; - } - nextPartSortingOrder++; - } - - return parts; - } - - private static SkinVisualsReference.VisualPart CreateUnitVisualPart( - VisualPartInfo info, - Transform parent, - int visualPartSortingOrder, - int outlineSortingOrder) - { - var visualPartObj = new GameObject(info.defaultSpriteName); - visualPartObj.transform.SetParent(parent); - - var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); - outlineObj.transform.SetParent(visualPartObj.transform); - - visualPartObj.transform.position = info.coordinates; - outlineObj.transform.position = info.coordinates; - visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - // this bs was hunting me for so long. that is the thing which makes outline hidden in ui - outlineObj.SetActive(false); - - var visualPart = info.ToVisualPart(false); - visualPart.visualPart = visualPartObj; - visualPart.outline = outlineObj; - - var renderer = visualPartObj.AddComponent(); - renderer.material = cachedUnitMaterial; - renderer.sortingOrder = visualPartSortingOrder; - renderer.sortingLayerName = "Units"; - visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; - - var outlineRenderer = outlineObj.AddComponent(); - outlineRenderer.material = cachedUnitMaterial; - outlineRenderer.sortingOrder = outlineSortingOrder; - outlineRenderer.sortingLayerName = "Units"; - visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; - - return visualPart; - } - - #endregion - #region Improvements - internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvementPrefabInfo) - { - if (improvementPrefabInfo.improvementType == null) - return; - - var baseBuilding = PrefabManager.GetPrefab(ImprovementData.Type.LumberHut); - if (baseBuilding == null) - return; - - var buildingInstance = GameObject.Instantiate(baseBuilding); - if (buildingInstance == null) - return; - - Transform buildingTransform = buildingInstance.transform; - for (int childIndex = buildingTransform.childCount - 1; childIndex >= 0; childIndex--) - { - GameObject.Destroy(buildingTransform.GetChild(childIndex).gameObject); - } - - var visualParts = ApplyBuildingVisualParts(improvementPrefabInfo, buildingTransform); - - var svr = buildingInstance.GetComponent(); - svr.visualParts = visualParts.ToArray(); - - GameObject.DontDestroyOnLoad(buildingInstance.gameObject); - - PrefabManager.improvements[(Polytopia.Data.ImprovementData.Type)improvementPrefabInfo.improvementType] = buildingInstance; - } - - private static List ApplyBuildingVisualParts( - ImprovementPrefabInfo improvementPrefabInfo, - Transform spriteContainer) - { - List parts = new(); - List visualPartInfos = improvementPrefabInfo.visualParts; - - if (visualPartInfos.Count == 0) - return parts; - - int nextPartSortingOrder = 0; - int nextOutlineSortingOrder = -visualPartInfos.Count; - foreach (var info in visualPartInfos) - { - parts.Add(CreateBuildingVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder, improvementPrefabInfo.needsOutlines)); - if (nextOutlineSortingOrder < -1) - { - nextOutlineSortingOrder++; - } - nextPartSortingOrder++; - } - - return parts; - } - - private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( - VisualPartInfo info, - Transform parent, - int visualPartSortingOrder, - int outlineSortingOrder, - bool needsOutline = false) - { - var visualPartObj = new GameObject(info.defaultSpriteName); - visualPartObj.transform.SetParent(parent); - - var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); - outlineObj.transform.SetParent(visualPartObj.transform); - - visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; - visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - outlineObj.SetActive(false); - - var visualPart = info.ToVisualPart(true); - visualPart.visualPart = visualPartObj; - visualPart.outline = outlineObj; - - var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); - visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; - - if (needsOutline) - { - var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); - visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; - } - - return visualPart; - } - - private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject targetGameObject, int sortingOrder, string sortingLayerName = "Terrain") - { - MeshFilter meshFilter = targetGameObject.AddComponent(); - MeshRenderer meshRenderer = targetGameObject.AddComponent(); - meshRenderer.receiveShadows = false; - meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; - meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off; - meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; - - PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetGameObject.AddComponent(); - polytopiaSpriteRenderer.meshFilter = meshFilter; - polytopiaSpriteRenderer.meshRenderer = meshRenderer; - - polytopiaSpriteRenderer.SortingLayer = SortingLayer.NameToID(sortingLayerName); - polytopiaSpriteRenderer.SortingOrder = sortingOrder; - if (cachedSharedMaterial != null) - { - polytopiaSpriteRenderer.SharedMaterial = cachedSharedMaterial; - } - return polytopiaSpriteRenderer; - } - - #endregion - #region Resources - - internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefabInfo) - { - if (resourcePrefabInfo.resourceType == null) - return; - - var baseResource = PrefabManager.GetPrefab(ResourceData.Type.Game); - if (baseResource == null) - return; - - var resourceInstance = GameObject.Instantiate(baseResource); - if (resourceInstance == null) - return; - - Transform resourceTransform = resourceInstance.transform; - for (int childIndex = resourceTransform.childCount - 1; childIndex >= 0; childIndex--) - { - GameObject.Destroy(resourceTransform.GetChild(childIndex).gameObject); - } - - var visualParts = ApplyResourceVisualParts(resourcePrefabInfo, resourceTransform); - - var svr = resourceInstance.GetComponent(); - svr.visualParts = visualParts.ToArray(); - - GameObject.DontDestroyOnLoad(resourceInstance.gameObject); - - PrefabManager.resources[(Polytopia.Data.ResourceData.Type)resourcePrefabInfo.resourceType] = resourceInstance; - } - - private static List ApplyResourceVisualParts( - ResourcePrefabInfo resourcePrefabInfo, - Transform spriteContainer) - { - List parts = new(); - List visualPartInfos = resourcePrefabInfo.visualParts; - - if (visualPartInfos.Count == 0) - return parts; - - int nextPartSortingOrder = 0; - int nextOutlineSortingOrder = -visualPartInfos.Count; - foreach (var info in visualPartInfos) - { - parts.Add(CreateResourceVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); - if (nextOutlineSortingOrder < -1) - { - nextOutlineSortingOrder++; - } - nextPartSortingOrder++; - } - - return parts; - } - - private static SkinVisualsReference.VisualPart CreateResourceVisualPart( - VisualPartInfo info, - Transform parent, - int visualPartSortingOrder, - int outlineSortingOrder) - { - var visualPartObj = new GameObject(info.defaultSpriteName); - visualPartObj.transform.SetParent(parent); - - var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); - outlineObj.transform.SetParent(visualPartObj.transform); - - visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; - visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - outlineObj.SetActive(false); - - var visualPart = info.ToVisualPart(false); - visualPart.visualPart = visualPartObj; - visualPart.outline = outlineObj; - - var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); - visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; - - var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); - visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; - - return visualPart; - } - - #endregion - - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Prefabs)); - } + internal static Dictionary unitsNew = new(); + internal static Dictionary> unitOverridesNew = new(); // maybe in the future will implement + internal static Dictionary unitUIOverridesNew = new(); + + internal static Material? cachedUnitMaterial; + internal static Material? cachedSharedMaterial; + internal const string CACHED_SHARED_MATERIAL_NAME = "SpriteMaterial"; + + public static List unitInfos = new(); + + public static List resourceInfos = new(); + + public static List improvementInfos = new(); + internal static Dictionary improvementPrefabInfosToCreate = new(); + internal static List resourcePrefabsInfosToCreate = new(); + + private static List weaponInfos = new(); + private static Dictionary weaponProjectilesCache = new(); + private static Dictionary weaponAnimTimeCache = new() + { + {UnitData.WeaponEnum.Sting, 0.5f}, + {UnitData.WeaponEnum.IceArrow, 1f}, + {UnitData.WeaponEnum.Gun, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnDarkPuff(); + {UnitData.WeaponEnum.FireBlow, 2f}, // __instance.Tile.SpawnDarkPuff(); + {UnitData.WeaponEnum.Poison, 2f}, // __instance.Tile.SpawnPoison(__instance.Owner.GetVisualSkin()); + {UnitData.WeaponEnum.Pierce, 1f}, + {UnitData.WeaponEnum.Water, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnPuff(); + }; + + [HarmonyPostfix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] + private static void PrefabManager_Awake_Postfix(PrefabManager __instance) + { + unitsNew.Clear(); + unitOverridesNew.Clear(); + unitUIOverridesNew.Clear(); + + foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) + { + if (cachedUnitMaterial == null) + { + SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); + if (skinVisualsReference != null && skinVisualsReference.visualParts != null) + { + foreach (VisualPart currentPart in skinVisualsReference.visualParts) + { + if (currentPart.visualPart == null) + { + continue; + } + + SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); + if (headSpriteRenderer != null) + { + cachedUnitMaterial = headSpriteRenderer.sharedMaterial; + break; + } + } + } + } + unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; + } + + foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) + { + if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) + { + overridesForCondition = new Dictionary(); + unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; + } + overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; + } + + foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) + { + unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; + } + + Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] + public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] + public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) + { + __result = uiOverridePrefab; + } + else + { + __result = ResolveUnitPrefab(unitType, tribe, skin); + } + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] + public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) + { + __result = ResolveUnitPrefab(type, tribe, skin); + return false; + } + + [HarmonyPostfix] // prolly remove later + [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] + public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) + { + bool flag = false; + flag = visualSetting.outline != null && visualSetting.outline.transform.parent == visualSetting.visualPart.transform; + if (!flag && visualSetting.visualPart.transform.childCount > 0) + { + visualSetting.outline = visualSetting.visualPart.transform.GetChild(0).gameObject; + flag = true; + } + bool flag2 = false; + if (flag) + { + string defaultSpriteName = visualSetting.DefaultSpriteName; + if (visualSetting.outline != null && visualSetting.outline.name == defaultSpriteName + "_Outline") + { + flag2 = true; + } + } + visualSetting.hasValidOutline = flag2; + } + + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] + // private static bool Unit_IsProjectile(ref bool __result, UnitData.WeaponEnum weapon) + // { + // if(!weaponProjectilesCache.ContainsKey(weapon)) + // return true; + + // __result = weaponProjectilesCache[weapon]; + // return false; + // } + + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] + // private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Action onComplete) + // { + // UnitData.WeaponEnum weaponEnum = __instance.unitData.weapon; + // List weaponPrefabInfos = weaponInfos.Where(weaponInfo => weaponInfo.weaponEnum == weaponEnum).ToList(); + // if(weaponPrefabInfos.Count == 0) + // return true; + + // WeaponPrefabInfo weaponPrefabInfo = weaponPrefabInfos.Last(); + // float chebyshevDistance = MapDataExtensions.ChebyshevDistance(__instance.Tile.Coordinates, target); + + // float animationTime = 0.2f + chebyshevDistance * 0.05f; + // Tile targetTile = MapRenderer.Current.GetTileInstance(target); + + // WeaponGFX pooledObject = ObjectPool.GetPooledObject(GetPrefab(weaponEnum).gameObject); + // pooledObject.IsUsed = true; + // Vector3 center = SkinVisualsRenderer.GetSpriteBounds(__instance.skinVisuals).center; + // pooledObject.transform.position = __instance.transform.position + center; + // pooledObject.SetSkin(__instance.Owner.GetVisualSkin()); + + // if ((bool)targetTile.Unit) + // { + // targetTile.Unit.Flipped = targetTile.Unit.UnitState.flipped; + // } + // __instance.Flipped = __instance.UnitState.flipped; + + // if(weaponPrefabInfo.weaponPuffInfo != null) + // { + // animationTime *= weaponPrefabInfo.weaponPuffInfo.animationMultiplier; + // if(weaponPrefabInfo.weaponPuffInfo.sway) + // __instance.Sway(); + // } + // if (Unit.IsProjectile(weaponEnum)) + // { + // if(weaponPrefabInfo.weaponPuffInfo != null && weaponPrefabInfo.weaponPuffInfo!.animationDelegate != null) + // pooledObject.AnimateRanged(animationTime, target, DelegateSupport.ConvertDelegate(weaponPrefabInfo.weaponPuffInfo!.animationDelegate!)); + // else + // pooledObject.AnimateRanged(animationTime, target); + // } + // else + // { + // pooledObject.AnimateCloseRangeAttack(0.2f); + // } + + // if (__instance.unitData.GetRange() < 2) + // { + // __instance.AnimateMeleeAttackMovement(targetTile, moveToTarget, onComplete); + // } + // else + // { + // GameManager.DelayCall((int)(animationTime * 1000f), onComplete); + // } + + // return false; + // } + + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] + // public static bool WeaponGFX_AnimateCloseRangeAttack(ref float animTime, Action onComplete) + // { + // animTime = 100000f; + // return true; + // } + + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] + // public static bool WeaponGFX_AnimateRanged(ref float animTime, WorldCoordinates to, Action onComplete) + // { + // animTime = 100000f; + // return true; + // } + + private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + if (SeasonManager.IsChristmas() + && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) + && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) + && christmasPrefab != null) + { + return christmasPrefab; + } + + SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); + if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) + { + return exactPrefab; + } + + if (skinType != SkinType.Default || tribeType != TribeType.None) + { + SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); + SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); + SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); + + if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) + || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) + || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) + { + unitsNew[exactKey] = fallbackPrefab; + return fallbackPrefab; + } + } + + Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); + unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); + return lastResortPrefab!; + } + + internal static void CreatePrefabs() + { + // get materials + Material[] allLoadedMaterials = Resources.FindObjectsOfTypeAll(); + foreach (Material loadedMaterial in allLoadedMaterials) + { + // Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); + + if (loadedMaterial.name == CACHED_SHARED_MATERIAL_NAME) + { + cachedSharedMaterial = loadedMaterial; + GameObject.DontDestroyOnLoad(cachedSharedMaterial); + break; + } + } + + // creates dummy improvements. those have one visual part, and default name is the enum cache name of the type + foreach (KeyValuePair improvementInfo in improvementPrefabInfosToCreate) + { + ImprovementData.Type improvementType = improvementInfo.Key; + improvementInfos.Add( + new ImprovementPrefabInfo() + { + improvementType = improvementType, + visualParts = new() + { + new() + { + defaultSpriteName = EnumCache.GetName(improvementType), + levels = improvementInfo.Value, + } + } + } + ); + } + + // creates dummy resources. those have one visual part, and default name is the enum cache name of the type + foreach (ResourceData.Type resourceType in resourcePrefabsInfosToCreate) + { + resourceInfos.Add( + new ResourcePrefabInfo() + { + resourceType = resourceType, + visualParts = new() + { + new() + { + defaultSpriteName = EnumCache.GetName(resourceType), + } + } + } + ); + } + + foreach (var unitPrefabInfo in unitInfos) + { + ProcessUnitPrefabInfo(unitPrefabInfo); + } + + foreach (var improvementPrefabInfo in improvementInfos) + { + ProcessImprovementPrefabInfo(improvementPrefabInfo); + } + + foreach (var resourcePrefabInfo in resourceInfos) + { + ProcessResourcePrefabInfo(resourcePrefabInfo); + } + } + + #region Units + internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) + { + // maybe just init new unit? hmmmmm will try later + var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); + if (baseUnit == null) + return; + + var unitInstance = GameObject.Instantiate(baseUnit); + if (unitInstance == null) + return; + + GameObject.Destroy(unitInstance.spriteContainer.gameObject); + + var spriteContainerObj = new GameObject("SpriteContainer"); + spriteContainerObj.transform.SetParent(unitInstance.transform, false); + var spriteContainer = spriteContainerObj.transform; + unitInstance.spriteContainer = spriteContainer; + + var visualParts = ApplyUnitVisualParts(unitPrefabInfo, spriteContainer); + + Transform? headPositionMarker = null; + foreach (var vp in visualParts) + { + if (vp.visualPart.gameObject.name == unitPrefabInfo.headPositionMarker) + { + headPositionMarker = vp.visualPart.gameObject.transform; + break; + } + } + + unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; + + var svr = unitInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(unitInstance.gameObject); + + if (unitPrefabInfo.uiOverride) + { + unitUIOverridesNew[unitPrefabInfo.skinnedKey] = unitInstance; + return; + } + unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; + } + + private static List ApplyUnitVisualParts( + UnitPrefabInfo unitPrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = unitPrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + var newVisualInfo = visualPartInfos; + newVisualInfo.Reverse(); + foreach (var info in newVisualInfo) + { + parts.Add(CreateUnitVisualPart(info, spriteContainer, info.sortingOrderOverride ?? nextPartSortingOrder, info.outlineSortingOrderOverride ?? nextOutlineSortingOrder)); + if (nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + } + + return parts; + } + + private static SkinVisualsReference.VisualPart CreateUnitVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = info.coordinates; + outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + // this bs was hunting me for so long. that is the thing which makes outline hidden in ui + outlineObj.SetActive(false); + + var visualPart = info.ToVisualPart(false); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + + var renderer = visualPartObj.AddComponent(); + renderer.material = cachedUnitMaterial; + renderer.sortingOrder = visualPartSortingOrder; + renderer.sortingLayerName = "Units"; + visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; + + var outlineRenderer = outlineObj.AddComponent(); + outlineRenderer.material = cachedUnitMaterial; + outlineRenderer.sortingOrder = outlineSortingOrder; + outlineRenderer.sortingLayerName = "Units"; + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; + + return visualPart; + } + + #endregion + #region Improvements + internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvementPrefabInfo) + { + if (improvementPrefabInfo.improvementType == null) + return; + + var baseBuilding = PrefabManager.GetPrefab(ImprovementData.Type.LumberHut); + if (baseBuilding == null) + return; + + var buildingInstance = GameObject.Instantiate(baseBuilding); + if (buildingInstance == null) + return; + + Transform buildingTransform = buildingInstance.transform; + for (int childIndex = buildingTransform.childCount - 1; childIndex >= 0; childIndex--) + { + GameObject.Destroy(buildingTransform.GetChild(childIndex).gameObject); + } + + var visualParts = ApplyBuildingVisualParts(improvementPrefabInfo, buildingTransform); + + var svr = buildingInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(buildingInstance.gameObject); + + PrefabManager.improvements[(Polytopia.Data.ImprovementData.Type)improvementPrefabInfo.improvementType] = buildingInstance; + } + + private static List ApplyBuildingVisualParts( + ImprovementPrefabInfo improvementPrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = improvementPrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + foreach (var info in visualPartInfos) + { + parts.Add(CreateBuildingVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder, improvementPrefabInfo.needsOutlines)); + if (nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + } + + return parts; + } + + private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder, + bool needsOutline = false) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + outlineObj.SetActive(false); + + var visualPart = info.ToVisualPart(true); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); + visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; + + if (needsOutline) + { + var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; + } + + return visualPart; + } + + private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject targetGameObject, int sortingOrder, string sortingLayerName = "Terrain") + { + MeshFilter meshFilter = targetGameObject.AddComponent(); + MeshRenderer meshRenderer = targetGameObject.AddComponent(); + meshRenderer.receiveShadows = false; + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + + PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetGameObject.AddComponent(); + polytopiaSpriteRenderer.meshFilter = meshFilter; + polytopiaSpriteRenderer.meshRenderer = meshRenderer; + + polytopiaSpriteRenderer.SortingLayer = SortingLayer.NameToID(sortingLayerName); + polytopiaSpriteRenderer.SortingOrder = sortingOrder; + if (cachedSharedMaterial != null) + { + polytopiaSpriteRenderer.SharedMaterial = cachedSharedMaterial; + } + return polytopiaSpriteRenderer; + } + + #endregion + #region Resources + + internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefabInfo) + { + if (resourcePrefabInfo.resourceType == null) + return; + + var baseResource = PrefabManager.GetPrefab(ResourceData.Type.Game); + if (baseResource == null) + return; + + var resourceInstance = GameObject.Instantiate(baseResource); + if (resourceInstance == null) + return; + + Transform resourceTransform = resourceInstance.transform; + for (int childIndex = resourceTransform.childCount - 1; childIndex >= 0; childIndex--) + { + GameObject.Destroy(resourceTransform.GetChild(childIndex).gameObject); + } + + var visualParts = ApplyResourceVisualParts(resourcePrefabInfo, resourceTransform); + + var svr = resourceInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(resourceInstance.gameObject); + + PrefabManager.resources[(Polytopia.Data.ResourceData.Type)resourcePrefabInfo.resourceType] = resourceInstance; + } + + private static List ApplyResourceVisualParts( + ResourcePrefabInfo resourcePrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = resourcePrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + foreach (var info in visualPartInfos) + { + parts.Add(CreateResourceVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); + if (nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + } + + return parts; + } + + private static SkinVisualsReference.VisualPart CreateResourceVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + outlineObj.SetActive(false); + + var visualPart = info.ToVisualPart(false); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); + visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; + + var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; + + return visualPart; + } + + #endregion + + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Prefabs)); + } } diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index f545572..2073701 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -10,225 +10,225 @@ namespace PolyMod.Managers; public static class TribePreviews { - /// - /// Represents a tile in a tribe preview. - /// - public class PreviewTile - { - /// The x-coordinate of the tile. - [JsonInclude] - public int? x = null; - /// The y-coordinate of the tile. - [JsonInclude] - public int? y = null; - /// The terrain type of the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public Polytopia.Data.TerrainData.Type terrainType = Polytopia.Data.TerrainData.Type.None; - /// The resource type on the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ResourceData.Type? resourceType = null; - /// The unit type on the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public UnitData.Type? unitType = null; - /// The improvement type on the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ImprovementData.Type? improvementType = null; - /// The effect types on the tile. - [JsonInclude] - [JsonConverter(typeof(EnumCacheListJson))] - public List tileEffects = new(); - } - - public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); - - [HarmonyPostfix] - [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] - public static void PreloadTribePreviews() - { - Dictionary previewSaveStateDatas = new(); - - SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; - foreach (string tribe in Registry.tribePreviews.Keys) - { - string previewId = "worldpreview_" + tribe; - PreviewTile[] customPreview = Registry.tribePreviews[tribe]; - previewSaveStateDatas[previewId] = new(TribePreviewRegistry.fallbackStateIndex, fallbackSaveStateData, customPreview); - } - - for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) - { - SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; - if (previewSaveStateDatas.TryGetValue(saveStateData.name, out PreviewInfo? existingPreview)) - { - previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, existingPreview.customPreview); - } - } - - foreach (string previewId in previewSaveStateDatas.Keys) - { - var data = previewSaveStateDatas[previewId]; - SaveStateData? customSaveStateData = ApplyCustomPreview(previewId, data.saveStateData, data.customPreview); - if (customSaveStateData == null) - continue; - - if (data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) - { - List saveStateDatas = TribePreviewRegistry.saveStateDatas.ToList(); - saveStateDatas.Add(customSaveStateData); - TribePreviewRegistry.saveStateDatas = saveStateDatas.ToArray(); - } - else - { - TribePreviewRegistry.saveStateDatas[data.arrayIdx] = customSaveStateData; - } - } - } - - private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) - { - SaveStateData? saveStateData = null; - if (DiskSerializationHelpers.FromLZ4CompressedByteArray( - originalPreview.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) - { - GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); - foreach (var previewTile in preview) - { - if (previewTile.x == null || previewTile.y == null) - continue; - - WorldCoordinates coordinates = new((int)previewTile.x, (int)previewTile.y); - TileData? tileData = currentGameState.Map.GetTile(coordinates); - if (tileData == null) - continue; - - if (previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) - tileData.terrain = previewTile.terrainType; - - if (previewTile.resourceType != null) - { - ResourceState? resourceState = null; - ResourceData.Type resourceType = (ResourceData.Type)previewTile.resourceType; - if (resourceType != ResourceData.Type.None) - { - resourceState = new ResourceState { type = resourceType }; - } - tileData.resource = resourceState; - } - - if (previewTile.unitType != null) - { - tileData.unit = null; - if (previewTile.unitType != Polytopia.Data.UnitData.Type.None && - currentGameState.TryGetPlayer(currentGameState.CurrentPlayer, out PlayerState playerState) && - currentGameState.GameLogicData.TryGetData((UnitData.Type)previewTile.unitType, out UnitData unitData)) - { - UnitState unitState = ActionUtils.TrainUnit(currentGameState, playerState, tileData, unitData); - unitState.moved = false; - unitState.attacked = false; - } - } - - - if (previewTile.improvementType != null) - { - tileData.improvement = null; - ImprovementData.Type improvementType = (ImprovementData.Type)previewTile.improvementType; - if ( - previewTile.improvementType != ImprovementData.Type.None && - currentGameState.GameLogicData.TryGetData( - improvementType, - out ImprovementData improvementData) - ) - { - tileData.improvement = new ImprovementState - { - type = improvementData.type, - borderSize = (ushort)improvementData.borderSize, - level = 0, - xp = 0, - production = 1, - founded = (ushort)currentGameState.CurrentTurn, - baseScore = (ushort)improvementData.GetScoreReward(), - founder = currentGameState.CurrentPlayer - }; - } - } - - if (previewTile.tileEffects.Count > 0) - tileData.effects = new(); - - foreach (TileData.EffectType tileEffect in previewTile.tileEffects) - { - tileData.AddEffect(tileEffect); - } - } - - saveStateData = ScriptableObject.CreateInstance(); - saveStateData.name = previewId; - saveStateData.byteArray = DiskSerializationHelpers.ToLZ4CompressedByteArray(clientSerializationWrapper, version); - } - - return saveStateData; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SelectTribePopup), nameof(SelectTribePopup.SetBackground))] - private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) - { - if (!Plugin.config.showCoordinates) - return; - - try - { - TribeType tribeType = (__instance.mixTribeData != null) ? __instance.mixTribeData.type : __instance.tribeData.type; - - __instance.mapSnapshot = new SpriteCamera.SnapshotMapData(); - __instance.mapSnapshot.LoadMapState( - TribePreviewRegistry.GetTribePreviewData(tribeType, __instance.SkinType) - ); - - float width = __instance.worldPreviewRawImage.rectTransform.GetWidth(); - float height = __instance.worldPreviewRawImage.rectTransform.GetHeight(); - - int tribeColor = PolytopiaDataManager.GetGameLogicData( - VersionManager.GameLogicDataVersion - ).GetTribeColor( - tribeType, - __instance.SkinType - ); - - var instance = SpriteCamera.instance; - float baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; - - instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; - - Texture2D texture2D = SpriteCamera.TakeSnapshotOfMapState( - __instance.mapSnapshot, - width, - height, - tribeType, - __instance.SkinType, - tribeType, - tribeColor - ); - - instance.spriteCamera.orthographicSize = baseOrthographicCameraSize; - - __instance.worldPreviewRawImage.texture = texture2D; - __instance.worldPreviewRawImage.color = Color.white; - } - catch (Exception ex) - { - Plugin.logger.LogWarning($"Failed to load debug tribe preview {ex.Message}"); - } - } - - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(TribePreviews)); - } + /// + /// Represents a tile in a tribe preview. + /// + public class PreviewTile + { + /// The x-coordinate of the tile. + [JsonInclude] + public int? x = null; + /// The y-coordinate of the tile. + [JsonInclude] + public int? y = null; + /// The terrain type of the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public Polytopia.Data.TerrainData.Type terrainType = Polytopia.Data.TerrainData.Type.None; + /// The resource type on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; + /// The unit type on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.Type? unitType = null; + /// The improvement type on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; + /// The effect types on the tile. + [JsonInclude] + [JsonConverter(typeof(EnumCacheListJson))] + public List tileEffects = new(); + } + + public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); + + [HarmonyPostfix] + [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] + public static void PreloadTribePreviews() + { + Dictionary previewSaveStateDatas = new(); + + SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; + foreach (string tribe in Registry.tribePreviews.Keys) + { + string previewId = "worldpreview_" + tribe; + PreviewTile[] customPreview = Registry.tribePreviews[tribe]; + previewSaveStateDatas[previewId] = new(TribePreviewRegistry.fallbackStateIndex, fallbackSaveStateData, customPreview); + } + + for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) + { + SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; + if (previewSaveStateDatas.TryGetValue(saveStateData.name, out PreviewInfo? existingPreview)) + { + previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, existingPreview.customPreview); + } + } + + foreach (string previewId in previewSaveStateDatas.Keys) + { + var data = previewSaveStateDatas[previewId]; + SaveStateData? customSaveStateData = ApplyCustomPreview(previewId, data.saveStateData, data.customPreview); + if (customSaveStateData == null) + continue; + + if (data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) + { + List saveStateDatas = TribePreviewRegistry.saveStateDatas.ToList(); + saveStateDatas.Add(customSaveStateData); + TribePreviewRegistry.saveStateDatas = saveStateDatas.ToArray(); + } + else + { + TribePreviewRegistry.saveStateDatas[data.arrayIdx] = customSaveStateData; + } + } + } + + private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) + { + SaveStateData? saveStateData = null; + if (DiskSerializationHelpers.FromLZ4CompressedByteArray( + originalPreview.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) + { + GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); + foreach (var previewTile in preview) + { + if (previewTile.x == null || previewTile.y == null) + continue; + + WorldCoordinates coordinates = new((int)previewTile.x, (int)previewTile.y); + TileData? tileData = currentGameState.Map.GetTile(coordinates); + if (tileData == null) + continue; + + if (previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) + tileData.terrain = previewTile.terrainType; + + if (previewTile.resourceType != null) + { + ResourceState? resourceState = null; + ResourceData.Type resourceType = (ResourceData.Type)previewTile.resourceType; + if (resourceType != ResourceData.Type.None) + { + resourceState = new ResourceState { type = resourceType }; + } + tileData.resource = resourceState; + } + + if (previewTile.unitType != null) + { + tileData.unit = null; + if (previewTile.unitType != Polytopia.Data.UnitData.Type.None && + currentGameState.TryGetPlayer(currentGameState.CurrentPlayer, out PlayerState playerState) && + currentGameState.GameLogicData.TryGetData((UnitData.Type)previewTile.unitType, out UnitData unitData)) + { + UnitState unitState = ActionUtils.TrainUnit(currentGameState, playerState, tileData, unitData); + unitState.moved = false; + unitState.attacked = false; + } + } + + + if (previewTile.improvementType != null) + { + tileData.improvement = null; + ImprovementData.Type improvementType = (ImprovementData.Type)previewTile.improvementType; + if ( + previewTile.improvementType != ImprovementData.Type.None && + currentGameState.GameLogicData.TryGetData( + improvementType, + out ImprovementData improvementData) + ) + { + tileData.improvement = new ImprovementState + { + type = improvementData.type, + borderSize = (ushort)improvementData.borderSize, + level = 0, + xp = 0, + production = 1, + founded = (ushort)currentGameState.CurrentTurn, + baseScore = (ushort)improvementData.GetScoreReward(), + founder = currentGameState.CurrentPlayer + }; + } + } + + if (previewTile.tileEffects.Count > 0) + tileData.effects = new(); + + foreach (TileData.EffectType tileEffect in previewTile.tileEffects) + { + tileData.AddEffect(tileEffect); + } + } + + saveStateData = ScriptableObject.CreateInstance(); + saveStateData.name = previewId; + saveStateData.byteArray = DiskSerializationHelpers.ToLZ4CompressedByteArray(clientSerializationWrapper, version); + } + + return saveStateData; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SelectTribePopup), nameof(SelectTribePopup.SetBackground))] + private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) + { + if (!Plugin.config.showCoordinates) + return; + + try + { + TribeType tribeType = (__instance.mixTribeData != null) ? __instance.mixTribeData.type : __instance.tribeData.type; + + __instance.mapSnapshot = new SpriteCamera.SnapshotMapData(); + __instance.mapSnapshot.LoadMapState( + TribePreviewRegistry.GetTribePreviewData(tribeType, __instance.SkinType) + ); + + float width = __instance.worldPreviewRawImage.rectTransform.GetWidth(); + float height = __instance.worldPreviewRawImage.rectTransform.GetHeight(); + + int tribeColor = PolytopiaDataManager.GetGameLogicData( + VersionManager.GameLogicDataVersion + ).GetTribeColor( + tribeType, + __instance.SkinType + ); + + var instance = SpriteCamera.instance; + float baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; + + instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; + + Texture2D texture2D = SpriteCamera.TakeSnapshotOfMapState( + __instance.mapSnapshot, + width, + height, + tribeType, + __instance.SkinType, + tribeType, + tribeColor + ); + + instance.spriteCamera.orthographicSize = baseOrthographicCameraSize; + + __instance.worldPreviewRawImage.texture = texture2D; + __instance.worldPreviewRawImage.color = Color.white; + } + catch (Exception ex) + { + Plugin.logger.LogWarning($"Failed to load debug tribe preview {ex.Message}"); + } + } + + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(TribePreviews)); + } } diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 44de3a4..457da3a 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -14,543 +14,588 @@ namespace PolyMod.Managers; /// public static class Visual { - /// Represents information about a sprite, such as its pivot and pixels per unit. - public class SpriteInfo - { - [JsonInclude] - public float? pixelsPerUnit; - - [JsonInclude] - public Vector2? pivot; - - [JsonInclude] - public SpriteOrigin? spriteOrigin = null; - - [JsonInclude] - public bool transformToOutline = false; - - [JsonInclude] - public float? gaussianBlurRadius = null; - - public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, bool transformToOutline = false, SpriteOrigin? spriteOrigin = null, float? gaussianBlurRadius = null) - { - this.pixelsPerUnit = pixelsPerUnit; - this.pivot = pivot; - this.spriteOrigin = spriteOrigin; - this.transformToOutline = transformToOutline; - this.gaussianBlurRadius = gaussianBlurRadius; - } - } - - public class SpriteOrigin - { - [JsonInclude] - public string? name; - - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - public OriginType originType = OriginType.Outer; - } - - public enum OriginType - { - Outer, // Outer means sprite comes from a mod, and not from game's files - Inner // Inner means sprite is to be fetched from game's files - } - - /// Represents information about a custom skin. - public record SkinInfo(int idx, string id, SkinData? skinData); - - /// A dictionary of custom widths for basic popups. - public static Dictionary basicPopupWidths = new(); - - public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); - - private const int BASIC_POPUP_LEGACY_ID = 29; - - /// The width the game gives its own popups, used as the floor for custom widths. - private const float DEFAULT_POPUP_WIDTH = 402f; - - /// Smallest gap left between two buttons before they are moved onto separate rows. - private const float POPUP_BUTTON_GAP = 8f; - - /// Vertical gap between two rows of popup buttons. - private const float POPUP_BUTTON_ROW_GAP = 10f; - - private const byte INVISIBLE_ALPHA = 2; - private const int ALPHA_BLEED_RINGS = 16; - private const int PREMULTIPLIED_MIN_EDGE_PIXELS = 64; - private const float PREMULTIPLIED_MAX_OUTLIER_SHARE = 0.005f; - - /// - /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. - /// - internal static Dictionary customFloodingSkins = new(); - - private static readonly Color WEEKLY_CHALLENGE_DISABLED_COLOR = new(0.42f, 0.42f, 0.42f, 1f); - - private static Dictionary? cachedSpriteDataReverse = null; - private static Dictionary cachedReversedNames = new(); - - #region General - - /// A placeholder patch for the TechItem.SetupComplete method. - [HarmonyPostfix] - [HarmonyPatch(typeof(TechItem), nameof(TechItem.SetupComplete))] - private static void TechItem_SetupComplete() - { - } - - /// Patches the sprite atlas manager to look up custom sprites. - internal static void CacheSpriteNames() - { - cachedSpriteDataReverse = new(); - foreach (Polytopia.Data.TerrainData.Type terrainType in Enum.GetValues()) - { - string result = SpriteData.TerrainToString(terrainType); - if (terrainType == Polytopia.Data.TerrainData.Type.Wetland) - { - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(Polytopia.Data.TerrainData.Type.Field) + "_flooded"); - continue; - } - - if (result == SpriteData.TILE_UNKNOWN) - continue; - - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(terrainType)); - } - - foreach (ResourceData.Type resourceType in Enum.GetValues()) - { - string result = SpriteData.ResourceToString(resourceType); - if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) - continue; - - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(resourceType)); - } - - foreach (ImprovementData.Type improvementType in Enum.GetValues()) - { - string result = SpriteData.ImprovementToString(improvementType); - if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) - continue; - - cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(improvementType)); - } - } - internal static string FormatSpriteName(string baseName) - { - if (cachedSpriteDataReverse == null) - CacheSpriteNames(); - - if (cachedReversedNames.TryGetValue(baseName, out string? cachedReversedName)) - return cachedReversedName; - - string formattedName = baseName; - foreach (var valuePair in cachedSpriteDataReverse!) - { - formattedName = formattedName.Replace(valuePair.Key, valuePair.Value); - } - cachedReversedNames[baseName] = formattedName; - return formattedName; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.TrySolveSpriteNameForLevelSprites))] - private static void SpriteAtlasManager_TrySolveSpriteNameForLevelSprites( - ref bool __result, - SpriteAtlasManager __instance, - Il2CppInterop.Runtime.InteropTypes.Arrays.Il2CppStringArray spriteNameVariants, int level, ref string result) - { - if (!__result) __result = true; // will crash original lookup if false.... - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] - private static void SpriteAtlasManager_DoSpriteLookup( - ref SpriteAtlasManager.SpriteLookupResult __result, - SpriteAtlasManager __instance, - string baseName, TribeType tribe, SkinType skin, int level) - { - ApplyRegisteredSprites(ref __result, baseName, tribe, skin, level); - - string formattedName = FormatSpriteName(baseName); - if (formattedName != baseName) - { - ApplyRegisteredSprites(ref __result, formattedName, tribe, skin, level); - } - } - - private static void ApplyRegisteredSprites( - ref SpriteAtlasManager.SpriteLookupResult lookupResult, - string spriteName, TribeType tribe, SkinType skin, int level) - { - Sprite? registeredSprite = Registry.GetSprite(spriteName, tribe, skin, level); - if (registeredSprite != null) - lookupResult.sprite = registeredSprite; - - Sprite? registeredOutlineSprite = Registry.GetSprite(spriteName + "_outline", tribe, skin, level); - if (registeredOutlineSprite != null) - lookupResult.outlineSprite = registeredOutlineSprite; - } - - [HarmonyPrefix] // its obsolete so may be removed soon by midjiwan - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[] { typeof(string), typeof(string), typeof(SpriteCallback) })] - private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) - { - string formattedName = FormatSpriteName(sprite); - - Sprite? resolvedSprite = Registry.GetSprite(formattedName); - - if (resolvedSprite == null && formattedName != sprite) - { - resolvedSprite = Registry.GetSprite(sprite); - } - - if (resolvedSprite == null) - { - return true; - } - - completion.Invoke(atlas, sprite, resolvedSprite); - return false; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] - private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) - { - if ((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) - __result = EnumCache.GetName(terrain); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] - private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) - { - if ((int)resource >= Plugin.AUTOIDX_STARTS_FROM) - __result = EnumCache.GetName(resource); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] - private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) - { - if ((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) - __result = EnumCache.GetName(improvement); - } - - #endregion - #region Level - - [HarmonyPostfix] - [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] - public static void Tile_RenderDebug(Tile __instance) - { - if (!Plugin.config.showCoordinates) - return; - - GameObject textObj = new GameObject("CoordinateText"); - textObj.transform.SetParent(__instance.transform); - textObj.transform.localPosition = new Vector3(0, 0.0f, 0); - - TextMeshPro textMesh = textObj.AddComponent(); - textMesh.text = __instance.Data.coordinates.ToString(); - textMesh.fontSize = 3; - textMesh.alignment = TextAlignmentOptions.Center; - textMesh.color = Color.white; - - MeshRenderer renderer = textObj.GetComponent(); - renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; - renderer.sortingOrder = __instance.Depth + 10; - } - - private static string GetLandSpriteName(TileData tileData) - { - if (!tileData.HasEffect(TileData.EffectType.Flooded)) - { - return SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Field); - } - - string wetlandSpriteName = SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Wetland); - - if (tileData.HasEffect(TileData.EffectType.Swamped)) - { - return wetlandSpriteName + "_swamp"; - } - - foreach (TileData.EffectType effectType in tileData.effects) - { - if (customFloodingSkins.TryGetValue(effectType, out SkinType skinType)) - { - return $"{wetlandSpriteName}_{EnumCache.GetName(skinType)}"; - } - } - - return wetlandSpriteName; - } - - /// Updates the terrain graphics with custom sprites. - [HarmonyPrefix] - [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] // Why prefix? I really hate repeating the logic. I would have to do the same bs 2 times.... anyway reviewers tell me ok? - private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile, TribeType climate, SkinType skin, bool shouldDesaturate) - { - - string spriteName = tile.Data.terrain switch - { - Polytopia.Data.TerrainData.Type.Water => __instance.waterSprites.GetSpriteName(tile), - Polytopia.Data.TerrainData.Type.Ocean => __instance.oceanSprites.GetSpriteName(tile), - Polytopia.Data.TerrainData.Type.Ice => __instance.iceSprites.GetSpriteName(tile), - _ => GetLandSpriteName(tile.Data), - }; - - SpriteAtlasManager.SpriteLookupResult spriteLookupResult = GameManager.GetSpriteAtlasManager().DoSpriteLookup(spriteName, climate, skin); - if (spriteLookupResult.HasSprite()) - { - __instance.spriteRenderer.Sprite = spriteLookupResult.sprite; - } - if (shouldDesaturate != __instance.isDesaturated) - { - TerrainMaterialHelper.SetSpriteSaturated(__instance.SpriteRenderer, shouldDesaturate); - __instance.isDesaturated = shouldDesaturate; - } - - return false; - } - - /// Adds custom flood tile effect when tile is flooded for custom aqua skins. - [HarmonyPostfix] - [HarmonyPatch(typeof(TileData), nameof(TileData.Flood))] - private static void TileData_Flood(TileData __instance, PlayerState playerState) - { - if (customFloodingSkins.ContainsValue(playerState.skinType)) - { - TileData.EffectType effectType = customFloodingSkins.FirstOrDefault(x => x.Value == playerState.skinType).Key; - __instance.AddEffect(effectType); - } - } - - /// Removes custom flood effect loc from tile tip header. - [HarmonyPostfix] - [HarmonyPatch(typeof(TileTipGenerator), nameof(TileTipGenerator.GetTileTipHeader))] - public static void GetTileTipHeader(ref string __result, TileData tileData, SkinType skin, - PlayerState playerState, GameState gameState, GameLogicData gameLogicData) - { - foreach (var effect in tileData.effects) - { - if (customFloodingSkins.ContainsKey(effect)) - { - string localizedEffect = Localization.GetSkinned(skin, playerState.tribe, $"tile.effect.{effect.GetName()}"); - __result = __result.Replace($", {localizedEffect}", string.Empty); - } - } - } - - /// Forces an update of the mesh for a PolytopiaSpriteRenderer with a custom sprite. - [HarmonyPostfix] - [HarmonyPatch(typeof(PolytopiaSpriteRenderer), nameof(PolytopiaSpriteRenderer.ForceUpdateMesh))] - private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRenderer __instance) - { - if (__instance.sprite == null || !string.IsNullOrEmpty(__instance.atlasName)) - return; - - MaterialPropertyBlock materialPropertyBlock = new(); - materialPropertyBlock.SetVector("_Flip", new Vector4(1f, 1f, 0f, 0f)); - materialPropertyBlock.SetTexture("_MainTex", __instance.sprite.texture); - __instance.meshRenderer.SetPropertyBlock(materialPropertyBlock); - } - - #endregion - #region Popups - - /// Updates the width of a basic popup if a custom width is set. - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines))] - private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(PopupBase __instance) - { - UpdateWidth(__instance); - } - - private static void UpdateWidth(PopupBase popup) - { - if (!basicPopupWidths.TryGetValue(popup.GetInstanceID(), out PopupWidth? width)) return; - - popup.rectTransform.SetWidth(GetResponsivePopupWidth(width.share, width.maximum)); - BasicPopupLegacy? legacy = popup.TryCast(); - if (legacy != null && legacy.buttonContainer != null) - LayoutPopupButtons(legacy.buttonContainer); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.ScreenSizeChanged))] - private static void SystemEvents_ScreenSizeChanged() - { - RelayoutSizedPopups(); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.SafeAreaChanged))] - private static void SystemEvents_SafeAreaChanged() - { - RelayoutSizedPopups(); - } - - private static void RelayoutSizedPopups() - { - foreach (PopupWidth width in new List(basicPopupWidths.Values)) - { - try - { - if (width.popup == null || !width.popup.IsShowing()) continue; - width.popup.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(ScreenManager.SafeHeight); - } - catch (Exception exception) - { - Plugin.logger.LogError($"Could not lay a popup out after a screen size change: {exception}"); - } - } - } - - /// - /// Turns a share of the usable screen width into a popup width in canvas units. - /// The safe area is reported in screen pixels, so it is converted with the canvas scale the - /// game itself uses when it sizes popups. - /// - /// Share of the usable width to take, between 0 and 1. - /// Widest the popup may get, so that text stays readable on wide screens. - /// A width in canvas units, never below the width of the game's own popups. - public static int GetResponsivePopupWidth(float share, float maximum) - { - if (share <= 0f) return Mathf.RoundToInt(maximum); - float usable = ScreenManager.SafeWidth * UICanvasScalerHelper.GetInvertedUIScale(); - float width = Mathf.Min(usable * share, maximum); - return Mathf.RoundToInt(Mathf.Max(width, DEFAULT_POPUP_WIDTH)); - } - - /// - /// Replaces the game's popup button layout. The game spaces the buttons with an integer division, - /// which stacks every button but the last on the left edge, and it never wraps, so a popup too - /// narrow for its buttons draws them on top of each other. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupButtonContainer), nameof(PopupButtonContainer.SetButtonData))] - private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __instance) - { - LayoutPopupButtons(__instance); - } - - /// - /// Lays a popup's buttons out in as many rows as the container's width needs. - /// - internal static void LayoutPopupButtons(PopupButtonContainer container) - { - if (container.buttons == null || container.buttons.Length == 0) return; - - float available = container.rectTransform.rect.width; - if (available <= 0f) return; - - List> rows = PackButtonsIntoRows(container, available); - - float rowHeight = 0f; - foreach (UITextButton button in container.buttons) - { - rowHeight = Mathf.Max(rowHeight, button.rectTransform.rect.height); - } - float stackHeight = rows.Count * rowHeight + (rows.Count - 1) * POPUP_BUTTON_ROW_GAP; - - // The container sits at the bottom of the popup with a bottom pivot, so it grows upwards. - container.rectTransform.SetHeight(stackHeight); - - for (int row = 0; row < rows.Count; row++) - { - float offsetY = stackHeight / 2f - rowHeight / 2f - row * (rowHeight + POPUP_BUTTON_ROW_GAP); - PlaceButtonRow(rows[row], offsetY); - } - } - - /// - /// Fills one row at a time until the next button would no longer fit beside the previous ones. - /// - private static List> PackButtonsIntoRows(PopupButtonContainer container, float available) - { - List> rows = new() { new() }; - float rowWidth = 0f; - foreach (UITextButton button in container.buttons) - { - float width = button.rectTransform.rect.width; - if (rows[^1].Count > 0 && rowWidth + POPUP_BUTTON_GAP + width > available) - { - rows.Add(new()); - rowWidth = 0f; - } - rowWidth += (rows[^1].Count > 0 ? POPUP_BUTTON_GAP : 0f) + width; - rows[^1].Add(button); - } - return rows; - } - - /// - /// Spreads one row of buttons across the container, or centres it when it holds a single button. - /// - private static void PlaceButtonRow(List row, float offsetY) - { - for (int i = 0; i < row.Count; i++) - { - // Anchoring to a fraction of the container keeps the row spread as the popup resizes, - // which is how the game places the buttons of its own popups. - Vector2 anchor = new((row.Count == 1) ? 0.5f : (i / (row.Count - 1.0f)), 0.5f); - RectTransform rect = row[i].rectTransform; - rect.anchorMin = anchor; - rect.anchorMax = anchor; - rect.pivot = anchor; - rect.anchoredPosition = new Vector2(0f, offsetY); - } - } - - /// Removes a popup's custom width when it is hidden. - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] - private static void PopupBase_Hide(PopupBase __instance) - { - basicPopupWidths.Remove(__instance.GetInstanceID()); - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] - private static void StartScreen_UI2_OnShow() - { - CreateInnerOriginSprites(); - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] - private static bool StartScreen_OnWeeklyChallengeClicked() - { - BasicPopup popup = PopupManager.GetBasicPopup(); - popup.Header = Localization.Get("polymod.hub"); - popup.Description = Localization.Get( - "polymod.wc.vanillaonly", - new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", Array.Empty()) } - ); - popup.buttonData = new PopupBase.PopupButtonData[] { new("buttons.ok") }; - popup.Show(); - return false; - } - - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RefreshWeeklyChallengeButton))] - private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __instance) - { - WeeklyChallengesButton weeklyChallengeButton = __instance.weeklyChallengeButton; - if (weeklyChallengeButton == null) - return; - - weeklyChallengeButton.SetColors( - WEEKLY_CHALLENGE_DISABLED_COLOR, - WEEKLY_CHALLENGE_DISABLED_COLOR, - WEEKLY_CHALLENGE_DISABLED_COLOR - ); - } + /// Represents information about a sprite, such as its pivot and pixels per unit. + public class SpriteInfo + { + [JsonInclude] + public float? pixelsPerUnit; + + [JsonInclude] + public Vector2? pivot; + + [JsonInclude] + public SpriteOrigin? spriteOrigin = null; + + [JsonInclude] + public bool transformToOutline = false; + + [JsonInclude] + public float? gaussianBlurRadius = null; + + public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, bool transformToOutline = false, SpriteOrigin? spriteOrigin = null, float? gaussianBlurRadius = null) + { + this.pixelsPerUnit = pixelsPerUnit; + this.pivot = pivot; + this.spriteOrigin = spriteOrigin; + this.transformToOutline = transformToOutline; + this.gaussianBlurRadius = gaussianBlurRadius; + } + } + + public class SpriteOrigin + { + [JsonInclude] + public string? name; + + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public OriginType originType = OriginType.Outer; + } + + public enum OriginType + { + Outer, // Outer means sprite comes from a mod, and not from game's files + Inner // Inner means sprite is to be fetched from game's files + } + + /// Represents information about a custom skin. + public record SkinInfo(int idx, string id, SkinData? skinData); + + /// A dictionary of custom widths for basic popups. + public static Dictionary basicPopupWidths = new(); + + public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); + + private const int BASIC_POPUP_LEGACY_ID = 29; + + /// The width the game gives its own popups, used as the floor for custom widths. + private const float DEFAULT_POPUP_WIDTH = 402f; + + /// Smallest gap left between two buttons before they are moved onto separate rows. + private const float POPUP_BUTTON_GAP = 8f; + + /// Vertical gap between two rows of popup buttons. + private const float POPUP_BUTTON_ROW_GAP = 10f; + + private const byte INVISIBLE_ALPHA = 2; + private const int ALPHA_BLEED_RINGS = 16; + private const int PREMULTIPLIED_MIN_EDGE_PIXELS = 64; + private const float PREMULTIPLIED_MAX_OUTLIER_SHARE = 0.005f; + + /// + /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. + /// + internal static Dictionary customFloodingSkins = new(); + + private static readonly Color WEEKLY_CHALLENGE_DISABLED_COLOR = new(0.42f, 0.42f, 0.42f, 1f); + + private static Dictionary? cachedSpriteDataReverse = null; + private static Dictionary cachedReversedNames = new(); + + #region General + + /// A placeholder patch for the TechItem.SetupComplete method. + [HarmonyPostfix] + [HarmonyPatch(typeof(TechItem), nameof(TechItem.SetupComplete))] + private static void TechItem_SetupComplete() + { + } + + /// Patches the sprite atlas manager to look up custom sprites. + internal static void CacheSpriteNames() + { + cachedSpriteDataReverse = new(); + foreach (Polytopia.Data.TerrainData.Type terrainType in Enum.GetValues()) + { + string result = SpriteData.TerrainToString(terrainType); + if (terrainType == Polytopia.Data.TerrainData.Type.Wetland) + { + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(Polytopia.Data.TerrainData.Type.Field) + "_flooded"); + continue; + } + + if (result == SpriteData.TILE_UNKNOWN) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(terrainType)); + } + + foreach (ResourceData.Type resourceType in Enum.GetValues()) + { + string result = SpriteData.ResourceToString(resourceType); + if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(resourceType)); + } + + foreach (ImprovementData.Type improvementType in Enum.GetValues()) + { + string result = SpriteData.ImprovementToString(improvementType); + if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(improvementType)); + } + } + internal static string FormatSpriteName(string baseName) + { + if (cachedSpriteDataReverse == null) + CacheSpriteNames(); + + if (cachedReversedNames.TryGetValue(baseName, out string? cachedReversedName)) + return cachedReversedName; + + string formattedName = baseName; + foreach (var valuePair in cachedSpriteDataReverse!) + { + formattedName = formattedName.Replace(valuePair.Key, valuePair.Value); + } + cachedReversedNames[baseName] = formattedName; + return formattedName; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.TrySolveSpriteNameForLevelSprites))] + private static void SpriteAtlasManager_TrySolveSpriteNameForLevelSprites( + ref bool __result, + SpriteAtlasManager __instance, + Il2CppInterop.Runtime.InteropTypes.Arrays.Il2CppStringArray spriteNameVariants, int level, ref string result) + { + if (!__result) __result = true; // will crash original lookup if false.... + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] + private static void SpriteAtlasManager_DoSpriteLookup( + ref SpriteAtlasManager.SpriteLookupResult __result, + SpriteAtlasManager __instance, + string baseName, TribeType tribe, SkinType skin, int level) + { + ApplyRegisteredSprites(ref __result, baseName, tribe, skin, level); + + string formattedName = FormatSpriteName(baseName); + if (formattedName != baseName) + { + ApplyRegisteredSprites(ref __result, formattedName, tribe, skin, level); + } + } + + private static void ApplyRegisteredSprites( + ref SpriteAtlasManager.SpriteLookupResult lookupResult, + string spriteName, TribeType tribe, SkinType skin, int level) + { + Sprite? registeredSprite = Registry.GetSprite(spriteName, tribe, skin, level); + if (registeredSprite != null) + lookupResult.sprite = registeredSprite; + + Sprite? registeredOutlineSprite = Registry.GetSprite(spriteName, tribe, skin, level, true); + if (registeredOutlineSprite != null) + lookupResult.outlineSprite = registeredOutlineSprite; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.GetSprite), new Type[] { typeof(string), typeof(string) })] + private static void SpriteAtlasManager_GetSprite(ref Sprite __result, string spriteName) + { + if (__result != null || string.IsNullOrEmpty(spriteName)) return; + if (Registry.sprites.TryGetValue(spriteName.ToLowerInvariant(), out Sprite? sprite)) + __result = sprite; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(MapDataExtensions), nameof(MapDataExtensions.GenerateShoreLines))] + private static void MapDataExtensions_GenerateShoreLines(MapData map) + { + int width = map.Width; + var tiles = map.Tiles; + for (int i = 0; i < tiles.Length; i++) + { + TileData.Shorelines shorelines = tiles[i].shorelines; + if (!shorelines.any) continue; + + if (shorelines.S.visible) SetShorelineSuffix(tiles[i - width], shorelines.S); + if (shorelines.N.visible) SetShorelineSuffix(tiles[i + width], shorelines.N); + if (shorelines.W.visible) SetShorelineSuffix(tiles[i - 1], shorelines.W); + if (shorelines.E.visible) SetShorelineSuffix(tiles[i + 1], shorelines.E); + } + } + + private static void SetShorelineSuffix(TileData neighbour, TileData.Shoreline shoreline) + { + string suffix = neighbour.Skin == SkinType.Swamp || neighbour.HasEffect(TileData.EffectType.Swamped) + ? "_swamp" + : ""; + if (neighbour.Skin != SkinType.None && neighbour.Skin != SkinType.Default && neighbour.Skin != SkinType.Swamp) + suffix = "_" + EnumCache.GetName(neighbour.Skin); + foreach (var effectToSkin in customFloodingSkins) + { + if (neighbour.HasEffect(effectToSkin.Key)) + { + suffix = "_" + EnumCache.GetName(effectToSkin.Value); + break; + } + } + shoreline.spriteExt = suffix; + } + + [HarmonyPrefix] // its obsolete so may be removed soon by midjiwan + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[] { typeof(string), typeof(string), typeof(SpriteCallback) })] + private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) + { + string formattedName = FormatSpriteName(sprite); + + Sprite? resolvedSprite = Registry.GetSprite(formattedName); + + if (resolvedSprite == null && formattedName != sprite) + { + resolvedSprite = Registry.GetSprite(sprite); + } + + if (resolvedSprite == null) + { + return true; + } + + completion.Invoke(atlas, sprite, resolvedSprite); + return false; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] + private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) + { + if ((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(terrain); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] + private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) + { + if ((int)resource >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(resource); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] + private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) + { + if ((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(improvement); + } + + #endregion + #region Level + + [HarmonyPostfix] + [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] + public static void Tile_RenderDebug(Tile __instance) + { + if (!Plugin.config.showCoordinates) + return; + + GameObject textObj = new GameObject("CoordinateText"); + textObj.transform.SetParent(__instance.transform); + textObj.transform.localPosition = new Vector3(0, 0.0f, 0); + + TextMeshPro textMesh = textObj.AddComponent(); + textMesh.text = __instance.Data.coordinates.ToString(); + textMesh.fontSize = 3; + textMesh.alignment = TextAlignmentOptions.Center; + textMesh.color = Color.white; + + MeshRenderer renderer = textObj.GetComponent(); + renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; + renderer.sortingOrder = __instance.Depth + 10; + } + + private static string GetLandSpriteName(TileData tileData) + { + if (!tileData.HasEffect(TileData.EffectType.Flooded)) + { + return SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Field); + } + + string wetlandSpriteName = SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Wetland); + + if (tileData.HasEffect(TileData.EffectType.Swamped)) + { + return wetlandSpriteName + "_swamp"; + } + + foreach (TileData.EffectType effectType in tileData.effects) + { + if (customFloodingSkins.TryGetValue(effectType, out SkinType skinType)) + { + return $"{wetlandSpriteName}_{EnumCache.GetName(skinType)}"; + } + } + + return wetlandSpriteName; + } + + /// Updates the terrain graphics with custom sprites. + [HarmonyPrefix] + [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] // Why prefix? I really hate repeating the logic. I would have to do the same bs 2 times.... anyway reviewers tell me ok? + private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile, TribeType climate, SkinType skin, bool shouldDesaturate) + { + + string spriteName = tile.Data.terrain switch + { + Polytopia.Data.TerrainData.Type.Water => __instance.waterSprites.GetSpriteName(tile), + Polytopia.Data.TerrainData.Type.Ocean => __instance.oceanSprites.GetSpriteName(tile), + Polytopia.Data.TerrainData.Type.Ice => __instance.iceSprites.GetSpriteName(tile), + _ => GetLandSpriteName(tile.Data), + }; + + SpriteAtlasManager.SpriteLookupResult spriteLookupResult = GameManager.GetSpriteAtlasManager().DoSpriteLookup(spriteName, climate, skin); + if (spriteLookupResult.HasSprite()) + { + __instance.spriteRenderer.Sprite = spriteLookupResult.sprite; + } + if (shouldDesaturate != __instance.isDesaturated) + { + TerrainMaterialHelper.SetSpriteSaturated(__instance.SpriteRenderer, shouldDesaturate); + __instance.isDesaturated = shouldDesaturate; + } + + return false; + } + + /// Adds custom flood tile effect when tile is flooded for custom aqua skins. + [HarmonyPostfix] + [HarmonyPatch(typeof(TileData), nameof(TileData.Flood))] + private static void TileData_Flood(TileData __instance, PlayerState playerState) + { + if (customFloodingSkins.ContainsValue(playerState.skinType)) + { + TileData.EffectType effectType = customFloodingSkins.FirstOrDefault(x => x.Value == playerState.skinType).Key; + __instance.AddEffect(effectType); + } + } + + /// Removes custom flood effect loc from tile tip header. + [HarmonyPostfix] + [HarmonyPatch(typeof(TileTipGenerator), nameof(TileTipGenerator.GetTileTipHeader))] + public static void GetTileTipHeader(ref string __result, TileData tileData, SkinType skin, + PlayerState playerState, GameState gameState, GameLogicData gameLogicData) + { + foreach (var effect in tileData.effects) + { + if (customFloodingSkins.ContainsKey(effect)) + { + string localizedEffect = Localization.GetSkinned(skin, playerState.tribe, $"tile.effect.{effect.GetName()}"); + __result = __result.Replace($", {localizedEffect}", string.Empty); + } + } + } + + /// Forces an update of the mesh for a PolytopiaSpriteRenderer with a custom sprite. + [HarmonyPostfix] + [HarmonyPatch(typeof(PolytopiaSpriteRenderer), nameof(PolytopiaSpriteRenderer.ForceUpdateMesh))] + private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRenderer __instance) + { + if (__instance.sprite == null || !string.IsNullOrEmpty(__instance.atlasName)) + return; + + MaterialPropertyBlock materialPropertyBlock = new(); + materialPropertyBlock.SetVector("_Flip", new Vector4(1f, 1f, 0f, 0f)); + materialPropertyBlock.SetTexture("_MainTex", __instance.sprite.texture); + __instance.meshRenderer.SetPropertyBlock(materialPropertyBlock); + } + + #endregion + #region Popups + + /// Updates the width of a basic popup if a custom width is set. + [HarmonyPostfix] + [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines))] + private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(PopupBase __instance) + { + UpdateWidth(__instance); + } + + private static void UpdateWidth(PopupBase popup) + { + if (!basicPopupWidths.TryGetValue(popup.GetInstanceID(), out PopupWidth? width)) return; + + popup.rectTransform.SetWidth(GetResponsivePopupWidth(width.share, width.maximum)); + BasicPopupLegacy? legacy = popup.TryCast(); + if (legacy != null && legacy.buttonContainer != null) + LayoutPopupButtons(legacy.buttonContainer); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.ScreenSizeChanged))] + private static void SystemEvents_ScreenSizeChanged() + { + RelayoutSizedPopups(); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.SafeAreaChanged))] + private static void SystemEvents_SafeAreaChanged() + { + RelayoutSizedPopups(); + } + + private static void RelayoutSizedPopups() + { + foreach (PopupWidth width in new List(basicPopupWidths.Values)) + { + try + { + if (width.popup == null || !width.popup.IsShowing()) continue; + width.popup.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(ScreenManager.SafeHeight); + } + catch (Exception exception) + { + Plugin.logger.LogError($"Could not lay a popup out after a screen size change: {exception}"); + } + } + } + + /// + /// Turns a share of the usable screen width into a popup width in canvas units. + /// The safe area is reported in screen pixels, so it is converted with the canvas scale the + /// game itself uses when it sizes popups. + /// + /// Share of the usable width to take, between 0 and 1. + /// Widest the popup may get, so that text stays readable on wide screens. + /// A width in canvas units, never below the width of the game's own popups. + public static int GetResponsivePopupWidth(float share, float maximum) + { + if (share <= 0f) return Mathf.RoundToInt(maximum); + float usable = ScreenManager.SafeWidth * UICanvasScalerHelper.GetInvertedUIScale(); + float width = Mathf.Min(usable * share, maximum); + return Mathf.RoundToInt(Mathf.Max(width, DEFAULT_POPUP_WIDTH)); + } + + /// + /// Replaces the game's popup button layout. The game spaces the buttons with an integer division, + /// which stacks every button but the last on the left edge, and it never wraps, so a popup too + /// narrow for its buttons draws them on top of each other. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(PopupButtonContainer), nameof(PopupButtonContainer.SetButtonData))] + private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __instance) + { + LayoutPopupButtons(__instance); + } + + /// + /// Lays a popup's buttons out in as many rows as the container's width needs. + /// + internal static void LayoutPopupButtons(PopupButtonContainer container) + { + if (container.buttons == null || container.buttons.Length == 0) return; + + float available = container.rectTransform.rect.width; + if (available <= 0f) return; + + List> rows = PackButtonsIntoRows(container, available); + + float rowHeight = 0f; + foreach (UITextButton button in container.buttons) + { + rowHeight = Mathf.Max(rowHeight, button.rectTransform.rect.height); + } + float stackHeight = rows.Count * rowHeight + (rows.Count - 1) * POPUP_BUTTON_ROW_GAP; + + // The container sits at the bottom of the popup with a bottom pivot, so it grows upwards. + container.rectTransform.SetHeight(stackHeight); + + for (int row = 0; row < rows.Count; row++) + { + float offsetY = stackHeight / 2f - rowHeight / 2f - row * (rowHeight + POPUP_BUTTON_ROW_GAP); + PlaceButtonRow(rows[row], offsetY); + } + } + + /// + /// Fills one row at a time until the next button would no longer fit beside the previous ones. + /// + private static List> PackButtonsIntoRows(PopupButtonContainer container, float available) + { + List> rows = new() { new() }; + float rowWidth = 0f; + foreach (UITextButton button in container.buttons) + { + float width = button.rectTransform.rect.width; + if (rows[^1].Count > 0 && rowWidth + POPUP_BUTTON_GAP + width > available) + { + rows.Add(new()); + rowWidth = 0f; + } + rowWidth += (rows[^1].Count > 0 ? POPUP_BUTTON_GAP : 0f) + width; + rows[^1].Add(button); + } + return rows; + } + + /// + /// Spreads one row of buttons across the container, or centres it when it holds a single button. + /// + private static void PlaceButtonRow(List row, float offsetY) + { + for (int i = 0; i < row.Count; i++) + { + // Anchoring to a fraction of the container keeps the row spread as the popup resizes, + // which is how the game places the buttons of its own popups. + Vector2 anchor = new((row.Count == 1) ? 0.5f : (i / (row.Count - 1.0f)), 0.5f); + RectTransform rect = row[i].rectTransform; + rect.anchorMin = anchor; + rect.anchorMax = anchor; + rect.pivot = anchor; + rect.anchoredPosition = new Vector2(0f, offsetY); + } + } + + /// Removes a popup's custom width when it is hidden. + [HarmonyPostfix] + [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] + private static void PopupBase_Hide(PopupBase __instance) + { + basicPopupWidths.Remove(__instance.GetInstanceID()); + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] + private static void StartScreen_UI2_OnShow() + { + CreateInnerOriginSprites(); + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] + private static bool StartScreen_OnWeeklyChallengeClicked() + { + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = Localization.Get( + "polymod.wc.vanillaonly", + new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", Array.Empty()) } + ); + popup.buttonData = new PopupBase.PopupButtonData[] { new("buttons.ok") }; + popup.Show(); + return false; + } + + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RefreshWeeklyChallengeButton))] + private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __instance) + { + WeeklyChallengesButton weeklyChallengeButton = __instance.weeklyChallengeButton; + if (weeklyChallengeButton == null) + return; + + weeklyChallengeButton.SetColors( + WEEKLY_CHALLENGE_DISABLED_COLOR, + WEEKLY_CHALLENGE_DISABLED_COLOR, + WEEKLY_CHALLENGE_DISABLED_COLOR + ); + } private const string MIGHTYLEADER = "mightyleader"; @@ -559,532 +604,532 @@ private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __i public static void PopupContentBuilder_GetMightyLeaderTopImage(ref Sprite __result, PlayerState player) { Sprite? sprite = Registry.GetSprite(MIGHTYLEADER, player.tribe, player.GetVisualSkin()); - if(sprite != null) + if (sprite != null) __result = sprite; } - /// Shows a basic popup with a custom width. - public static void ShowSetWidth(this BasicPopupLegacy self, int width) - { - basicPopupWidths[self.GetInstanceID()] = new(self, 0f, width); - self.Show(); - } - - /// Shows a basic popup sized to a share of the usable screen width. - public static void ShowSetWidth(this BasicPopupLegacy self, float share, float maximum) - { - basicPopupWidths[self.GetInstanceID()] = new(self, share, maximum); - self.Show(); - } - - #endregion - - internal static BasicPopupLegacy GetBasicPopupLegacy() - { - WhatsNewPopup whatsNewPopup = PopupManager.GetWhatsNewPopup(); - BasicPopupLegacy original = PopupManager.instance.popupPrefabs[BASIC_POPUP_LEGACY_ID].Cast(); - BasicPopupLegacy basicPopupLegacy = UnityEngine.Object.Instantiate(original, PopupManager.instance.transform); - basicPopupLegacy.buttonContainer = GameObject.Instantiate(whatsNewPopup.buttonContainer, basicPopupLegacy.transform); - basicPopupLegacy.popupId = "basicPopupLegacy"; - basicPopupLegacy.popupManager = PopupManager.instance; - basicPopupLegacy.Init(); - basicPopupLegacy.identifier = null; - basicPopupLegacy.rectTransform.SetAsLastSibling(); - return basicPopupLegacy; - } - - public static Texture2D BuildTexture(byte[] data) - { - Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); - texture.LoadImage(data); - Color32[] pixels = texture.GetPixels32(); - if (LooksPremultiplied(pixels)) - Unpremultiply(pixels); - BleedAlphaEdges(pixels, texture.width, texture.height); - texture.SetPixels32(pixels); - texture.filterMode = FilterMode.Trilinear; - texture.wrapMode = TextureWrapMode.Clamp; - texture.Apply(); - return texture; - } - - internal static bool LooksPremultiplied(Color32[] pixels) - { - int edge = 0; - int brighterThanAlpha = 0; - foreach (Color32 pixel in pixels) - { - if (pixel.a == 0 || pixel.a == 255) continue; - edge++; - if (Math.Max(pixel.r, Math.Max(pixel.g, pixel.b)) > pixel.a) - brighterThanAlpha++; - } - return edge >= PREMULTIPLIED_MIN_EDGE_PIXELS - && brighterThanAlpha <= edge * PREMULTIPLIED_MAX_OUTLIER_SHARE; - } - - internal static void Unpremultiply(Color32[] pixels) - { - for (int i = 0; i < pixels.Length; i++) - { - byte alpha = pixels[i].a; - if (alpha == 0 || alpha == byte.MaxValue) continue; - pixels[i] = new Color32( - (byte)Math.Min(byte.MaxValue, pixels[i].r * byte.MaxValue / alpha), - (byte)Math.Min(byte.MaxValue, pixels[i].g * byte.MaxValue / alpha), - (byte)Math.Min(byte.MaxValue, pixels[i].b * byte.MaxValue / alpha), - alpha - ); - } - } - - internal static void BleedAlphaEdges(Color32[] pixels, int width, int height) - { - bool[] hasColour = new bool[pixels.Length]; - List frontier = new(); - for (int i = 0; i < pixels.Length; i++) - { - if (pixels[i].a <= INVISIBLE_ALPHA) continue; - hasColour[i] = true; - frontier.Add(i); - } - if (frontier.Count == 0 || frontier.Count == pixels.Length) return; - - for (int ring = 0; ring < ALPHA_BLEED_RINGS && frontier.Count > 0; ring++) - { - List nextFrontier = new(); - foreach (int index in frontier) - { - int x = index % width; - int y = index / width; - Color32 source = pixels[index]; - - for (int offsetY = -1; offsetY <= 1; offsetY++) - { - int neighbourY = y + offsetY; - if (neighbourY < 0 || neighbourY >= height) continue; - - for (int offsetX = -1; offsetX <= 1; offsetX++) - { - int neighbourX = x + offsetX; - if (neighbourX < 0 || neighbourX >= width) continue; - - int neighbour = neighbourY * width + neighbourX; - if (hasColour[neighbour]) continue; - - hasColour[neighbour] = true; - pixels[neighbour] = new Color32( - source.r, source.g, source.b, pixels[neighbour].a - ); - nextFrontier.Add(neighbour); - } - } - } - frontier = nextFrontier; - } - } - - /// Builds a sprite from raw byte data. - /// The raw byte data of the image. - /// The pivot point of the sprite. - /// The number of pixels per unit for the sprite. - /// The created sprite. - public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) - { - return BuildSpriteWithTexture(BuildTexture(data), pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); - } - - /// Builds a sprite from a texture. - /// The texture to create the sprite from. - /// The pivot point of the sprite. - /// The number of pixels per unit for the sprite. - /// The created sprite. - public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) - { - if (transformToOutline) texture = TransformToOutline(texture); - - if (gaussianBlurRadius != null) texture = ApplyGaussianBlur(texture, gaussianBlurRadius.Value); - - return Sprite.Create( - texture, - new(0, 0, texture.width, texture.height), - pivot ?? new(0.5f, 0.5f), - pixelsPerUnit ?? 2112f - ); ; - } - - public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSizeInPixels = 8, Color? color = null) - { - Plugin.logger.LogInfo("Transforming texture to outline..."); - if (color == null) - color = Color.white; - - int sourceWidthInPixels = sourceTexture.width; - int sourceHeightInPixels = sourceTexture.height; - int outputWidthInPixels = sourceWidthInPixels + borderSizeInPixels * 2; - int outputHeightInPixels = sourceHeightInPixels + borderSizeInPixels * 2; - - Color[] sourcePixels = sourceTexture.GetPixels(); - bool[] filledMask = new bool[outputWidthInPixels * outputHeightInPixels]; - int borderSquared = borderSizeInPixels * borderSizeInPixels; - - for (int pixelY = 0; pixelY < sourceHeightInPixels; pixelY++) - { - for (int pixelX = 0; pixelX < sourceWidthInPixels; pixelX++) - { - if (sourcePixels[pixelY * sourceWidthInPixels + pixelX].a <= 0.01f) continue; - - int centerX = pixelX + borderSizeInPixels; - int centerY = pixelY + borderSizeInPixels; - - for (int offsetY = -borderSizeInPixels; offsetY <= borderSizeInPixels; offsetY++) - { - for (int offsetX = -borderSizeInPixels; offsetX <= borderSizeInPixels; offsetX++) - { - if (offsetX * offsetX + offsetY * offsetY > borderSquared) continue; - - filledMask[(centerY + offsetY) * outputWidthInPixels + (centerX + offsetX)] = true; - } - } - } - } - - Color[] outputPixels = new Color[filledMask.Length]; - for (int pixelIndex = 0; pixelIndex < outputPixels.Length; pixelIndex++) - { - outputPixels[pixelIndex] = filledMask[pixelIndex] ? color.Value : Color.clear; - } - - Texture2D whiteSilhouetteTexture = new Texture2D(outputWidthInPixels, outputHeightInPixels, TextureFormat.RGBA32, false); - whiteSilhouetteTexture.SetPixels(outputPixels); - whiteSilhouetteTexture.Apply(); - return whiteSilhouetteTexture; - } - - private static float[] BuildGaussianKernelWeights(float sigma, int kernelRadiusInPixels) - { - float[] kernelWeights = new float[kernelRadiusInPixels * 2 + 1]; - float kernelWeightSum = 0f; - for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) - { - int distanceFromCenter = kernelIndex - kernelRadiusInPixels; - kernelWeights[kernelIndex] = MathF.Exp(-(distanceFromCenter * distanceFromCenter) / (2f * sigma * sigma)); - kernelWeightSum += kernelWeights[kernelIndex]; - } - for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) - { - kernelWeights[kernelIndex] /= kernelWeightSum; - } - return kernelWeights; - } - - private static byte ConvertUnitFloatToByte(float unitValue) - { - return (byte)Math.Clamp(unitValue * 255f + 0.5f, 0f, 255f); - } - - // basically ai generated as my bs was working, but 15 times slower - public static Texture2D ApplyGaussianBlur(Texture2D sourceTexture, float radius = 2f) - { - Plugin.logger.LogInfo($"Applying blur with radius {radius}..."); - int textureWidthInPixels = sourceTexture.width; - int textureHeightInPixels = sourceTexture.height; - - float sigma = Math.Max(radius / 2f, 0.01f); - int kernelRadiusInPixels = Math.Max(1, (int)MathF.Ceiling(sigma * 3f)); - float[] kernelWeights = BuildGaussianKernelWeights(sigma, kernelRadiusInPixels); - - Color32[] sourcePixels = sourceTexture.GetPixels32(); - int totalPixelCount = sourcePixels.Length; - const float byteToUnitFloat = 1f / 255f; - - float[] premultipliedChannels = new float[totalPixelCount * 4]; - for (int pixelIndex = 0; pixelIndex < totalPixelCount; pixelIndex++) - { - Color32 sourcePixel = sourcePixels[pixelIndex]; - float alpha = sourcePixel.a * byteToUnitFloat; - int channelOffset = pixelIndex * 4; - premultipliedChannels[channelOffset + 0] = sourcePixel.r * byteToUnitFloat * alpha; - premultipliedChannels[channelOffset + 1] = sourcePixel.g * byteToUnitFloat * alpha; - premultipliedChannels[channelOffset + 2] = sourcePixel.b * byteToUnitFloat * alpha; - premultipliedChannels[channelOffset + 3] = alpha; - } - - float[] horizontallyBlurredChannels = new float[premultipliedChannels.Length]; - Parallel.For(0, textureHeightInPixels, pixelY => - { - int rowStartPixelIndex = pixelY * textureWidthInPixels; - for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) - { - float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; - for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) - { - int sampleX = pixelX + kernelIndex - kernelRadiusInPixels; - if (sampleX < 0) sampleX = 0; - else if (sampleX >= textureWidthInPixels) sampleX = textureWidthInPixels - 1; - - int sampleOffset = (rowStartPixelIndex + sampleX) * 4; - float kernelWeight = kernelWeights[kernelIndex]; - accumulatedRed += premultipliedChannels[sampleOffset + 0] * kernelWeight; - accumulatedGreen += premultipliedChannels[sampleOffset + 1] * kernelWeight; - accumulatedBlue += premultipliedChannels[sampleOffset + 2] * kernelWeight; - accumulatedAlpha += premultipliedChannels[sampleOffset + 3] * kernelWeight; - } - int outputOffset = (rowStartPixelIndex + pixelX) * 4; - horizontallyBlurredChannels[outputOffset + 0] = accumulatedRed; - horizontallyBlurredChannels[outputOffset + 1] = accumulatedGreen; - horizontallyBlurredChannels[outputOffset + 2] = accumulatedBlue; - horizontallyBlurredChannels[outputOffset + 3] = accumulatedAlpha; - } - }); - - Color32[] blurredPixels = new Color32[totalPixelCount]; - Parallel.For(0, textureHeightInPixels, pixelY => - { - for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) - { - float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; - for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) - { - int sampleY = pixelY + kernelIndex - kernelRadiusInPixels; - if (sampleY < 0) sampleY = 0; - else if (sampleY >= textureHeightInPixels) sampleY = textureHeightInPixels - 1; - - int sampleOffset = (sampleY * textureWidthInPixels + pixelX) * 4; - float kernelWeight = kernelWeights[kernelIndex]; - accumulatedRed += horizontallyBlurredChannels[sampleOffset + 0] * kernelWeight; - accumulatedGreen += horizontallyBlurredChannels[sampleOffset + 1] * kernelWeight; - accumulatedBlue += horizontallyBlurredChannels[sampleOffset + 2] * kernelWeight; - accumulatedAlpha += horizontallyBlurredChannels[sampleOffset + 3] * kernelWeight; - } - - Color32 blurredPixel = default; - if (accumulatedAlpha > 0.0001f) - { - blurredPixel.r = ConvertUnitFloatToByte(accumulatedRed / accumulatedAlpha); - blurredPixel.g = ConvertUnitFloatToByte(accumulatedGreen / accumulatedAlpha); - blurredPixel.b = ConvertUnitFloatToByte(accumulatedBlue / accumulatedAlpha); - blurredPixel.a = ConvertUnitFloatToByte(accumulatedAlpha); - } - blurredPixels[pixelY * textureWidthInPixels + pixelX] = blurredPixel; - } - }); - - Texture2D blurredTexture = new Texture2D(textureWidthInPixels, textureHeightInPixels, TextureFormat.RGBA32, false); - blurredTexture.SetPixels32(blurredPixels); - blurredTexture.Apply(); - return blurredTexture; - } - - internal static List> pendingInnerOriginSpriteInfos = new(); - - private static Vector2 GetPivotPreset(string spriteName) - { - return spriteName.Split("_")[0] switch - { - "field" => new Vector2(0.5f, 0.0f), - "mountain" => new Vector2(0.5f, -0.375f), - _ => new Vector2(0.5f, 0.5f), - }; - } - - internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, string spriteName, Sprite sprite) - { - Plugin.logger.LogInfo($"Registering sprite {spriteName}"); - spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); - spriteAtlasManager.cachedSprites["Heads"][spriteName] = sprite; - Registry.sprites[spriteName] = sprite; - } - - // Runs early: only touches your own textures, nothing from SpriteAtlasManager's lookup state. - public static void CreateSprites() - { - Plugin.logger.LogInfo($"Creating sprites with outer origin..."); - pendingInnerOriginSpriteInfos.Clear(); - - SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); - const float defaultPixelsPerUnit = 2112f; - - foreach (KeyValuePair spriteInfoPair in Registry.spriteInfos) - { - string spriteName = spriteInfoPair.Key; - SpriteInfo spriteInfo = spriteInfoPair.Value; - - bool isInnerOrigin = spriteInfo.spriteOrigin != null - && spriteInfo.spriteOrigin.originType == OriginType.Inner; - - if (isInnerOrigin) - { - pendingInnerOriginSpriteInfos.Add(spriteInfoPair); - continue; - } - - KeyValuePair textureEntry; - if (!Registry.textures.TryGetValue(spriteName, out textureEntry)) // search texture - { - if (spriteInfo.spriteOrigin == null || - spriteInfo.spriteOrigin.originType != OriginType.Outer || - spriteInfo.spriteOrigin.name == null || - !Registry.textures.TryGetValue(spriteInfo.spriteOrigin.name, out textureEntry)) // search texture in outer sprite origin - { - continue; - } - } - - - Vector2 pivot = spriteInfo.pivot ?? GetPivotPreset(spriteName); - float pixelsPerUnit = spriteInfo.pixelsPerUnit ?? defaultPixelsPerUnit; - bool transformToOutline = spriteInfo.transformToOutline; - float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; - - Sprite sprite = BuildSpriteWithTexture(textureEntry.Key, pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); - Registry.textures[spriteName] = new KeyValuePair(textureEntry.Key, true); - RegisterSprite(spriteAtlasManager, spriteName, sprite); - } - - foreach (KeyValuePair> texturePair in Registry.textures) - { - if (texturePair.Value.Value) - { - continue; - } - - string spriteName = texturePair.Key; - Sprite sprite = BuildSpriteWithTexture(texturePair.Value.Key, GetPivotPreset(spriteName), defaultPixelsPerUnit); - RegisterSprite(spriteAtlasManager, spriteName, sprite); - } - } - - internal static (byte[], SpriteInfo) SpriteToPng(Sprite sprite) - { - Texture2D bakedTexture = BakeSpriteToTexture(sprite); - - byte[] pngBytes = ImageConversion.EncodeToPNG(bakedTexture); - UnityEngine.Object.Destroy(bakedTexture); - - Vector2 normalizedPivot = GetNormalizedPivot(sprite); - - return (pngBytes, new SpriteInfo(sprite.pixelsPerUnit, normalizedPivot)); - } - - private static Vector2 GetNormalizedPivot(Sprite sourceSprite) - { - return new Vector2( - sourceSprite.pivot.x / sourceSprite.rect.width, - sourceSprite.pivot.y / sourceSprite.rect.height - ); - } - - private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) - { - Texture2D atlasTexture = sourceSprite.texture; - int spriteWidth = (int)sourceSprite.rect.width; - int spriteHeight = (int)sourceSprite.rect.height; - float sourcePixelsPerUnit = sourceSprite.pixelsPerUnit; - Vector2 sourcePivotInPixels = sourceSprite.pivot; - - var meshVertices = sourceSprite.vertices; - var meshUvs = sourceSprite.uv; - var meshTriangles = sourceSprite.triangles; - - RenderTexture renderTexture = RenderTexture.GetTemporary( - spriteWidth, spriteHeight, 0, - RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); - RenderTexture previousActiveRenderTexture = RenderTexture.active; - RenderTexture.active = renderTexture; - GL.Clear(true, true, Color.clear); - - Material spriteMaterial = new Material(Shader.Find("Sprites/Default")); - spriteMaterial.mainTexture = atlasTexture; - spriteMaterial.SetPass(0); - - GL.PushMatrix(); - GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); - GL.Begin(GL.TRIANGLES); - for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) - { - int vertexIndex = meshTriangles[triangleCornerIndex]; - Vector2 uv = meshUvs[vertexIndex]; - Vector2 vertex = meshVertices[vertexIndex]; - - GL.TexCoord(new Vector3(uv.x, uv.y, 0)); - GL.Vertex3( - vertex.x * sourcePixelsPerUnit + sourcePivotInPixels.x, - vertex.y * sourcePixelsPerUnit + sourcePivotInPixels.y, - 0); - } - GL.End(); - GL.PopMatrix(); - - Texture2D bakedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); - bakedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); - - Color32[] bakedPixels = bakedTexture.GetPixels32(); - Unpremultiply(bakedPixels); - BleedAlphaEdges(bakedPixels, spriteWidth, spriteHeight); - bakedTexture.SetPixels32(bakedPixels); - - bakedTexture.Apply(); - bakedTexture.wrapMode = TextureWrapMode.Clamp; - - RenderTexture.active = previousActiveRenderTexture; - RenderTexture.ReleaseTemporary(renderTexture); - UnityEngine.Object.Destroy(spriteMaterial); - - return bakedTexture; - } - - public static void CreateInnerOriginSprites() - { - Plugin.logger.LogInfo($"Creating sprites with inner origin..."); - SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); - - foreach (KeyValuePair spriteInfoPair in pendingInnerOriginSpriteInfos) - { - string spriteName = spriteInfoPair.Key; - SpriteInfo spriteInfo = spriteInfoPair.Value; - - Sprite originalSprite = spriteAtlasManager - .DoSpriteLookup(spriteInfo.spriteOrigin!.name, TribeType.None, SkinType.Default) - .sprite; - - if (originalSprite == null) - { - Plugin.logger.LogWarning($"Inner origin sprite '{spriteInfo.spriteOrigin.name}' not found for '{spriteName}'"); - continue; - } - - bool hasPivotOverride = spriteInfo.pivot != null; - bool hasPixelsPerUnitOverride = spriteInfo.pixelsPerUnit != null; - - Sprite sprite = originalSprite; - - if (hasPivotOverride || hasPixelsPerUnitOverride) - { - Vector2 normalizedOriginalPivot = new( - originalSprite.pivot.x / originalSprite.rect.width, - originalSprite.pivot.y / originalSprite.rect.height - ); - - Vector2 finalPivot = hasPivotOverride ? spriteInfo.pivot!.Value : normalizedOriginalPivot; - float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteInfo.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; - bool transformToOutline = spriteInfo.transformToOutline; - float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; - - Texture2D bakedTexture = BakeSpriteToTexture(originalSprite); - sprite = BuildSpriteWithTexture(bakedTexture, finalPivot, finalPixelsPerUnit, transformToOutline, gaussianBlurRadius); - sprite.name = spriteName; - } - - RegisterSprite(spriteAtlasManager, spriteName, sprite); - } - - pendingInnerOriginSpriteInfos.Clear(); - } - - /// Initializes the Visual manager by patching the necessary methods. - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(Visual)); - } + /// Shows a basic popup with a custom width. + public static void ShowSetWidth(this BasicPopupLegacy self, int width) + { + basicPopupWidths[self.GetInstanceID()] = new(self, 0f, width); + self.Show(); + } + + /// Shows a basic popup sized to a share of the usable screen width. + public static void ShowSetWidth(this BasicPopupLegacy self, float share, float maximum) + { + basicPopupWidths[self.GetInstanceID()] = new(self, share, maximum); + self.Show(); + } + + #endregion + + internal static BasicPopupLegacy GetBasicPopupLegacy() + { + WhatsNewPopup whatsNewPopup = PopupManager.GetWhatsNewPopup(); + BasicPopupLegacy original = PopupManager.instance.popupPrefabs[BASIC_POPUP_LEGACY_ID].Cast(); + BasicPopupLegacy basicPopupLegacy = UnityEngine.Object.Instantiate(original, PopupManager.instance.transform); + basicPopupLegacy.buttonContainer = GameObject.Instantiate(whatsNewPopup.buttonContainer, basicPopupLegacy.transform); + basicPopupLegacy.popupId = "basicPopupLegacy"; + basicPopupLegacy.popupManager = PopupManager.instance; + basicPopupLegacy.Init(); + basicPopupLegacy.identifier = null; + basicPopupLegacy.rectTransform.SetAsLastSibling(); + return basicPopupLegacy; + } + + public static Texture2D BuildTexture(byte[] data) + { + Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); + texture.LoadImage(data); + Color32[] pixels = texture.GetPixels32(); + if (LooksPremultiplied(pixels)) + Unpremultiply(pixels); + BleedAlphaEdges(pixels, texture.width, texture.height); + texture.SetPixels32(pixels); + texture.filterMode = FilterMode.Trilinear; + texture.wrapMode = TextureWrapMode.Clamp; + texture.Apply(); + return texture; + } + + internal static bool LooksPremultiplied(Color32[] pixels) + { + int edge = 0; + int brighterThanAlpha = 0; + foreach (Color32 pixel in pixels) + { + if (pixel.a == 0 || pixel.a == 255) continue; + edge++; + if (Math.Max(pixel.r, Math.Max(pixel.g, pixel.b)) > pixel.a) + brighterThanAlpha++; + } + return edge >= PREMULTIPLIED_MIN_EDGE_PIXELS + && brighterThanAlpha <= edge * PREMULTIPLIED_MAX_OUTLIER_SHARE; + } + + internal static void Unpremultiply(Color32[] pixels) + { + for (int i = 0; i < pixels.Length; i++) + { + byte alpha = pixels[i].a; + if (alpha == 0 || alpha == byte.MaxValue) continue; + pixels[i] = new Color32( + (byte)Math.Min(byte.MaxValue, pixels[i].r * byte.MaxValue / alpha), + (byte)Math.Min(byte.MaxValue, pixels[i].g * byte.MaxValue / alpha), + (byte)Math.Min(byte.MaxValue, pixels[i].b * byte.MaxValue / alpha), + alpha + ); + } + } + + internal static void BleedAlphaEdges(Color32[] pixels, int width, int height) + { + bool[] hasColour = new bool[pixels.Length]; + List frontier = new(); + for (int i = 0; i < pixels.Length; i++) + { + if (pixels[i].a <= INVISIBLE_ALPHA) continue; + hasColour[i] = true; + frontier.Add(i); + } + if (frontier.Count == 0 || frontier.Count == pixels.Length) return; + + for (int ring = 0; ring < ALPHA_BLEED_RINGS && frontier.Count > 0; ring++) + { + List nextFrontier = new(); + foreach (int index in frontier) + { + int x = index % width; + int y = index / width; + Color32 source = pixels[index]; + + for (int offsetY = -1; offsetY <= 1; offsetY++) + { + int neighbourY = y + offsetY; + if (neighbourY < 0 || neighbourY >= height) continue; + + for (int offsetX = -1; offsetX <= 1; offsetX++) + { + int neighbourX = x + offsetX; + if (neighbourX < 0 || neighbourX >= width) continue; + + int neighbour = neighbourY * width + neighbourX; + if (hasColour[neighbour]) continue; + + hasColour[neighbour] = true; + pixels[neighbour] = new Color32( + source.r, source.g, source.b, pixels[neighbour].a + ); + nextFrontier.Add(neighbour); + } + } + } + frontier = nextFrontier; + } + } + + /// Builds a sprite from raw byte data. + /// The raw byte data of the image. + /// The pivot point of the sprite. + /// The number of pixels per unit for the sprite. + /// The created sprite. + public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) + { + return BuildSpriteWithTexture(BuildTexture(data), pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); + } + + /// Builds a sprite from a texture. + /// The texture to create the sprite from. + /// The pivot point of the sprite. + /// The number of pixels per unit for the sprite. + /// The created sprite. + public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) + { + if (transformToOutline) texture = TransformToOutline(texture); + + if (gaussianBlurRadius != null) texture = ApplyGaussianBlur(texture, gaussianBlurRadius.Value); + + return Sprite.Create( + texture, + new(0, 0, texture.width, texture.height), + pivot ?? new(0.5f, 0.5f), + pixelsPerUnit ?? 2112f + ); ; + } + + public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSizeInPixels = 8, Color? color = null) + { + Plugin.logger.LogInfo("Transforming texture to outline..."); + if (color == null) + color = Color.white; + + int sourceWidthInPixels = sourceTexture.width; + int sourceHeightInPixels = sourceTexture.height; + int outputWidthInPixels = sourceWidthInPixels + borderSizeInPixels * 2; + int outputHeightInPixels = sourceHeightInPixels + borderSizeInPixels * 2; + + Color[] sourcePixels = sourceTexture.GetPixels(); + bool[] filledMask = new bool[outputWidthInPixels * outputHeightInPixels]; + int borderSquared = borderSizeInPixels * borderSizeInPixels; + + for (int pixelY = 0; pixelY < sourceHeightInPixels; pixelY++) + { + for (int pixelX = 0; pixelX < sourceWidthInPixels; pixelX++) + { + if (sourcePixels[pixelY * sourceWidthInPixels + pixelX].a <= 0.01f) continue; + + int centerX = pixelX + borderSizeInPixels; + int centerY = pixelY + borderSizeInPixels; + + for (int offsetY = -borderSizeInPixels; offsetY <= borderSizeInPixels; offsetY++) + { + for (int offsetX = -borderSizeInPixels; offsetX <= borderSizeInPixels; offsetX++) + { + if (offsetX * offsetX + offsetY * offsetY > borderSquared) continue; + + filledMask[(centerY + offsetY) * outputWidthInPixels + (centerX + offsetX)] = true; + } + } + } + } + + Color[] outputPixels = new Color[filledMask.Length]; + for (int pixelIndex = 0; pixelIndex < outputPixels.Length; pixelIndex++) + { + outputPixels[pixelIndex] = filledMask[pixelIndex] ? color.Value : Color.clear; + } + + Texture2D whiteSilhouetteTexture = new Texture2D(outputWidthInPixels, outputHeightInPixels, TextureFormat.RGBA32, false); + whiteSilhouetteTexture.SetPixels(outputPixels); + whiteSilhouetteTexture.Apply(); + return whiteSilhouetteTexture; + } + + private static float[] BuildGaussianKernelWeights(float sigma, int kernelRadiusInPixels) + { + float[] kernelWeights = new float[kernelRadiusInPixels * 2 + 1]; + float kernelWeightSum = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int distanceFromCenter = kernelIndex - kernelRadiusInPixels; + kernelWeights[kernelIndex] = MathF.Exp(-(distanceFromCenter * distanceFromCenter) / (2f * sigma * sigma)); + kernelWeightSum += kernelWeights[kernelIndex]; + } + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + kernelWeights[kernelIndex] /= kernelWeightSum; + } + return kernelWeights; + } + + private static byte ConvertUnitFloatToByte(float unitValue) + { + return (byte)Math.Clamp(unitValue * 255f + 0.5f, 0f, 255f); + } + + // basically ai generated as my bs was working, but 15 times slower + public static Texture2D ApplyGaussianBlur(Texture2D sourceTexture, float radius = 2f) + { + Plugin.logger.LogInfo($"Applying blur with radius {radius}..."); + int textureWidthInPixels = sourceTexture.width; + int textureHeightInPixels = sourceTexture.height; + + float sigma = Math.Max(radius / 2f, 0.01f); + int kernelRadiusInPixels = Math.Max(1, (int)MathF.Ceiling(sigma * 3f)); + float[] kernelWeights = BuildGaussianKernelWeights(sigma, kernelRadiusInPixels); + + Color32[] sourcePixels = sourceTexture.GetPixels32(); + int totalPixelCount = sourcePixels.Length; + const float byteToUnitFloat = 1f / 255f; + + float[] premultipliedChannels = new float[totalPixelCount * 4]; + for (int pixelIndex = 0; pixelIndex < totalPixelCount; pixelIndex++) + { + Color32 sourcePixel = sourcePixels[pixelIndex]; + float alpha = sourcePixel.a * byteToUnitFloat; + int channelOffset = pixelIndex * 4; + premultipliedChannels[channelOffset + 0] = sourcePixel.r * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 1] = sourcePixel.g * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 2] = sourcePixel.b * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 3] = alpha; + } + + float[] horizontallyBlurredChannels = new float[premultipliedChannels.Length]; + Parallel.For(0, textureHeightInPixels, pixelY => + { + int rowStartPixelIndex = pixelY * textureWidthInPixels; + for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) + { + float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int sampleX = pixelX + kernelIndex - kernelRadiusInPixels; + if (sampleX < 0) sampleX = 0; + else if (sampleX >= textureWidthInPixels) sampleX = textureWidthInPixels - 1; + + int sampleOffset = (rowStartPixelIndex + sampleX) * 4; + float kernelWeight = kernelWeights[kernelIndex]; + accumulatedRed += premultipliedChannels[sampleOffset + 0] * kernelWeight; + accumulatedGreen += premultipliedChannels[sampleOffset + 1] * kernelWeight; + accumulatedBlue += premultipliedChannels[sampleOffset + 2] * kernelWeight; + accumulatedAlpha += premultipliedChannels[sampleOffset + 3] * kernelWeight; + } + int outputOffset = (rowStartPixelIndex + pixelX) * 4; + horizontallyBlurredChannels[outputOffset + 0] = accumulatedRed; + horizontallyBlurredChannels[outputOffset + 1] = accumulatedGreen; + horizontallyBlurredChannels[outputOffset + 2] = accumulatedBlue; + horizontallyBlurredChannels[outputOffset + 3] = accumulatedAlpha; + } + }); + + Color32[] blurredPixels = new Color32[totalPixelCount]; + Parallel.For(0, textureHeightInPixels, pixelY => + { + for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) + { + float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int sampleY = pixelY + kernelIndex - kernelRadiusInPixels; + if (sampleY < 0) sampleY = 0; + else if (sampleY >= textureHeightInPixels) sampleY = textureHeightInPixels - 1; + + int sampleOffset = (sampleY * textureWidthInPixels + pixelX) * 4; + float kernelWeight = kernelWeights[kernelIndex]; + accumulatedRed += horizontallyBlurredChannels[sampleOffset + 0] * kernelWeight; + accumulatedGreen += horizontallyBlurredChannels[sampleOffset + 1] * kernelWeight; + accumulatedBlue += horizontallyBlurredChannels[sampleOffset + 2] * kernelWeight; + accumulatedAlpha += horizontallyBlurredChannels[sampleOffset + 3] * kernelWeight; + } + + Color32 blurredPixel = default; + if (accumulatedAlpha > 0.0001f) + { + blurredPixel.r = ConvertUnitFloatToByte(accumulatedRed / accumulatedAlpha); + blurredPixel.g = ConvertUnitFloatToByte(accumulatedGreen / accumulatedAlpha); + blurredPixel.b = ConvertUnitFloatToByte(accumulatedBlue / accumulatedAlpha); + blurredPixel.a = ConvertUnitFloatToByte(accumulatedAlpha); + } + blurredPixels[pixelY * textureWidthInPixels + pixelX] = blurredPixel; + } + }); + + Texture2D blurredTexture = new Texture2D(textureWidthInPixels, textureHeightInPixels, TextureFormat.RGBA32, false); + blurredTexture.SetPixels32(blurredPixels); + blurredTexture.Apply(); + return blurredTexture; + } + + internal static List> pendingInnerOriginSpriteInfos = new(); + + private static Vector2 GetPivotPreset(string spriteName) + { + return spriteName.Split("_")[0] switch + { + "field" => new Vector2(0.5f, 0.0f), + "mountain" => new Vector2(0.5f, -0.375f), + _ => new Vector2(0.5f, 0.5f), + }; + } + + internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, string spriteName, Sprite sprite) + { + Plugin.logger.LogInfo($"Registering sprite {spriteName}"); + spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); + spriteAtlasManager.cachedSprites["Heads"][spriteName] = sprite; + Registry.sprites[spriteName] = sprite; + } + + // Runs early: only touches your own textures, nothing from SpriteAtlasManager's lookup state. + public static void CreateSprites() + { + Plugin.logger.LogInfo($"Creating sprites with outer origin..."); + pendingInnerOriginSpriteInfos.Clear(); + + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + const float defaultPixelsPerUnit = 2112f; + + foreach (KeyValuePair spriteInfoPair in Registry.spriteInfos) + { + string spriteName = spriteInfoPair.Key; + SpriteInfo spriteInfo = spriteInfoPair.Value; + + bool isInnerOrigin = spriteInfo.spriteOrigin != null + && spriteInfo.spriteOrigin.originType == OriginType.Inner; + + if (isInnerOrigin) + { + pendingInnerOriginSpriteInfos.Add(spriteInfoPair); + continue; + } + + KeyValuePair textureEntry; + if (!Registry.textures.TryGetValue(spriteName, out textureEntry)) // search texture + { + if (spriteInfo.spriteOrigin == null || + spriteInfo.spriteOrigin.originType != OriginType.Outer || + spriteInfo.spriteOrigin.name == null || + !Registry.textures.TryGetValue(spriteInfo.spriteOrigin.name, out textureEntry)) // search texture in outer sprite origin + { + continue; + } + } + + + Vector2 pivot = spriteInfo.pivot ?? GetPivotPreset(spriteName); + float pixelsPerUnit = spriteInfo.pixelsPerUnit ?? defaultPixelsPerUnit; + bool transformToOutline = spriteInfo.transformToOutline; + float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; + + Sprite sprite = BuildSpriteWithTexture(textureEntry.Key, pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); + Registry.textures[spriteName] = new KeyValuePair(textureEntry.Key, true); + RegisterSprite(spriteAtlasManager, spriteName, sprite); + } + + foreach (KeyValuePair> texturePair in Registry.textures) + { + if (texturePair.Value.Value) + { + continue; + } + + string spriteName = texturePair.Key; + Sprite sprite = BuildSpriteWithTexture(texturePair.Value.Key, GetPivotPreset(spriteName), defaultPixelsPerUnit); + RegisterSprite(spriteAtlasManager, spriteName, sprite); + } + } + + internal static (byte[], SpriteInfo) SpriteToPng(Sprite sprite) + { + Texture2D bakedTexture = BakeSpriteToTexture(sprite); + + byte[] pngBytes = ImageConversion.EncodeToPNG(bakedTexture); + UnityEngine.Object.Destroy(bakedTexture); + + Vector2 normalizedPivot = GetNormalizedPivot(sprite); + + return (pngBytes, new SpriteInfo(sprite.pixelsPerUnit, normalizedPivot)); + } + + private static Vector2 GetNormalizedPivot(Sprite sourceSprite) + { + return new Vector2( + sourceSprite.pivot.x / sourceSprite.rect.width, + sourceSprite.pivot.y / sourceSprite.rect.height + ); + } + + private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) + { + Texture2D atlasTexture = sourceSprite.texture; + int spriteWidth = (int)sourceSprite.rect.width; + int spriteHeight = (int)sourceSprite.rect.height; + float sourcePixelsPerUnit = sourceSprite.pixelsPerUnit; + Vector2 sourcePivotInPixels = sourceSprite.pivot; + + var meshVertices = sourceSprite.vertices; + var meshUvs = sourceSprite.uv; + var meshTriangles = sourceSprite.triangles; + + RenderTexture renderTexture = RenderTexture.GetTemporary( + spriteWidth, spriteHeight, 0, + RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); + RenderTexture previousActiveRenderTexture = RenderTexture.active; + RenderTexture.active = renderTexture; + GL.Clear(true, true, Color.clear); + + Material spriteMaterial = new Material(Shader.Find("Sprites/Default")); + spriteMaterial.mainTexture = atlasTexture; + spriteMaterial.SetPass(0); + + GL.PushMatrix(); + GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); + GL.Begin(GL.TRIANGLES); + for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) + { + int vertexIndex = meshTriangles[triangleCornerIndex]; + Vector2 uv = meshUvs[vertexIndex]; + Vector2 vertex = meshVertices[vertexIndex]; + + GL.TexCoord(new Vector3(uv.x, uv.y, 0)); + GL.Vertex3( + vertex.x * sourcePixelsPerUnit + sourcePivotInPixels.x, + vertex.y * sourcePixelsPerUnit + sourcePivotInPixels.y, + 0); + } + GL.End(); + GL.PopMatrix(); + + Texture2D bakedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); + bakedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); + + Color32[] bakedPixels = bakedTexture.GetPixels32(); + Unpremultiply(bakedPixels); + BleedAlphaEdges(bakedPixels, spriteWidth, spriteHeight); + bakedTexture.SetPixels32(bakedPixels); + + bakedTexture.Apply(); + bakedTexture.wrapMode = TextureWrapMode.Clamp; + + RenderTexture.active = previousActiveRenderTexture; + RenderTexture.ReleaseTemporary(renderTexture); + UnityEngine.Object.Destroy(spriteMaterial); + + return bakedTexture; + } + + public static void CreateInnerOriginSprites() + { + Plugin.logger.LogInfo($"Creating sprites with inner origin..."); + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + + foreach (KeyValuePair spriteInfoPair in pendingInnerOriginSpriteInfos) + { + string spriteName = spriteInfoPair.Key; + SpriteInfo spriteInfo = spriteInfoPair.Value; + + Sprite originalSprite = spriteAtlasManager + .DoSpriteLookup(spriteInfo.spriteOrigin!.name, TribeType.None, SkinType.Default) + .sprite; + + if (originalSprite == null) + { + Plugin.logger.LogWarning($"Inner origin sprite '{spriteInfo.spriteOrigin.name}' not found for '{spriteName}'"); + continue; + } + + bool hasPivotOverride = spriteInfo.pivot != null; + bool hasPixelsPerUnitOverride = spriteInfo.pixelsPerUnit != null; + + Sprite sprite = originalSprite; + + if (hasPivotOverride || hasPixelsPerUnitOverride) + { + Vector2 normalizedOriginalPivot = new( + originalSprite.pivot.x / originalSprite.rect.width, + originalSprite.pivot.y / originalSprite.rect.height + ); + + Vector2 finalPivot = hasPivotOverride ? spriteInfo.pivot!.Value : normalizedOriginalPivot; + float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteInfo.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; + bool transformToOutline = spriteInfo.transformToOutline; + float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; + + Texture2D bakedTexture = BakeSpriteToTexture(originalSprite); + sprite = BuildSpriteWithTexture(bakedTexture, finalPivot, finalPixelsPerUnit, transformToOutline, gaussianBlurRadius); + sprite.name = spriteName; + } + + RegisterSprite(spriteAtlasManager, spriteName, sprite); + } + + pendingInnerOriginSpriteInfos.Clear(); + } + + /// Initializes the Visual manager by patching the necessary methods. + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Visual)); + } } diff --git a/src/Mod.cs b/src/Mod.cs index 684d035..3d36389 100644 --- a/src/Mod.cs +++ b/src/Mod.cs @@ -5,119 +5,119 @@ namespace PolyMod; /// public class Mod { - /// - /// Represents a dependency of a mod. - /// - /// The unique identifier of the dependency. - /// The minimum compatible version of the dependency, or null for no minimum. - /// The maximum compatible version of the dependency, or null for no maximum. - /// Whether the dependency is required for the mod to function. - public record Dependency(string id, Version? min, Version? max, bool required = true); + /// + /// Represents a dependency of a mod. + /// + /// The unique identifier of the dependency. + /// The minimum compatible version of the dependency, or null for no minimum. + /// The maximum compatible version of the dependency, or null for no maximum. + /// Whether the dependency is required for the mod to function. + public record Dependency(string id, Version? min, Version? max, bool required = true); - /// - /// Represents the manifest of a mod, containing metadata. - /// - /// The unique identifier of the mod. - /// The name of the mod. - /// A description of the mod. - /// The version of the mod. - /// The authors of the mod. - /// The dependencies of the mod. - /// Whether the mod is client-side only. - public record Manifest(string id, string? name, string? description, Version version, string[] authors, Dependency[]? dependencies, bool client = false); + /// + /// Represents the manifest of a mod, containing metadata. + /// + /// The unique identifier of the mod. + /// The name of the mod. + /// A description of the mod. + /// The version of the mod. + /// The authors of the mod. + /// The dependencies of the mod. + /// Whether the mod is client-side only. + public record Manifest(string id, string? name, string? description, Version version, string[] authors, Dependency[]? dependencies, bool client = false); - /// - /// Represents a file included in a mod. - /// - /// The name of the file. - /// The content of the file as a byte array. - public record File(string name, byte[] bytes); + /// + /// Represents a file included in a mod. + /// + /// The name of the file. + /// The content of the file as a byte array. + public record File(string name, byte[] bytes); - /// - /// Represents the loading status of a mod. - /// - public enum Status - { - /// - /// The mod was loaded successfully. - /// - Success, - /// - /// An error occurred while loading the mod. - /// - Error, - /// - /// The mod's dependencies were not satisfied. - /// - DependenciesUnsatisfied, - } + /// + /// Represents the loading status of a mod. + /// + public enum Status + { + /// + /// The mod was loaded successfully. + /// + Success, + /// + /// An error occurred while loading the mod. + /// + Error, + /// + /// The mod's dependencies were not satisfied. + /// + DependenciesUnsatisfied, + } - /// - /// The unique identifier of the mod. - /// - public string id; + /// + /// The unique identifier of the mod. + /// + public string id; - /// - /// The name of the mod. - /// - public string? name; + /// + /// The name of the mod. + /// + public string? name; - /// - /// A description of the mod. - /// - public string? description; + /// + /// A description of the mod. + /// + public string? description; - /// - /// The version of the mod. - /// - public Version version; + /// + /// The version of the mod. + /// + public Version version; - /// - /// The authors of the mod. - /// - public string[] authors; + /// + /// The authors of the mod. + /// + public string[] authors; - /// - /// The dependencies of the mod. - /// - public Dependency[]? dependencies; + /// + /// The dependencies of the mod. + /// + public Dependency[]? dependencies; - /// - /// Whether the mod is client-side only. - /// - public bool client; + /// + /// Whether the mod is client-side only. + /// + public bool client; - /// - /// The loading status of the mod. - /// - public Status status; + /// + /// The loading status of the mod. + /// + public Status status; - /// - /// The files included in the mod. - /// - public List files; + /// + /// The files included in the mod. + /// + public List files; - /// - /// The checksum of the mod, derived from its id, version and file contents. - /// - public string checksum = string.Empty; + /// + /// The checksum of the mod, derived from its id, version and file contents. + /// + public string checksum = string.Empty; - /// - /// Initializes a new instance of the class. - /// - /// The manifest of the mod. - /// The loading status of the mod. - /// The files included in the mod. - public Mod(Manifest manifest, Status status, List files) - { - id = manifest.id; - name = manifest.name ?? manifest.id; - description = manifest.description; - version = manifest.version; - authors = manifest.authors; - dependencies = manifest.dependencies; - client = manifest.client; - this.status = status; - this.files = files; - } + /// + /// Initializes a new instance of the class. + /// + /// The manifest of the mod. + /// The loading status of the mod. + /// The files included in the mod. + public Mod(Manifest manifest, Status status, List files) + { + id = manifest.id; + name = manifest.name ?? manifest.id; + description = manifest.description; + version = manifest.version; + authors = manifest.authors; + dependencies = manifest.dependencies; + client = manifest.client; + this.status = status; + this.files = files; + } } diff --git a/src/NullableFix.cs b/src/NullableFix.cs index 6048dd2..1c7e549 100644 --- a/src/NullableFix.cs +++ b/src/NullableFix.cs @@ -2,48 +2,48 @@ // verify whether it is needed at all bruv, i tested one time quickly and it easily compiled namespace System.Runtime.CompilerServices { - /// - /// A polyfill for the Nullable attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] - public sealed class NullableAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The nullable flags. - public NullableAttribute(byte b) { } + /// + /// A polyfill for the Nullable attribute, which is used by the compiler for nullable reference type analysis. + /// + [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] + public sealed class NullableAttribute : System.Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The nullable flags. + public NullableAttribute(byte b) { } - /// - /// Initializes a new instance of the class. - /// - /// The nullable flags. - public NullableAttribute(byte[] b) { } - } + /// + /// Initializes a new instance of the class. + /// + /// The nullable flags. + public NullableAttribute(byte[] b) { } + } - /// - /// A polyfill for the NullableContext attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false)] - public sealed class NullableContextAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The nullable context flags. - public NullableContextAttribute(byte b) { } - } + /// + /// A polyfill for the NullableContext attribute, which is used by the compiler for nullable reference type analysis. + /// + [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false)] + public sealed class NullableContextAttribute : System.Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The nullable context flags. + public NullableContextAttribute(byte b) { } + } - /// - /// A polyfill for the NullablePublicOnly attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.Module)] - public sealed class NullablePublicOnlyAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// Whether to apply nullable analysis to public members only. - public NullablePublicOnlyAttribute(bool b) { } - } + /// + /// A polyfill for the NullablePublicOnly attribute, which is used by the compiler for nullable reference type analysis. + /// + [System.AttributeUsage(System.AttributeTargets.Module)] + public sealed class NullablePublicOnlyAttribute : System.Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// Whether to apply nullable analysis to public members only. + public NullablePublicOnlyAttribute(bool b) { } + } } diff --git a/src/Plugin.cs b/src/Plugin.cs index 74f7813..1e854e2 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -14,214 +14,214 @@ namespace PolyMod; [BepInPlugin("com.polymod", "PolyMod", VERSION)] public partial class Plugin : BepInEx.Unity.IL2CPP.BasePlugin { - internal static string? Token { get; set; } - internal static bool ValidLaunch { get; set; } = false; - internal static bool Disabled { get; set; } = false; - - /// - /// Represents the configuration for PolyMod. - /// - /// Whether to enable debug mode. - internal record PolyConfig( - bool debug = false, - bool showCoordinates = false, - bool allowUnsafeIndexes = false, - string overrideDeviceId = "" - ) - { - public List disabledMods { get; init; } = new(); - }; - - /// - /// The starting index for automatically assigned IDs. - /// - internal const int AUTOIDX_STARTS_FROM = 1000; - - /// - /// The key used to store the last version for which the incompatibility warning was shown. - /// - internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY - = "INCOMPATIBILITY_WARNING_LAST_VERSION"; - - /// - /// The prefix of the player prefs keys holding the mod checksum a saved game was created with. - /// - internal const string STATE_CHECKSUM_KEY_PREFIX = "POLYMOD_STATE_CHECKSUM_"; - - internal const int LAUNCH_DATA_TIMEOUT = 2000; - - /// - /// The base path for PolyMod files. - /// - public static readonly string BASE_PATH = Path.Combine(BepInEx.Paths.BepInExRootPath, ".."); - - /// - /// The path to the mods directory. - /// - public static readonly string MODS_PATH = Path.Combine(BASE_PATH, "Mods"); - - /// - /// The path to the directory where game data is dumped. - /// - public static readonly string DUMPED_DATA_PATH = Path.Combine(BASE_PATH, "DumpedData"); - - /// - /// The path to the directory where localization is dumped. - /// - public static readonly string LOGIC_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Logic"); - - /// - /// The path to the directory where gameLogicData and avatarData are dumped. - /// - public static readonly string LOCALIZATION_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Localization"); - - /// - /// The path to the directory where sprites and sprite infos are dumped. - /// - public static readonly string SPRITES_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Sprites"); - - /// - /// The path to the directory where prefabs datas are dumped. - /// - public static readonly string PREFABS_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Prefabs"); - - /// - /// The path to the PolyMod configuration file. - /// - internal static readonly string CONFIG_PATH = Path.Combine(BASE_PATH, "PolyMod.json"); - - /// - /// The path to the checksum file. - /// - internal static readonly string CHECKSUM_PATH - = Path.Combine(BASE_PATH, "CHECKSUM"); - - internal static readonly string PERSISTENT_DATA_PATH = Path.Combine(BASE_PATH, "PersistentData"); - - /// - /// The link to the PolyMod Discord server. - /// - internal static readonly string DISCORD_LINK = "https://discord.gg/eWPdhWtfVy"; - - /// - /// A list of log messages to ignore. - /// - internal static readonly List LOG_MESSAGES_IGNORE = new() - { - "Failed to find atlas", - "Could not find sprite", - "Couldn't find prefab for type", - "MARKET: id:", - "Missing name for value", - }; + internal static string? Token { get; set; } + internal static bool ValidLaunch { get; set; } = false; + internal static bool Disabled { get; set; } = false; + + /// + /// Represents the configuration for PolyMod. + /// + /// Whether to enable debug mode. + internal record PolyConfig( + bool debug = false, + bool showCoordinates = false, + bool allowUnsafeIndexes = false, + string overrideDeviceId = "" + ) + { + public List disabledMods { get; init; } = new(); + }; + + /// + /// The starting index for automatically assigned IDs. + /// + internal const int AUTOIDX_STARTS_FROM = 1000; + + /// + /// The key used to store the last version for which the incompatibility warning was shown. + /// + internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY + = "INCOMPATIBILITY_WARNING_LAST_VERSION"; + + /// + /// The prefix of the player prefs keys holding the mod checksum a saved game was created with. + /// + internal const string STATE_CHECKSUM_KEY_PREFIX = "POLYMOD_STATE_CHECKSUM_"; + + internal const int LAUNCH_DATA_TIMEOUT = 2000; + + /// + /// The base path for PolyMod files. + /// + public static readonly string BASE_PATH = Path.Combine(BepInEx.Paths.BepInExRootPath, ".."); + + /// + /// The path to the mods directory. + /// + public static readonly string MODS_PATH = Path.Combine(BASE_PATH, "Mods"); + + /// + /// The path to the directory where game data is dumped. + /// + public static readonly string DUMPED_DATA_PATH = Path.Combine(BASE_PATH, "DumpedData"); + + /// + /// The path to the directory where localization is dumped. + /// + public static readonly string LOGIC_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Logic"); + + /// + /// The path to the directory where gameLogicData and avatarData are dumped. + /// + public static readonly string LOCALIZATION_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Localization"); + + /// + /// The path to the directory where sprites and sprite infos are dumped. + /// + public static readonly string SPRITES_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Sprites"); + + /// + /// The path to the directory where prefabs datas are dumped. + /// + public static readonly string PREFABS_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Prefabs"); + + /// + /// The path to the PolyMod configuration file. + /// + internal static readonly string CONFIG_PATH = Path.Combine(BASE_PATH, "PolyMod.json"); + + /// + /// The path to the checksum file. + /// + internal static readonly string CHECKSUM_PATH + = Path.Combine(BASE_PATH, "CHECKSUM"); + + internal static readonly string PERSISTENT_DATA_PATH = Path.Combine(BASE_PATH, "PersistentData"); + + /// + /// The link to the PolyMod Discord server. + /// + internal static readonly string DISCORD_LINK = "https://discord.gg/eWPdhWtfVy"; + + /// + /// A list of log messages to ignore. + /// + internal static readonly List LOG_MESSAGES_IGNORE = new() + { + "Failed to find atlas", + "Could not find sprite", + "Couldn't find prefab for type", + "MARKET: id:", + "Missing name for value", + }; #pragma warning disable CS8618 - /// - /// The PolyMod configuration. - /// - internal static PolyConfig config; - - /// - /// The logger instance for PolyMod. - /// - internal static ManualLogSource logger; + /// + /// The PolyMod configuration. + /// + internal static PolyConfig config; + + /// + /// The logger instance for PolyMod. + /// + internal static ManualLogSource logger; #pragma warning restore CS8618 - /// - /// The entry point for the plugin. - /// - public override void Load() - { - try - { - config = JsonSerializer.Deserialize(File.ReadAllText(CONFIG_PATH))!; - } - catch - { - config = new(); - } - WriteConfig(); - UpdateConsole(); - logger = Log; - ConfigFile.CoreConfig[new("Logging.Disk", "WriteUnityLog")].BoxedValue = true; - - CaptureLaunchData(); - - if (Disabled) - return; - - Compatibility.Init(); - - Audio.Init(); - Loc.Init(); - - Visual.Init(); - Prefabs.Init(); - TribePreviews.Init(); - - Hub.Init(); - Main.Init(); - } - - internal static void CaptureLaunchData() - { - try - { - using var client = new NamedPipeClientStream( - ".", "PolyMod.Launcher", PipeDirection.In, PipeOptions.CurrentUserOnly); - client.Connect(LAUNCH_DATA_TIMEOUT); - - using var reader = new StreamReader(client); - var line = reader.ReadLine(); - if (string.IsNullOrEmpty(line)) return; - using var doc = JsonDocument.Parse(line); - var root = doc.RootElement; - - ValidLaunch = root.GetProperty("validLaunch").GetBoolean(); - Disabled = root.GetProperty("disabled").GetBoolean(); - Token = root.GetProperty("token").GetString() ?? ""; - } - catch - { - ValidLaunch = false; - } - ValidLaunch = true; - } - - /// - /// Gets a resource stream from the assembly. - /// - /// The ID of the resource. - /// The resource stream. - internal static Stream GetResource(string id) - { - return Assembly.GetExecutingAssembly().GetManifestResourceStream( - $"{typeof(Plugin).Namespace}.resources.{id}" - )!; - } - - /// - /// Writes the configuration to disk. - /// - internal static void WriteConfig() - { - File.WriteAllText(CONFIG_PATH, JsonSerializer.Serialize(config)); - } - - /// - /// Updates the console based on the debug configuration. - /// - internal static void UpdateConsole() - { - if (config.debug) - { - ConsoleManager.CreateConsole(); - } - else if (OperatingSystem.IsWindows()) - { - // BepInEx's Unix console driver throws unsupported on detach. Off-Windows there is no separate console window, so there is nothing to detach. - ConsoleManager.DetachConsole(); - } - } + /// + /// The entry point for the plugin. + /// + public override void Load() + { + try + { + config = JsonSerializer.Deserialize(File.ReadAllText(CONFIG_PATH))!; + } + catch + { + config = new(); + } + WriteConfig(); + UpdateConsole(); + logger = Log; + ConfigFile.CoreConfig[new("Logging.Disk", "WriteUnityLog")].BoxedValue = true; + + CaptureLaunchData(); + + if (Disabled) + return; + + Compatibility.Init(); + + Audio.Init(); + Loc.Init(); + + Visual.Init(); + Prefabs.Init(); + TribePreviews.Init(); + + Hub.Init(); + Main.Init(); + } + + internal static void CaptureLaunchData() + { + try + { + using var client = new NamedPipeClientStream( + ".", "PolyMod.Launcher", PipeDirection.In, PipeOptions.CurrentUserOnly); + client.Connect(LAUNCH_DATA_TIMEOUT); + + using var reader = new StreamReader(client); + var line = reader.ReadLine(); + if (string.IsNullOrEmpty(line)) return; + using var doc = JsonDocument.Parse(line); + var root = doc.RootElement; + + ValidLaunch = root.GetProperty("validLaunch").GetBoolean(); + Disabled = root.GetProperty("disabled").GetBoolean(); + Token = root.GetProperty("token").GetString() ?? ""; + } + catch + { + ValidLaunch = false; + } + ValidLaunch = true; + } + + /// + /// Gets a resource stream from the assembly. + /// + /// The ID of the resource. + /// The resource stream. + internal static Stream GetResource(string id) + { + return Assembly.GetExecutingAssembly().GetManifestResourceStream( + $"{typeof(Plugin).Namespace}.resources.{id}" + )!; + } + + /// + /// Writes the configuration to disk. + /// + internal static void WriteConfig() + { + File.WriteAllText(CONFIG_PATH, JsonSerializer.Serialize(config)); + } + + /// + /// Updates the console based on the debug configuration. + /// + internal static void UpdateConsole() + { + if (config.debug) + { + ConsoleManager.CreateConsole(); + } + else if (OperatingSystem.IsWindows()) + { + // BepInEx's Unix console driver throws unsupported on detach. Off-Windows there is no separate console window, so there is nothing to detach. + ConsoleManager.DetachConsole(); + } + } } diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index a0eee86..5ae47db 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -8,110 +8,110 @@ namespace PolyMod; public class BasePrefabInfo { - [JsonInclude] - public List visualParts = new(); + [JsonInclude] + public List visualParts = new(); } public class UnitPrefabInfo : BasePrefabInfo { - [JsonInclude] - public SkinnedKey skinnedKey; + [JsonInclude] + public SkinnedKey skinnedKey; - [JsonInclude] - public string headPositionMarker = ""; + [JsonInclude] + public string headPositionMarker = ""; - [JsonInclude] - public bool uiOverride = false; + [JsonInclude] + public bool uiOverride = false; } public class ImprovementPrefabInfo : BasePrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ImprovementData.Type? improvementType = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; - [JsonInclude] - public bool needsOutlines = false; + [JsonInclude] + public bool needsOutlines = false; } public class ResourcePrefabInfo : BasePrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ResourceData.Type? resourceType = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; } internal class WeaponPrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - internal UnitData.WeaponEnum? weaponEnum = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal UnitData.WeaponEnum? weaponEnum = null; - [JsonInclude] - internal string spriteName = ""; + [JsonInclude] + internal string spriteName = ""; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - internal PathType pathType = PathType.CatmullRom; + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + internal PathType pathType = PathType.CatmullRom; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - internal PathMode pathMode = PathMode.Sidescroller2D; + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + internal PathMode pathMode = PathMode.Sidescroller2D; - [JsonInclude] - internal int pathResolution = 10; + [JsonInclude] + internal int pathResolution = 10; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - internal Ease pathEase = Ease.Linear; + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + internal Ease pathEase = Ease.Linear; - [JsonInclude] - internal float lookAheadOffset = 0.01f; + [JsonInclude] + internal float lookAheadOffset = 0.01f; - [JsonInclude] - internal float handleAngleOffset = 0.3f; + [JsonInclude] + internal float handleAngleOffset = 0.3f; - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - internal SFXTypes sfxType = SFXTypes.None; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal SFXTypes sfxType = SFXTypes.None; - [JsonInclude] - internal WeaponPuffInfo? weaponPuffInfo = null; + [JsonInclude] + internal WeaponPuffInfo? weaponPuffInfo = null; - [JsonInclude] - internal WeaponRangedInfo? weaponRangedInfo = null; + [JsonInclude] + internal WeaponRangedInfo? weaponRangedInfo = null; } internal class WeaponPuffInfo { - [JsonInclude] - internal bool sway = false; + [JsonInclude] + internal bool sway = false; - internal float animationMultiplier = 1f; + internal float animationMultiplier = 1f; - internal Action? initialDelegate = null; + internal Action? initialDelegate = null; - internal Action? animationDelegate = null; + internal Action? animationDelegate = null; - // [JsonInclude] Nuh uh, I wont do ts - // public List puffsToSpawn = new(); + // [JsonInclude] Nuh uh, I wont do ts + // public List puffsToSpawn = new(); } internal class WeaponRangedInfo { - [JsonInclude] - internal float centerOffset = 0.15f; + [JsonInclude] + internal float centerOffset = 0.15f; } internal class GFXPrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - internal GFXType? gfxType = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal GFXType? gfxType = null; } internal class UnitEffectPrefabInfo { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - internal UnitEffect? unitEffect = null; + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal UnitEffect? unitEffect = null; } diff --git a/src/Prefabs/PrefabsInfo.cs b/src/Prefabs/PrefabsInfo.cs index 5da59c4..50f639b 100644 --- a/src/Prefabs/PrefabsInfo.cs +++ b/src/Prefabs/PrefabsInfo.cs @@ -5,15 +5,15 @@ namespace PolyMod; public class PrefabsInfo { - [JsonInclude] - public List units = new(); + [JsonInclude] + public List units = new(); - [JsonInclude] - public List improvements = new(); + [JsonInclude] + public List improvements = new(); - [JsonInclude] - public List resources = new(); + [JsonInclude] + public List resources = new(); - // [JsonInclude] - private List weapons = new(); + // [JsonInclude] + private List weapons = new(); } diff --git a/src/Prefabs/SkinnedKey.cs b/src/Prefabs/SkinnedKey.cs index 53cfa52..41c57d5 100644 --- a/src/Prefabs/SkinnedKey.cs +++ b/src/Prefabs/SkinnedKey.cs @@ -7,50 +7,50 @@ namespace PolyMod; public readonly struct SkinnedKey : IEquatable { - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public UnitData.Type unitType { get; } - - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public TribeType tribeType { get; } - - [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public SkinType skinType { get; } - - [JsonConstructor] - public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) - { - this.unitType = unitType; - this.tribeType = tribeType; - this.skinType = skinType; - } - - public bool Equals(SkinnedKey other) - { - return unitType == other.unitType - && tribeType == other.tribeType - && skinType == other.skinType; - } - - public override bool Equals(object? obj) - { - return obj is SkinnedKey otherKey && Equals(otherKey); - } - - public override int GetHashCode() - { - return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); - } - - public static bool operator ==(SkinnedKey left, SkinnedKey right) - { - return left.Equals(right); - } - - public static bool operator !=(SkinnedKey left, SkinnedKey right) - { - return !left.Equals(right); - } + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.Type unitType { get; } + + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public TribeType tribeType { get; } + + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public SkinType skinType { get; } + + [JsonConstructor] + public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + this.unitType = unitType; + this.tribeType = tribeType; + this.skinType = skinType; + } + + public bool Equals(SkinnedKey other) + { + return unitType == other.unitType + && tribeType == other.tribeType + && skinType == other.skinType; + } + + public override bool Equals(object? obj) + { + return obj is SkinnedKey otherKey && Equals(otherKey); + } + + public override int GetHashCode() + { + return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); + } + + public static bool operator ==(SkinnedKey left, SkinnedKey right) + { + return left.Equals(right); + } + + public static bool operator !=(SkinnedKey left, SkinnedKey right) + { + return !left.Equals(right); + } } diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs index 329b3ef..9a4136e 100644 --- a/src/Prefabs/VisualPartInfo.cs +++ b/src/Prefabs/VisualPartInfo.cs @@ -6,76 +6,76 @@ namespace PolyMod; public class VisualPartInfo { - [JsonInclude] - public string? defaultSpriteName; + [JsonInclude] + public string? defaultSpriteName; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; - [JsonInclude] - [JsonConverter(typeof(EnumNameJson))] - public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific - [JsonInclude] - public Vector2 coordinates = new Vector2(0, 0); + [JsonInclude] + public Vector2 coordinates = new Vector2(0, 0); - [JsonInclude] - public float rotation = 0f; + [JsonInclude] + public float rotation = 0f; - [JsonInclude] - public bool tintable = false; + [JsonInclude] + public bool tintable = false; - [JsonInclude] - public bool levels = false; // improvement specific + [JsonInclude] + public bool levels = false; // improvement specific - [JsonInclude] - public int? sortingOrderOverride = null; + [JsonInclude] + public int? sortingOrderOverride = null; - [JsonInclude] - public int? outlineSortingOrderOverride = null; + [JsonInclude] + public int? outlineSortingOrderOverride = null; - public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) - { - return new SkinVisualsReference.VisualPart - { - DefaultSpriteName = defaultSpriteName, - tintable = tintable, - skinLogic = skinningLogic, - improvementSkinLogic = improvementSkinningLogic, - levels = levels, - isImprovement = isImprovement, - }; - } + public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) + { + return new SkinVisualsReference.VisualPart + { + DefaultSpriteName = defaultSpriteName, + tintable = tintable, + skinLogic = skinningLogic, + improvementSkinLogic = improvementSkinningLogic, + levels = levels, + isImprovement = isImprovement, + }; + } - public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) - { - int? sortingOrderOverride = null; - SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); - if (spriteRenderer != null) - { - sortingOrderOverride = spriteRenderer.sortingOrder; - } + public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) + { + int? sortingOrderOverride = null; + SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); + if (spriteRenderer != null) + { + sortingOrderOverride = spriteRenderer.sortingOrder; + } - int? outlineSortingOrderOverride = null; + int? outlineSortingOrderOverride = null; - if (visualPart.outline != null) - { - spriteRenderer = visualPart.outline.GetComponent(); - if (spriteRenderer != null) - { - outlineSortingOrderOverride = spriteRenderer.sortingOrder; - } - } + if (visualPart.outline != null) + { + spriteRenderer = visualPart.outline.GetComponent(); + if (spriteRenderer != null) + { + outlineSortingOrderOverride = spriteRenderer.sortingOrder; + } + } - coordinates = visualPart.visualPart.transform.position; - rotation = visualPart.visualPart.transform.rotation.z; - defaultSpriteName = visualPart.DefaultSpriteName; - tintable = visualPart.tintable; - skinningLogic = visualPart.skinLogic; - improvementSkinningLogic = visualPart.improvementSkinLogic; - levels = visualPart.levels; - this.sortingOrderOverride = sortingOrderOverride; - this.outlineSortingOrderOverride = outlineSortingOrderOverride; - } + coordinates = visualPart.visualPart.transform.position; + rotation = visualPart.visualPart.transform.rotation.z; + defaultSpriteName = visualPart.DefaultSpriteName; + tintable = visualPart.tintable; + skinningLogic = visualPart.skinLogic; + improvementSkinningLogic = visualPart.improvementSkinLogic; + levels = visualPart.levels; + this.sortingOrderOverride = sortingOrderOverride; + this.outlineSortingOrderOverride = outlineSortingOrderOverride; + } } diff --git a/src/Registry.cs b/src/Registry.cs index 8944632..2c02448 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -1,7 +1,6 @@ using System.Globalization; using LibCpp2IL; using PolyMod.Managers; -using PolytopiaBackendBase.Game; using UnityEngine; using PolytopiaBackendBase.Common; @@ -12,136 +11,131 @@ namespace PolyMod; /// public static class Registry { - /// - /// The next available index for automatically assigned IDs. - /// - public static int autoidx = Plugin.AUTOIDX_STARTS_FROM; - - /// - /// A dictionary of all loaded sprites, keyed by their name. - /// - public static Dictionary sprites = new(); - - public static Dictionary> textures = new(); // string = texture name, bool, whether texture was processed or not. reviwers, pls tell me how to improve - - /// - /// A dictionary of all loaded audio clips, keyed by their name. - /// - public static Dictionary audioClips = new(); - - /// - /// A dictionary of all loaded mods, keyed by their ID. - /// - public static Dictionary mods = new(); - - /// - /// A dictionary of tribe previews, keyed by tribe name. - /// - public static Dictionary tribePreviews = new(); - - /// - /// A dictionary of sprite information, keyed by sprite name. - /// - public static Dictionary spriteInfos = new(); - - /// - /// A dictionary of loaded asset bundles, keyed by their name. - /// - public static Dictionary assetBundles = new(); - - /// - /// A list of custom tribes. - /// - public static List customTribes = new(); - - /// - /// A list of custom skin information. - /// - public static List skinInfo = new(); - - /// - /// The next available index for climate styles. - /// - public static int climateAutoidx = (int)Enum.GetValues().Last(); - - /// - /// The next available index for game modes. - /// - public static int gameModesAutoidx = Enum.GetValues().Length; - - public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it - - public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1, bool outline = false) - { - string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); - string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); - string levelText = (level == -1) ? "" : level.ToString(CultureInfo.InvariantCulture); - return GetSpriteByText(baseName, tribeText, skinText, levelText, outline); - } - /// - /// Gets a sprite from the registry, trying to find the best match. - /// - public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", string levelText = "", bool outline = false) - { - Sprite? sprite = null; - baseName = baseName.ToLowerInvariant(); - tribeText = tribeText.ToLowerInvariant(); - skinText = skinText.ToLowerInvariant(); - - List spriteNameVariants = new(); - - if (levelText != string.Empty) - baseName += $"_{levelText}"; - - spriteNameVariants.Add(baseName); - spriteNameVariants.Add(baseName + "_" + tribeText); - spriteNameVariants.Add(baseName + "_" + skinText); - spriteNameVariants.Add(baseName + "_" + tribeText + "_" + skinText); - - foreach (string spriteName in spriteNameVariants) - { - sprite = sprites.GetOrDefault(outline ? spriteName + "_outline" : spriteName, sprite); - } - - return sprite; - } - - /// - /// Gets an audio clip from the registry. - /// - /// The name of the audio clip. - /// The requested audio clip, or null if not found. - public static AudioClip? GetAudioClip(string name, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default) - { - string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); - string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); - return GetAudioClipByText(name, tribeText, skinText); - } - - /// - /// Gets an audio clip from the registry, trying to find the best match. - /// - public static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") - { - AudioSource? audioSource = null; - baseName = baseName.ToLowerInvariant(); - tribeText = tribeText.ToLowerInvariant(); - skinText = skinText.ToLowerInvariant(); - - List audioNameVariants = new() - { - baseName, - baseName + "_" + tribeText, - baseName + "_" + skinText, - baseName + "_" + tribeText + "_" + skinText, - }; - - foreach (string audioName in audioNameVariants) - { - audioSource = audioClips.GetOrDefault(audioName, audioSource); - } - - if (audioSource == null) return null; - return audioSource.clip; - } + /// + /// The next available index for automatically assigned IDs. + /// + internal static int autoidx = Plugin.AUTOIDX_STARTS_FROM; + + /// + /// A dictionary of all loaded sprites, keyed by their name. + /// + internal static Dictionary sprites = new(); + + internal static Dictionary> textures = new(); // string = texture name, bool, whether texture was processed or not. reviwers, pls tell me how to improve + + /// + /// A dictionary of all loaded audio clips, keyed by their name. + /// + internal static Dictionary audioClips = new(); + + /// + /// A dictionary of all loaded mods, keyed by their ID. + /// + internal static Dictionary mods = new(); + + /// + /// A dictionary of tribe previews, keyed by tribe name. + /// + internal static Dictionary tribePreviews = new(); + + /// + /// A dictionary of sprite information, keyed by sprite name. + /// + internal static Dictionary spriteInfos = new(); + + /// + /// A dictionary of loaded asset bundles, keyed by their name. + /// + internal static Dictionary assetBundles = new(); + + /// + /// A list of custom tribes. + /// + internal static List customTribes = new(); + + /// + /// A list of custom skin information. + /// + internal static List skinInfo = new(); + + /// + /// The next available index for climate styles. + /// + internal static int climateAutoidx = (int)Enum.GetValues().Last(); + + public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it + + public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1, bool outline = false) + { + string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); + string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); + string levelText = (level == -1) ? "" : level.ToString(CultureInfo.InvariantCulture); + return GetSpriteByText(baseName, tribeText, skinText, levelText, outline); + } + /// + /// Gets a sprite from the registry, trying to find the best match. + /// + public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", string levelText = "", bool outline = false) + { + Sprite? sprite = null; + baseName = baseName.ToLowerInvariant(); + tribeText = tribeText.ToLowerInvariant(); + skinText = skinText.ToLowerInvariant(); + + List spriteNameVariants = new(); + + if (levelText != string.Empty) + baseName += $"_{levelText}"; + + spriteNameVariants.Add(baseName); + spriteNameVariants.Add(baseName + "_" + tribeText); + spriteNameVariants.Add(baseName + "_" + skinText); + spriteNameVariants.Add(baseName + "_" + tribeText + "_" + skinText); + + foreach (string spriteName in spriteNameVariants) + { + sprite = sprites.GetOrDefault(outline ? spriteName + "_outline" : spriteName, sprite); + } + + return sprite; + } + + /// + /// Gets an audio clip from the registry. + /// + /// The name of the audio clip. + /// The requested audio clip, or null if not found. + public static AudioClip? GetAudioClip(string name, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default) + { + string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); + string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); + return GetAudioClipByText(name, tribeText, skinText); + } + + /// + /// Gets an audio clip from the registry, trying to find the best match. + /// + public static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") + { + AudioSource? audioSource = null; + baseName = baseName.ToLowerInvariant(); + tribeText = tribeText.ToLowerInvariant(); + skinText = skinText.ToLowerInvariant(); + + List audioNameVariants = new() + { + baseName, + baseName + "_" + tribeText, + baseName + "_" + skinText, + baseName + "_" + tribeText + "_" + skinText, + }; + + foreach (string audioName in audioNameVariants) + { + audioSource = audioClips.GetOrDefault(audioName, audioSource); + } + + if (audioSource == null) return null; + return audioSource.clip; + } } diff --git a/src/Util.cs b/src/Util.cs index cae4707..885a025 100644 --- a/src/Util.cs +++ b/src/Util.cs @@ -12,141 +12,141 @@ namespace PolyMod; /// internal static class Util { - /// - /// Wraps a managed type for use in the Il2Cpp runtime. - /// - /// The type to wrap. - /// The Il2Cpp representation of the type. - internal static Il2CppSystem.Type WrapType() where T : class - { - if (!ClassInjector.IsTypeRegisteredInIl2Cpp()) - ClassInjector.RegisterTypeInIl2Cpp(); - return Il2CppType.From(typeof(T)); - } + /// + /// Wraps a managed type for use in the Il2Cpp runtime. + /// + /// The type to wrap. + /// The Il2Cpp representation of the type. + internal static Il2CppSystem.Type WrapType() where T : class + { + if (!ClassInjector.IsTypeRegisteredInIl2Cpp()) + ClassInjector.RegisterTypeInIl2Cpp(); + return Il2CppType.From(typeof(T)); + } - /// - /// Computes the SHA256 hash of an object's string representation. - /// - /// The object to hash. - /// The hexadecimal string representation of the hash. - internal static string Hash(object data) - { - return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(data.ToString()!))); - } + /// + /// Computes the SHA256 hash of an object's string representation. + /// + /// The object to hash. + /// The hexadecimal string representation of the hash. + internal static string Hash(object data) + { + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(data.ToString()!))); + } - /// - /// Computes the SHA256 hash of raw bytes. - /// - /// The bytes to hash. - /// The hexadecimal string representation of the hash. - internal static string HashBytes(byte[] data) - { - return Convert.ToHexString(SHA256.HashData(data)); - } + /// + /// Computes the SHA256 hash of raw bytes. + /// + /// The bytes to hash. + /// The hexadecimal string representation of the hash. + internal static string HashBytes(byte[] data) + { + return Convert.ToHexString(SHA256.HashData(data)); + } - /// - /// Gets the name of a JToken from its path. - /// - /// The JToken. - /// The part of the path to retrieve, from the end. - /// The name of the JToken. - internal static string GetJTokenName(JToken token, int n = 1) - { - return token.Path.Split('.')[^n]; - } + /// + /// Gets the name of a JToken from its path. + /// + /// The JToken. + /// The part of the path to retrieve, from the end. + /// The name of the JToken. + internal static string GetJTokenName(JToken token, int n = 1) + { + return token.Path.Split('.')[^n]; + } - /// - /// Converts an Il2CppSystem.Version to a System.Version. - /// - /// The Il2CppSystem.Version to convert. - /// The equivalent System.Version. - internal static Version Cast(this Il2CppSystem.Version self) - { - return new(self.ToString()); - } + /// + /// Converts an Il2CppSystem.Version to a System.Version. + /// + /// The Il2CppSystem.Version to convert. + /// The equivalent System.Version. + internal static Version Cast(this Il2CppSystem.Version self) + { + return new(self.ToString()); + } - /// - /// Synchronously unwraps the result of a Task. - /// - /// The result type of the Task. - /// The Task to unwrap. - /// The result of the Task. - internal static T UnwrapAsync(this Task self) - { - return self.GetAwaiter().GetResult(); - } + /// + /// Synchronously unwraps the result of a Task. + /// + /// The result type of the Task. + /// The Task to unwrap. + /// The result of the Task. + internal static T UnwrapAsync(this Task self) + { + return self.GetAwaiter().GetResult(); + } - /// - /// Removes the revision component from a Version. - /// - /// The Version to modify. - /// A new Version with the revision set to -1. - internal static Version CutRevision(this Version self) - { - return new(self.Major, self.Minor, self.Build); - } + /// + /// Removes the revision component from a Version. + /// + /// The Version to modify. + /// A new Version with the revision set to -1. + internal static Version CutRevision(this Version self) + { + return new(self.Major, self.Minor, self.Build); + } - /// - /// Compares two version strings to see if the first is older or equal to the second. - /// Pre-release tags follow semantic-version rules: the part after the first dash is - /// split on dots, purely numeric identifiers compare numerically and sort before - /// alphanumeric ones, and a longer identifier list is newer. A version with a - /// pre-release tag is always older than the same version without one. - /// - /// The first version string. - /// The second version string. - /// True if version1 is older or equal to version2, false otherwise. - internal static bool IsVersionOlderOrEqual(this string version1, string version2) - { - Version core1 = ParseVersion(version1, out string? pre1); - Version core2 = ParseVersion(version2, out string? pre2); + /// + /// Compares two version strings to see if the first is older or equal to the second. + /// Pre-release tags follow semantic-version rules: the part after the first dash is + /// split on dots, purely numeric identifiers compare numerically and sort before + /// alphanumeric ones, and a longer identifier list is newer. A version with a + /// pre-release tag is always older than the same version without one. + /// + /// The first version string. + /// The second version string. + /// True if version1 is older or equal to version2, false otherwise. + internal static bool IsVersionOlderOrEqual(this string version1, string version2) + { + Version core1 = ParseVersion(version1, out string? pre1); + Version core2 = ParseVersion(version2, out string? pre2); - if (core1 != core2) - return core1 < core2; + if (core1 != core2) + return core1 < core2; - return ComparePreRelease(pre1, pre2) <= 0; - } + return ComparePreRelease(pre1, pre2) <= 0; + } - private static Version ParseVersion(string version, out string? preRelease) - { - int dash = version.IndexOf('-'); - if (dash < 0) - { - preRelease = null; - return new Version(version); - } - preRelease = version[(dash + 1)..]; - if (preRelease.Length == 0) - preRelease = null; - return new Version(version[..dash]); - } + private static Version ParseVersion(string version, out string? preRelease) + { + int dash = version.IndexOf('-'); + if (dash < 0) + { + preRelease = null; + return new Version(version); + } + preRelease = version[(dash + 1)..]; + if (preRelease.Length == 0) + preRelease = null; + return new Version(version[..dash]); + } - private static int ComparePreRelease(string? left, string? right) - { - if (left == null && right == null) return 0; - if (left == null) return 1; - if (right == null) return -1; + private static int ComparePreRelease(string? left, string? right) + { + if (left == null && right == null) return 0; + if (left == null) return 1; + if (right == null) return -1; - string[] leftIds = left.Split('.'); - string[] rightIds = right.Split('.'); - int shared = Math.Min(leftIds.Length, rightIds.Length); - for (int i = 0; i < shared; i++) - { - int comparison = CompareIdentifier(leftIds[i], rightIds[i]); - if (comparison != 0) - return comparison; - } - return leftIds.Length.CompareTo(rightIds.Length); - } + string[] leftIds = left.Split('.'); + string[] rightIds = right.Split('.'); + int shared = Math.Min(leftIds.Length, rightIds.Length); + for (int i = 0; i < shared; i++) + { + int comparison = CompareIdentifier(leftIds[i], rightIds[i]); + if (comparison != 0) + return comparison; + } + return leftIds.Length.CompareTo(rightIds.Length); + } - private static int CompareIdentifier(string left, string right) - { - bool leftNumeric = left.Length > 0 && left.All(char.IsDigit); - bool rightNumeric = right.Length > 0 && right.All(char.IsDigit); - if (leftNumeric && rightNumeric) - return long.Parse(left, CultureInfo.InvariantCulture).CompareTo(long.Parse(right, CultureInfo.InvariantCulture)); - if (leftNumeric) return -1; - if (rightNumeric) return 1; - return string.Compare(left, right, StringComparison.Ordinal); - } + private static int CompareIdentifier(string left, string right) + { + bool leftNumeric = left.Length > 0 && left.All(char.IsDigit); + bool rightNumeric = right.Length > 0 && right.All(char.IsDigit); + if (leftNumeric && rightNumeric) + return long.Parse(left, CultureInfo.InvariantCulture).CompareTo(long.Parse(right, CultureInfo.InvariantCulture)); + if (leftNumeric) return -1; + if (rightNumeric) return 1; + return string.Compare(left, right, StringComparison.Ordinal); + } } diff --git a/src/WavDecoder.cs b/src/WavDecoder.cs deleted file mode 100644 index 736ca52..0000000 --- a/src/WavDecoder.cs +++ /dev/null @@ -1,157 +0,0 @@ -using System.Buffers.Binary; - -namespace PolyMod; - -/// -/// Decodes RIFF WAVE files into the interleaved float samples Unity wants. -/// -public static class WavDecoder -{ - /// - /// The decoded contents of a WAVE file. - /// - /// Interleaved samples in the -1 to 1 range, channel by channel. - /// Number of channels the samples are interleaved across. - /// Sample rate in hertz. - public record WavData(float[] samples, int channels, int frequency) - { - /// Number of sample frames, which is the length Unity asks for. - public int lengthSamples => samples.Length / channels; - } - - private const ushort FORMAT_PCM = 1; - private const ushort FORMAT_FLOAT = 3; - private const ushort FORMAT_EXTENSIBLE = 0xFFFE; - - private const int HEADER_LENGTH = 12; - private const int CHUNK_HEADER_LENGTH = 8; - private const int FORMAT_CHUNK_LENGTH = 16; - private const int EXTENSIBLE_CHUNK_LENGTH = 40; - - /// - /// Decodes a WAVE file held in memory. - /// - /// The whole file, starting at its RIFF header. - /// The samples plus the channel count and sample rate needed to play them. - /// The file is not a WAVE file this can decode. - public static WavData Decode(byte[] data) - { - ReadOnlySpan file = data; - if (file.Length < HEADER_LENGTH || ReadId(file, 0) != "RIFF" || ReadId(file, 8) != "WAVE") - throw new InvalidDataException("Not a RIFF WAVE file."); - - ushort format = 0; - ushort channels = 0; - ushort bitsPerSample = 0; - int frequency = 0; - int dataOffset = -1; - int dataLength = 0; - - int offset = HEADER_LENGTH; - while (offset + CHUNK_HEADER_LENGTH <= file.Length) - { - string id = ReadId(file, offset); - uint declared = BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(offset + 4, 4)); - int payload = offset + CHUNK_HEADER_LENGTH; - int size = (int)Math.Min(declared, (uint)(file.Length - payload)); - - if (id == "fmt " && size >= FORMAT_CHUNK_LENGTH) - { - format = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload, 2)); - channels = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload + 2, 2)); - frequency = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(payload + 4, 4)); - bitsPerSample = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload + 14, 2)); - if (format == FORMAT_EXTENSIBLE && size >= EXTENSIBLE_CHUNK_LENGTH) - format = BinaryPrimitives.ReadUInt16LittleEndian(file.Slice(payload + 24, 2)); - } - else if (id == "data") - { - dataOffset = payload; - dataLength = size; - } - - offset = payload + size + (size & 1); - } - - if (channels < 1) throw new InvalidDataException("WAVE file declares no channels."); - if (frequency < 1) throw new InvalidDataException("WAVE file declares no sample rate."); - if (bitsPerSample < 8 || bitsPerSample % 8 != 0) - throw new InvalidDataException($"Unsupported WAVE bit depth {bitsPerSample}."); - if (dataOffset < 0) throw new InvalidDataException("WAVE file has no data chunk."); - - int bytesPerSample = bitsPerSample / 8; - int count = dataLength / bytesPerSample; - count -= count % channels; - if (count < 1) throw new InvalidDataException("WAVE file holds no samples."); - - float[] samples = ReadSamples(file.Slice(dataOffset), format, bitsPerSample, count); - return new WavData(samples, channels, frequency); - } - - private static float[] ReadSamples(ReadOnlySpan payload, ushort format, ushort bitsPerSample, int count) - { - float[] samples = new float[count]; - int step = bitsPerSample / 8; - - if (format == FORMAT_PCM) - { - switch (bitsPerSample) - { - case 8: - for (int i = 0; i < count; i++) - samples[i] = (payload[i] - 128) / 128f; - return samples; - case 16: - for (int i = 0; i < count; i++) - samples[i] = BinaryPrimitives.ReadInt16LittleEndian(payload.Slice(i * step, 2)) / 32768f; - return samples; - case 24: - for (int i = 0; i < count; i++) - { - int at = i * step; - int value = payload[at] | (payload[at + 1] << 8) | ((sbyte)payload[at + 2] << 16); - samples[i] = value / 8388608f; - } - return samples; - case 32: - for (int i = 0; i < count; i++) - samples[i] = BinaryPrimitives.ReadInt32LittleEndian(payload.Slice(i * step, 4)) / 2147483648f; - return samples; - } - } - else if (format == FORMAT_FLOAT) - { - switch (bitsPerSample) - { - case 32: - for (int i = 0; i < count; i++) - samples[i] = BitConverter.Int32BitsToSingle( - BinaryPrimitives.ReadInt32LittleEndian(payload.Slice(i * step, 4)) - ); - return samples; - case 64: - for (int i = 0; i < count; i++) - samples[i] = (float)BitConverter.Int64BitsToDouble( - BinaryPrimitives.ReadInt64LittleEndian(payload.Slice(i * step, 8)) - ); - return samples; - } - } - - throw new InvalidDataException( - $"Unsupported WAVE format {format} at {bitsPerSample} bits per sample. " - + "Save the file as PCM or float WAVE." - ); - } - - private static string ReadId(ReadOnlySpan file, int offset) - { - return new string(new char[] - { - (char)file[offset], - (char)file[offset + 1], - (char)file[offset + 2], - (char)file[offset + 3], - }); - } -} diff --git a/tests/CheckDependenciesTests.cs b/tests/CheckDependenciesTests.cs index 95276d0..b297606 100644 --- a/tests/CheckDependenciesTests.cs +++ b/tests/CheckDependenciesTests.cs @@ -4,56 +4,56 @@ namespace Tests; public class CheckDependenciesTests { - [Fact] - public void MissingRequiredDependencyMarksModUnsatisfied() - { - var mod = ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); - Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); - } + [Fact] + public void MissingRequiredDependencyMarksModUnsatisfied() + { + var mod = ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); + Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); + } - [Fact] - public void VersionBelowMinimumMarksModUnsatisfied() - { - var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: null); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); - Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); - } + [Fact] + public void VersionBelowMinimumMarksModUnsatisfied() + { + var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: null); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); + Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); + } - [Fact] - public void VersionAboveMaximumMarksModUnsatisfied() - { - var dep = new Mod.Dependency("a", min: null, max: new Version(1, 0, 0)); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); - Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); - } + [Fact] + public void VersionAboveMaximumMarksModUnsatisfied() + { + var dep = new Mod.Dependency("a", min: null, max: new Version(1, 0, 0)); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); + Assert.Equal(Mod.Status.DependenciesUnsatisfied, mod.status); + } - [Fact] - public void VersionEqualToBoundsIsAllowed() - { - var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: new Version(2, 0, 0)); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); - Assert.Equal(Mod.Status.Success, mod.status); - } + [Fact] + public void VersionEqualToBoundsIsAllowed() + { + var dep = new Mod.Dependency("a", min: new Version(2, 0, 0), max: new Version(2, 0, 0)); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a", version: new Version(2, 0, 0)), mod)); + Assert.Equal(Mod.Status.Success, mod.status); + } - [Fact] - public void SatisfiedDependencyKeepsModSuccessful() - { - var dep = new Mod.Dependency("a", min: new Version(1, 0, 0), max: new Version(2, 0, 0)); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); - Assert.Equal(Mod.Status.Success, mod.status); - } + [Fact] + public void SatisfiedDependencyKeepsModSuccessful() + { + var dep = new Mod.Dependency("a", min: new Version(1, 0, 0), max: new Version(2, 0, 0)); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(ModFactory.MakeMod("a"), mod)); + Assert.Equal(Mod.Status.Success, mod.status); + } - [Fact] - public void MissingOptionalDependencyOnlyWarns() - { - var dep = new Mod.Dependency("ghost", null, null, required: false); - var mod = ModFactory.MakeMod("b", dependencies: dep); - Loader.CheckDependencies(ModFactory.Mods(mod)); - Assert.Equal(Mod.Status.Success, mod.status); - } + [Fact] + public void MissingOptionalDependencyOnlyWarns() + { + var dep = new Mod.Dependency("ghost", null, null, required: false); + var mod = ModFactory.MakeMod("b", dependencies: dep); + Loader.CheckDependencies(ModFactory.Mods(mod)); + Assert.Equal(Mod.Status.Success, mod.status); + } } diff --git a/tests/CompatibilityTests.cs b/tests/CompatibilityTests.cs index 30ffe8e..8768a6e 100644 --- a/tests/CompatibilityTests.cs +++ b/tests/CompatibilityTests.cs @@ -6,129 +6,129 @@ namespace Tests; public class CompatibilityTests { - private static Mod MakeModWithFiles(string id, Version version, params (string Name, string Content)[] files) - { - List modFiles = new(); - foreach ((string name, string content) in files) - modFiles.Add(new Mod.File(name, Encoding.UTF8.GetBytes(content))); - - Mod.Manifest manifest = new(id, null, null, version, new[] { "author" }, null); - return new Mod(manifest, Mod.Status.Success, modFiles); - } - - // The launcher computes this same value from the mod's .polymod archive. If this literal has to - // change, PolyModLauncher's ModChecksum must change with it or multiplayer checks will disagree. - [Fact] - public void ModChecksumMatchesTheLauncher() - { - Mod mod = MakeModWithFiles( - "testmod", - new Version(1, 2, 3), - ("sprites.json", "{\"a\":1}"), - ("nested/thing.txt", "hello world"), - ("code.dll", "not really a dll")); - - Assert.Equal( - "34A44D3156F856C4A6CACB16379B529E797230E7F1DB9A32E1E3682D416405AC", - Compatibility.ComputeModChecksum(mod)); - } - - [Fact] - public void ModChecksumIgnoresFileOrder() - { - Mod ordered = MakeModWithFiles( - "testmod", - new Version(1, 0, 0), - ("a.txt", "first"), - ("b.txt", "second")); - Mod reversed = MakeModWithFiles( - "testmod", - new Version(1, 0, 0), - ("b.txt", "second"), - ("a.txt", "first")); - - Assert.Equal( - Compatibility.ComputeModChecksum(ordered), - Compatibility.ComputeModChecksum(reversed)); - } - - [Fact] - public void ModChecksumChangesWithFileContents() - { - Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); - Mod edited = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "firsT")); - - Assert.NotEqual( - Compatibility.ComputeModChecksum(original), - Compatibility.ComputeModChecksum(edited)); - } - - [Fact] - public void ModChecksumChangesWithVersion() - { - Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); - Mod bumped = MakeModWithFiles("testmod", new Version(1, 0, 1), ("a.txt", "first")); - - Assert.NotEqual( - Compatibility.ComputeModChecksum(original), - Compatibility.ComputeModChecksum(bumped)); - } - - [Fact] - public void GlobalChecksumIgnoresClientOnlyMods() - { - Mod shared = MakeModWithFiles("sharedmod", new Version(1, 0, 0), ("a.txt", "first")); - - Dictionary withoutClient = new() { { shared.id, shared } }; - Compatibility.ComputeChecksums(withoutClient); - string before = Compatibility.checksum; - - Mod clientOnly = MakeModWithFiles("clientmod", new Version(1, 0, 0), ("b.txt", "second")); - clientOnly.client = true; - - Dictionary withClient = new() - { - { shared.id, shared }, - { clientOnly.id, clientOnly }, - }; - Compatibility.ComputeChecksums(withClient); - - Assert.Equal(before, Compatibility.checksum); - } - - // The game deletes saves through APIs that hand the id over as a Guid in some places and as a - // string in others. If those produced different keys the stored checksum would never be purged. - [Fact] - public void GameIdNormalizesAcrossTheFormsTheGameUses() - { - Guid gameId = Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301"); - string expected = "3f2504e0-4f89-11d3-9a0c-0305e82c3301"; - - Assert.Equal(expected, Compatibility.NormalizeGameId(gameId)); - Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString())); - Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString().ToUpperInvariant())); - Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString("B"))); - } - - [Fact] - public void GlobalChecksumIgnoresModOrder() - { - Mod first = MakeModWithFiles("alpha", new Version(1, 0, 0), ("a.txt", "first")); - Mod second = MakeModWithFiles("beta", new Version(1, 0, 0), ("b.txt", "second")); - - Compatibility.ComputeChecksums(new Dictionary - { - { first.id, first }, - { second.id, second }, - }); - string ordered = Compatibility.checksum; - - Compatibility.ComputeChecksums(new Dictionary - { - { second.id, second }, - { first.id, first }, - }); - - Assert.Equal(ordered, Compatibility.checksum); - } + private static Mod MakeModWithFiles(string id, Version version, params (string Name, string Content)[] files) + { + List modFiles = new(); + foreach ((string name, string content) in files) + modFiles.Add(new Mod.File(name, Encoding.UTF8.GetBytes(content))); + + Mod.Manifest manifest = new(id, null, null, version, new[] { "author" }, null); + return new Mod(manifest, Mod.Status.Success, modFiles); + } + + // The launcher computes this same value from the mod's .polymod archive. If this literal has to + // change, PolyModLauncher's ModChecksum must change with it or multiplayer checks will disagree. + [Fact] + public void ModChecksumMatchesTheLauncher() + { + Mod mod = MakeModWithFiles( + "testmod", + new Version(1, 2, 3), + ("sprites.json", "{\"a\":1}"), + ("nested/thing.txt", "hello world"), + ("code.dll", "not really a dll")); + + Assert.Equal( + "34A44D3156F856C4A6CACB16379B529E797230E7F1DB9A32E1E3682D416405AC", + Compatibility.ComputeModChecksum(mod)); + } + + [Fact] + public void ModChecksumIgnoresFileOrder() + { + Mod ordered = MakeModWithFiles( + "testmod", + new Version(1, 0, 0), + ("a.txt", "first"), + ("b.txt", "second")); + Mod reversed = MakeModWithFiles( + "testmod", + new Version(1, 0, 0), + ("b.txt", "second"), + ("a.txt", "first")); + + Assert.Equal( + Compatibility.ComputeModChecksum(ordered), + Compatibility.ComputeModChecksum(reversed)); + } + + [Fact] + public void ModChecksumChangesWithFileContents() + { + Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); + Mod edited = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "firsT")); + + Assert.NotEqual( + Compatibility.ComputeModChecksum(original), + Compatibility.ComputeModChecksum(edited)); + } + + [Fact] + public void ModChecksumChangesWithVersion() + { + Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); + Mod bumped = MakeModWithFiles("testmod", new Version(1, 0, 1), ("a.txt", "first")); + + Assert.NotEqual( + Compatibility.ComputeModChecksum(original), + Compatibility.ComputeModChecksum(bumped)); + } + + [Fact] + public void GlobalChecksumIgnoresClientOnlyMods() + { + Mod shared = MakeModWithFiles("sharedmod", new Version(1, 0, 0), ("a.txt", "first")); + + Dictionary withoutClient = new() { { shared.id, shared } }; + Compatibility.ComputeChecksums(withoutClient); + string before = Compatibility.checksum; + + Mod clientOnly = MakeModWithFiles("clientmod", new Version(1, 0, 0), ("b.txt", "second")); + clientOnly.client = true; + + Dictionary withClient = new() + { + { shared.id, shared }, + { clientOnly.id, clientOnly }, + }; + Compatibility.ComputeChecksums(withClient); + + Assert.Equal(before, Compatibility.checksum); + } + + // The game deletes saves through APIs that hand the id over as a Guid in some places and as a + // string in others. If those produced different keys the stored checksum would never be purged. + [Fact] + public void GameIdNormalizesAcrossTheFormsTheGameUses() + { + Guid gameId = Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301"); + string expected = "3f2504e0-4f89-11d3-9a0c-0305e82c3301"; + + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId)); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString())); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString().ToUpperInvariant())); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString("B"))); + } + + [Fact] + public void GlobalChecksumIgnoresModOrder() + { + Mod first = MakeModWithFiles("alpha", new Version(1, 0, 0), ("a.txt", "first")); + Mod second = MakeModWithFiles("beta", new Version(1, 0, 0), ("b.txt", "second")); + + Compatibility.ComputeChecksums(new Dictionary + { + { first.id, first }, + { second.id, second }, + }); + string ordered = Compatibility.checksum; + + Compatibility.ComputeChecksums(new Dictionary + { + { second.id, second }, + { first.id, first }, + }); + + Assert.Equal(ordered, Compatibility.checksum); + } } diff --git a/tests/LoaderTests.cs b/tests/LoaderTests.cs index e056664..f7aae24 100644 --- a/tests/LoaderTests.cs +++ b/tests/LoaderTests.cs @@ -4,57 +4,57 @@ namespace Tests; public class LoaderTests { - private static string[] Ids(Dictionary mods) => - mods.Select(kv => kv.Key).ToArray(); + private static string[] Ids(Dictionary mods) => + mods.Select(kv => kv.Key).ToArray(); - [Fact] - public void DependencyLoadsBeforeDependent() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), - ModFactory.MakeMod("a")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(new[] { "a", "b" }, Ids(mods)); - } + [Fact] + public void DependencyLoadsBeforeDependent() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), + ModFactory.MakeMod("a")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(new[] { "a", "b" }, Ids(mods)); + } - [Fact] - public void TransitiveChainSortsDeepestFirst() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("c", dependencies: new Mod.Dependency("b", null, null)), - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), - ModFactory.MakeMod("a")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(new[] { "a", "b", "c" }, Ids(mods)); - } + [Fact] + public void TransitiveChainSortsDeepestFirst() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("c", dependencies: new Mod.Dependency("b", null, null)), + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null)), + ModFactory.MakeMod("a")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(new[] { "a", "b", "c" }, Ids(mods)); + } - [Fact] - public void DependencyCycleReturnsFalseAndLeavesDictionaryUntouched() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("a", dependencies: new Mod.Dependency("b", null, null)), - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null))); - Assert.False(Loader.SortMods(mods)); - Assert.Equal(new[] { "a", "b" }, Ids(mods)); - } + [Fact] + public void DependencyCycleReturnsFalseAndLeavesDictionaryUntouched() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("a", dependencies: new Mod.Dependency("b", null, null)), + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("a", null, null))); + Assert.False(Loader.SortMods(mods)); + Assert.Equal(new[] { "a", "b" }, Ids(mods)); + } - [Fact] - public void DependencyOnMissingModDoesNotBlockSorting() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)), - ModFactory.MakeMod("a")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(2, mods.Count); - } + [Fact] + public void DependencyOnMissingModDoesNotBlockSorting() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("b", dependencies: new Mod.Dependency("ghost", null, null)), + ModFactory.MakeMod("a")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(2, mods.Count); + } - [Fact] - public void FailedModsSinkToEnd() - { - var mods = ModFactory.Mods( - ModFactory.MakeMod("bad", Mod.Status.Error), - ModFactory.MakeMod("good")); - Assert.True(Loader.SortMods(mods)); - Assert.Equal(new[] { "good", "bad" }, Ids(mods)); - } + [Fact] + public void FailedModsSinkToEnd() + { + var mods = ModFactory.Mods( + ModFactory.MakeMod("bad", Mod.Status.Error), + ModFactory.MakeMod("good")); + Assert.True(Loader.SortMods(mods)); + Assert.Equal(new[] { "good", "bad" }, Ids(mods)); + } } diff --git a/tests/ModFactory.cs b/tests/ModFactory.cs index 2e2c9a1..1a78280 100644 --- a/tests/ModFactory.cs +++ b/tests/ModFactory.cs @@ -4,14 +4,14 @@ namespace Tests; internal static class ModFactory { - internal static Mod MakeMod( - string id, - Mod.Status status = Mod.Status.Success, - Version? version = null, - params Mod.Dependency[] dependencies) => - new(new Mod.Manifest(id, null, null, version ?? new Version(1, 0, 0), new[] { "author" }, dependencies), - status, new()); + internal static Mod MakeMod( + string id, + Mod.Status status = Mod.Status.Success, + Version? version = null, + params Mod.Dependency[] dependencies) => + new(new Mod.Manifest(id, null, null, version ?? new Version(1, 0, 0), new[] { "author" }, dependencies), + status, new()); - internal static Dictionary Mods(params Mod[] mods) => - mods.ToDictionary(mod => mod.id); + internal static Dictionary Mods(params Mod[] mods) => + mods.ToDictionary(mod => mod.id); } diff --git a/tests/TestSetup.cs b/tests/TestSetup.cs index 4e8e3b2..87f54f1 100644 --- a/tests/TestSetup.cs +++ b/tests/TestSetup.cs @@ -7,24 +7,24 @@ namespace Tests; internal static class TestSetup { - [ModuleInitializer] - internal static void Init() - { - var root = AppContext.BaseDirectory; - var prop = typeof(BepInEx.Paths).GetProperty( - nameof(BepInEx.Paths.BepInExRootPath), - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); - try - { - prop?.SetValue(null, root); - } - catch (ArgumentException) - { - var field = typeof(BepInEx.Paths) - .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) - .FirstOrDefault(f => f.Name.Contains("BepInExRootPath", StringComparison.Ordinal)); - field?.SetValue(null, root); - } - Plugin.logger ??= new ManualLogSource("tests"); - } + [ModuleInitializer] + internal static void Init() + { + var root = AppContext.BaseDirectory; + var prop = typeof(BepInEx.Paths).GetProperty( + nameof(BepInEx.Paths.BepInExRootPath), + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); + try + { + prop?.SetValue(null, root); + } + catch (ArgumentException) + { + var field = typeof(BepInEx.Paths) + .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) + .FirstOrDefault(f => f.Name.Contains("BepInExRootPath", StringComparison.Ordinal)); + field?.SetValue(null, root); + } + Plugin.logger ??= new ManualLogSource("tests"); + } } diff --git a/tests/UtilTests.cs b/tests/UtilTests.cs index 7b42ad1..2bb4799 100644 --- a/tests/UtilTests.cs +++ b/tests/UtilTests.cs @@ -4,31 +4,31 @@ namespace Tests; public class UtilTests { - [Theory] - [InlineData("1.0.0", "2.0.0", true)] // older core - [InlineData("2.0.0", "1.0.0", false)] // newer core - [InlineData("2.0.0", "2.0.0", true)] // equal - [InlineData("2.0", "2.0.0", true)] // shorter version sorts first - [InlineData("2.0.0.1", "2.0.0", false)] // revision makes it newer - [InlineData("2.0.0", "2.0.0-beta", false)] // release is newer than its pre-release - [InlineData("2.0.0-beta", "2.0.0", true)] - [InlineData("2.0.0-alpha", "2.0.0-beta", true)] // alphanumeric identifiers compare lexically - [InlineData("2.0.0-rc.9", "2.0.0-rc.10", true)] // numeric identifiers compare numerically - [InlineData("2.0.0-rc.10", "2.0.0-rc.9", false)] - [InlineData("2.0.0-9", "2.0.0-10", true)] - [InlineData("2.0.0-1", "2.0.0-alpha", true)] // numeric sorts before alphanumeric - [InlineData("2.0.0-pre", "2.0.0-pre.1", true)] // more identifiers mean a newer pre-release - [InlineData("2.0.0-pre.1", "2.0.0-pre", false)] - [InlineData("2.0.0-alpha-1", "2.0.0-alpha-2", true)] // everything after the first dash is the tag - [InlineData("2.0.0-alpha-2", "2.0.0-alpha-1", false)] - public void VersionComparisons(string version, string other, bool expected) => - Assert.Equal(expected, version.IsVersionOlderOrEqual(other)); + [Theory] + [InlineData("1.0.0", "2.0.0", true)] // older core + [InlineData("2.0.0", "1.0.0", false)] // newer core + [InlineData("2.0.0", "2.0.0", true)] // equal + [InlineData("2.0", "2.0.0", true)] // shorter version sorts first + [InlineData("2.0.0.1", "2.0.0", false)] // revision makes it newer + [InlineData("2.0.0", "2.0.0-beta", false)] // release is newer than its pre-release + [InlineData("2.0.0-beta", "2.0.0", true)] + [InlineData("2.0.0-alpha", "2.0.0-beta", true)] // alphanumeric identifiers compare lexically + [InlineData("2.0.0-rc.9", "2.0.0-rc.10", true)] // numeric identifiers compare numerically + [InlineData("2.0.0-rc.10", "2.0.0-rc.9", false)] + [InlineData("2.0.0-9", "2.0.0-10", true)] + [InlineData("2.0.0-1", "2.0.0-alpha", true)] // numeric sorts before alphanumeric + [InlineData("2.0.0-pre", "2.0.0-pre.1", true)] // more identifiers mean a newer pre-release + [InlineData("2.0.0-pre.1", "2.0.0-pre", false)] + [InlineData("2.0.0-alpha-1", "2.0.0-alpha-2", true)] // everything after the first dash is the tag + [InlineData("2.0.0-alpha-2", "2.0.0-alpha-1", false)] + public void VersionComparisons(string version, string other, bool expected) => + Assert.Equal(expected, version.IsVersionOlderOrEqual(other)); - [Fact] - public void HashProducesUppercaseSha256Hex() - { - Assert.Equal( - "9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08", - Util.Hash("test")); - } + [Fact] + public void HashProducesUppercaseSha256Hex() + { + Assert.Equal( + "9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08", + Util.Hash("test")); + } } diff --git a/tests/VersionJsonTests.cs b/tests/VersionJsonTests.cs index d080b15..f85fe15 100644 --- a/tests/VersionJsonTests.cs +++ b/tests/VersionJsonTests.cs @@ -5,13 +5,13 @@ namespace Tests; public class VersionJsonTests { - private static readonly JsonSerializerOptions options = new() { Converters = { new VersionJson() } }; + private static readonly JsonSerializerOptions options = new() { Converters = { new VersionJson() } }; - [Fact] - public void VersionRoundTripsThroughString() - { - var json = JsonSerializer.Serialize(new Version(1, 2, 3), options); - Assert.Equal("\"1.2.3\"", json); - Assert.Equal(new Version(1, 2, 3), JsonSerializer.Deserialize(json, options)); - } + [Fact] + public void VersionRoundTripsThroughString() + { + var json = JsonSerializer.Serialize(new Version(1, 2, 3), options); + Assert.Equal("\"1.2.3\"", json); + Assert.Equal(new Version(1, 2, 3), JsonSerializer.Deserialize(json, options)); + } } From c4712c5ec4e3a015a5202f13eb39121624a7394d Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 9 Nov 2026 18:13:40 +0100 Subject: [PATCH 33/42] added docstrings --- src/Api/Config.cs | 60 +++- src/Api/GLDConfig.cs | 34 +++ src/Api/PolyScript.cs | 65 ++++- src/Dumper.cs | 69 ++++- src/Json/EnumCacheJson.cs | 78 ++--- src/Json/EnumNameJson.cs | 23 +- src/Json/JsonMerger.cs | 45 ++- src/Json/Vector2Json.cs | 22 +- src/Json/VersionJson.cs | 22 +- src/Loader.cs | 256 ++++++++++++++--- src/Managers/Audio.cs | 38 ++- src/Managers/Compatibility.cs | 121 ++++++-- src/Managers/Hub.cs | 116 +++++++- src/Managers/Loc.cs | 58 +++- src/Managers/Main.cs | 218 ++++++++++---- src/Managers/Prefabs.cs | 269 +++++++++++++++++ src/Managers/TribePreviews.cs | 69 ++++- src/Managers/Visual.cs | 512 ++++++++++++++++++++++++++++++--- src/Mod.cs | 71 ++--- src/NullableFix.cs | 25 +- src/Plugin.cs | 95 ++++-- src/Prefabs/OtherPrefabInfo.cs | 117 ++++++++ src/Prefabs/PrefabsInfo.cs | 13 + src/Prefabs/SkinnedKey.cs | 44 +++ src/Prefabs/VisualPartInfo.cs | 54 ++++ src/Registry.cs | 83 ++++-- src/Util.cs | 85 ++++-- 27 files changed, 2268 insertions(+), 394 deletions(-) diff --git a/src/Api/Config.cs b/src/Api/Config.cs index 88b8045..047a2f0 100644 --- a/src/Api/Config.cs +++ b/src/Api/Config.cs @@ -4,8 +4,18 @@ namespace PolyMod.Api; /// -/// Allows mods to save config. +/// The config of a mod. It keeps the config object in memory and reads it from and writes it to a JSON file. /// +/// +/// +/// To use a config, call first. Then use or . +/// Call to write your changes to disk. +/// +/// +/// The class uses System.Text.Json to read and write the config object. +/// +/// +/// The type of the config object. public class Config where T : class { private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; @@ -15,6 +25,11 @@ public class Config where T : class private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); private readonly string perModConfigPath; private T? defaultConfig; + /// + /// Makes a config for a mod and reads the config from disk if the config file exists. + /// + /// The mod name, normally the mod id. The config uses it as the file name or as the key in mods.json. + /// The place on disk for the config. public Config(string modName, ConfigTypes configType) { this.modName = modName; @@ -23,6 +38,13 @@ public Config(string modName, ConfigTypes configType) Load(); } + /// + /// Reads the config from disk into memory. + /// For , the method reads the file Mods/{modName}.json. + /// For , the method reads the value with the mod name as its key in mods.json. + /// If the file does not exist, the method does not change the config in memory. + /// + /// The config type is not a known value. internal void Load() // can be called internally if config changes; gui config not implemented yet { switch (configType) @@ -52,8 +74,11 @@ public Config(string modName, ConfigTypes configType) } } /// - /// Sets the default if the config does not exist yet. Always call this before reading from the config. + /// Sets the default config. Call this method before you read or edit the config. + /// If there is no config in memory, the method uses the default config and writes it to disk. + /// If there is a config in memory, for example a config that the constructor read from disk, the method keeps that config. /// + /// The config object to use when there is no config in memory. public void SetDefaultConfig(T defaultValue) { defaultConfig = defaultValue; @@ -63,37 +88,51 @@ public void SetDefaultConfig(T defaultValue) } /// - /// Writes the **entire** config. Usage not recommended, use Edit() instead + /// Replaces the full config object in memory. To change only some values, use . + /// This method does not write to disk. Call to write the config to disk. /// + /// The new config object. public void Write(T config) { currentConfig = config; } /// - /// Gets the config. Should only be called after setting a default. + /// Gets the config object that is in memory. /// + /// The config object. Changes to it stay in memory until you call . + /// There is no config in memory. This occurs when there is no config on disk and you did not call . public T Get() { return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); } /// - /// Edits the config. Should only be called after setting a default. + /// Calls an action on the config object that is in memory, so that the action can change the config. /// - /// Call SaveChanges after editing + /// This method does not write to disk. Call after you edit the config. + /// The action that changes the config object. + /// There is no config in memory. This occurs when there is no config on disk and you did not call . public void Edit(Action editor) { editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); } /// - /// Gets part of the config. Should only be called after setting a default + /// Gets one value from the config object that is in memory. /// + /// The type of the value. + /// The function that gets the value from the config object. + /// The value that gives. + /// There is no config in memory. This occurs when there is no config on disk and you did not call . public TResult Get(Func getter) { return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); } /// - /// Writes the config to disk + /// Writes the config object that is in memory to disk as indented JSON. + /// For , the method replaces the file Mods/{modName}.json. + /// For , the method replaces the value with the mod name as its key in mods.json. + /// It keeps the values of other mods in mods.json. /// + /// The config type is not a known value. public void SaveChanges() { switch (configType) @@ -113,9 +152,14 @@ public void SaveChanges() } } + /// + /// The places on disk for a config. + /// public enum ConfigTypes { + /// The config is in its own file, Mods/{modName}.json. PerMod, + /// The config is a value in the shared mods.json file in the game folder, with the mod name as its key. Exposed } } diff --git a/src/Api/GLDConfig.cs b/src/Api/GLDConfig.cs index 758d60b..15bc345 100644 --- a/src/Api/GLDConfig.cs +++ b/src/Api/GLDConfig.cs @@ -5,6 +5,20 @@ namespace PolyMod.Api; +/// +/// A GLD patch template with config values. +/// PolyMod uses it for each patch.json and patch_*.json file of a mod. +/// +/// +/// +/// A patch file can use the Scriban template syntax. In the template, write {{ config "key" "default" }} to get a config value. +/// The function gets the value with that key from the section of the mod in mods.json, as text. +/// If the key does not exist, the function adds the key with the default value and gives the default value. +/// +/// +/// The users can change the values in mods.json. The changes apply the next time that PolyMod loads the patch. +/// +/// public class GldConfigTemplate { private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); @@ -13,12 +27,21 @@ public class GldConfigTemplate private JsonObject currentConfig = new(); private string modName; + /// + /// Makes a template from the text of a patch file and reads the config values of the mod from mods.json. + /// + /// The text of the patch file. + /// The mod id. The template uses it as the key of the mod section in mods.json. public GldConfigTemplate(string templateText, string modName) { this.templateText = templateText; this.modName = modName; Load(); } + /// + /// Reads the config values of the mod from mods.json. + /// If the file does not exist, or the mod does not have a JSON object in it, the method uses an empty config. + /// private void Load() { if (File.Exists(ConfigPath)) @@ -35,6 +58,12 @@ private void Load() currentConfig = new JsonObject(); } + /// + /// Renders the template with the config values of the mod. + /// If the text does not contain {{, the method gives the text without changes. + /// If the template uses a key that is not in the config, the method writes the default value to mods.json. + /// + /// The rendered text, or null if the template has an error. The method writes the error to the log. public string? Render() { if (!templateText.Contains("{{")) return templateText; @@ -75,6 +104,11 @@ private void Load() return result; } + /// + /// Writes the config values of the mod to mods.json as indented JSON. + /// The method replaces the section of the mod and keeps the sections of other mods. + /// If the file does not exist or does not contain a JSON object, the method makes a new file. + /// public void SaveChanges() { JsonObject modsConfigJson; diff --git a/src/Api/PolyScript.cs b/src/Api/PolyScript.cs index cb2383a..757b6a7 100644 --- a/src/Api/PolyScript.cs +++ b/src/Api/PolyScript.cs @@ -3,31 +3,58 @@ namespace PolyMod.Api; +/// +/// The base class of all mod scripts. Do not use this class directly. +/// To make a mod script, make a subclass of or . +/// +/// +/// When PolyMod loads a mod assembly, it finds the first type in the assembly that is a subclass of this class. +/// It makes an instance of that type, calls , and then calls . +/// public abstract class PolyScriptBase { /// - /// Initializes the PolyScript with the given mod and logger. + /// Gives the mod and the logger to the script. PolyMod calls this method before . /// - /// The mod instance. - /// The logger instance. + /// The mod that the script belongs to. + /// The log source of the mod. internal abstract void Initialize(Mod mod, ManualLogSource logger); - /// > - /// Called when the mod is loaded. + /// + /// Starts the mod script. PolyMod calls this method one time, after it loads the mod assembly. + /// Put the code that starts your mod here, for example the code that applies your Harmony patches. /// public abstract void Load(); /// - /// Called when the mod is unloaded. + /// Stops the mod script. PolyMod does not call this method at this time. /// public abstract void Unload(); + /// + /// Makes a script. The constructor is internal, so only classes in PolyMod can be direct subclasses. + /// internal PolyScriptBase() { } } +/// +/// The base class for a mod script with a typed per-mod config and a typed exposed config. +/// +/// +/// Make a subclass and override . +/// Before PolyMod calls , it sets the , , , and properties. +/// +/// The type of the per-mod config object. +/// The type of the exposed config object. public abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class { + /// + /// Sets the and properties. + /// Makes the per-mod config and the exposed config, with the mod id as the mod name. + /// + /// The mod that the script belongs to. + /// The log source of the mod. internal override void Initialize(Mod mod, ManualLogSource logger) { Mod = mod; @@ -36,19 +63,45 @@ internal override void Initialize(Mod mod, ManualLogSource logger) Logger = logger; } + /// + /// Gets the contents of a file of the mod. + /// + /// The name of the file in the mod. The name must match exactly. + /// The bytes of the file, or null if the mod does not have a file with that name. internal byte[]? GetFile(string fileName) { return Registry.mods[Mod.id].files.FirstOrDefault(f => f.name == fileName)?.bytes; } + /// + /// Does nothing. Override this method to stop your mod. PolyMod does not call this method at this time. + /// public override void Unload() { } + /// + /// Gets the mod that the script belongs to. + /// public Mod Mod { get; private set; } = null!; + /// + /// Gets the per-mod config. PolyMod keeps it in the file Mods/{mod id}.json. + /// Call before you read it. + /// protected Config Config { get; private set; } = null!; + /// + /// Gets the exposed config. PolyMod keeps it in the shared mods.json file, with the mod id as its key. + /// Call before you read it. + /// protected Config ExposedConfig { get; private set; } = null!; + /// + /// Gets the log source of the mod. Use it to write messages to the BepInEx log. + /// protected ManualLogSource Logger { get; private set; } = null!; } +/// +/// The base class for a mod script that uses for the per-mod config and the exposed config. +/// Make a subclass and override . +/// public abstract class PolyScript : PolyScript { } diff --git a/src/Dumper.cs b/src/Dumper.cs index 343044a..cd072c9 100644 --- a/src/Dumper.cs +++ b/src/Dumper.cs @@ -8,8 +8,8 @@ namespace PolyMod.Managers; /// -/// Writes the game's own data (logic, localization, sprites, tribe previews and prefabs) to disk -/// so that mod authors can use it as a reference. +/// The manager that writes the data of the game to disk as a reference for mod authors. +/// It writes the game logic, the localization, the sprites, the tribe previews, and the prefabs. /// internal static class Dumper { @@ -30,8 +30,18 @@ internal static class Dumper Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; + /// + /// Gets the full path of the folder that contains the dump. + /// internal static string RootPath => Path.GetFullPath(Plugin.DUMPED_DATA_PATH); + /// + /// Makes the dump folder and writes all parts of the dump. + /// + /// + /// The method calls , , , , and . + /// Each of these methods writes an error to the log if it fails, and the next method runs. + /// internal static void DumpAll() { Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); @@ -43,8 +53,12 @@ internal static void DumpAll() } /// - /// Dumps every version of the game logic and avatar data. + /// Writes each version of the game logic data and of the avatar data to . /// + /// + /// The file names are GameLogicData{version}.json and AvatarData{version}.json. + /// If an error occurs, the method writes it to the log. + /// internal static void DumpLogic() { try @@ -71,6 +85,15 @@ internal static void DumpLogic() } } + /// + /// Writes the localization of the game to . + /// + /// + /// The method uses the first localization source of the game. + /// For each language, it writes a language_{code}.json file with all terms that have a translation. + /// For each category, it writes a localization_{category}.csv file. + /// If an error occurs, the method writes it to the log. + /// internal static void DumpLocalization() { try @@ -111,6 +134,16 @@ internal static void DumpLocalization() } } + /// + /// Writes the sprites of the loaded atlases to . + /// + /// + /// The method uses the atlas list in AtlasData.raw and skips each atlas that is not loaded. + /// For each atlas, it makes a folder with the atlas name. + /// It writes each sprite of the atlas as a PNG file in that folder. + /// It also writes the sprite information of the atlas to sprites_{atlas}.json. + /// If an error occurs, the method writes it to the log. + /// internal static void DumpSprites() { try @@ -150,6 +183,16 @@ internal static void DumpSprites() } } + /// + /// Writes the tribe preview map of each tribe to . + /// + /// + /// The method uses only the preview of the default skin. + /// For each tribe that has a preview, it reads the save state of the preview. + /// It writes the terrain, resource, unit, improvement, and tile effects of each tile to preview_{tribe}.json. + /// If the method cannot read a save state, it writes a warning and skips that tribe. + /// If an error occurs, the method writes it to the log. + /// internal static void DumpTribePreviews() { try @@ -193,6 +236,16 @@ internal static void DumpTribePreviews() } } + /// + /// Writes the unit, improvement, and resource prefabs to prefabs.json in . + /// + /// + /// The method writes the file in the format. + /// The units come from , and the improvements and resources come from PrefabManager. + /// The method skips each prefab that has no SkinVisualsReference. + /// It does not write weapon prefabs. + /// If an error occurs, the method writes it to the log. + /// internal static void DumpPrefabs() { try @@ -268,6 +321,16 @@ internal static void DumpPrefabs() } } + /// + /// Gets the descriptions of the visual parts of a prefab. + /// + /// + /// The method skips each visual part that is null or that has no visual part object. + /// If the prefab has no SkinVisualsReference or no visual parts, the method writes a warning. + /// + /// The prefab to read. + /// The key of the prefab. The method uses it only in the warning. + /// The descriptions of the visual parts, or null if the prefab has no SkinVisualsReference or no visual parts. private static List? CollectVisualParts(Component prefab, object key) { SkinVisualsReference skinVisualsReference = prefab.GetComponent(); diff --git a/src/Json/EnumCacheJson.cs b/src/Json/EnumCacheJson.cs index 5f561c6..964e0ff 100644 --- a/src/Json/EnumCacheJson.cs +++ b/src/Json/EnumCacheJson.cs @@ -4,33 +4,38 @@ namespace PolyMod.Json; /// -/// A custom JSON converter for enum types that integrates with EnumCache. -/// Supports serializing and deserializing enums by their cached string names, -/// and works with both single enum values and property names. +/// The JSON converter that reads and writes a game enum value as its name in EnumCache. +/// The JSON form is a string, for example "imperius". The converter also reads and writes the value as a property name. /// -/// The enum type being converted. +/// +/// Use this converter for enums that mods can extend, because EnumCache also has the names of the values that mods add. +/// +/// The enum type to convert. public class EnumCacheJson : JsonConverter where T : struct, Enum { /// - /// Determines whether the converter can handle the given type. - /// Supports both the enum type and . + /// Finds if the converter accepts a type. + /// The method gives true for and for of . /// - /// The type to check for compatibility. - /// True if the type can be converted; otherwise false. + /// + /// The method can read only . For lists, use . + /// + /// The type to check. + /// True if the type is or of , otherwise false. public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(T) || typeToConvert == typeof(List); } /// - /// Reads a JSON string and converts it into the corresponding enum value - /// using the EnumCache lookup. + /// Reads a JSON string and gets the enum value with that name from EnumCache. + /// If EnumCache does not have the name, EnumCache throws an exception. /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// The enum value represented by the JSON string. - /// Thrown if the type is not supported. + /// The JSON reader, at a string token or a property name token. + /// The type to read. It must be . + /// The serializer options. The method does not use them. + /// The enum value that has the name in the JSON string. + /// is not . public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (typeToConvert == typeof(T)) @@ -43,34 +48,35 @@ public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerial /// - /// Writes the enum value as its cached string representation. + /// Writes the enum value as a JSON string with its name from EnumCache. /// /// The JSON writer. /// The enum value to write. - /// Serialization options. + /// The serializer options. The method does not use them. public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WriteStringValue(EnumCache.GetName(value)); } /// - /// Reads a JSON property name and converts it into the corresponding enum value. + /// Reads a JSON property name and gets the enum value with that name from EnumCache. + /// The method calls . /// - /// The JSON reader. - /// The target type. - /// Serialization options. - /// The enum value represented by the property name. + /// The JSON reader, at a property name token. + /// The type to read. It must be . + /// The serializer options. The method does not use them. + /// The enum value that has the name in the property name. public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return Read(ref reader, typeToConvert, options); } /// - /// Writes the enum value as a property name using its cached string representation. + /// Writes the enum value as a JSON property name with its name from EnumCache. /// /// The JSON writer. /// The enum value to write. - /// Serialization options. + /// The serializer options. The method does not use them. public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WritePropertyName(EnumCache.GetName(value)); @@ -78,25 +84,25 @@ public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSer } /// -/// A custom JSON converter for lists of enum values that integrates with EnumCache. -/// Serializes enum values as strings and deserializes them back into a list of enums. +/// The JSON converter that reads and writes a list of game enum values as their names in EnumCache. +/// The JSON form is an array of strings, for example ["imperius", "bardur"]. /// -/// The enum type being converted. +/// The enum type of the list items. public class EnumCacheListJson : JsonConverter> where T : struct, Enum { /// - /// Inner converter used to handle individual enum values. + /// The converter that reads and writes each item of the list. /// private readonly EnumCacheJson _inner = new(); /// - /// Reads a JSON array of enum string values and converts them into a list of enum values. + /// Reads a JSON array of strings and gets the enum value for each string from EnumCache. /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// A list of enum values. - /// Thrown if the JSON is not an array. + /// The JSON reader, at the start of the array. + /// The type to read. The method does not use it. + /// The serializer options. The method gives them to the item converter. + /// The list of enum values, in the same order as the array. + /// The JSON value is not an array. public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var list = new List(); @@ -116,11 +122,11 @@ public override List Read(ref Utf8JsonReader reader, Type typeToConvert, Json } /// - /// Writes a list of enum values as a JSON array of strings. + /// Writes a list of enum values as a JSON array of strings with their names from EnumCache. /// /// The JSON writer. /// The list of enum values to write. - /// Serialization options. + /// The serializer options. The method gives them to the item converter. public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) { writer.WriteStartArray(); diff --git a/src/Json/EnumNameJson.cs b/src/Json/EnumNameJson.cs index f4e7231..e60517d 100644 --- a/src/Json/EnumNameJson.cs +++ b/src/Json/EnumNameJson.cs @@ -4,11 +4,24 @@ namespace PolyMod.Json; /// -/// Converts fixed (non-extensible) enums to and from their plain string names. -/// Use this for enums that are not registered in EnumCache. +/// The JSON converter that reads and writes an enum value as its C# member name. +/// The JSON form is a string, for example "Linear". /// +/// +/// Use this converter for enums that mods cannot extend and that EnumCache does not have. +/// +/// The enum type to convert. public class EnumNameJson : JsonConverter where TEnum : struct, Enum { + /// + /// Reads a JSON string and gets the enum value with that member name. The name is not case-sensitive. + /// The method uses Enum.TryParse, so it also accepts numeric strings. + /// + /// The JSON reader, at a string token. + /// The type to read. The method does not use it. + /// The serializer options. The method does not use them. + /// The enum value that has the name in the JSON string. + /// The JSON value is null or is not a member name of . The message shows the valid names. public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { string? enumName = reader.GetString(); @@ -22,6 +35,12 @@ public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSe throw new JsonException($"Unknown {typeof(TEnum).Name} value '{enumName}'. Valid values: {validNames}"); } + /// + /// Writes the enum value as a JSON string with its C# member name. + /// + /// The JSON writer. + /// The enum value to write. + /// The serializer options. The method does not use them. public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); diff --git a/src/Json/JsonMerger.cs b/src/Json/JsonMerger.cs index 4b6d8c3..e14edab 100644 --- a/src/Json/JsonMerger.cs +++ b/src/Json/JsonMerger.cs @@ -4,16 +4,28 @@ namespace PolyMod.Json; /// -/// Provides functionality to merge JSON objects, with special handling for arrays. +/// The merge of a JSON patch into a JSON object, for example a GLD patch into the game logic data. /// +/// +/// +/// Objects merge recursively. A value in the patch replaces the value in the original, and a null value in the patch sets the value to null. +/// +/// +/// Arrays have special rules. A string that starts with + adds the string without the + to the original array. +/// A string that starts with - removes all equal strings from the original array. +/// In an array with the name skins, a plain string also adds the string. +/// If an array has none of these items, the patch array replaces the original array. +/// If an array has some of these items, the merge ignores the other plain strings in it. +/// +/// public static class JsonMerger { /// - /// Merges a patch JObject into an original JObject. + /// Merges a patch into an original JSON object. The method changes and . /// - /// The original JObject. - /// The patch JObject to merge. - /// The merged JObject. + /// The JSON object to change. + /// The JSON object with the changes. + /// The object, after the merge. public static JObject Merge(JObject original, JObject patch) { patch = MergeRecursive(original, patch); @@ -22,11 +34,13 @@ public static JObject Merge(JObject original, JObject patch) } /// - /// Recursively applies custom merging logic to arrays. + /// Replaces each array in the patch with the result of , at all levels of the patch. + /// If the original does not have a matching array or object, the method uses an empty one. + /// After this method, a normal merge with array replacement gives the correct arrays. /// - /// - /// - /// + /// The JSON object that the patch applies to. + /// The JSON object with the changes. The method changes this object. + /// The object, with the merged arrays. private static JObject MergeRecursive(JObject original, JObject patch) { foreach (var property in patch.Properties().ToArray().ToList()) @@ -61,12 +75,15 @@ private static JObject MergeRecursive(JObject original, JObject patch) } /// - /// Merges two JArrays, with special handling for adding and removing elements. + /// Merges a patch array into a copy of an original array. + /// A string that starts with + adds the string without the +. A string that starts with - removes all equal strings. + /// The method adds all items that are not strings. It ignores plain strings, but adds them if is true. + /// If the patch has no + strings, no - strings, and no plain strings in a skins array, the method gives a copy of the patch array. /// - /// The original JArray. - /// The patch JArray to merge. - /// A flag to indicate if the array is a 'skins' array, which has special merging logic. - /// The merged JArray. + /// The original array. The method does not change it. + /// The patch array. + /// True if the array has the name skins. Then plain strings add to the original array. + /// A new array with the merged items. private static JArray MergeArrays(JArray original, JArray patch, bool isSkins) { var result = new JArray(original); diff --git a/src/Json/Vector2Json.cs b/src/Json/Vector2Json.cs index 1957c4d..ef66d56 100644 --- a/src/Json/Vector2Json.cs +++ b/src/Json/Vector2Json.cs @@ -5,17 +5,19 @@ namespace PolyMod.Json; /// -/// Converts a to and from a JSON array of two numbers. +/// The JSON converter that reads and writes a . +/// The JSON form is an array of two numbers, x and y, for example [0.5, -1]. /// public class Vector2Json : JsonConverter { /// - /// Reads and converts the JSON to a . + /// Reads a JSON array of two numbers and makes a from them. /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. + /// The JSON reader, at the start of the array. + /// The type to read. The method does not use it. + /// The serializer options. The method does not use them. + /// The vector with the first number as x and the second number as y. + /// The JSON value is not an array, an item is not a number, or the array does not have exactly two items. public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { List values = new(); @@ -33,11 +35,11 @@ public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, Json } /// - /// Writes a specified value as JSON. + /// Writes a as a JSON array of two numbers, x and y. /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. + /// The JSON writer. + /// The vector to write. + /// The serializer options. The method does not use them. public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) { writer.WriteStartArray(); diff --git a/src/Json/VersionJson.cs b/src/Json/VersionJson.cs index 21c6c81..fe97094 100644 --- a/src/Json/VersionJson.cs +++ b/src/Json/VersionJson.cs @@ -4,28 +4,30 @@ namespace PolyMod.Json; /// -/// Converts a to and from a JSON string. +/// The JSON converter that reads and writes a . +/// The JSON form is a version string, for example "1.2.3". /// public class VersionJson : JsonConverter { /// - /// Reads and converts the JSON to a . + /// Reads a JSON string and makes a from it. + /// The constructor throws an exception if the string is null or is not a valid version. /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. + /// The JSON reader, at a string token. + /// The type to read. The method does not use it. + /// The serializer options. The method does not use them. + /// The version from the JSON string. public override Version? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(reader.GetString()!); } /// - /// Writes a specified value as JSON. + /// Writes a as a JSON string, for example "1.2.3". /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. + /// The JSON writer. + /// The version to write. + /// The serializer options. The method does not use them. public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); diff --git a/src/Loader.cs b/src/Loader.cs index 7a18e3a..6cd40a9 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -18,7 +18,7 @@ namespace PolyMod; /// -/// Handles loading of mods and their assets. +/// The methods that register mods, sort them, load their files and apply their GLD data. /// internal static class Loader { @@ -38,10 +38,15 @@ internal static class Loader PropertyNameCaseInsensitive = true, }; + /// + /// The C# type that PolyMod uses for one GLD data category. + /// + /// The C# type of the data category. To make EnumCache mappings, this type must be an enum. + /// If true, makes EnumCache mappings for new entries of the category. If false, it only calls the type handlers. internal record TypeMapping(Type type, bool shouldCreateCache = true); /// - /// Mappings from JSON data types to their corresponding C# types. + /// The type mappings of the GLD data categories, keyed by the category name in the GLD, for example unitData. /// internal static Dictionary typeMappings = new() { @@ -61,8 +66,20 @@ internal record TypeMapping(Type type, bool shouldCreateCache = true); }; /// - /// Handlers for processing specific data types during mod loading. + /// The type handlers that calls for each GLD entry, keyed by the C# type of the data category. /// + /// + /// Each handler gets the JSON object of the entry and a flag. + /// The flag is true when calls the handler just after it made a new EnumCache mapping for the entry. + /// The flag is false in the second pass, in which calls the handler for all entries of the category. + /// + /// : in the first pass, adds the tribe to and gives it a new style and climate. In the second pass, makes EnumCache mappings for new skins, makes a flood tile effect for each new skin of a tribe with the Flooded ability, changes the skin ids to indexes, and keeps the tribe preview. + /// UnitData.Type: in the second pass, adds the embarksTo value to Main.embarkNames and changes the weapon name to its index. + /// ImprovementData.Type: in the second pass, adds the improvement to the prefabs to make if prefab is true. It also adds the attractsResource, attractsToTerrain and infoOverride values to the related dictionaries. + /// ResourceData.Type: in the second pass, adds the resource to the prefabs to make if prefab is true. + /// SkinData: changes the name of the entry to lowercase. + /// + /// internal static readonly Dictionary>> typeHandlers = new() { [typeof(TribeType)] = new List>() { @@ -220,22 +237,37 @@ out TribeAbility.Type tribeAbilityType }; /// - /// Adds a new data type for patching. + /// Adds a type mapping for a GLD data category. makes EnumCache mappings for new entries of this category. + /// If already contains the category name, the method does nothing. /// - /// The identifier for the data type in JSON. - /// "The C# type corresponding to the identifier. + /// The name of the data category in the GLD, for example unitData. + /// The C# enum type of the data category. public static void AddPatchDataType(string typeId, Type type) { if (!typeMappings.ContainsKey(typeId)) typeMappings.Add(typeId, new TypeMapping(type)); } + /// + /// Adds a type mapping for a GLD data category. + /// If already contains the category name, the method does nothing. + /// + /// The name of the data category in the GLD, for example unitData. + /// The C# type of the data category. + /// If true, makes EnumCache mappings for new entries of the category. If false, it only calls the type handlers. public static void AddPatchDataType(string typeId, Type type, bool shouldCreateCache) { if (!typeMappings.ContainsKey(typeId)) typeMappings.Add(typeId, new TypeMapping(type, shouldCreateCache)); } + /// + /// Adds a type handler for a C# type to . + /// A type mapping for the type must exist in . + /// If no type mapping exists, the method writes a warning to the log and does not add the handler. + /// + /// The C# type of the data category. + /// The handler to add. It gets the JSON object of a GLD entry and a flag. The flag is true when just made a new EnumCache mapping for the entry. public static void AddTypeHandler(Type type, Action handler) { string typeString = type.ToString(); @@ -253,9 +285,20 @@ public static void AddTypeHandler(Type type, Action handler) } /// - /// Loads all mods from the mods directory. + /// Finds the mods in and adds them to a dictionary. /// - /// A dictionary to populate with the loaded mods. + /// + /// The method makes the mods directory if it does not exist. + /// A mod can be a directory, a .polymod file or a .zip file. + /// The method reads all files of the mod and gets the manifest from manifest.json at the root. + /// It does not add a mod if the manifest is missing, not valid, or has an id that the dictionary already contains. + /// A manifest is not valid if it has no id, no version or no authors. + /// A manifest is also not valid if the id is polytopia or contains characters other than lowercase letters and underscores. + /// The method also does not add a mod that the configuration disables. + /// For each mod that it does not add, the method writes an error to the log. + /// The method gives each added mod the status and then calls . + /// + /// The dictionary to which the method adds the mods, keyed by the mod id. internal static void RegisterMods(Dictionary mods) { Directory.CreateDirectory(Plugin.MODS_PATH); @@ -341,6 +384,14 @@ ref manifest CheckDependencies(mods); } + /// + /// Adds one file of a mod to the file list, or reads it as the manifest. + /// If the file is manifest.json at the root of the mod, the method parses it into and does not add it to the list. + /// + /// The path of the file, relative to the root of the mod. + /// The contents of the file. + /// The file list of the mod. + /// The manifest of the mod. The method sets it when the file is manifest.json. private static void ProcessModFile(string fullName, byte[] bytes, List files, ref Mod.Manifest? manifest) { if (fullName == "manifest.json") @@ -354,6 +405,19 @@ private static void ProcessModFile(string fullName, byte[] bytes, List files.Add(new(fullName, bytes)); } + /// + /// Sorts the registered mods and loads their assemblies, sprite info files and language files. + /// + /// + /// The method uses , not . + /// First, it sorts the mods with . If there is a dependency cycle, the method stops. + /// For each mod with the status , it loads the .dll files, the sprite info files and the language files. + /// A sprite info file has the name sprites.json or sprites_*.json. + /// A language file has the name language.json or language_*.json. + /// At the end, it calls Compatibility.ComputeChecksums. + /// + /// A dictionary of mods. The method does not use this parameter. + /// Set to true if the mods have a dependency cycle, false otherwise. internal static void LoadMods(Dictionary mods, out bool dependencyCycle) { dependencyCycle = !SortMods(Registry.mods); @@ -388,6 +452,16 @@ internal static void LoadMods(Dictionary mods, out bool dependencyC Compatibility.ComputeChecksums(Registry.mods); } + /// + /// Checks the dependencies of each mod in a dictionary. + /// + /// + /// A dependency fails if the dictionary does not contain it, or if its version is out of the permitted range. + /// For a required dependency that fails, the method writes an error to the log. + /// It also sets the status of the mod to . + /// For an optional dependency that fails, the method only writes a warning to the log. + /// + /// The mods to check, keyed by the mod id. internal static void CheckDependencies(Dictionary mods) { foreach (var (id, mod) in mods) @@ -428,10 +502,17 @@ internal static void CheckDependencies(Dictionary mods) } /// - /// Sorts mods based on their dependencies using a topological sort. + /// Sorts the mods in a dictionary so that each mod comes after its dependencies. /// - /// The dictionary of mods to sort. - /// True if the mods could be sorted (no circular dependencies), false otherwise. + /// + /// The method uses a topological sort on the mods with the status . + /// It ignores dependencies that are not in the dictionary or that do not have the status . + /// If the sort succeeds, the method replaces the contents of the dictionary. + /// The sorted mods come first, then the mods with a different status. + /// If there is a dependency cycle, the method does not change the dictionary. + /// + /// The mods to sort, keyed by the mod id. + /// True if the sort succeeds, false if the mods have a dependency cycle. internal static bool SortMods(Dictionary mods) { Stopwatch s = new(); @@ -493,10 +574,19 @@ internal static bool SortMods(Dictionary mods) } /// - /// Loads an assembly file from a mod. + /// Loads a .dll file of a mod as an assembly and starts its code. /// - /// The mod the assembly belongs to. - /// The assembly file to load. + /// + /// If the assembly has a subclass of , the method makes an instance of the first one. + /// It calls Initialize and then Load on that instance, and does nothing more. + /// If the assembly has no such subclass, the method calls each static Load(ManualLogSource) method and each static Load() method in the assembly. + /// If a static Load method or the constructor of the subclass throws an exception, the method writes an error to the log. + /// It also sets the status of the mod to . + /// The method catches only exceptions of the type . + /// For this reason, it does not catch an exception from Initialize or from Load on a instance. + /// + /// The mod that contains the file. + /// The .dll file to load. public static void LoadAssemblyFile(Mod mod, Mod.File file) { try @@ -542,9 +632,14 @@ public static void LoadAssemblyFile(Mod mod, Mod.File file) } /// - /// Loads a localization file from a mod. + /// Loads a localization file of a mod and adds its terms to the game localization. /// - /// The mod the localization file belongs to. + /// + /// The file is a JSON object. Each key is a term name, and each value is an object that maps language names to texts. + /// The method gives the data to Loc.BuildAndLoadLocalization. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. /// The localization file to load. public static void LoadLocalizationFile(Mod mod, Mod.File file) { @@ -560,6 +655,17 @@ public static void LoadLocalizationFile(Mod mod, Mod.File file) } } + /// + /// Loads a language file of a mod and adds it to Loc.languagesToAdd. + /// + /// + /// The file is a JSON object that maps term names to texts. + /// If an error occurs, the method writes the error to the log. + /// An error occurs, for example, when a different file already added the same language code. + /// + /// The mod that contains the file. + /// The language file to load. + /// The language code from the file name. It is the text after language_, or an empty string for language.json. public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) { try @@ -578,10 +684,12 @@ public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) } /// - /// Loads a sprite file from a mod. + /// Loads a PNG file of a mod as a texture and adds it to . + /// The key is the lowercase file name without the extension. + /// The method does not make a sprite. Visual.CreateSprites makes the sprites later. /// - /// The mod the sprite file belongs to. - /// The sprite file to load. + /// The mod that contains the file. The method does not use this parameter. + /// The PNG file to load. public static void LoadTextureFile(Mod mod, Mod.File file) { string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); @@ -590,11 +698,16 @@ public static void LoadTextureFile(Mod mod, Mod.File file) } /// - /// Loads a sprite info file from a mod. + /// Loads a sprite info file of a mod and adds its sprite infos to . /// - /// The mod the sprite info file belongs to. + /// + /// The method changes each sprite name and each sprite origin name to lowercase. + /// A sprite info replaces an existing sprite info with the same name. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. /// The sprite info file to load. - /// A dictionary of sprite information, or null if an error occurred. + /// The sprite infos from the file, keyed by the sprite name as the file gives it, or null if an error occurs. public static Dictionary? LoadSpriteInfoFile(Mod mod, Mod.File file) { try @@ -625,9 +738,15 @@ public static void LoadTextureFile(Mod mod, Mod.File file) } /// - /// Loads an audio file from a mod. + /// Loads an audio file of a mod and adds it to . /// - /// The mod the audio file belongs to. + /// + /// The method uses Audio.BuildAudioClip to make the audio clip. + /// It puts the clip on a new audio source that stays loaded when the scene changes. + /// The key is the lowercase file name without the extension. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. /// The audio file to load. public static void LoadAudioFile(Mod mod, Mod.File file) { @@ -651,6 +770,14 @@ public static void LoadAudioFile(Mod mod, Mod.File file) } } + /// + /// Loads a prefabs file of a mod. + /// The method adds its unit, improvement and resource prefab infos to the lists in Prefabs. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. + /// The prefabs file to load. public static void LoadPrefabsFile(Mod mod, Mod.File file) { try @@ -671,6 +798,13 @@ public static void LoadPrefabsFile(Mod mod, Mod.File file) } } + /// + /// Loads a unit prefab file of a mod and adds its unit prefab info to Prefabs.unitInfos. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. + /// The unit prefab file to load. public static void LoadUnitPrefabFile(Mod mod, Mod.File file) { try @@ -689,6 +823,13 @@ public static void LoadUnitPrefabFile(Mod mod, Mod.File file) } } + /// + /// Loads an improvement prefab file of a mod and adds its improvement prefab info to Prefabs.improvementInfos. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. + /// The improvement prefab file to load. public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) { try @@ -707,6 +848,13 @@ public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) } } + /// + /// Loads a resource prefab file of a mod and adds its resource prefab info to Prefabs.resourceInfos. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. + /// The resource prefab file to load. public static void LoadResourcePrefabFile(Mod mod, Mod.File file) { try @@ -726,11 +874,13 @@ public static void LoadResourcePrefabFile(Mod mod, Mod.File file) } /// - /// Loads and applies a game logic data patch from a mod. + /// Merges a GLD patch of a mod into the GLD. + /// The method uses , which changes in place. + /// If an error occurs, the method writes the error to the log and sets the status of the mod to . /// - /// The mod the patch belongs to. - /// The original game logic data. - /// The patch to apply. + /// The mod that contains the patch. + /// The GLD as a JSON object. The method changes this object. + /// The patch to merge. public static void LoadGameLogicDataPatch(Mod mod, JObject gld, JObject patch) { try @@ -747,9 +897,10 @@ public static void LoadGameLogicDataPatch(Mod mod, JObject gld, JObject patch) } /// - /// Loads an asset bundle from a mod. + /// Loads a .bundle file of a mod as an asset bundle and adds it to . + /// The key is the file name without the extension. /// - /// The mod the asset bundle belongs to. + /// The mod that contains the file. The method does not use this parameter. /// The asset bundle file to load. public static void LoadAssetBundle(Mod mod, Mod.File file) { @@ -760,10 +911,12 @@ public static void LoadAssetBundle(Mod mod, Mod.File file) } /// - /// Processes the merged game logic data after all mods have been loaded and patched. + /// Uses the merged GLD to make enum mappings and to fill the PolyMod overrides. + /// The method calls , , and in sequence. + /// If an error occurs, the method writes the error to the log. /// - /// The game logic data object to populate. - /// The root JObject of the merged game logic data. + /// The game logic data. The method does not use this parameter. + /// The root JSON object of the merged GLD. internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject rootObject) { try @@ -779,6 +932,9 @@ internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject r } } + /// + /// Adds each tribe in to GameLogicData.legacyTribeTypesOrder, if the list does not contain it. + /// internal static void ProcessCustomTribes() { foreach (var tribe in Registry.customTribes) @@ -791,9 +947,20 @@ internal static void ProcessCustomTribes() } /// - /// Creates EnumCache mappings for custom enum values and invokes type handlers. + /// Makes EnumCache mappings for new GLD entries and calls the type handlers. /// - /// + /// + /// The method does two passes over all entries of all data categories in the GLD. + /// In the first pass, it uses only entries that have an idx, in categories with shouldCreateCache set to true. + /// If the type of the category is not an enum, the method writes a warning to the log and ignores the entry. + /// If idx is -1, the method sets idx to the next value of . + /// If allowUnsafeIndexes is true, the method also uses an entry with an idx larger than all existing enum values. + /// The method ignores all other entries in the first pass. + /// For each entry that it uses, it calls EnumCache.AddMapping two times. The first call adds the name, and the second call adds the type. + /// Then it calls the type handlers of the category with the flag set to true. + /// In the second pass, the method calls the type handlers for all entries of categories in , with the flag set to false. + /// + /// The root JSON object of the merged GLD. internal static void CreateMappings(JObject rootObject) { foreach (JToken jtoken in rootObject.SelectTokens("$.*.*").ToArray()) @@ -879,8 +1046,16 @@ internal static void CreateMappings(JObject rootObject) } /// - /// Processes the prefab registry and populates the PrefabManager with custom prefabs. + /// Loads the prefab files in . /// + /// + /// The method uses the file name to select the load method. + /// It calls for prefabs.json, for unitPrefab.json, + /// for improvementPrefab.json and for resourcePrefab.json. + /// Each of these names can also have a suffix that starts with an underscore, for example unitPrefab_knight.json. + /// The method ignores other files. + /// If an error occurs, the method writes the error to the log and stops. + /// internal static void ProcessFilesQueue() { try @@ -926,7 +1101,9 @@ internal static void ProcessFilesQueue() } /// - /// Processes embark overrides by mapping original embark unit types to configured overrides. + /// Changes the unit ids in Main.embarkNames to unit types and adds them to Main.embarkOverrides. + /// Each entry maps a unit to the unit that it becomes when it embarks. + /// If a unit id is not valid, the method writes an error to the log and continues with the next entry. /// internal static void ProcessEmbarkOverrides() { @@ -947,7 +1124,10 @@ internal static void ProcessEmbarkOverrides() } /// - /// Processes attract overrides by mapping improvements to resources and terrain types based on configured overrides. + /// Changes the ids in Main.attractsResourceNames and Main.attractsTerrainNames to enum values. + /// The method adds the results to Main.attractsResourceOverrides and Main.attractsTerrainOverrides. + /// Each entry maps an improvement to the resource that it attracts, or to the terrain on which it attracts resources. + /// If an id is not valid, the method writes an error to the log and continues with the next entry. /// internal static void ProcessAttractOverrides() { diff --git a/src/Managers/Audio.cs b/src/Managers/Audio.cs index 1fcceb2..c7c7475 100644 --- a/src/Managers/Audio.cs +++ b/src/Managers/Audio.cs @@ -5,13 +5,20 @@ namespace PolyMod.Managers; /// -/// Manages custom audio for PolyMod. +/// The manager for custom audio. +/// It replaces game music, nature sounds, and sound effects with the registered audio clips of mods. +/// At this time, is a stub, so the registered clips have no audio data. /// public static class Audio { /// - /// Patches the music data to get custom nature audio clips. + /// A Harmony prefix on MusicData.GetNatureAudioClip. + /// It finds a registered nature audio clip for the tribe and skin. /// + /// The audio clip that the game uses. The patch sets it to the mod clip, if one exists. + /// The tribe of the audio clip. + /// The skin of the audio clip. + /// False if a mod clip exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetNatureAudioClip))] private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) @@ -26,8 +33,13 @@ private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeTy } /// - /// Patches the music data to get custom music audio clips. + /// A Harmony prefix on MusicData.GetMusicAudioClip. + /// It finds a registered music audio clip for the tribe and skin. /// + /// The audio clip that the game uses. The patch sets it to the mod clip, if one exists. + /// The tribe of the audio clip. + /// The skin of the audio clip. + /// False if a mod clip exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetMusicAudioClip))] private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) @@ -42,8 +54,13 @@ private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeTyp } /// - /// Patches the audio SFX data to get custom sound effect clips. + /// A Harmony prefix on AudioSFXData.GetClip. + /// It finds a registered audio clip with the name of the sound effect type, for the skin. /// + /// The audio clip that the game uses. The patch sets it to the mod clip, if one exists. + /// The sound effect type. + /// The skin of the audio clip. + /// False if a mod clip exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(AudioSFXData), nameof(AudioSFXData.GetClip))] private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, SkinType skinType) @@ -61,20 +78,19 @@ private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, Sk } /// - /// Builds an audio clip from raw byte data. + /// A stub for the method that makes an audio clip from the bytes of an audio file. + /// It does not read the data. It only gives a new empty audio clip. /// - /// The byte data of the audio file, which has to be a WAVE file. - /// The name to give the clip inside Unity. - /// The created audio clip. - /// The data is not a WAVE file that can be decoded. - /// The game build cannot create audio clips. + /// The bytes of the audio file. The method does not use them. + /// The name for the audio clip. The method does not use it. + /// A new empty audio clip with no name and no audio data. public static AudioClip BuildAudioClip(byte[] data, string name = "polymod_audio") { return new(); } /// - /// Initializes the Audio manager by patching the necessary methods. + /// Applies all Harmony patches in the class. /// internal static void Init() { diff --git a/src/Managers/Compatibility.cs b/src/Managers/Compatibility.cs index 55b2e28..8646f1f 100644 --- a/src/Managers/Compatibility.cs +++ b/src/Managers/Compatibility.cs @@ -5,22 +5,30 @@ namespace PolyMod.Managers; /// -/// Manages compatibility checks for mods, including checksum verification and version warnings. +/// The compatibility checks for mods. They compare mod checksums with the checksums of saved games. +/// They also show the warnings for an invalid launch and for a new game version. /// internal static class Compatibility { /// - /// The checksum of all loaded mods. + /// The global checksum of all loaded mods that are not client-side mods. /// internal static string checksum = string.Empty; /// - /// Whether the game settings should be reset due to a change in mods. + /// The flag that tells if the tribe and skin selection must go back to the default values. + /// It is true when the global checksum is different from the checksum of the last start. /// internal static bool shouldResetSettings = false; private static bool sawSignatureWarning; private const string downloadLink = "https://polymod.dev/download/"; + /// + /// Calculates the checksum of each mod and the global checksum. + /// The method uses only the mods that loaded successfully, and skips client-side mods and the polytopia mod. + /// It puts each checksum in and the global checksum in . + /// + /// The mods, with their ids as keys. public static void ComputeChecksums(Dictionary mods) { List signatures = new(); @@ -37,6 +45,12 @@ public static void ComputeChecksums(Dictionary mods) checksum = Util.Hash(string.Join("\n", signatures)); } + /// + /// Calculates the checksum of one mod from its id, its version, and the names and contents of its files. + /// The method skips directory entries and sorts the files by name, so the order of the files has no effect. + /// + /// The mod to calculate the checksum for. + /// The SHA256 checksum of the mod as a hexadecimal string. public static string ComputeModChecksum(Mod mod) { List entries = new(); @@ -53,9 +67,9 @@ public static string ComputeModChecksum(Mod mod) } /// - /// Gets the player prefs key holding the checksum a saved game was created with. + /// Gets the player prefs key that keeps the global checksum for a saved game. /// - /// The id of the saved game. + /// The id of the saved game, as a Guid or a string. /// The player prefs key. private static string StateChecksumKey(object gameId) { @@ -63,21 +77,22 @@ private static string StateChecksumKey(object gameId) } /// - /// Normalizes a game id so that the same save always maps to one key. The game hands ids over - /// as a Guid in some places and as a string in others, and those do not always match in case - /// or in whether they are wrapped in braces. + /// Changes a game id to one standard text form, so that one saved game always has one key. + /// The game gives ids as a Guid in some methods and as a string in other methods. + /// The method removes the braces and changes all letters to lowercase. /// /// The id of the saved game, as a Guid or a string. - /// The normalized id. + /// The game id in lowercase, without braces. internal static string NormalizeGameId(object gameId) { return gameId.ToString()!.Trim('{', '}').ToLowerInvariant(); } /// - /// Gets the path of the signature file older versions wrote for a saved game. + /// Gets the path of the legacy .signatures file for a saved game. + /// The file is in the persistent data folder of the game. /// - /// The id of the saved game. + /// The id of the saved game, as a Guid or a string. /// The path of the legacy signature file. private static string LegacyStateChecksumPath(object gameId) { @@ -85,9 +100,9 @@ private static string LegacyStateChecksumPath(object gameId) } /// - /// Stores the current mod checksum for a saved game. + /// Writes the current global checksum to the player prefs for a saved game. /// - /// The id of the saved game. + /// The id of the saved game, as a Guid or a string. internal static void SaveStateChecksum(object gameId) { PlayerPrefs.SetString(StateChecksumKey(gameId), checksum); @@ -95,11 +110,12 @@ internal static void SaveStateChecksum(object gameId) } /// - /// Reads the mod checksum a saved game was created with, migrating it out of the - /// signature file older versions used. + /// Reads the global checksum that the player prefs keep for a saved game. + /// If the player prefs do not have the checksum, the method reads the legacy signature file. + /// It then writes that checksum to the player prefs and deletes the legacy file. /// - /// The id of the saved game. - /// The stored checksum, or an empty string when there is none. + /// The id of the saved game, as a Guid or a string. + /// The saved checksum, or an empty string if there is no saved checksum. internal static string ReadStateChecksum(object gameId) { string key = StateChecksumKey(gameId); @@ -117,6 +133,11 @@ internal static string ReadStateChecksum(object gameId) return legacyChecksum; } + /// + /// Deletes the saved checksum of a saved game from the player prefs. + /// It also deletes the legacy signature file if it exists. + /// + /// The id of the saved game, as a Guid or a string. internal static void DeleteStateChecksum(object gameId) { PlayerPrefs.DeleteKey(StateChecksumKey(gameId)); @@ -128,9 +149,14 @@ internal static void DeleteStateChecksum(object gameId) } /// - /// Checks the signature of a saved game to ensure it is compatible with the current mods. + /// Compares the saved checksum of a saved game with the current global checksum. + /// If the checksums are different and debug mode is off, the method shows a mismatch popup. + /// If the saved checksum is empty or cannot be read, the method skips the check. + /// If sawSignatureWarning is true, the method sets it to false and skips the check. /// - /// True if the signatures match or if the check is ignored, false otherwise. + /// The original game action. The method does not use this parameter. + /// The id of the saved game. + /// False if the checksums are different and debug mode is off. True in all other conditions. private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) { if (sawSignatureWarning) @@ -178,7 +204,17 @@ private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) } /// - /// Performs compatibility checks when the start screen is shown. + /// + /// Postfix patch for StartScreen_UI2.OnShow. It does the compatibility checks when the start screen opens. + /// If the launch is not valid and the platform is not Android, it shows a popup with the exit and download buttons, and stops. + /// + /// + /// It writes the global checksum to the checksum file. If the checksum changed since the last start, it sets . + /// + /// + /// If the game version is newer than the version of the last warning, it saves the game version and shows a version mismatch popup. + /// If there is no version of the last warning, it uses the game version that PolyMod supports. + /// /// [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] @@ -260,8 +296,10 @@ void OpenSite() } /// - /// Checks the signature of a pass-and-play game before loading it. + /// Prefix patch for GameInfoPopup.OnMainButtonClicked. It compares the checksum of the game in the popup before the game opens. /// + /// The game info popup. + /// False to stop the game from opening when the checksums are different. True to let the original method run. [HarmonyPrefix] [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.OnMainButtonClicked))] private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) @@ -270,8 +308,11 @@ private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) } /// - /// Checks the signature of a single-player game before resuming it. + /// Prefix patch for StartScreen_UI2.OnResumeButtonLongPress. The game calls that method on a long press of the resume button. + /// The patch compares the checksum of the first single-player saved game before the original method runs. /// + /// The start screen. + /// False to skip the original method when the checksums are different. True to let the original method run. [HarmonyPrefix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnResumeButtonLongPress))] private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) @@ -280,8 +321,9 @@ private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) } /// - /// Deletes the stored checksum of a pass-and-play game when it is deleted. + /// Postfix patch for GameInfoPopup.DeletePaPGame. It deletes the saved checksum of the pass-and-play game that the user deleted. /// + /// The game info popup of the deleted game. [HarmonyPostfix] [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.DeletePaPGame))] private static void GameInfoPopup_DeletePaPGame(GameInfoPopup __instance) @@ -289,6 +331,13 @@ private static void GameInfoPopup_DeletePaPGame(GameInfoPopup __instance) DeleteStateChecksum(__instance.gameId); } + /// + /// Prefix patch for LocalSaveFileUtils.DeleteSaveFile. It deletes the saved checksum of the saved game before the game deletes the save file. + /// The original method always runs. + /// + /// The type of the saved game. + /// The id of the saved game. + /// The value that tells the game to delete only the local file. The patch does not use it. [HarmonyPrefix] [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteSaveFile))] private static void LocalSaveFileUtils_DeleteSaveFile(PolytopiaBackendBase.Game.GameType gameType, string gameId, bool localOnly) @@ -297,8 +346,11 @@ private static void LocalSaveFileUtils_DeleteSaveFile(PolytopiaBackendBase.Game. } /// - /// Deletes the stored checksums of all saved games of a type when they are deleted. + /// Prefix patch for LocalSaveFileUtils.DeleteAllSaveFilesOfType. It deletes the saved checksums of all saved games of one type. + /// The patch runs before the game deletes the save files. The original method always runs. /// + /// The type of the saved games to delete. + /// The value that tells the game to delete only the local files. The patch does not use it. [HarmonyPrefix] [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteAllSaveFilesOfType))] private static void LocalSaveFileUtils_DeleteAllSaveFilesOfType(PolytopiaBackendBase.Game.GameType gameType, bool localOnly) @@ -310,8 +362,12 @@ private static void LocalSaveFileUtils_DeleteAllSaveFilesOfType(PolytopiaBackend } /// - /// Deletes the stored checksum of a game when the match ends. + /// Prefix patch for GameManager.MatchEnded. It deletes the saved checksum of the current game when the match ends. + /// The original method always runs. /// + /// The value that tells if the local player won. The patch does not use it. + /// The score details of the match. The patch does not use them. + /// The id of the winner. The patch does not use it. [HarmonyPrefix] [HarmonyPatch(typeof(GameManager), nameof(GameManager.MatchEnded))] private static void GameManager_MatchEnded(bool localPlayerIsWinner, ScoreDetails scoreDetails, byte winnerId) @@ -320,8 +376,11 @@ private static void GameManager_MatchEnded(bool localPlayerIsWinner, ScoreDetail } /// - /// Stores the current mod checksum when a new game session is created. + /// Postfix patch for the ClientBase.CreateSession overload that takes game settings and a game id. + /// It writes the current global checksum for the new game. /// + /// The settings of the new game. The patch does not use them. + /// The id of the new game. [HarmonyPostfix] [HarmonyPatch(typeof(ClientBase), nameof(ClientBase.CreateSession), typeof(GameSettings), typeof(Il2CppSystem.Guid))] private static void ClientBase_CreateSession(GameSettings settings, Il2CppSystem.Guid gameId) @@ -330,8 +389,11 @@ private static void ClientBase_CreateSession(GameSettings settings, Il2CppSystem } /// - /// Resets game settings if necessary when the tribe selector screen is shown. + /// Prefix patch for TribeSelectorScreen.Show. If is true, it calls + /// and sets the flag to false. /// + /// The value that tells the game to show the screen without animation. The patch does not use it. + /// Always true, so the original method always runs. [HarmonyPrefix] [HarmonyPatch(typeof(TribeSelectorScreen), nameof(TribeSelectorScreen.Show))] private static bool TribeSelectorScreen_Show(bool instant = false) @@ -345,7 +407,8 @@ private static bool TribeSelectorScreen_Show(bool instant = false) } /// - /// Restores the preliminary game settings to their default values. + /// Clears the disabled tribes and the selected skins in the preliminary game settings. + /// Then it writes these settings to disk. /// internal static void RestorePreliminaryGameSettings() { @@ -355,7 +418,7 @@ internal static void RestorePreliminaryGameSettings() } /// - /// Initializes the Compatibility manager by patching the necessary methods. + /// Applies all Harmony patches in the class. /// internal static void Init() { diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 728b650..c8d3eff 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -7,8 +7,20 @@ namespace PolyMod.Managers; +/// +/// The PolyMod hub. It adds the hub button and the version label to the start screen. +/// It shows the hub popup with the list of mods, and the config popup with the PolyMod settings. +/// internal static class Hub { + /// + /// A PolyMod setting that the config popup shows and that the user can toggle. + /// + /// The localization key of the button that toggles the setting. + /// The localization key of the setting name. + /// The localization key of the setting description. + /// The function that gets the current state of the setting. + /// The action that changes the setting to the opposite state. private record Setting( string buttonKey, string nameKey, @@ -32,7 +44,7 @@ Action toggle private const float START_SCREEN_MARGIN = 50f; private const float VERSION_LABEL_FONT_SIZE = 18f; private const float VERSION_LABEL_GAP = 10f; - /// Margin the game keeps between the safe area and its own corner widgets. + /// The distance between the edge of the safe area and the version label. private const float VERSION_LABEL_MARGIN = 15f; private const float ROUND_BUTTON_TITLE_GAP = 10f; private const string INTRO = "intro.mp4"; @@ -69,6 +81,10 @@ Action toggle private static PopupBase? openPopup = null; + /// + /// Gets a value that tells if the last popup that the hub opened is still on the screen. + /// If that popup is closed or destroyed, the property removes the reference to it and gives false. + /// public static bool IsPopupOpen { get @@ -86,6 +102,13 @@ public static bool IsPopupOpen } } + /// + /// Prefix patch for SplashController.LoadAndPlayClip. It replaces the splash video with the PolyMod intro video. + /// The patch writes the embedded intro.mp4 resource to the persistent data folder and plays that file. + /// The write starts asynchronously and the patch does not wait for it to complete. + /// + /// The splash controller that plays the video. + /// Always false, so the original method does not run. [HarmonyPrefix] [HarmonyPatch(typeof(SplashController), nameof(SplashController.LoadAndPlayClip))] private static bool SplashController_LoadAndPlayClip(SplashController __instance) @@ -98,6 +121,13 @@ private static bool SplashController_LoadAndPlayClip(SplashController __instance return false; } + /// + /// Postfix patch for StartScreen_UI2.Init. It makes the PolyMod widgets on the start screen. + /// It adds the hub button with the PolyMod icon and a badge that shows the number of broken mods. + /// It also adds the label with the PolyMod version. + /// If the mods have a dependency cycle, it shows the dependency cycle popup. + /// + /// The parent transform that the game gives to the start screen. [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.Init))] private static void StartScreen_UI2_Init(RectTransform transform) @@ -122,8 +152,15 @@ private static void StartScreen_UI2_Init(RectTransform transform) } /// - /// Patches the start screen layout to place the PolyMod hub button and the version label. + /// Postfix patch for StartScreen_UI2.RunLayout. It puts the hub button and the version label in position. + /// The hub button goes near the top-right corner of the safe area. + /// The badge on the button shows the current number of broken mods. + /// The version label goes in the bottom-left corner of the safe area. + /// If the label touches the settings button, the patch moves the label above that button. + /// If the widgets do not exist, the patch writes a warning to the log and stops. /// + /// The start screen. + /// The screen size that the game uses for this layout. [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RunLayout))] private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, ScreenBase_UI2.ScreenSize screenSize) @@ -166,6 +203,10 @@ private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, Screen } } + /// + /// Postfix patch for GameManager.Update. It opens the hub popup when the user pushes Ctrl+Tab. + /// The patch does nothing if a popup that the hub opened is still on the screen. + /// [HarmonyPostfix] [HarmonyPatch(typeof(GameManager), nameof(GameManager.Update))] private static void GameManager_Update() @@ -175,6 +216,11 @@ private static void GameManager_Update() ShowPolyModHub(); } + /// + /// Shows the hub popup. The popup has a header text, the list of mods, and a footer text. + /// It has the back, Discord, and config buttons. + /// In debug mode, it also has the dump and hot reload buttons, which do not close the popup. + /// internal static void ShowPolyModHub() { BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); @@ -205,6 +251,11 @@ internal static void ShowPolyModHub() popup.ShowSetWidth(HUB_POPUP_WIDTH_SHARE, HUB_POPUP_MAX_WIDTH); } + /// + /// Shows the config popup with the list of PolyMod settings and their states. + /// Each setting has a button that toggles the setting, writes the config to disk, and refreshes the list. + /// These buttons do not close the popup. The back button opens the hub popup again. + /// internal static void ShowConfigPopup() { BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); @@ -231,6 +282,10 @@ void OnSettingClicked() popup.ShowSetWidth(SETTINGS_POPUP_WIDTH_SHARE, SETTINGS_POPUP_MAX_WIDTH); } + /// + /// Shows a popup that tells the user that the mods have a dependency cycle. + /// The user cannot skip the popup. Its only button closes the game. + /// private static void ShowDependencyCyclePopup() { BasicPopup popup = PopupManager.GetBasicPopupWithData( @@ -253,6 +308,10 @@ private static void ShowDependencyCyclePopup() popup.Show(); } + /// + /// Dumps the game data to disk and shows a popup with the path of the dump folder. + /// The popup has a button that opens the dump folder. If the folder does not open, the method writes an error to the log. + /// private static void DumpData() { Dumper.DumpAll(); @@ -282,6 +341,10 @@ void OpenDumpFolder() popup.Show(); } + /// + /// Shows a popup that tells the user that hot reload is not available. + /// This method is a stub. It does not reload mods. + /// private static void HotReload() { BasicPopup popup = PopupManager.GetBasicPopup(); @@ -291,6 +354,12 @@ private static void HotReload() popup.Show(); } + /// + /// Makes the rich text list of mods for the hub popup. + /// The list starts with a summary line that shows the number of loaded mods, the total number of mods, and the short global checksum. + /// An entry for each mod follows the summary line. + /// + /// The rich text list of mods, or a muted text that tells the user that there are no mods. private static string BuildModList() { if (Registry.mods.Count == 0) @@ -320,10 +389,10 @@ private static string BuildModList() } /// - /// Shortens a checksum to the leading characters shown in the hub. + /// Gets the first 12 characters of a checksum, which the hub shows. /// /// The full checksum. - /// The shortened checksum. + /// The first 12 characters of the checksum, the full checksum if it is shorter, or "-" if the checksum is null or empty. private static string ShortChecksum(string checksum) { if (string.IsNullOrEmpty(checksum)) return "-"; @@ -331,6 +400,13 @@ private static string ShortChecksum(string checksum) return checksum.Length <= CHECKSUM_LENGTH ? checksum : checksum.Substring(0, CHECKSUM_LENGTH); } + /// + /// Makes the rich text entry of one mod for the hub popup. + /// The entry shows the name, the version, and the status in its status color. + /// It also shows the authors, the short checksum, and the description when the mod has them. + /// + /// The mod to show. + /// The rich text entry of the mod. private static string BuildModEntry(Mod mod) { string status = Localization.Get( @@ -362,6 +438,11 @@ private static string BuildModEntry(Mod mod) return string.Join("\n", lines); } + /// + /// Makes the rich text list of settings for the config popup. + /// Each entry shows the setting name, its state in green or red, and a muted description. + /// + /// The rich text list of settings. private static string BuildSettingsList() { List blocks = new(); @@ -378,8 +459,18 @@ private static string BuildSettingsList() return string.Join("\n\n", blocks); } + /// + /// Puts a text in a rich text color tag with the muted gray color. + /// + /// The text to change. + /// The text in the muted color. private static string Muted(string text) => $"{text}"; + /// + /// Gets the color that the hub uses to show a mod status. + /// + /// The status of the mod. + /// Green for , amber for , and red for all other values. private static string StatusColor(Mod.Status status) => status switch { Mod.Status.Success => COLOR_ENABLED, @@ -387,6 +478,10 @@ private static string BuildSettingsList() _ => COLOR_DISABLED, }; + /// + /// Counts the mods that do not have the status. + /// + /// The number of broken mods. private static int CountBrokenMods() { int broken = 0; @@ -397,9 +492,19 @@ private static int CountBrokenMods() return broken; } + /// + /// Changes a managed action into an IL2CPP action that popup buttons can use. + /// + /// The managed action. + /// The IL2CPP action that calls . private static Il2CppSystem.Action Callback(Action callback) => DelegateSupport.ConvertDelegate(callback)!; + /// + /// Puts strings into an IL2CPP object array for the format arguments of Localization.Get. + /// + /// The strings to put into the array. + /// The IL2CPP object array with the strings in the same order. private static Il2CppSystem.Object[] Args(params string[] values) { Il2CppSystem.Object[] arguments = new Il2CppSystem.Object[values.Length]; @@ -410,6 +515,9 @@ private static Il2CppSystem.Object[] Args(params string[] values) return arguments; } + /// + /// Applies all Harmony patches in the class. + /// internal static void Init() { Harmony.CreateAndPatchAll(typeof(Hub)); diff --git a/src/Managers/Loc.cs b/src/Managers/Loc.cs index 0c76da6..46b1e47 100644 --- a/src/Managers/Loc.cs +++ b/src/Managers/Loc.cs @@ -10,16 +10,32 @@ namespace PolyMod.Managers; /// -/// Manages localization for PolyMod. +/// The manager for localization. It adds mod terms and mod languages to the localization of the game. /// public static class Loc { + /// + /// The languages that mods add, keyed by language code. + /// Each value maps term keys to the text in that language. + /// The language key gives the name of the language. + /// internal static Dictionary> languagesToAdd = new(); + /// + /// The localization keys that replace the info text of improvements, keyed by the enum name of the improvement. + /// internal static Dictionary buildingsInfoOverrides = new(); /// - /// Patches the localization getter to handle custom enum values. + /// A Harmony prefix on Localization.Get(string, Il2CppReferenceArray). + /// It finds a custom enum value in the parts of the key, which are separated by dots. + /// A custom enum value is a number that is not less than . + /// The patch gets the enum name of this value from the enum caches of the type mappings in . + /// Then it replaces the number in the key with the enum name. + /// If the key has more than one custom value, the patch uses only the last value. /// + /// The localization key. The patch can change it. + /// The format arguments of the localized text. The patch does not use them. + /// Always true, which runs the original method. [HarmonyPrefix] [HarmonyPatch(typeof(Localization), nameof(Localization.Get), typeof(string), typeof(Il2CppReferenceArray))] private static bool Localization_Get(ref string key, Il2CppReferenceArray args) @@ -74,6 +90,14 @@ private static bool Localization_Get(ref string key, Il2CppReferenceArray + /// A Harmony prefix on Localization.Init. + /// If the localization is already initialized, the patch does nothing. + /// If not, it sets the missing language code of Elyrion in the first language source. + /// Then it adds each language in to the source, if the source does not have that language code. + /// It adds the missing terms and sets the text of each term for that language. + /// + /// Always true, which runs the original method. [HarmonyPrefix] [HarmonyPatch(typeof(Localization), nameof(Localization.Init))] private static bool Localization_Init() @@ -121,6 +145,18 @@ private static bool Localization_Init() return true; } + /// + /// A Harmony prefix on BuildingUtils.GetInfo. + /// If has a key for the improvement, the patch gives the localized text of that key. + /// The localization uses the skin of the local player and the tribe of the owner. + /// + /// The info text of the improvement. The patch sets it if an override exists. + /// The skin of the local player. + /// The data of the improvement. + /// The state of the improvement. The patch does not use it. + /// The player that owns the improvement, or null. If null, the patch uses no tribe. + /// The tile of the improvement. The patch does not use it. + /// False if an override exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(BuildingUtils), nameof(BuildingUtils.GetInfo))] private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCurrentLocalPlayer, @@ -141,9 +177,13 @@ private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCu } /// - /// Builds and loads localization data from a dictionary. + /// Adds the terms of a mod localization file to the first language source of the game. + /// The method changes each key with . + /// It adds the TribeSkins/ prefix to a key that starts with tribeskins. + /// For each game language, the term gets the text in that language. + /// If that text does not exist, the term gets the English text, or else the term name. /// - /// A dictionary containing the localization data. + /// The terms, keyed by term key. Each value maps language names to text. internal static void BuildAndLoadLocalization(Dictionary> localization) { foreach (var (key, data) in localization) @@ -160,6 +200,14 @@ internal static void BuildAndLoadLocalization(Dictionary + /// Changes a key from a mod into a localization key. + /// The method replaces each underscore with a dot. Then it replaces each pair of dots with one underscore. + /// Thus, one underscore becomes a dot, and two underscores become one underscore. + /// The method does not change dashes. + /// + /// The key from the mod. + /// The localization key. internal static string ReplaceDashesWithDots(string key) { string name = key.Replace("_", "."); @@ -167,7 +215,7 @@ internal static string ReplaceDashesWithDots(string key) } /// - /// Initializes the Loc manager by patching the necessary methods. + /// Applies all Harmony patches in the class. /// internal static void Init() { diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index d288783..83f52ed 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -7,72 +7,89 @@ using System.Text.RegularExpressions; using UnityEngine; using PolytopiaBackendBase.Common; -using Steamworks; namespace PolyMod.Managers; /// -/// The main manager for PolyMod, responsible for initializing the mod and patching game logic. +/// The main manager of PolyMod. It registers and loads the mods, and it patches game logic. /// public static class Main { private static readonly string[] polytopiaAuthors = { "Midjiwan AB" }; + /// + /// The flag that shows that the mod dependencies contain a cycle. + /// When it is true, loads only the PolyMod localization. + /// internal static bool dependencyCycle; /// - /// The maximum tier for technology, used to extend the tech tree. + /// The highest tech tier that gets an ID in TechItem.techTierFirebaseId. + /// adds the IDs for the tiers from 0 to this value. /// internal const int MAX_TECH_TIER = 100; /// - /// A stopwatch to measure the time taken to load mods. + /// The stopwatch that measures the time to register and load the mods. + /// It measures the sum of the time in and in . /// internal static readonly Stopwatch stopwatch = new(); /// - /// Whether the mod has been fully initialized. + /// The flag that shows that ran. + /// uses it to call only one time. /// internal static bool fullyInitialized; /// - /// A dictionary mapping unit IDs to the IDs of the units they embark into. + /// The embark overrides from the GLD, by ID. + /// The key is the ID of a unit, and the value is the ID of the unit that it embarks into. /// internal static Dictionary embarkNames = new(); /// - /// A dictionary mapping unit types to the types of the units they embark into. + /// The embark overrides, by unit type. + /// The key is the type of a unit, and the value is the type of the unit that it embarks into. /// internal static Dictionary embarkOverrides = new(); /// - /// Whether an embark action is currently being executed. + /// The flag that shows that an EmbarkAction runs now. + /// sets it to true, and sets it to false. /// internal static bool currentlyEmbarking = false; /// - /// A dictionary mapping improvement IDs to the IDs of the resources they attract. + /// The resources that improvements attract, by ID, from the GLD. + /// The key is the ID of an improvement, and the value is the ID of the resource. /// internal static Dictionary attractsResourceNames = new(); /// - /// A dictionary mapping improvement IDs to the IDs of the terrain types they attract resources on. + /// The terrains on which improvements make attracted resources, by ID, from the GLD. + /// The key is the ID of an improvement, and the value is the ID of the terrain. /// internal static Dictionary attractsTerrainNames = new(); /// - /// A dictionary mapping improvement types to the types of the resources they attract. + /// The resources that improvements attract, by type. + /// If an improvement is not in this lookup, uses the Game resource. /// internal static Dictionary attractsResourceOverrides = new(); /// - /// A dictionary mapping improvement types to the types of the terrain they attract resources on. + /// The terrains on which improvements make attracted resources, by type. + /// If an improvement is not in this lookup, uses the Forest terrain. /// internal static Dictionary attractsTerrainOverrides = new(); /// - /// Patches the game logic data parsing to load PolyMod content. + /// Patches GameLogicData.AddGameLogicPlaceholders as a prefix. + /// Calls the first time that the game parses the GLD. + /// The original method always runs after this prefix. /// + /// The game logic data that the game parses. + /// The root JSON object of the GLD. merges the mod patches into it. [HarmonyPrefix] [HarmonyPatch(typeof(GameLogicData), nameof(GameLogicData.AddGameLogicPlaceholders))] private static void GameLogicData_AddGameLogicPlaceholders(GameLogicData __instance, ref JObject rootObject) @@ -85,8 +102,15 @@ private static void GameLogicData_AddGameLogicPlaceholders(GameLogicData __insta } /// - /// Patches the purchase manager to unlock custom skins. + /// Patches PurchaseManager.IsSkinUnlocked as a prefix. + /// Unlocks all custom skins. /// + /// Set to true when the skin is a custom skin, otherwise false. + /// The skin to check. + /// + /// False when the skin ID is or more and the skin is not SkinType.Test. + /// Then the original method does not run. True for all other skins, so the original method runs. + /// [HarmonyPrefix] [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsSkinUnlocked))] private static bool PurchaseManager_IsSkinUnlockedInternal(ref bool __result, SkinType skinType) @@ -96,8 +120,11 @@ private static bool PurchaseManager_IsSkinUnlockedInternal(ref bool __result, Sk } /// - /// Patches the purchase manager to unlock custom tribes. + /// Patches PurchaseManager.IsTribeUnlocked as a postfix. + /// Unlocks all custom tribes. /// + /// Set to true when the tribe ID is or more. Other tribes keep the original result. + /// The tribe to check. [HarmonyPostfix] [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsTribeUnlocked))] private static void PurchaseManager_IsTribeUnlocked(ref bool __result, TribeType type) @@ -106,8 +133,12 @@ private static void PurchaseManager_IsTribeUnlocked(ref bool __result, TribeType } /// - /// Patches the steam purchase manager to unlock custom content. + /// Patches SteamPlatformPurchaseManager.IsProductUnlocked as a prefix. + /// Gives true for a null product. Other products use the original method. /// + /// Set to true when is null, otherwise false. + /// The product to check. + /// False when is null, so the original method does not run. Otherwise true. [HarmonyPrefix] [HarmonyPatch(typeof(SteamPlatformPurchaseManager), nameof(SteamPlatformPurchaseManager.IsProductUnlocked))] private static bool SteamPlatformPurchaseManager_IsProductUnlocked(ref bool __result, IAPProduct iapProduct) @@ -117,8 +148,11 @@ private static bool SteamPlatformPurchaseManager_IsProductUnlocked(ref bool __re } /// - /// Patches the purchase manager to add custom tribes to the list of unlocked tribes. + /// Patches PurchaseManager.GetUnlockedTribes as a postfix. + /// Adds each tribe in to the list of unlocked tribes. /// + /// The list of unlocked tribes. The method adds the custom tribes to it. + /// The value from the original call. The method does not use it. [HarmonyPostfix] [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.GetUnlockedTribes))] private static void PurchaseManager_GetUnlockedTribes( @@ -130,8 +164,13 @@ private static void PurchaseManager_GetUnlockedTribes( } /// - /// Patches the Unity log callback to filter out spammy messages. + /// Patches IL2CPPUnityLogSource.UnityLogCallback as a prefix. + /// Stops Unity log messages that contain a text from . /// + /// The text of the log message. + /// The exception text of the log message. The method does not use it. + /// The type of the log message. The method does not use it. + /// False when the message contains a text to ignore, so the message is not logged. Otherwise true. [HarmonyPrefix] [HarmonyPatch(typeof(IL2CPPUnityLogSource), nameof(IL2CPPUnityLogSource.UnityLogCallback))] private static bool IL2CPPUnityLogSource_UnityLogCallback(string logLine, string exception, LogType type) @@ -145,8 +184,22 @@ private static bool IL2CPPUnityLogSource_UnityLogCallback(string logLine, string } /// - /// Patches the tech view to correctly display the tech tree with custom technologies. + /// Patches TechView.CreateNode as a prefix. + /// Replaces the original method with a version that calculates the angle between branches of the tech tree. /// + /// + /// The original method uses a fixed angle of 72 degrees between branches. + /// This method divides 360 by the number of techs that the Basic tech unlocks for the tribe of the local player. + /// The division uses integers, so the angle has no decimal part. + /// For each tech that unlocks, the method makes a tech item with the tribe override of the tech. + /// It calls CreateNode again for each tech that unlocks more techs. + /// At the end, it calls OnItemsRefreshed if it is set. + /// + /// The tech view that makes the tree. + /// The tech whose unlocked techs become the new nodes. + /// The tech item of , or null for the root of the tree. + /// The angle of the parent item, in degrees. + /// Always false, so the original method does not run. [HarmonyPrefix] [HarmonyPatch(typeof(TechView), nameof(TechView.CreateNode))] public static bool TechView_CreateNode(TechView __instance, TechData data, TechItem parentItem, float angle) @@ -181,8 +234,12 @@ public static bool TechView_CreateNode(TechView __instance, TechData data, TechI } /// - /// Patches the embark action to set a flag indicating that an embark is in progress. + /// Patches EmbarkAction.Execute as a prefix. + /// Sets to true. /// + /// The embark action. The method does not use it. + /// The game state. The method does not use it. + /// Always true, so the original method runs. [HarmonyPrefix] [HarmonyPatch(typeof(EmbarkAction), nameof(EmbarkAction.Execute))] private static bool EmbarkAction_Execute_Prefix(EmbarkAction __instance, GameState gameState) @@ -192,8 +249,21 @@ private static bool EmbarkAction_Execute_Prefix(EmbarkAction __instance, GameSta } /// - /// Patches the unit training method to handle custom embark units. + /// Patches ActionUtils.TrainUnit as a prefix. + /// Changes the trained unit to the embark override during an embark action. /// + /// + /// The method does nothing if the tile or the unit on the tile is null. + /// If is true, it finds the type of the unit on the tile in . + /// If the type is there, it replaces with the data of the override type. + /// Then it sets to false. + /// + /// The unit state that the original method gives. The method does not change it. + /// The game state. + /// The player that trains the unit. The method does not use it. + /// The tile of the unit that embarks. + /// The data of the unit to train. The method can replace it. + /// Always true, so the original method runs. [HarmonyPrefix] [HarmonyPatch(typeof(ActionUtils), nameof(ActionUtils.TrainUnit))] private static bool ActionUtils_TrainUnit(ref UnitState __result, GameState gameState, PlayerState playerState, TileData tile, ref UnitData unitData) @@ -215,8 +285,23 @@ private static bool ActionUtils_TrainUnit(ref UnitState __result, GameState game } /// - /// Patches the start turn action to handle the 'Attract' ability for custom improvements. + /// Patches StartTurnAction.Execute as a postfix. + /// Replaces the resource actions of the Attract improvement ability with actions that use the PolyMod attract overrides. /// + /// + /// First, the method removes all CreateResource actions from the action stack. + /// Then it finds each tile of the player that has an improvement with the Attract ability. + /// The improvement must have an age that is a multiple of its growth rate, and the turn must be more than 0. + /// For each such tile, the method finds the first tile in the area with radius 1 that has no improvement and no resource. + /// That tile must also belong to the player and have the target terrain. + /// On that tile, the method adds a CreateResourceAction with the reason Attract. + /// + /// The resource comes from , and the default is Game. + /// The target terrain comes from , and the default is Forest. + /// + /// + /// The start turn action. It gives the ID of the player. + /// The game state. [HarmonyPostfix] [HarmonyPatch(typeof(StartTurnAction), nameof(StartTurnAction.Execute))] private static void StartTurnAction_Execute(StartTurnAction __instance, GameState state) @@ -270,10 +355,16 @@ private static void StartTurnAction_Execute(StartTurnAction __instance, GameStat } /// - /// Serialization fixes for custom (modded) content. - /// GamePlayerSummary stores the tribe as a single byte, which custom tribe ids (>= 1000) overflow into garbage. - /// Instead the tribe is clamped to None before the untouched native serializer runs and menu summaries show a generic icon for custom tribes, nothing more. + /// Patches GamePlayerSummary.Serialize as a prefix. + /// Sets the tribe to TribeType.None when the tribe ID is 255 or more. /// + /// + /// The summary writes the tribe as one byte, and a custom tribe ID does not fit in one byte. + /// The original method then writes TribeType.None. + /// Because of this, game summaries in the menu do not show the icon of a custom tribe. + /// + /// The player summary to write. + /// Always true, so the original method runs. [HarmonyPrefix] [HarmonyPatch(typeof(GamePlayerSummary), nameof(GamePlayerSummary.Serialize))] private static bool GamePlayerSummary_Serialize(GamePlayerSummary __instance) @@ -287,10 +378,16 @@ private static bool GamePlayerSummary_Serialize(GamePlayerSummary __instance) } /// - /// Serialization fixes for custom (modded) content. - /// PlayerState stores the play climate as a single byte, which custom climate ids (>= 1000) overflow into garbage. - /// Instead the climate is overriden by the tribe value, as those are effectively the same. + /// Patches PlayerState.Deserialize as a postfix. + /// Sets the climate of a player with a custom tribe to the tribe value. /// + /// + /// The player state reads the climate as one byte, and a custom climate ID does not fit in one byte. + /// The method sets the climate when the tribe ID is or more. + /// + /// The player state that the original method read. + /// The reader of the data. The method does not use it. + /// The version of the data. The method does not use it. [HarmonyPostfix] [HarmonyPatch(typeof(PlayerState), nameof(PlayerState.Deserialize))] private static void PlayerState_Deserialize(PlayerState __instance, Il2CppSystem.IO.BinaryReader reader, int version) @@ -300,33 +397,16 @@ private static void PlayerState_Deserialize(PlayerState __instance, Il2CppSystem __instance.climate = __instance.tribe; } } - [HarmonyPrefix] - [HarmonyPatch(typeof(NativeHelpers), nameof(NativeHelpers.IsValidInstall))] - public static bool NativeHelpers_IsValidInstall(ref bool __result) - { - __result = true; - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(SteamClient), nameof(SteamClient.IsValid), MethodType.Getter)] - public static bool SteamClient_IsValid(ref bool __result) - { - __result = true; - return false; - } - - [HarmonyPrefix] - [HarmonyPatch(typeof(SteamClient), nameof(SteamClient.RestartAppIfNecessary))] - public static bool SteamClient_IsValid(ref bool __result, uint appid) - { - __result = false; - return false; - } /// - /// Initializes the Main manager. + /// Applies the Harmony patches of this class, then registers and loads the mods. /// + /// + /// The method adds the game itself as the mod polytopia with the status Success. + /// Then it calls and . + /// It keeps the dependency cycle result in . + /// The method measures its time with . + /// internal static void Init() { stopwatch.Start(); @@ -346,6 +426,11 @@ internal static void Init() stopwatch.Stop(); } + /// + /// Patches the getter of Application.persistentDataPath as a postfix. + /// Replaces the path with . + /// + /// Set to . [HarmonyPostfix] [HarmonyPatch(typeof(UnityEngine.Application), nameof(UnityEngine.Application.persistentDataPath), MethodType.Getter)] private static void Application_persistentDataPath_get(ref string __result) @@ -354,9 +439,28 @@ private static void Application_persistentDataPath_get(ref string __result) } /// - /// Loads all mod content. + /// Loads the content of all mods that have the status Success. /// - /// The JSON object representing the game logic data. + /// + /// First, the method loads the PolyMod localization. If is true, it stops there. + /// Then it reads the files of each mod and uses the file name or the file extension to select the action: + /// + /// localization.json and localization_*.json: calls . + /// patch.json and patch_*.json: renders the file as a and merges it into with . If the render gives null, the mod gets the status Error. + /// prefabs, unitPrefab, improvementPrefab, and resourcePrefab JSON files: adds the file to . + /// Files with the extension .png: calls . + /// Files with the extension .bundle: calls . + /// + /// The method stops reading the files of a mod when the status of the mod is not Success. + /// It does not load .wav files. + /// + /// After all mods, the method fills TechItem.techTierFirebaseId with IDs for the tiers from 0 to . + /// Then it calls , , , and . + /// Last, it writes the load time to the log. + /// + /// + /// The game logic data that the game parses. + /// The root JSON object of the GLD. The method merges the mod patches into it. internal static void Load(GameLogicData gameLogicData, JObject json) { stopwatch.Start(); @@ -431,9 +535,9 @@ internal static void Load(GameLogicData gameLogicData, JObject json) case ".png": Loader.LoadTextureFile(mod, file); break; - case ".wav": - Loader.LoadAudioFile(mod, file); - break; + // case ".wav": + // Loader.LoadAudioFile(mod, file); + // break; case ".bundle": Loader.LoadAssetBundle(mod, file); break; diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index 07d3a0e..841f1c6 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -7,22 +7,74 @@ namespace PolyMod.Managers; +/// +/// The manager that makes custom unit, improvement, and resource prefabs from mod data. +/// It also replaces the unit prefab lookup of . +/// public static class Prefabs { + /// + /// The lookup of unit prefabs by . + /// It contains the unit prefabs of the game and the custom unit prefabs that are not UI overrides. + /// also adds fallback prefabs to it. + /// internal static Dictionary unitsNew = new(); + /// + /// The lookup of unit prefabs for each OverrideCondition, for example Christmas. + /// The key is the condition, and the value gives the prefab for each unit type. + /// It contains only the override prefabs of the game. + /// internal static Dictionary> unitOverridesNew = new(); // maybe in the future will implement + /// + /// The lookup of unit prefabs that the UI shows in place of the usual unit prefab, by . + /// It contains the UI override prefabs of the game and the custom prefabs that have set. + /// internal static Dictionary unitUIOverridesNew = new(); + /// + /// The shared material of the first unit sprite renderer that finds. + /// Custom unit visual parts and their outlines use this material. + /// internal static Material? cachedUnitMaterial; + /// + /// The loaded material that has the name . + /// Custom improvement and resource visual parts use this material. + /// internal static Material? cachedSharedMaterial; + /// + /// The name of the material that finds and keeps in . + /// internal const string CACHED_SHARED_MATERIAL_NAME = "SpriteMaterial"; + /// + /// The descriptions of the custom unit prefabs from the mod prefab files. + /// makes one prefab for each item. + /// public static List unitInfos = new(); + /// + /// The descriptions of the custom resource prefabs. + /// It contains the items from the mod prefab files and the default items that adds. + /// makes one prefab for each item. + /// public static List resourceInfos = new(); + /// + /// The descriptions of the custom improvement prefabs. + /// It contains the items from the mod prefab files and the default items that adds. + /// makes one prefab for each item. + /// public static List improvementInfos = new(); + /// + /// The improvement types that get a default prefab. + /// The loader adds each GLD improvement that has the prefab value set to true. + /// The value is true when the GLD maxLevel of the improvement is more than 0. + /// internal static Dictionary improvementPrefabInfosToCreate = new(); + /// + /// The resource types that get a default prefab. + /// The loader adds each GLD resource that has the prefab value set to true. + /// internal static List resourcePrefabsInfosToCreate = new(); private static List weaponInfos = new(); @@ -38,6 +90,17 @@ public static class Prefabs {UnitData.WeaponEnum.Water, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnPuff(); }; + /// + /// Patches PrefabManager.Awake as a postfix. + /// Fills the PolyMod unit lookups from the prefab lists of the game. + /// + /// + /// The method clears , , and . + /// Then it adds the unit prefabs, the unit override prefabs, and the unit UI override prefabs of the game. + /// If is null, it keeps the shared material of the first unit sprite renderer that it finds. + /// The method also clears the custom unit prefabs that added before. + /// + /// The that the game starts. [HarmonyPostfix] [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] private static void PrefabManager_Awake_Postfix(PrefabManager __instance) @@ -90,6 +153,15 @@ private static void PrefabManager_Awake_Postfix(PrefabManager __instance) Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); } + /// + /// Patches PrefabManager.HasUIUnitOverride as a prefix. + /// Replaces the original check with a check in . + /// + /// Set to true when contains the key, otherwise false. + /// The unit type. + /// The tribe. + /// The skin. + /// Always false, so the original method does not run. [HarmonyPrefix] [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) @@ -98,6 +170,19 @@ public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, return false; } + /// + /// Patches PrefabManager.GetUnitOrUiOverride as a prefix. + /// Replaces the original method with a lookup in the PolyMod unit lookups. + /// + /// + /// The method first finds the key in . + /// If the key is not there, it uses . + /// + /// Set to the UI override prefab, or to the usual unit prefab. + /// The unit type. + /// The tribe. + /// The skin. + /// Always false, so the original method does not run. [HarmonyPrefix] [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) @@ -113,6 +198,15 @@ public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType return false; } + /// + /// Patches PrefabManager.GetPrefab(UnitData.Type, TribeType, SkinType) as a prefix. + /// Replaces the original method with . + /// + /// Set to the unit prefab that gives. + /// The unit type. + /// The tribe. + /// The skin. + /// Always false, so the original method does not run. [HarmonyPrefix] [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) @@ -121,6 +215,17 @@ public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type return false; } + /// + /// Patches SkinVisualsReference.SetupVisualPart as a postfix. + /// Does the outline check for the visual part again and sets hasValidOutline. + /// + /// + /// If the outline is not a child of the visual part object, the method uses the first child as the outline. + /// It does this only when the visual part object has children. + /// Then it sets hasValidOutline to true only when the outline name is the default sprite name plus _Outline. + /// + /// The visual part that the original method configured. + /// The value from the original call. The method does not use it. [HarmonyPostfix] // prolly remove later [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) @@ -228,6 +333,22 @@ public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovem // return true; // } + /// + /// Finds the unit prefab for a unit type, a tribe, and a skin. + /// + /// + /// The method tries these steps in this sequence: + /// + /// If it is the Christmas season, it uses the Christmas override prefab for the unit type. + /// It uses the prefab in for the exact key. + /// If the skin is not SkinType.Default or the tribe is not TribeType.None, it tries the key with no tribe, then the key with the default skin, then the key with no tribe and the default skin. It adds the prefab that it finds to for the exact key. + /// It writes a log message and uses the prefab for the default unit type with no tribe and the default skin. + /// + /// + /// The unit type. + /// The tribe. + /// The skin. + /// The unit prefab, or null if the last step also finds no prefab. private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) { if (SeasonManager.IsChristmas() @@ -264,6 +385,16 @@ private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeTyp return lastResortPrefab!; } + /// + /// Makes all custom prefabs from the mod data. calls this method after the mod files are loaded. + /// + /// + /// First, the method finds the material and keeps it in . + /// Then it adds a default description to for each item in . + /// It also adds a default description to for each item in . + /// Each default description has one visual part, and its sprite name is the EnumCache name of the type. + /// Last, it makes one prefab for each item in , , and . + /// internal static void CreatePrefabs() { // get materials @@ -335,6 +466,23 @@ internal static void CreatePrefabs() } #region Units + /// + /// Makes a unit prefab from a and adds it to a unit lookup. + /// + /// + /// The method makes a copy of the default Imperius Warrior prefab. + /// It removes the sprite container of the copy and adds an empty SpriteContainer object. + /// Then it adds the visual parts from . + /// The head position marker is the visual part with the name . + /// If no visual part has this name, the method uses the first visual part that it made. + /// + /// The method keeps the prefab when the scene changes. + /// If is true, it adds the prefab to , otherwise to . + /// The key is . + /// If the method cannot get the Warrior prefab or make a copy, it does nothing. + /// + /// + /// The description of the unit prefab. internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) { // maybe just init new unit? hmmmmm will try later @@ -380,6 +528,19 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; } + /// + /// Makes the visual parts of a custom unit prefab. + /// + /// + /// The method reverses the sequence of in the description itself. + /// Then it makes the visual parts in the new sequence with . + /// The first part gets the sorting order 0, and each next part gets a sorting order that is 1 more. + /// The outline sorting order starts at minus the number of parts and increases by 1 for each part, to a maximum of -1. + /// and replace these values when they are set. + /// + /// The description of the unit prefab. + /// The transform that becomes the parent of the visual parts. + /// The visual parts, or an empty list if the description has no visual parts. private static List ApplyUnitVisualParts( UnitPrefabInfo unitPrefabInfo, Transform spriteContainer) @@ -407,6 +568,21 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) return parts; } + /// + /// Makes one visual part of a custom unit prefab, with its outline. + /// + /// + /// The visual part object has the name . + /// The outline object has the same name plus _Outline, and it is a child of the visual part object. + /// The method sets the world position and the z rotation in degrees of both objects from the description. + /// It deactivates the outline object, which keeps the outline hidden in the UI. + /// Both objects get a SpriteRenderer that uses in the Units sorting layer. + /// + /// The description of the visual part. + /// The transform that becomes the parent of the visual part object. + /// The sorting order of the visual part renderer. + /// The sorting order of the outline renderer. + /// The visual part. private static SkinVisualsReference.VisualPart CreateUnitVisualPart( VisualPartInfo info, Transform parent, @@ -447,6 +623,17 @@ private static SkinVisualsReference.VisualPart CreateUnitVisualPart( #endregion #region Improvements + /// + /// Makes an improvement prefab from an and puts it in PrefabManager.improvements. + /// + /// + /// The method makes a copy of the Lumber Hut prefab and removes all children of the copy. + /// Then it adds the visual parts from . + /// It keeps the prefab when the scene changes. + /// The prefab replaces the prefab of the same improvement type in PrefabManager.improvements. + /// If is null, or the method cannot get the Lumber Hut prefab or make a copy, it does nothing. + /// + /// The description of the improvement prefab. internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvementPrefabInfo) { if (improvementPrefabInfo.improvementType == null) @@ -476,6 +663,18 @@ internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvem PrefabManager.improvements[(Polytopia.Data.ImprovementData.Type)improvementPrefabInfo.improvementType] = buildingInstance; } + /// + /// Makes the visual parts of a custom improvement prefab. + /// + /// + /// The method makes the visual parts in the sequence of with . + /// The first part gets the sorting order 0, and each next part gets a sorting order that is 1 more. + /// The outline sorting order starts at minus the number of parts and increases by 1 for each part, to a maximum of -1. + /// The method does not use or . + /// + /// The description of the improvement prefab. + /// The transform that becomes the parent of the visual parts. + /// The visual parts, or an empty list if the description has no visual parts. private static List ApplyBuildingVisualParts( ImprovementPrefabInfo improvementPrefabInfo, Transform spriteContainer) @@ -501,6 +700,23 @@ internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvem return parts; } + /// + /// Makes one visual part of a custom improvement prefab, with its outline. + /// + /// + /// The visual part object has the name . + /// The outline object has the same name plus _Outline, and it is a child of the visual part object. + /// The method sets the world position and the z rotation in degrees of both objects from the description. + /// It deactivates the outline object. + /// The visual part object gets a PolytopiaSpriteRenderer from . + /// The outline object gets a renderer only when is true. + /// + /// The description of the visual part. + /// The transform that becomes the parent of the visual part object. + /// The sorting order of the visual part renderer. + /// The sorting order of the outline renderer. + /// True to add a renderer to the outline object. + /// The visual part, marked as an improvement part. private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( VisualPartInfo info, Transform parent, @@ -535,6 +751,18 @@ private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( return visualPart; } + /// + /// Adds a MeshFilter, a MeshRenderer, and a PolytopiaSpriteRenderer to an object. + /// + /// + /// The mesh renderer does not cast or receive shadows, and it does not use light probes or reflection probes. + /// The method sets the sorting layer and the sorting order of the sprite renderer. + /// If is not null, the sprite renderer uses it as the shared material. + /// + /// The object that gets the components. + /// The sorting order of the sprite renderer. + /// The name of the sorting layer of the sprite renderer. The default is Terrain. + /// The new PolytopiaSpriteRenderer. private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject targetGameObject, int sortingOrder, string sortingLayerName = "Terrain") { MeshFilter meshFilter = targetGameObject.AddComponent(); @@ -560,6 +788,17 @@ private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject tar #endregion #region Resources + /// + /// Makes a resource prefab from a and puts it in PrefabManager.resources. + /// + /// + /// The method makes a copy of the Game resource prefab and removes all children of the copy. + /// Then it adds the visual parts from . + /// It keeps the prefab when the scene changes. + /// The prefab replaces the prefab of the same resource type in PrefabManager.resources. + /// If is null, or the method cannot get the Game prefab or make a copy, it does nothing. + /// + /// The description of the resource prefab. internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefabInfo) { if (resourcePrefabInfo.resourceType == null) @@ -589,6 +828,18 @@ internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefab PrefabManager.resources[(Polytopia.Data.ResourceData.Type)resourcePrefabInfo.resourceType] = resourceInstance; } + /// + /// Makes the visual parts of a custom resource prefab. + /// + /// + /// The method makes the visual parts in the sequence of with . + /// The first part gets the sorting order 0, and each next part gets a sorting order that is 1 more. + /// The outline sorting order starts at minus the number of parts and increases by 1 for each part, to a maximum of -1. + /// The method does not use or . + /// + /// The description of the resource prefab. + /// The transform that becomes the parent of the visual parts. + /// The visual parts, or an empty list if the description has no visual parts. private static List ApplyResourceVisualParts( ResourcePrefabInfo resourcePrefabInfo, Transform spriteContainer) @@ -614,6 +865,21 @@ internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefab return parts; } + /// + /// Makes one visual part of a custom resource prefab, with its outline. + /// + /// + /// The visual part object has the name . + /// The outline object has the same name plus _Outline, and it is a child of the visual part object. + /// The method sets the world position and the z rotation in degrees of both objects from the description. + /// It deactivates the outline object. + /// Both objects get a PolytopiaSpriteRenderer from . + /// + /// The description of the visual part. + /// The transform that becomes the parent of the visual part object. + /// The sorting order of the visual part renderer. + /// The sorting order of the outline renderer. + /// The visual part. private static SkinVisualsReference.VisualPart CreateResourceVisualPart( VisualPartInfo info, Transform parent, @@ -646,6 +912,9 @@ private static SkinVisualsReference.VisualPart CreateResourceVisualPart( #endregion + /// + /// Applies the Harmony patches of this class. + /// internal static void Init() { Harmony.CreateAndPatchAll(typeof(Prefabs)); diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs index 2073701..e920e28 100644 --- a/src/Managers/TribePreviews.cs +++ b/src/Managers/TribePreviews.cs @@ -8,43 +8,75 @@ namespace PolyMod.Managers; +/// +/// The manager for the world previews that the tribe selection screen shows. +/// It changes the preview maps of tribes with the preview tiles from mods. +/// public static class TribePreviews { /// - /// Represents a tile in a tribe preview. + /// The changes to one tile of a tribe preview map. A mod gives these changes in the preview field of a tribe. /// public class PreviewTile { - /// The x-coordinate of the tile. + /// The x coordinate of the tile. If it is null, PolyMod does not change a tile. [JsonInclude] public int? x = null; - /// The y-coordinate of the tile. + /// The y coordinate of the tile. If it is null, PolyMod does not change a tile. [JsonInclude] public int? y = null; - /// The terrain type of the tile. + /// The new terrain type of the tile. If it is None, PolyMod keeps the terrain. [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public Polytopia.Data.TerrainData.Type terrainType = Polytopia.Data.TerrainData.Type.None; - /// The resource type on the tile. + /// + /// The new resource type on the tile. If it is null, PolyMod keeps the resource. + /// If it is None, PolyMod removes the resource. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public ResourceData.Type? resourceType = null; - /// The unit type on the tile. + /// + /// The new unit type on the tile. If it is null, PolyMod keeps the unit. + /// If it is None, PolyMod removes the unit. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public UnitData.Type? unitType = null; - /// The improvement type on the tile. + /// + /// The new improvement type on the tile. If it is null, PolyMod keeps the improvement. + /// If it is None, PolyMod removes the improvement. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public ImprovementData.Type? improvementType = null; - /// The effect types on the tile. + /// + /// The new effect types on the tile. If the list is empty, PolyMod keeps the effects. + /// If not, the list replaces all effects of the tile. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheListJson))] public List tileEffects = new(); } + /// + /// The data that PolyMod uses to make the preview of one tribe. + /// + /// + /// The index of the preview in TribePreviewRegistry.saveStateDatas. + /// For a tribe without a game preview, it is the index of the fallback preview. + /// + /// The game preview that PolyMod changes. + /// The tile changes from the mod. public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); + /// + /// A Harmony postfix on TribePreviewRegistry.PreloadTribePreviews. + /// It applies the preview tiles in to the preview of each tribe. + /// The preview of a tribe has the name worldpreview_ and the tribe name. + /// If the game has a preview with that name, the patch replaces it with the changed copy. + /// If not, the patch changes a copy of the fallback preview and adds it to the list of previews. + /// [HarmonyPostfix] [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] public static void PreloadTribePreviews() @@ -88,6 +120,17 @@ public static void PreloadTribePreviews() } } + /// + /// Makes a changed copy of a preview with the given tile changes. + /// The method reads the game state from the compressed bytes of the preview and changes the tiles. + /// It skips a tile change without coordinates or with coordinates that are not on the map. + /// A new unit belongs to the current player and can move and attack. + /// A new improvement starts at level 0, and the current player is its founder. + /// + /// The name of the new preview. + /// The preview to copy. The method does not change it. + /// The tile changes to apply. + /// The new preview, or null if the method cannot read the bytes of the original preview. private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) { SaveStateData? saveStateData = null; @@ -175,6 +218,13 @@ public static void PreloadTribePreviews() return saveStateData; } + /// + /// A Harmony postfix on SelectTribePopup.SetBackground. + /// If the showCoordinates setting is on, it replaces the world preview image with a new snapshot. + /// The snapshot uses two times the camera size, so it shows a larger area of the preview map. + /// If the snapshot fails, the patch writes a warning to the log. + /// + /// The tribe selection popup. [HarmonyPostfix] [HarmonyPatch(typeof(SelectTribePopup), nameof(SelectTribePopup.SetBackground))] private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) @@ -227,6 +277,9 @@ private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) } } + /// + /// Applies all Harmony patches in the class. + /// internal static void Init() { Harmony.CreateAndPatchAll(typeof(TribePreviews)); diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 457da3a..630cf5a 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -10,28 +10,59 @@ namespace PolyMod.Managers; /// -/// Manages visual aspects of the game, including sprites, UI, and in-game objects. +/// The manager for sprites, textures, terrain graphics, and popups. +/// It also contains the Harmony patches that change how the game shows these items. /// public static class Visual { - /// Represents information about a sprite, such as its pivot and pixels per unit. + /// + /// The settings that PolyMod uses to make a sprite, such as the pivot and the pixels per unit. + /// A mod gives these settings in a sprites.json file. + /// public class SpriteInfo { + /// + /// The number of texture pixels in one world unit. + /// If this value is null, PolyMod uses 2112 for a mod texture and the original value for a game sprite. + /// [JsonInclude] public float? pixelsPerUnit; + /// + /// The pivot of the sprite, as a fraction of the sprite size. + /// If this value is null, PolyMod uses a preset pivot for a mod texture and the original pivot for a game sprite. + /// [JsonInclude] public Vector2? pivot; + /// + /// The source of the sprite image. + /// If this value is null, PolyMod uses the mod texture that has the same name as the sprite. + /// [JsonInclude] public SpriteOrigin? spriteOrigin = null; + /// + /// If true, PolyMod changes the image into a white silhouette with a border before it makes the sprite. + /// [JsonInclude] public bool transformToOutline = false; + /// + /// The radius of the Gaussian blur that PolyMod applies to the image. + /// If this value is null, PolyMod does not apply a blur. + /// [JsonInclude] public float? gaussianBlurRadius = null; + /// + /// Makes a new with the given settings. + /// + /// The number of texture pixels in one world unit, or null to use the default value. + /// The pivot of the sprite, or null to use the default pivot. + /// If true, the image changes into a white silhouette with a border. + /// The source of the sprite image, or null to use the texture with the same name. + /// The radius of the Gaussian blur, or null for no blur. public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, bool transformToOutline = false, SpriteOrigin? spriteOrigin = null, float? gaussianBlurRadius = null) { this.pixelsPerUnit = pixelsPerUnit; @@ -42,39 +73,77 @@ public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, bool transformToOutline } } + /// + /// The source of the image for a sprite that a describes. + /// public class SpriteOrigin { + /// + /// The name of the source image. + /// For , it is the name of a mod texture. + /// For , it is the name of a game sprite. + /// [JsonInclude] public string? name; + /// + /// The type of the source. The default value is . + /// [JsonInclude] [JsonConverter(typeof(EnumNameJson))] public OriginType originType = OriginType.Outer; } + /// + /// The types of source for the image of a sprite. + /// public enum OriginType { + /// The image comes from a texture in a mod. Outer, // Outer means sprite comes from a mod, and not from game's files + /// The image comes from a sprite in the game files. Inner // Inner means sprite is to be fetched from game's files } - /// Represents information about a custom skin. + /// + /// The data about a custom skin that a mod adds. + /// + /// The enum value that PolyMod gives to the skin. + /// The ID of the skin in the GLD. + /// The skin data, or null if PolyMod did not make it. public record SkinInfo(int idx, string id, SkinData? skinData); - /// A dictionary of custom widths for basic popups. + /// + /// The custom widths of shown popups, keyed by the Unity instance ID of the popup. + /// PolyMod removes an entry when the popup closes. + /// public static Dictionary basicPopupWidths = new(); + /// + /// The custom width settings of one popup. + /// + /// The popup that uses the custom width. + /// The share of the usable screen width, from 0 to 1. A value of 0 or less gives a fixed width. + /// The maximum width in canvas units. With a fixed width, this is the width of the popup. public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); private const int BASIC_POPUP_LEGACY_ID = 29; - /// The width the game gives its own popups, used as the floor for custom widths. + /// + /// The width of the game's own popups, in canvas units. + /// A popup with a screen share never gets a smaller width than this value. + /// private const float DEFAULT_POPUP_WIDTH = 402f; - /// Smallest gap left between two buttons before they are moved onto separate rows. + /// + /// The horizontal gap between two popup buttons in one row, in canvas units. + /// If a button and this gap do not fit in the row, the button goes to a new row. + /// private const float POPUP_BUTTON_GAP = 8f; - /// Vertical gap between two rows of popup buttons. + /// + /// The vertical gap between two rows of popup buttons, in canvas units. + /// private const float POPUP_BUTTON_ROW_GAP = 10f; private const byte INVISIBLE_ALPHA = 2; @@ -83,7 +152,8 @@ public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); private const float PREMULTIPLIED_MAX_OUTLIER_SHARE = 0.005f; /// - /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. + /// The custom skins that can flood tiles, keyed by the custom flood tile effect of each skin. + /// The loader adds an entry for each custom skin that has the Flooded tribe ability. /// internal static Dictionary customFloodingSkins = new(); @@ -94,14 +164,21 @@ public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); #region General - /// A placeholder patch for the TechItem.SetupComplete method. + /// + /// A Harmony postfix on TechItem.SetupComplete. It is empty and does not change the game. + /// [HarmonyPostfix] [HarmonyPatch(typeof(TechItem), nameof(TechItem.SetupComplete))] private static void TechItem_SetupComplete() { } - /// Patches the sprite atlas manager to look up custom sprites. + /// + /// Fills the cache that maps game sprite names to PolyMod enum names. + /// The cache contains the names of terrain, resource, and improvement sprites. + /// The wetland sprite name maps to the field name with the _flooded suffix. + /// Unknown terrain and placeholder sprite names are not in the cache. + /// internal static void CacheSpriteNames() { cachedSpriteDataReverse = new(); @@ -138,6 +215,13 @@ internal static void CacheSpriteNames() cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(improvementType)); } } + /// + /// Changes a game sprite name into a name that uses PolyMod enum names. + /// The method replaces each cached game sprite name in the text with its enum name. + /// It fills the name cache on the first call and keeps each result in a second cache. + /// + /// The sprite name that the game uses. + /// The sprite name with enum names. If no part matches, the method gives the same name. internal static string FormatSpriteName(string baseName) { if (cachedSpriteDataReverse == null) @@ -155,6 +239,15 @@ internal static string FormatSpriteName(string baseName) return formattedName; } + /// + /// A Harmony postfix on SpriteAtlasManager.TrySolveSpriteNameForLevelSprites. + /// It always sets the result to true, because a false result makes the original sprite lookup fail. + /// + /// The result of the original method. The patch sets it to true. + /// The sprite atlas manager. + /// The sprite name variants that the original method examines. + /// The level of the sprite. + /// The sprite name that the original method found. The patch does not change it. [HarmonyPostfix] [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.TrySolveSpriteNameForLevelSprites))] private static void SpriteAtlasManager_TrySolveSpriteNameForLevelSprites( @@ -165,6 +258,18 @@ private static void SpriteAtlasManager_TrySolveSpriteNameForLevelSprites( if (!__result) __result = true; // will crash original lookup if false.... } + /// + /// A Harmony postfix on SpriteAtlasManager.DoSpriteLookup. + /// It replaces the sprite and the outline sprite in the result with registered mod sprites. + /// First, it uses the original sprite name. Then it uses the name from , if that name is different. + /// A sprite from the second name replaces a sprite from the first name. + /// + /// The lookup result of the original method. The patch can change its sprites. + /// The sprite atlas manager. + /// The sprite name that the game looks for. + /// The tribe of the sprite. + /// The skin of the sprite. + /// The level of the sprite. [HarmonyPostfix] [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] private static void SpriteAtlasManager_DoSpriteLookup( @@ -181,6 +286,15 @@ private static void SpriteAtlasManager_DoSpriteLookup( } } + /// + /// Puts the registered mod sprite and outline sprite for a name into a lookup result. + /// If the registry has no sprite of a type, the method keeps the sprite of that type in the result. + /// + /// The lookup result to change. + /// The sprite name to find in the registry. + /// The tribe of the sprite. + /// The skin of the sprite. + /// The level of the sprite. private static void ApplyRegisteredSprites( ref SpriteAtlasManager.SpriteLookupResult lookupResult, string spriteName, TribeType tribe, SkinType skin, int level) @@ -194,6 +308,12 @@ private static void ApplyRegisteredSprites( lookupResult.outlineSprite = registeredOutlineSprite; } + /// + /// A Harmony postfix on SpriteAtlasManager.GetSprite(string, string). + /// If the original method found no sprite, the patch gives the registered mod sprite with the lowercase name. + /// + /// The sprite that the original method found. The patch sets it only if it is null. + /// The name of the sprite. [HarmonyPostfix] [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.GetSprite), new Type[] { typeof(string), typeof(string) })] private static void SpriteAtlasManager_GetSprite(ref Sprite __result, string spriteName) @@ -203,6 +323,11 @@ private static void SpriteAtlasManager_GetSprite(ref Sprite __result, string spr __result = sprite; } + /// + /// A Harmony postfix on MapDataExtensions.GenerateShoreLines. + /// For each visible shoreline of a tile, it sets the sprite suffix from the skin and effects of the adjacent tile. + /// + /// The map that has the shorelines. [HarmonyPostfix] [HarmonyPatch(typeof(MapDataExtensions), nameof(MapDataExtensions.GenerateShoreLines))] private static void MapDataExtensions_GenerateShoreLines(MapData map) @@ -221,6 +346,15 @@ private static void MapDataExtensions_GenerateShoreLines(MapData map) } } + /// + /// Sets the sprite suffix of a shoreline from the skin and effects of a tile. + /// The suffix is _swamp for a swamp skin or a swamped tile. + /// For a different custom or tribe skin, the suffix is an underscore and the skin name. + /// A custom flood effect on the tile replaces the suffix with the name of the related skin. + /// If no rule applies, the suffix is empty. + /// + /// The tile that gives the skin and the effects. + /// The shoreline to change. private static void SetShorelineSuffix(TileData neighbour, TileData.Shoreline shoreline) { string suffix = neighbour.Skin == SkinType.Swamp || neighbour.HasEffect(TileData.EffectType.Swamped) @@ -239,6 +373,15 @@ private static void SetShorelineSuffix(TileData neighbour, TileData.Shoreline sh shoreline.spriteExt = suffix; } + /// + /// A Harmony prefix on SpriteAtlasManager.LoadSprite(string, string, SpriteCallback). + /// It finds a registered mod sprite with the name from , and then with the original name. + /// If it finds a sprite, it calls the callback with that sprite. + /// + /// The name of the atlas. + /// The name of the sprite. + /// The callback that gets the sprite. + /// False if the patch found a mod sprite, which skips the original method. True if not. [HarmonyPrefix] // its obsolete so may be removed soon by midjiwan [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[] { typeof(string), typeof(string), typeof(SpriteCallback) })] private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) @@ -261,6 +404,12 @@ private static bool LoadSprite(string atlas, string sprite, SpriteCallback compl return false; } + /// + /// A Harmony postfix on SpriteData.TerrainToString. + /// For a custom terrain type, it replaces the sprite name with the enum name of the terrain. + /// + /// The sprite name that the original method gives. + /// The terrain type. [HarmonyPostfix] [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) @@ -269,6 +418,12 @@ private static void SpriteData_TerrainToString(ref string __result, Polytopia.Da __result = EnumCache.GetName(terrain); } + /// + /// A Harmony postfix on SpriteData.ResourceToString. + /// For a custom resource type, it replaces the sprite name with the enum name of the resource. + /// + /// The sprite name that the original method gives. + /// The resource type. [HarmonyPostfix] [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) @@ -277,6 +432,12 @@ private static void SpriteData_ResourceToString(ref string __result, ResourceDat __result = EnumCache.GetName(resource); } + /// + /// A Harmony postfix on SpriteData.ImprovementToString. + /// For a custom improvement type, it replaces the sprite name with the enum name of the improvement. + /// + /// The sprite name that the original method gives. + /// The improvement type. [HarmonyPostfix] [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) @@ -288,6 +449,12 @@ private static void SpriteData_ImprovementToString(ref string __result, Improvem #endregion #region Level + /// + /// A Harmony postfix on Tile.RenderDebug. + /// If the showCoordinates setting is on, it adds a child object with white text that shows the tile coordinates. + /// The text uses the terrain sorting layer, above the tile. + /// + /// The tile. [HarmonyPostfix] [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] public static void Tile_RenderDebug(Tile __instance) @@ -310,6 +477,15 @@ public static void Tile_RenderDebug(Tile __instance) renderer.sortingOrder = __instance.Depth + 10; } + /// + /// Gets the terrain sprite name for a land tile. + /// A tile that is not flooded uses the field sprite name. + /// A flooded tile uses the wetland sprite name. + /// A swamped tile adds the _swamp suffix to the wetland name. + /// A tile with a custom flood effect adds an underscore and the name of the related skin. + /// + /// The data of the tile. + /// The terrain sprite name for the tile. private static string GetLandSpriteName(TileData tileData) { if (!tileData.HasEffect(TileData.EffectType.Flooded)) @@ -335,7 +511,19 @@ private static string GetLandSpriteName(TileData tileData) return wetlandSpriteName; } - /// Updates the terrain graphics with custom sprites. + /// + /// A Harmony prefix on TerrainRenderer.UpdateGraphics that replaces the original method. + /// Water, ocean, and ice tiles use the sprite names from the sprite sets of the renderer. + /// Other tiles use the name from . + /// The patch finds the sprite for the climate and skin, and sets it if the lookup has a sprite. + /// It also changes the desaturation of the sprite when the requested state is different. + /// + /// The terrain renderer. + /// The tile to show. + /// The tribe that gives the climate of the tile. + /// The skin of the tile. + /// If true, the renderer shows the sprite without color saturation. + /// Always false, which skips the original method. [HarmonyPrefix] [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] // Why prefix? I really hate repeating the logic. I would have to do the same bs 2 times.... anyway reviewers tell me ok? private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile, TribeType climate, SkinType skin, bool shouldDesaturate) @@ -363,7 +551,12 @@ private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, T return false; } - /// Adds custom flood tile effect when tile is flooded for custom aqua skins. + /// + /// A Harmony postfix on TileData.Flood. + /// If the skin of the player is in , it adds the custom flood effect of that skin to the tile. + /// + /// The tile that is flooded. + /// The player that floods the tile. [HarmonyPostfix] [HarmonyPatch(typeof(TileData), nameof(TileData.Flood))] private static void TileData_Flood(TileData __instance, PlayerState playerState) @@ -375,7 +568,16 @@ private static void TileData_Flood(TileData __instance, PlayerState playerState) } } - /// Removes custom flood effect loc from tile tip header. + /// + /// A Harmony postfix on TileTipGenerator.GetTileTipHeader. + /// It removes the localized name of each custom flood effect on the tile from the header text. + /// + /// The header text that the original method gives. + /// The data of the tile. + /// The skin that the localization uses. + /// The player whose tribe the localization uses. + /// The state of the game. The patch does not use it. + /// The game logic data. The patch does not use it. [HarmonyPostfix] [HarmonyPatch(typeof(TileTipGenerator), nameof(TileTipGenerator.GetTileTipHeader))] public static void GetTileTipHeader(ref string __result, TileData tileData, SkinType skin, @@ -391,7 +593,12 @@ public static void GetTileTipHeader(ref string __result, TileData tileData, Skin } } - /// Forces an update of the mesh for a PolytopiaSpriteRenderer with a custom sprite. + /// + /// A Harmony postfix on PolytopiaSpriteRenderer.ForceUpdateMesh. + /// For a renderer that has a sprite and no atlas name, it sets a material property block on the mesh renderer. + /// The block sets _MainTex to the sprite texture and sets _Flip to no flip. + /// + /// The sprite renderer. [HarmonyPostfix] [HarmonyPatch(typeof(PolytopiaSpriteRenderer), nameof(PolytopiaSpriteRenderer.ForceUpdateMesh))] private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRenderer __instance) @@ -408,7 +615,11 @@ private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRende #endregion #region Popups - /// Updates the width of a basic popup if a custom width is set. + /// + /// A Harmony postfix on PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines. + /// It applies the custom width of the popup, if the popup has one. + /// + /// The popup. [HarmonyPostfix] [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines))] private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(PopupBase __instance) @@ -416,6 +627,12 @@ private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines UpdateWidth(__instance); } + /// + /// Applies the custom width from to a popup. + /// If the popup is a BasicPopupLegacy with a button container, the method also arranges the buttons again. + /// If the popup has no custom width, the method does nothing. + /// + /// The popup to change. private static void UpdateWidth(PopupBase popup) { if (!basicPopupWidths.TryGetValue(popup.GetInstanceID(), out PopupWidth? width)) return; @@ -426,6 +643,10 @@ private static void UpdateWidth(PopupBase popup) LayoutPopupButtons(legacy.buttonContainer); } + /// + /// A Harmony postfix on SystemEvents.ScreenSizeChanged. + /// It refreshes the size of each shown popup that has a custom width. + /// [HarmonyPostfix] [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.ScreenSizeChanged))] private static void SystemEvents_ScreenSizeChanged() @@ -433,6 +654,10 @@ private static void SystemEvents_ScreenSizeChanged() RelayoutSizedPopups(); } + /// + /// A Harmony postfix on SystemEvents.SafeAreaChanged. + /// It refreshes the size of each shown popup that has a custom width. + /// [HarmonyPostfix] [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.SafeAreaChanged))] private static void SystemEvents_SafeAreaChanged() @@ -440,6 +665,11 @@ private static void SystemEvents_SafeAreaChanged() RelayoutSizedPopups(); } + /// + /// Refreshes the size of each shown popup in . + /// The method calls RefreshHeightWhenHeightIsKnownAndDontUseCoroutines with the safe screen height. + /// It writes an error to the log for each popup that fails, and continues with the next popup. + /// private static void RelayoutSizedPopups() { foreach (PopupWidth width in new List(basicPopupWidths.Values)) @@ -457,13 +687,16 @@ private static void RelayoutSizedPopups() } /// - /// Turns a share of the usable screen width into a popup width in canvas units. - /// The safe area is reported in screen pixels, so it is converted with the canvas scale the - /// game itself uses when it sizes popups. + /// Changes a share of the usable screen width into a popup width in canvas units. + /// The method changes the safe screen width from screen pixels to canvas units with the UI scale of the game. + /// If is 0 or less, the method gives as a fixed width. /// - /// Share of the usable width to take, between 0 and 1. - /// Widest the popup may get, so that text stays readable on wide screens. - /// A width in canvas units, never below the width of the game's own popups. + /// The share of the usable width, from 0 to 1. + /// The maximum width in canvas units. It keeps text easy to read on wide screens. + /// + /// The width in canvas units, rounded to an integer. + /// For a share above 0, the width is not smaller than the width of the game's own popups. + /// public static int GetResponsivePopupWidth(float share, float maximum) { if (share <= 0f) return Mathf.RoundToInt(maximum); @@ -473,10 +706,12 @@ public static int GetResponsivePopupWidth(float share, float maximum) } /// - /// Replaces the game's popup button layout. The game spaces the buttons with an integer division, - /// which stacks every button but the last on the left edge, and it never wraps, so a popup too - /// narrow for its buttons draws them on top of each other. + /// A Harmony postfix on PopupButtonContainer.SetButtonData. + /// It replaces the button positions that the game sets with the positions from . + /// The game puts all buttons in one row, so buttons can show on top of each other in a narrow popup. + /// The patch applies to the buttons of all popups. /// + /// The button container of the popup. [HarmonyPostfix] [HarmonyPatch(typeof(PopupButtonContainer), nameof(PopupButtonContainer.SetButtonData))] private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __instance) @@ -485,8 +720,12 @@ private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __in } /// - /// Lays a popup's buttons out in as many rows as the container's width needs. + /// Arranges the buttons of a popup in rows that fit the width of the container. + /// All rows have the height of the highest button, with between them. + /// The method sets the height of the container to the height of all rows, and puts the first row at the top. + /// If the container has no buttons or no width, the method does nothing. /// + /// The button container of the popup. internal static void LayoutPopupButtons(PopupButtonContainer container) { if (container.buttons == null || container.buttons.Length == 0) return; @@ -514,8 +753,14 @@ internal static void LayoutPopupButtons(PopupButtonContainer container) } /// - /// Fills one row at a time until the next button would no longer fit beside the previous ones. + /// Puts the buttons of a container into rows, in their original sequence. + /// The method adds each button to the current row. + /// If the button and the gap do not fit in the remaining width, the method starts a new row. + /// A row always contains at least one button, also if that button is wider than the container. /// + /// The button container of the popup. + /// The width of the container, in canvas units. + /// The rows of buttons, from the first row to the last row. private static List> PackButtonsIntoRows(PopupButtonContainer container, float available) { List> rows = new() { new() }; @@ -535,8 +780,12 @@ private static List> PackButtonsIntoRows(PopupButtonContainer } /// - /// Spreads one row of buttons across the container, or centres it when it holds a single button. + /// Puts one row of buttons across the width of the container. + /// The method anchors each button to a fraction of the container width, from the left edge to the right edge. + /// A row with one button goes to the center. /// + /// The buttons in the row. + /// The vertical position of the row from the center of the container, in canvas units. private static void PlaceButtonRow(List row, float offsetY) { for (int i = 0; i < row.Count; i++) @@ -552,7 +801,11 @@ private static void PlaceButtonRow(List row, float offsetY) } } - /// Removes a popup's custom width when it is hidden. + /// + /// A Harmony postfix on PopupBase.Hide. + /// It removes the entry of the popup from . + /// + /// The popup that closes. [HarmonyPostfix] [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] private static void PopupBase_Hide(PopupBase __instance) @@ -560,6 +813,10 @@ private static void PopupBase_Hide(PopupBase __instance) basicPopupWidths.Remove(__instance.GetInstanceID()); } + /// + /// A Harmony postfix on StartScreen_UI2.OnShow. + /// It calls to make the sprites that use game sprites as a source. + /// [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] private static void StartScreen_UI2_OnShow() @@ -567,6 +824,12 @@ private static void StartScreen_UI2_OnShow() CreateInnerOriginSprites(); } + /// + /// A Harmony prefix on StartScreen_UI2.OnWeeklyChallengeClicked. + /// It shows a popup that tells the player that the weekly challenge is only for the game without mods. + /// The popup has one OK button. + /// + /// Always false, which skips the original method. [HarmonyPrefix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] private static bool StartScreen_OnWeeklyChallengeClicked() @@ -582,6 +845,12 @@ private static bool StartScreen_OnWeeklyChallengeClicked() return false; } + /// + /// A Harmony postfix on StartScreen_UI2.RefreshWeeklyChallengeButton. + /// It sets all colors of the weekly challenge button to gray, to show that the button is not available. + /// If the start screen has no weekly challenge button, the patch does nothing. + /// + /// The start screen. [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RefreshWeeklyChallengeButton))] private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __instance) @@ -599,6 +868,12 @@ private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __i private const string MIGHTYLEADER = "mightyleader"; + /// + /// A Harmony postfix on PopupContentBuilder.GetMightyLeaderTopImage. + /// It replaces the image with the registered mightyleader sprite for the tribe and visual skin of the player, if one exists. + /// + /// The image that the original method gives. + /// The player that the popup is for. [HarmonyPostfix] [HarmonyPatch(typeof(PopupContentBuilder), nameof(PopupContentBuilder.GetMightyLeaderTopImage))] public static void PopupContentBuilder_GetMightyLeaderTopImage(ref Sprite __result, PlayerState player) @@ -608,14 +883,26 @@ public static void PopupContentBuilder_GetMightyLeaderTopImage(ref Sprite __resu __result = sprite; } - /// Shows a basic popup with a custom width. + /// + /// Shows a popup with a fixed custom width. + /// The method adds the width to and then shows the popup. + /// + /// The popup to show. + /// The width of the popup, in canvas units. public static void ShowSetWidth(this BasicPopupLegacy self, int width) { basicPopupWidths[self.GetInstanceID()] = new(self, 0f, width); self.Show(); } - /// Shows a basic popup sized to a share of the usable screen width. + /// + /// Shows a popup with a width that is a share of the usable screen width. + /// The method adds the width settings to and then shows the popup. + /// calculates the width. + /// + /// The popup to show. + /// The share of the usable screen width, from 0 to 1. + /// The maximum width of the popup, in canvas units. public static void ShowSetWidth(this BasicPopupLegacy self, float share, float maximum) { basicPopupWidths[self.GetInstanceID()] = new(self, share, maximum); @@ -624,6 +911,13 @@ public static void ShowSetWidth(this BasicPopupLegacy self, float share, float m #endregion + /// + /// Makes a new BasicPopupLegacy from the popup prefab of the game. + /// The method copies the button container of the "What's new" popup into the new popup. + /// It sets the popup ID to basicPopupLegacy and calls Init on the popup. + /// It also puts the popup in front of the other popups. + /// + /// The new popup. It is not shown. internal static BasicPopupLegacy GetBasicPopupLegacy() { WhatsNewPopup whatsNewPopup = PopupManager.GetWhatsNewPopup(); @@ -638,6 +932,14 @@ internal static BasicPopupLegacy GetBasicPopupLegacy() return basicPopupLegacy; } + /// + /// Makes a texture from the bytes of an image file, such as a PNG file. + /// If the image looks premultiplied, the method changes it back to straight alpha. + /// The method also copies color into the transparent pixels near the edges of the image. + /// The texture uses trilinear filter mode, clamp wrap mode, and mipmaps. + /// + /// The bytes of the image file. + /// The new texture. public static Texture2D BuildTexture(byte[] data) { Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); @@ -653,6 +955,16 @@ public static Texture2D BuildTexture(byte[] data) return texture; } + /// + /// Finds if the pixels of an image look premultiplied by alpha. + /// The method examines only the pixels that are partly transparent. + /// In a premultiplied image, no color channel of such a pixel is more than its alpha. + /// + /// The pixels of the image. + /// + /// True if the image has at least 64 partly transparent pixels, and not more than 0.5% of them have a color channel above alpha. + /// False if not. + /// internal static bool LooksPremultiplied(Color32[] pixels) { int edge = 0; @@ -668,6 +980,12 @@ internal static bool LooksPremultiplied(Color32[] pixels) && brighterThanAlpha <= edge * PREMULTIPLIED_MAX_OUTLIER_SHARE; } + /// + /// Changes premultiplied pixels to straight alpha in the same array. + /// The method divides the color channels of each partly transparent pixel by its alpha, with a maximum of 255. + /// It does not change fully transparent pixels and fully opaque pixels. + /// + /// The pixels to change. internal static void Unpremultiply(Color32[] pixels) { for (int i = 0; i < pixels.Length; i++) @@ -683,6 +1001,17 @@ internal static void Unpremultiply(Color32[] pixels) } } + /// + /// Copies the color of visible pixels into the adjacent transparent pixels, in the same array. + /// This stops dark edges around a sprite when the GPU filters the texture. + /// A pixel with an alpha of 2 or less has no color for this method. + /// The method spreads the color one pixel at a time, for a maximum of 16 pixels from the visible area. + /// It keeps the alpha of each pixel. + /// If all pixels or no pixels are visible, the method does nothing. + /// + /// The pixels of the image, row by row. + /// The width of the image, in pixels. + /// The height of the image, in pixels. internal static void BleedAlphaEdges(Color32[] pixels, int width, int height) { bool[] hasColour = new bool[pixels.Length]; @@ -729,21 +1058,32 @@ internal static void BleedAlphaEdges(Color32[] pixels, int width, int height) } } - /// Builds a sprite from raw byte data. - /// The raw byte data of the image. - /// The pivot point of the sprite. - /// The number of pixels per unit for the sprite. - /// The created sprite. + /// + /// Makes a sprite from the bytes of an image file. + /// The method makes the texture with and the sprite with . + /// + /// The bytes of the image file. + /// The pivot of the sprite, as a fraction of the sprite size. If null, the pivot is the center. + /// The number of texture pixels in one world unit. + /// If true, the image changes into a white silhouette with a border. + /// The radius of the Gaussian blur, or null for no blur. + /// The new sprite. public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) { return BuildSpriteWithTexture(BuildTexture(data), pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); } - /// Builds a sprite from a texture. - /// The texture to create the sprite from. - /// The pivot point of the sprite. - /// The number of pixels per unit for the sprite. - /// The created sprite. + /// + /// Makes a sprite that uses all of a texture. + /// If is true, the method first changes the texture with . + /// Then, if the blur radius is not null, it applies . + /// + /// The texture for the sprite. + /// The pivot of the sprite, as a fraction of the sprite size. If null, the pivot is the center. + /// The number of texture pixels in one world unit. If null, the method uses 2112. + /// If true, the image changes into a white silhouette with a border. + /// The radius of the Gaussian blur, or null for no blur. + /// The new sprite. public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) { if (transformToOutline) texture = TransformToOutline(texture); @@ -758,6 +1098,17 @@ public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = ); ; } + /// + /// Makes a silhouette texture with a border from the visible pixels of a texture. + /// The new texture is larger than the source texture by the border size on each side. + /// Each pixel within the border size of a visible source pixel gets the given color. + /// All other pixels are transparent. + /// A source pixel is visible if its alpha is more than 0.01. + /// + /// The texture that gives the shape. + /// The width of the border around the shape, in pixels. + /// The color of the silhouette. If null, the method uses white. + /// A new RGBA32 texture without mipmaps. public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSizeInPixels = 8, Color? color = null) { Plugin.logger.LogInfo("Transforming texture to outline..."); @@ -806,6 +1157,12 @@ public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSi return whiteSilhouetteTexture; } + /// + /// Makes the weights of a one-dimensional Gaussian kernel. The sum of the weights is 1. + /// + /// The standard deviation of the Gaussian function, in pixels. + /// The number of weights on each side of the center weight. + /// An array of 2 * kernelRadiusInPixels + 1 weights. private static float[] BuildGaussianKernelWeights(float sigma, int kernelRadiusInPixels) { float[] kernelWeights = new float[kernelRadiusInPixels * 2 + 1]; @@ -823,12 +1180,28 @@ private static float[] BuildGaussianKernelWeights(float sigma, int kernelRadiusI return kernelWeights; } + /// + /// Changes a value from the range 0 to 1 into a byte from 0 to 255, rounded to the nearest integer. + /// The method clamps values that are out of the range. + /// + /// The value to change. + /// The byte value. private static byte ConvertUnitFloatToByte(float unitValue) { return (byte)Math.Clamp(unitValue * 255f + 0.5f, 0f, 255f); } // basically ai generated as my bs was working, but 15 times slower + /// + /// Makes a blurred copy of a texture with a Gaussian blur. + /// The method blurs the rows and then the columns, on more than one thread. + /// It blurs premultiplied colors, so transparent pixels do not make the edges dark. + /// At the edges of the texture, the method uses the nearest edge pixel. + /// The standard deviation is half of the radius, and the kernel reaches three standard deviations. + /// + /// The texture to blur. The method does not change it. + /// The radius of the blur, in pixels. + /// A new RGBA32 texture without mipmaps. public static Texture2D ApplyGaussianBlur(Texture2D sourceTexture, float radius = 2f) { Plugin.logger.LogInfo($"Applying blur with radius {radius}..."); @@ -921,8 +1294,19 @@ public static Texture2D ApplyGaussianBlur(Texture2D sourceTexture, float radius return blurredTexture; } + /// + /// The sprite names and sprite infos of the sprites that have an origin. + /// fills this list, and makes the sprites and clears it. + /// internal static List> pendingInnerOriginSpriteInfos = new(); + /// + /// Gets the default pivot for a sprite from the part of its name before the first underscore. + /// + /// The name of the sprite. + /// + /// The pivot (0.5, 0) for field, the pivot (0.5, -0.375) for mountain, and the center for all other names. + /// private static Vector2 GetPivotPreset(string spriteName) { return spriteName.Split("_")[0] switch @@ -933,6 +1317,14 @@ private static Vector2 GetPivotPreset(string spriteName) }; } + /// + /// Adds a sprite to the Heads cache of the sprite atlas manager and to . + /// If a sprite with the same name exists, the method replaces it. + /// The method writes the sprite name to the log. + /// + /// The sprite atlas manager of the game. + /// The name of the sprite. + /// The sprite to add. internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, string spriteName, Sprite sprite) { Plugin.logger.LogInfo($"Registering sprite {spriteName}"); @@ -942,6 +1334,15 @@ internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, strin } // Runs early: only touches your own textures, nothing from SpriteAtlasManager's lookup state. + /// + /// Makes and registers the sprites from mod textures. + /// First, the method makes a sprite for each entry in . + /// It uses the texture with the sprite name, or else the texture with the origin name. + /// It skips an entry without a texture, and keeps entries for . + /// It marks the texture entry with the sprite name as processed in . + /// Then it makes a sprite with the default settings for each texture that is not processed. + /// A texture that only an origin name uses is not processed, so it also gets a sprite with its own name. + /// public static void CreateSprites() { Plugin.logger.LogInfo($"Creating sprites with outer origin..."); @@ -1000,6 +1401,12 @@ public static void CreateSprites() } } + /// + /// Changes a sprite into PNG bytes and a sprite info. + /// The method draws the sprite into a new texture with and encodes that texture as PNG. + /// + /// The sprite to change. + /// The PNG bytes, and a sprite info with the pixels per unit and the pivot of the sprite. internal static (byte[], SpriteInfo) SpriteToPng(Sprite sprite) { Texture2D bakedTexture = BakeSpriteToTexture(sprite); @@ -1012,6 +1419,11 @@ internal static (byte[], SpriteInfo) SpriteToPng(Sprite sprite) return (pngBytes, new SpriteInfo(sprite.pixelsPerUnit, normalizedPivot)); } + /// + /// Gets the pivot of a sprite as a fraction of the sprite size. + /// + /// The sprite. + /// The pivot, with values from 0 to 1 for a pivot in the sprite rectangle. private static Vector2 GetNormalizedPivot(Sprite sourceSprite) { return new Vector2( @@ -1020,6 +1432,14 @@ private static Vector2 GetNormalizedPivot(Sprite sourceSprite) ); } + /// + /// Draws the mesh of a sprite into a new texture that has the size of the sprite rectangle. + /// The method uses the Sprites/Default shader and a temporary render texture. + /// It changes the pixels to straight alpha and copies color into the transparent edge pixels. + /// It sets the active render texture back to the previous value. + /// + /// The sprite to draw. It can be a part of an atlas. + /// A new RGBA32 texture without mipmaps, with clamp wrap mode. private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) { Texture2D atlasTexture = sourceSprite.texture; @@ -1079,6 +1499,14 @@ private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) return bakedTexture; } + /// + /// Makes and registers the sprites in , and then clears that list. + /// For each entry, the method finds the game sprite with the origin name. + /// If the game sprite does not exist, it writes a warning to the log and skips the entry. + /// If the entry has a pivot or pixels per unit, the method makes a new sprite with these settings. + /// Only a new sprite gets the outline and blur settings. + /// Without a pivot and pixels per unit, the method registers the game sprite with no changes. + /// public static void CreateInnerOriginSprites() { Plugin.logger.LogInfo($"Creating sprites with inner origin..."); @@ -1127,7 +1555,9 @@ public static void CreateInnerOriginSprites() pendingInnerOriginSpriteInfos.Clear(); } - /// Initializes the Visual manager by patching the necessary methods. + /// + /// Applies all Harmony patches in the class. + /// internal static void Init() { Harmony.CreateAndPatchAll(typeof(Visual)); diff --git a/src/Mod.cs b/src/Mod.cs index 3d36389..b1742f9 100644 --- a/src/Mod.cs +++ b/src/Mod.cs @@ -1,69 +1,72 @@ namespace PolyMod; /// -/// Represents a mod in the PolyMod framework. +/// A mod that PolyMod found in the mods directory, or the base game entry with the id polytopia. /// public class Mod { /// - /// Represents a dependency of a mod. + /// A dependency of a mod on a different mod, as the manifest gives it. /// - /// The unique identifier of the dependency. - /// The minimum compatible version of the dependency, or null for no minimum. - /// The maximum compatible version of the dependency, or null for no maximum. - /// Whether the dependency is required for the mod to function. + /// The id of the mod that this mod needs. + /// The lowest version of the dependency that is permitted, or null for no lower limit. + /// The highest version of the dependency that is permitted, or null for no upper limit. + /// + /// If true, the mod gets the status when the dependency is missing or has a bad version. + /// If false, PolyMod only writes a warning to the log. + /// public record Dependency(string id, Version? min, Version? max, bool required = true); /// - /// Represents the manifest of a mod, containing metadata. + /// The data from the manifest.json file of a mod. /// - /// The unique identifier of the mod. - /// The name of the mod. - /// A description of the mod. + /// The id of the mod. It must contain only lowercase letters and underscores, and it must not be polytopia. + /// The name of the mod to show, or null to use the id. + /// The description of the mod, or null. /// The version of the mod. - /// The authors of the mod. - /// The dependencies of the mod. - /// Whether the mod is client-side only. + /// The names of the authors of the mod. The array must not be empty. + /// The dependencies of the mod, or null for no dependencies. + /// If true, the mod is client-side only and PolyMod does not include it in the mod checksum. public record Manifest(string id, string? name, string? description, Version version, string[] authors, Dependency[]? dependencies, bool client = false); /// - /// Represents a file included in a mod. + /// A file in a mod, other than manifest.json. /// - /// The name of the file. - /// The content of the file as a byte array. + /// The path of the file, relative to the root of the mod directory or archive. + /// The contents of the file. public record File(string name, byte[] bytes); /// - /// Represents the loading status of a mod. + /// The load status of a mod. /// public enum Status { /// - /// The mod was loaded successfully. + /// The mod has no errors. PolyMod loads its files. /// Success, /// - /// An error occurred while loading the mod. + /// An error occurred when PolyMod loaded the mod. /// Error, /// - /// The mod's dependencies were not satisfied. + /// A required dependency of the mod is missing or has a version that is not permitted. /// DependenciesUnsatisfied, } /// - /// The unique identifier of the mod. + /// The id of the mod. /// public string id; /// - /// The name of the mod. + /// The name of the mod to show. If the manifest has no name, this is the id. /// public string? name; /// - /// A description of the mod. + /// The description of the mod, or null. /// public string? description; @@ -73,41 +76,43 @@ public enum Status public Version version; /// - /// The authors of the mod. + /// The names of the authors of the mod. /// public string[] authors; /// - /// The dependencies of the mod. + /// The dependencies of the mod, or null. /// public Dependency[]? dependencies; /// - /// Whether the mod is client-side only. + /// If true, the mod is client-side only and PolyMod does not include it in the mod checksum. /// public bool client; /// - /// The loading status of the mod. + /// The load status of the mod. /// public Status status; /// - /// The files included in the mod. + /// The files of the mod. This list does not contain manifest.json. /// public List files; /// - /// The checksum of the mod, derived from its id, version and file contents. + /// The SHA-256 checksum of the mod, as a hexadecimal string. + /// PolyMod makes it from the id, the version, and the name and contents of each file. + /// It stays empty for client-side mods, for the base game entry, and for mods that do not have the status . /// public string checksum = string.Empty; /// - /// Initializes a new instance of the class. + /// Makes a mod from a manifest. /// - /// The manifest of the mod. - /// The loading status of the mod. - /// The files included in the mod. + /// The manifest that gives the id, name, description, version, authors, dependencies and client value. + /// The initial load status of the mod. + /// The files of the mod. public Mod(Manifest manifest, Status status, List files) { id = manifest.id; diff --git a/src/NullableFix.cs b/src/NullableFix.cs index 1c7e549..20b4278 100644 --- a/src/NullableFix.cs +++ b/src/NullableFix.cs @@ -3,47 +3,50 @@ namespace System.Runtime.CompilerServices { /// - /// A polyfill for the Nullable attribute, which is used by the compiler for nullable reference type analysis. + /// A local copy of the attribute that the compiler writes to show the nullability of a type. + /// The compiler uses this copy when the referenced assemblies do not supply the attribute. /// [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] public sealed class NullableAttribute : System.Attribute { /// - /// Initializes a new instance of the class. + /// Makes a new with one nullability flag. The constructor does not keep the value. /// - /// The nullable flags. + /// The nullability flag for the type. public NullableAttribute(byte b) { } /// - /// Initializes a new instance of the class. + /// Makes a new with a nullability flag for each part of a type. The constructor does not keep the values. /// - /// The nullable flags. + /// The nullability flags for the type and its type arguments. public NullableAttribute(byte[] b) { } } /// - /// A polyfill for the NullableContext attribute, which is used by the compiler for nullable reference type analysis. + /// A local copy of the attribute that the compiler writes to give the default nullability for a type or method. + /// The compiler uses this copy when the referenced assemblies do not supply the attribute. /// [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false)] public sealed class NullableContextAttribute : System.Attribute { /// - /// Initializes a new instance of the class. + /// Makes a new . The constructor does not keep the value. /// - /// The nullable context flags. + /// The default nullability flag. public NullableContextAttribute(byte b) { } } /// - /// A polyfill for the NullablePublicOnly attribute, which is used by the compiler for nullable reference type analysis. + /// A local copy of the attribute that the compiler writes to a module when it keeps nullability data only for public members. + /// The compiler uses this copy when the referenced assemblies do not supply the attribute. /// [System.AttributeUsage(System.AttributeTargets.Module)] public sealed class NullablePublicOnlyAttribute : System.Attribute { /// - /// Initializes a new instance of the class. + /// Makes a new . The constructor does not keep the value. /// - /// Whether to apply nullable analysis to public members only. + /// True if the module also has nullability data for internal members. public NullablePublicOnlyAttribute(bool b) { } } } diff --git a/src/Plugin.cs b/src/Plugin.cs index 1e854e2..bd62ba6 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -9,19 +9,34 @@ namespace PolyMod; /// -/// Main plugin class for PolyMod. +/// The BepInEx plugin of PolyMod. BepInEx loads this plugin and calls . /// [BepInPlugin("com.polymod", "PolyMod", VERSION)] public partial class Plugin : BepInEx.Unity.IL2CPP.BasePlugin { + /// + /// Gets or sets the token that the PolyMod launcher sends, or null if PolyMod did not get a token. + /// internal static string? Token { get; set; } + /// + /// Gets or sets a value that tells if the game start is valid. + /// sets this value. + /// If it is false, PolyMod shows an error popup on the start screen, but not on Android. + /// internal static bool ValidLaunch { get; set; } = false; + /// + /// Gets or sets a value that is true when the PolyMod launcher tells PolyMod not to start. + /// If it is true, stops before it starts the managers. + /// internal static bool Disabled { get; set; } = false; /// - /// Represents the configuration for PolyMod. + /// The configuration of PolyMod. PolyMod reads it from and writes it to the same file. /// - /// Whether to enable debug mode. + /// If true, PolyMod shows the BepInEx console. + /// If true, PolyMod shows the coordinates of the tiles. + /// If true, a mod can give a fixed idx to a new enum value, if the idx is larger than all existing values of the enum. + /// A device id value. No code in PolyMod reads this value at this time. internal record PolyConfig( bool debug = false, bool showCoordinates = false, @@ -29,73 +44,83 @@ internal record PolyConfig( string overrideDeviceId = "" ) { + /// + /// Gets the ids of the mods that PolyMod does not register. + /// public List disabledMods { get; init; } = new(); }; /// - /// The starting index for automatically assigned IDs. + /// The first index that PolyMod gives to an automatically indexed enum value. + /// PolyMod also uses this value to identify enum values that mods add. /// internal const int AUTOIDX_STARTS_FROM = 1000; /// - /// The key used to store the last version for which the incompatibility warning was shown. + /// The player prefs key that keeps the last game version for which PolyMod showed the incompatibility warning. /// internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY = "INCOMPATIBILITY_WARNING_LAST_VERSION"; /// - /// The prefix of the player prefs keys holding the mod checksum a saved game was created with. + /// The prefix of the player prefs keys that keep the mod checksum of each saved game. /// internal const string STATE_CHECKSUM_KEY_PREFIX = "POLYMOD_STATE_CHECKSUM_"; + /// + /// The maximum time, in milliseconds, that waits to connect to the PolyMod launcher. + /// internal const int LAUNCH_DATA_TIMEOUT = 2000; /// - /// The base path for PolyMod files. + /// The root directory of PolyMod files. This is the parent directory of the BepInEx root directory. /// public static readonly string BASE_PATH = Path.Combine(BepInEx.Paths.BepInExRootPath, ".."); /// - /// The path to the mods directory. + /// The path of the directory that contains the mods. /// public static readonly string MODS_PATH = Path.Combine(BASE_PATH, "Mods"); /// - /// The path to the directory where game data is dumped. + /// The path of the directory to which PolyMod writes the dumped game data. /// public static readonly string DUMPED_DATA_PATH = Path.Combine(BASE_PATH, "DumpedData"); /// - /// The path to the directory where localization is dumped. + /// The path of the directory to which PolyMod writes the dumped GLD and avatar data. /// public static readonly string LOGIC_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Logic"); /// - /// The path to the directory where gameLogicData and avatarData are dumped. + /// The path of the directory to which PolyMod writes the dumped localization. /// public static readonly string LOCALIZATION_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Localization"); /// - /// The path to the directory where sprites and sprite infos are dumped. + /// The path of the directory to which PolyMod writes the dumped sprites and sprite infos. /// public static readonly string SPRITES_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Sprites"); /// - /// The path to the directory where prefabs datas are dumped. + /// The path of the directory to which PolyMod writes the dumped prefab data. /// public static readonly string PREFABS_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Prefabs"); /// - /// The path to the PolyMod configuration file. + /// The path of the PolyMod configuration file, PolyMod.json. /// internal static readonly string CONFIG_PATH = Path.Combine(BASE_PATH, "PolyMod.json"); /// - /// The path to the checksum file. + /// The path of the file that keeps the mod checksum of the last game start. /// internal static readonly string CHECKSUM_PATH = Path.Combine(BASE_PATH, "CHECKSUM"); + /// + /// The path of the directory that PolyMod gives to the game as Application.persistentDataPath. + /// internal static readonly string PERSISTENT_DATA_PATH = Path.Combine(BASE_PATH, "PersistentData"); /// @@ -104,7 +129,8 @@ internal static readonly string CHECKSUM_PATH internal static readonly string DISCORD_LINK = "https://discord.gg/eWPdhWtfVy"; /// - /// A list of log messages to ignore. + /// The text parts of Unity log messages that PolyMod does not write to the log. + /// If a log message contains one of these texts, PolyMod removes the message. /// internal static readonly List LOG_MESSAGES_IGNORE = new() { @@ -118,19 +144,27 @@ internal static readonly string CHECKSUM_PATH #pragma warning disable CS8618 /// - /// The PolyMod configuration. + /// The current configuration of PolyMod. reads it from . /// internal static PolyConfig config; /// - /// The logger instance for PolyMod. + /// The BepInEx log source of PolyMod. /// internal static ManualLogSource logger; #pragma warning restore CS8618 /// - /// The entry point for the plugin. + /// Starts PolyMod. BepInEx calls this method when it loads the plugin. /// + /// + /// The method reads the configuration from . + /// If the file is missing or not valid, it uses the default configuration. + /// Then it writes the configuration back to the file and updates the console. + /// It sets the BepInEx Logging.Disk.WriteUnityLog setting to true and calls . + /// If is true, the method stops there. + /// Otherwise, it starts the PolyMod managers. + /// public override void Load() { try @@ -164,6 +198,16 @@ public override void Load() Main.Init(); } + /// + /// Gets the launch data from the PolyMod launcher through the named pipe PolyMod.Launcher. + /// + /// + /// The method waits a maximum of milliseconds to connect. + /// It reads one line of JSON and sets , and from it. + /// If the line is empty, the method stops and does not change these values. + /// If an error occurs, the method sets to false. + /// In all cases other than an empty line, the method then sets to true. + /// internal static void CaptureLaunchData() { try @@ -190,10 +234,11 @@ internal static void CaptureLaunchData() } /// - /// Gets a resource stream from the assembly. + /// Opens a stream to a resource that is embedded in the PolyMod assembly. + /// The full resource name is PolyMod.resources. followed by . /// - /// The ID of the resource. - /// The resource stream. + /// The file name of the resource, for example localization.json. + /// The stream of the resource. The value is null if the resource does not exist. internal static Stream GetResource(string id) { return Assembly.GetExecutingAssembly().GetManifestResourceStream( @@ -202,7 +247,7 @@ internal static Stream GetResource(string id) } /// - /// Writes the configuration to disk. + /// Writes the current as JSON to . /// internal static void WriteConfig() { @@ -210,7 +255,9 @@ internal static void WriteConfig() } /// - /// Updates the console based on the debug configuration. + /// Shows or hides the BepInEx console. The debug value of controls this. + /// If debug is true, the method makes the console. + /// If debug is false, the method detaches the console on Windows and does nothing on other operating systems. /// internal static void UpdateConsole() { diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs index 5ae47db..d2ec8e5 100644 --- a/src/Prefabs/OtherPrefabInfo.cs +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -6,111 +6,228 @@ namespace PolyMod; +/// +/// The base description of a prefab that PolyMod makes from mod JSON. +/// public class BasePrefabInfo { + /// + /// The descriptions of the visual parts of the prefab. + /// [JsonInclude] public List visualParts = new(); } +/// +/// The description of a custom unit prefab. +/// It comes from the units list of a prefabs file or from a unitPrefab file. +/// public class UnitPrefabInfo : BasePrefabInfo { + /// + /// The unit type, the tribe, and the skin that the prefab is for. + /// [JsonInclude] public SkinnedKey skinnedKey; + /// + /// The name of the visual part that is the head position marker of the unit. + /// If no visual part has this name, PolyMod uses the first visual part that it makes. + /// [JsonInclude] public string headPositionMarker = ""; + /// + /// The flag that makes the prefab a UI override. + /// When it is true, the UI shows this prefab in place of the usual unit prefab. + /// [JsonInclude] public bool uiOverride = false; } +/// +/// The description of a custom improvement prefab. +/// It comes from the improvements list of a prefabs file or from an improvementPrefab file. +/// PolyMod also makes a default description for each GLD improvement that has the prefab value set to true. +/// public class ImprovementPrefabInfo : BasePrefabInfo { + /// + /// The improvement type that the prefab is for. + /// If it is null, PolyMod does not make the prefab. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public ImprovementData.Type? improvementType = null; + /// + /// The flag that adds a renderer to the outline of each visual part. + /// When it is false, the outline objects have no renderer. + /// [JsonInclude] public bool needsOutlines = false; } +/// +/// The description of a custom resource prefab. +/// It comes from the resources list of a prefabs file or from a resourcePrefab file. +/// PolyMod also makes a default description for each GLD resource that has the prefab value set to true. +/// public class ResourcePrefabInfo : BasePrefabInfo { + /// + /// The resource type that the prefab is for. + /// If it is null, PolyMod does not make the prefab. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public ResourceData.Type? resourceType = null; } +/// +/// The description of a custom weapon prefab. +/// PolyMod does not read or use this type now. +/// internal class WeaponPrefabInfo { + /// + /// The weapon type that the prefab is for. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] internal UnitData.WeaponEnum? weaponEnum = null; + /// + /// The name of the sprite of the weapon. + /// [JsonInclude] internal string spriteName = ""; + /// + /// The DOTween path type of the weapon movement. + /// [JsonInclude] [JsonConverter(typeof(EnumNameJson))] internal PathType pathType = PathType.CatmullRom; + /// + /// The DOTween path mode of the weapon movement. + /// [JsonInclude] [JsonConverter(typeof(EnumNameJson))] internal PathMode pathMode = PathMode.Sidescroller2D; + /// + /// The DOTween path resolution of the weapon movement. + /// [JsonInclude] internal int pathResolution = 10; + /// + /// The DOTween ease of the weapon movement. + /// [JsonInclude] [JsonConverter(typeof(EnumNameJson))] internal Ease pathEase = Ease.Linear; + /// + /// The look-ahead offset of the weapon movement. + /// [JsonInclude] internal float lookAheadOffset = 0.01f; + /// + /// The handle angle offset of the weapon path. + /// [JsonInclude] internal float handleAngleOffset = 0.3f; + /// + /// The sound effect of the weapon. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] internal SFXTypes sfxType = SFXTypes.None; + /// + /// The puff settings of the weapon, or null. + /// [JsonInclude] internal WeaponPuffInfo? weaponPuffInfo = null; + /// + /// The ranged attack settings of the weapon, or null. + /// [JsonInclude] internal WeaponRangedInfo? weaponRangedInfo = null; } +/// +/// The puff settings of a custom weapon. +/// PolyMod does not use this type now. +/// internal class WeaponPuffInfo { + /// + /// The flag that makes the attacking unit sway. + /// [JsonInclude] internal bool sway = false; + /// + /// The value that multiplies the animation time of the attack. + /// internal float animationMultiplier = 1f; + /// + /// The action to call at the start of the attack, or null. + /// internal Action? initialDelegate = null; + /// + /// The action to call during the ranged animation, or null. + /// internal Action? animationDelegate = null; // [JsonInclude] Nuh uh, I wont do ts // public List puffsToSpawn = new(); } +/// +/// The ranged attack settings of a custom weapon. +/// PolyMod does not use this type now. +/// internal class WeaponRangedInfo { + /// + /// The center offset of the ranged attack. + /// [JsonInclude] internal float centerOffset = 0.15f; } +/// +/// The description of a custom GFX prefab. +/// PolyMod does not use this type now. +/// internal class GFXPrefabInfo { + /// + /// The GFX type that the prefab is for. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] internal GFXType? gfxType = null; } +/// +/// The description of a custom unit effect prefab. +/// PolyMod does not use this type now. +/// internal class UnitEffectPrefabInfo { + /// + /// The unit effect that the prefab is for. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] internal UnitEffect? unitEffect = null; diff --git a/src/Prefabs/PrefabsInfo.cs b/src/Prefabs/PrefabsInfo.cs index 50f639b..bd33633 100644 --- a/src/Prefabs/PrefabsInfo.cs +++ b/src/Prefabs/PrefabsInfo.cs @@ -3,14 +3,27 @@ namespace PolyMod; +/// +/// The content of a prefabs file of a mod. +/// The dumper also writes the prefabs of the game in this format. +/// public class PrefabsInfo { + /// + /// The descriptions of the unit prefabs. + /// [JsonInclude] public List units = new(); + /// + /// The descriptions of the improvement prefabs. + /// [JsonInclude] public List improvements = new(); + /// + /// The descriptions of the resource prefabs. + /// [JsonInclude] public List resources = new(); diff --git a/src/Prefabs/SkinnedKey.cs b/src/Prefabs/SkinnedKey.cs index 41c57d5..6134779 100644 --- a/src/Prefabs/SkinnedKey.cs +++ b/src/Prefabs/SkinnedKey.cs @@ -5,20 +5,38 @@ namespace PolyMod; +/// +/// The key of a unit prefab: a unit type, a tribe, and a skin. +/// public readonly struct SkinnedKey : IEquatable { + /// + /// Gets the unit type. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public UnitData.Type unitType { get; } + /// + /// Gets the tribe. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public TribeType tribeType { get; } + /// + /// Gets the skin. + /// [JsonInclude] [JsonConverter(typeof(EnumCacheJson))] public SkinType skinType { get; } + /// + /// Makes a key from a unit type, a tribe, and a skin. + /// + /// The unit type. + /// The tribe. + /// The skin. [JsonConstructor] public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) { @@ -27,6 +45,11 @@ public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType this.skinType = skinType; } + /// + /// Compares this key with another key. + /// + /// The key to compare. + /// True when the unit type, the tribe, and the skin are all equal, otherwise false. public bool Equals(SkinnedKey other) { return unitType == other.unitType @@ -34,21 +57,42 @@ public bool Equals(SkinnedKey other) && skinType == other.skinType; } + /// + /// Compares this key with an object. + /// + /// The object to compare. + /// True when the object is a that is equal to this key, otherwise false. public override bool Equals(object? obj) { return obj is SkinnedKey otherKey && Equals(otherKey); } + /// + /// Gets the hash code of the key. + /// + /// A hash code that combines the unit type, the tribe, and the skin. public override int GetHashCode() { return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); } + /// + /// Compares two keys. + /// + /// The first key. + /// The second key. + /// True when the keys are equal, otherwise false. public static bool operator ==(SkinnedKey left, SkinnedKey right) { return left.Equals(right); } + /// + /// Compares two keys. + /// + /// The first key. + /// The second key. + /// True when the keys are not equal, otherwise false. public static bool operator !=(SkinnedKey left, SkinnedKey right) { return !left.Equals(right); diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs index 9a4136e..ad0e87c 100644 --- a/src/Prefabs/VisualPartInfo.cs +++ b/src/Prefabs/VisualPartInfo.cs @@ -4,37 +4,81 @@ namespace PolyMod; +/// +/// The description of one visual part of a prefab, as mod JSON gives it. +/// public class VisualPartInfo { + /// + /// The default sprite name of the visual part. + /// PolyMod also uses it as the name of the visual part object. + /// [JsonInclude] public string? defaultSpriteName; + /// + /// The logic that selects the skin of the sprite. The default is UseTribe. + /// [JsonInclude] [JsonConverter(typeof(EnumNameJson))] public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; + /// + /// The logic that selects the skin of the sprite for an improvement. The default is FoundingTribe. + /// Only improvements use this value. + /// [JsonInclude] [JsonConverter(typeof(EnumNameJson))] public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific + /// + /// The world position of the visual part. + /// [JsonInclude] public Vector2 coordinates = new Vector2(0, 0); + /// + /// The rotation of the visual part around the z axis, in degrees. + /// [JsonInclude] public float rotation = 0f; + /// + /// The flag that lets the game tint the sprite with the team color. + /// [JsonInclude] public bool tintable = false; + /// + /// The flag that makes the sprite change with the level of the improvement. + /// Only improvements use this value. + /// [JsonInclude] public bool levels = false; // improvement specific + /// + /// The sorting order of the visual part renderer, or null to use the calculated sorting order. + /// Only unit prefabs use this value. + /// [JsonInclude] public int? sortingOrderOverride = null; + /// + /// The sorting order of the outline renderer, or null to use the calculated sorting order. + /// Only unit prefabs use this value. + /// [JsonInclude] public int? outlineSortingOrderOverride = null; + /// + /// Makes a game visual part from this description. + /// + /// + /// The method copies the sprite name, the tint flag, the skin logic values, and the level flag. + /// It does not make the objects or the renderers of the visual part. + /// + /// True to mark the visual part as an improvement part. + /// The new visual part. public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) { return new SkinVisualsReference.VisualPart @@ -48,6 +92,16 @@ public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) }; } + /// + /// Sets all values of this description from a game visual part. + /// + /// + /// The sorting orders come from the SpriteRenderer of the visual part object and of the outline object. + /// If an object has no SpriteRenderer, its sorting order is null. + /// gets the world position of the visual part object. + /// gets the z component of the rotation quaternion, not an angle in degrees. + /// + /// The visual part to copy. Its visual part object must not be null. public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) { int? sortingOrderOverride = null; diff --git a/src/Registry.cs b/src/Registry.cs index 2c02448..de7f52d 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -7,64 +7,88 @@ namespace PolyMod; /// -/// A central registry for storing and accessing modded content. +/// The central store of the mods and the mod content that PolyMod loads. /// public static class Registry { /// - /// The next available index for automatically assigned IDs. + /// The next free index for an automatically indexed enum value. + /// PolyMod uses this one counter for all enum types, which include tribes, units, skins and tile effects. + /// The counter starts at . /// internal static int autoidx = Plugin.AUTOIDX_STARTS_FROM; /// - /// A dictionary of all loaded sprites, keyed by their name. + /// The sprites that PolyMod made from mod textures, keyed by the lowercase sprite name. /// internal static Dictionary sprites = new(); + /// + /// The textures from the PNG files of mods, keyed by the lowercase file name without the extension. + /// The value contains the texture and a flag. + /// The flag is true when PolyMod already made a sprite from the texture with a sprite info. + /// internal static Dictionary> textures = new(); // string = texture name, bool, whether texture was processed or not. reviwers, pls tell me how to improve /// - /// A dictionary of all loaded audio clips, keyed by their name. + /// The audio sources of mod audio files, keyed by the lowercase file name without the extension. + /// Each audio source holds one audio clip. /// internal static Dictionary audioClips = new(); /// - /// A dictionary of all loaded mods, keyed by their ID. + /// All registered mods, keyed by the mod id. + /// This dictionary also contains the base game entry with the id polytopia. /// internal static Dictionary mods = new(); /// - /// A dictionary of tribe previews, keyed by tribe name. + /// The custom preview tiles of tribes, keyed by the tribe id from the GLD. /// internal static Dictionary tribePreviews = new(); /// - /// A dictionary of sprite information, keyed by sprite name. + /// The sprite infos from the sprites.json and sprites_*.json files of mods, keyed by the lowercase sprite name. /// internal static Dictionary spriteInfos = new(); /// - /// A dictionary of loaded asset bundles, keyed by their name. + /// The asset bundles from the .bundle files of mods, keyed by the file name without the extension. /// internal static Dictionary assetBundles = new(); /// - /// A list of custom tribes. + /// The tribe types of the custom tribes that mods add. /// internal static List customTribes = new(); /// - /// A list of custom skin information. + /// The skin infos of the custom skins that mods add. /// internal static List skinInfo = new(); /// - /// The next available index for climate styles. + /// The next free value for the style and the climate of a custom tribe. + /// The counter starts at the value of the last member. /// internal static int climateAutoidx = (int)Enum.GetValues().Last(); + /// + /// The prefab files that PolyMod loads after it merges the GLD patches. + /// The key is the mod and the value is the file. + /// public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it + /// + /// Gets the mod sprite that is the best match for a base name, a tribe, a skin and a level. + /// The method changes the tribe and the skin to their EnumCache names and calls . + /// + /// The base name of the sprite. + /// The tribe of the sprite, or for no tribe. + /// The skin of the sprite, or for no skin. + /// The level of the sprite, or -1 for no level. + /// If true, the method finds the outline variant of the sprite. + /// The sprite that is the best match, or null if no sprite matches. public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1, bool outline = false) { string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); @@ -73,8 +97,22 @@ public static class Registry return GetSpriteByText(baseName, tribeText, skinText, levelText, outline); } /// - /// Gets a sprite from the registry, trying to find the best match. + /// Gets the mod sprite that is the best match for a base name, a tribe text, a skin text and a level text. /// + /// + /// The method changes the base name, the tribe text and the skin text to lowercase. + /// If the level text is not empty, the method adds _level to the base name. + /// Then it tries these names in sequence: base, base_tribe, base_skin and base_tribe_skin. + /// If is true, the method adds _outline to each name. + /// A sprite that the method finds later replaces a sprite that it found before. + /// The result is the sprite with the most specific name that exists in . + /// + /// The base name of the sprite. + /// The tribe part of the sprite name, or an empty string. + /// The skin part of the sprite name, or an empty string. + /// The level part of the sprite name, or an empty string for no level. + /// If true, the method finds the outline variant of the sprite. + /// The sprite that is the best match, or null if no sprite matches. public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", string levelText = "", bool outline = false) { Sprite? sprite = null; @@ -101,10 +139,13 @@ public static class Registry } /// - /// Gets an audio clip from the registry. + /// Gets the mod audio clip that is the best match for a name, a tribe and a skin. + /// The method changes the tribe and the skin to their EnumCache names and calls . /// - /// The name of the audio clip. - /// The requested audio clip, or null if not found. + /// The base name of the audio clip. + /// The tribe of the audio clip, or for no tribe. + /// The skin of the audio clip, or for no skin. + /// The audio clip that is the best match, or null if no audio clip matches. public static AudioClip? GetAudioClip(string name, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default) { string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); @@ -113,8 +154,18 @@ public static class Registry } /// - /// Gets an audio clip from the registry, trying to find the best match. + /// Gets the mod audio clip that is the best match for a base name, a tribe text and a skin text. /// + /// + /// The method changes all three texts to lowercase. + /// Then it tries these names in sequence: base, base_tribe, base_skin and base_tribe_skin. + /// An audio source that the method finds later replaces an audio source that it found before. + /// The result is the clip of the audio source with the most specific name that exists in . + /// + /// The base name of the audio clip. + /// The tribe part of the audio name, or an empty string. + /// The skin part of the audio name, or an empty string. + /// The clip of the audio source that is the best match, or null if no audio source matches. public static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") { AudioSource? audioSource = null; diff --git a/src/Util.cs b/src/Util.cs index 885a025..8ede6b2 100644 --- a/src/Util.cs +++ b/src/Util.cs @@ -8,15 +8,16 @@ namespace PolyMod; /// -/// A collection of utility methods for the PolyMod framework. +/// The helper methods that PolyMod uses for types, hashes, JSON tokens, tasks and versions. /// internal static class Util { /// - /// Wraps a managed type for use in the Il2Cpp runtime. + /// Gets the Il2Cpp type of a managed type. + /// If the managed type is not registered in Il2Cpp, the method registers it first. /// - /// The type to wrap. - /// The Il2Cpp representation of the type. + /// The managed type. + /// The Il2CppSystem.Type of . internal static Il2CppSystem.Type WrapType() where T : class { if (!ClassInjector.IsTypeRegisteredInIl2Cpp()) @@ -25,77 +26,80 @@ internal static Il2CppSystem.Type WrapType() where T : class } /// - /// Computes the SHA256 hash of an object's string representation. + /// Gets the SHA-256 hash of the string value of an object. + /// The method uses ToString on the object and UTF-8 to make the bytes. /// /// The object to hash. - /// The hexadecimal string representation of the hash. + /// The hash as an uppercase hexadecimal string. internal static string Hash(object data) { return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(data.ToString()!))); } /// - /// Computes the SHA256 hash of raw bytes. + /// Gets the SHA-256 hash of a byte array. /// /// The bytes to hash. - /// The hexadecimal string representation of the hash. + /// The hash as an uppercase hexadecimal string. internal static string HashBytes(byte[] data) { return Convert.ToHexString(SHA256.HashData(data)); } /// - /// Gets the name of a JToken from its path. + /// Gets one part of the path of a JSON token. + /// The method splits the path at each dot and counts the parts from the end. /// - /// The JToken. - /// The part of the path to retrieve, from the end. - /// The name of the JToken. + /// The JSON token. + /// The position of the part from the end of the path. The value 1 gives the last part. + /// The part of the path at position from the end. internal static string GetJTokenName(JToken token, int n = 1) { return token.Path.Split('.')[^n]; } /// - /// Converts an Il2CppSystem.Version to a System.Version. + /// Changes an Il2CppSystem.Version to a . + /// The method parses the string value of the Il2Cpp version. /// - /// The Il2CppSystem.Version to convert. - /// The equivalent System.Version. + /// The Il2Cpp version to change. + /// A with the same value. internal static Version Cast(this Il2CppSystem.Version self) { return new(self.ToString()); } /// - /// Synchronously unwraps the result of a Task. + /// Waits for a task to complete and gets its result. + /// The method blocks the thread that calls it. /// - /// The result type of the Task. - /// The Task to unwrap. - /// The result of the Task. + /// The type of the result of the task. + /// The task to wait for. + /// The result of the task. internal static T UnwrapAsync(this Task self) { return self.GetAwaiter().GetResult(); } /// - /// Removes the revision component from a Version. + /// Makes a copy of a version without the revision part. /// - /// The Version to modify. - /// A new Version with the revision set to -1. + /// The version to copy. + /// A new version with the same major, minor and build parts, and no revision part. internal static Version CutRevision(this Version self) { return new(self.Major, self.Minor, self.Build); } /// - /// Compares two version strings to see if the first is older or equal to the second. - /// Pre-release tags follow semantic-version rules: the part after the first dash is - /// split on dots, purely numeric identifiers compare numerically and sort before - /// alphanumeric ones, and a longer identifier list is newer. A version with a - /// pre-release tag is always older than the same version without one. + /// Compares two version strings. + /// The method first compares the core versions, which are the parts before the first dash. + /// If the core versions are equal, it compares the pre-release tags with semantic version rules. + /// A version with a pre-release tag is older than the same version without a tag. /// /// The first version string. /// The second version string. - /// True if version1 is older or equal to version2, false otherwise. + /// True if is older than or equal to , false if it is newer. internal static bool IsVersionOlderOrEqual(this string version1, string version2) { Version core1 = ParseVersion(version1, out string? pre1); @@ -107,6 +111,13 @@ internal static bool IsVersionOlderOrEqual(this string version1, string version2 return ComparePreRelease(pre1, pre2) <= 0; } + /// + /// Splits a version string into a core version and a pre-release tag. + /// The pre-release tag is the text after the first dash. + /// + /// The version string to parse. + /// The pre-release tag, or null if there is no dash or no text after the dash. + /// The core version, which is the text before the first dash. private static Version ParseVersion(string version, out string? preRelease) { int dash = version.IndexOf('-'); @@ -121,6 +132,15 @@ private static Version ParseVersion(string version, out string? preRelease) return new Version(version[..dash]); } + /// + /// Compares two pre-release tags with semantic version rules. + /// A null tag (no pre-release) is newer than a tag that is not null. + /// The method splits each tag at the dots and compares the identifiers in sequence. + /// If all shared identifiers are equal, the tag with more identifiers is newer. + /// + /// The first pre-release tag, or null. + /// The second pre-release tag, or null. + /// A negative value if is older, zero if the tags are equal, or a positive value if is newer. private static int ComparePreRelease(string? left, string? right) { if (left == null && right == null) return 0; @@ -139,6 +159,15 @@ private static int ComparePreRelease(string? left, string? right) return leftIds.Length.CompareTo(rightIds.Length); } + /// + /// Compares two identifiers of a pre-release tag. + /// The method compares two numeric identifiers as numbers. + /// A numeric identifier is older than an identifier that contains other characters. + /// The method compares two identifiers that are not numeric by ordinal string order. + /// + /// The first identifier. + /// The second identifier. + /// A negative value if is older, zero if the identifiers are equal, or a positive value if is newer. private static int CompareIdentifier(string left, string right) { bool leftNumeric = left.Length > 0 && left.All(char.IsDigit); From bfb5fdc2314066c2178dc3a64e5aeb75bf79544c Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Mon, 9 Nov 2026 21:33:25 +0100 Subject: [PATCH 34/42] disabled achievements --- resources/localization.json | 4 ++++ src/Managers/Main.cs | 16 ++++++++++++++++ src/Managers/Visual.cs | 30 ++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/resources/localization.json b/resources/localization.json index 1a97e23..f3cad9d 100644 --- a/resources/localization.json +++ b/resources/localization.json @@ -237,6 +237,10 @@ "English": "{0} is only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", "Russian": "{0} доступен только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера." }, + "polymod_achi_vanillaonly": { + "English": "Achievements are only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", + "Russian": "Достижения доступны только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера." + }, "polymod_title_invalid": { "English": "Invalid Launch", "Russian": "Неверный Запуск" diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 83f52ed..24b9caf 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -398,6 +398,22 @@ private static void PlayerState_Deserialize(PlayerState __instance, Il2CppSystem } } + [HarmonyPrefix] + [HarmonyPatch(typeof(AchievementManager), nameof(AchievementManager.CheckAchievements))] + [HarmonyPatch(typeof(AchievementManager), nameof(AchievementManager.CheckHoudini))] + private static bool AchievementManager_CheckAchievementsAndHoudini() + { + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AchievementManager), nameof(AchievementManager.IsAchievementValid))] + private static bool IsAchievementValid(ref bool __result, Achievement achievement, GameState gameState) + { + __result = false; + return false; + } + /// /// Applies the Harmony patches of this class, then registers and loads the mods. /// diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 630cf5a..6c0e72d 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -866,6 +866,36 @@ private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __i ); } + [HarmonyPostfix] + [HarmonyPatch(typeof(ThroneRoomScreen_UI2), nameof(ThroneRoomScreen_UI2.RunLayout))] + private static void ThroneRoomScreen_UI2_RunLayout(ThroneRoomScreen_UI2 __instance) + { + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + foreach (Achievement achievement in GameManager.GetAchievementManager().GetAchievements()) + { + if (!__instance.achievementButtons.TryGetValue(achievement.type, out UIRoundButton_UI2 button)) + continue; + + button.SetSprite(spriteAtlasManager.GetSprite(achievement.GetSpriteName() + "_bw", "UI")); + button.SetStyle(UIButtonBase_UI2.ButtonStyle.Disabled); + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(ThroneRoomScreen_UI2), nameof(ThroneRoomScreen_UI2.OnAchievementButtonCliced))] + private static bool ThroneRoomScreen_UI2_OnAchievementButtonCliced() + { + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = Localization.Get( + "polymod.achi.vanillaonly", + new Il2CppSystem.Object[] { Localization.Get("throne.achievements", Array.Empty()) } + ); + popup.buttonData = new PopupBase.PopupButtonData[] { new("buttons.ok") }; + popup.Show(); + return false; + } + private const string MIGHTYLEADER = "mightyleader"; /// From d4abe8c3ed8943717398428efce1434c65912ad2 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Tue, 10 Nov 2026 20:02:14 +0100 Subject: [PATCH 35/42] review fixes + added some missing loc --- .editorconfig | 9 +- README.md | 2 +- resources/localization.json | 267 ++++++++++++++++++++++------------ src/Api/Config.cs | 29 ++-- src/Api/GLDConfig.cs | 12 +- src/Api/PolyScript.cs | 21 ++- src/Loader.cs | 15 +- src/Managers/Compatibility.cs | 6 +- src/Managers/Main.cs | 12 +- src/Managers/Prefabs.cs | 13 +- src/Managers/Visual.cs | 68 ++++----- src/NullableFix.cs | 52 ------- src/Plugin.cs | 2 - src/Prefabs/VisualPartInfo.cs | 4 +- src/Registry.cs | 8 +- 15 files changed, 276 insertions(+), 244 deletions(-) delete mode 100644 src/NullableFix.cs diff --git a/.editorconfig b/.editorconfig index bf10af8..4d3e7c3 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,10 +5,15 @@ charset = utf-8 insert_final_newline = true trim_trailing_whitespace = true -[*.{json,yml,yaml}] -indent_style = space +[*.json] +indent_style = tab +tab_width = 4 indent_size = 4 +[*.{yml,yaml}] +indent_style = space +indent_size = 2 + [*.cs] indent_style = space tab_width = 4 diff --git a/README.md b/README.md index 408cd22..138e97f 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ | | x86 | ARM | |:-------:|:---:|:---:| | Windows | ✅ | ❌ | -| Linux | ✅ | ❌ | +| Linux | ⏺️ | ❌ | | MacOS | ❌ | ❌ | | Android | ➖ | 🚧 | | IOS | ➖ | ❌ | diff --git a/resources/localization.json b/resources/localization.json index f3cad9d..1010202 100644 --- a/resources/localization.json +++ b/resources/localization.json @@ -43,38 +43,54 @@ "Elyrion": "{0}þr∑∑Ŧ!{1}\niii ŋ∑ƒ ƒ§§π mȱΔ#:", "German (Germany)": "{0} Willkommen! {1}\nDiese Mods sind gerade eben geladen:" }, - "polymod_hub_mod": { - "English": "Name: {0}\nStatus: {1}\nAuthors: {2}\nVersion: {3}\nDescription: {4}", - "Russian": "Имя: {0}\nСтатус: {1}\nАвторы: {2}\nВерсия: {3}\nОписание: {4}", - "Turkish": "İsim: {0}\nDurum: {1}\nYaratıcılar: {2}\nSürüm: {3}", - "Spanish (Mexico)": "Titulo: {0}\nEstado: {1}\nPublicador: {2}\nVersion: {3}", - "French (France)": "Titre: {0}\nEtat: {1}\nAuteurs: {2}\nVersion: {3}", - "Polish": "Nazwa: {0}\nStatus: {1}\nAutorzy: {2}\nWersja: {3}", - "Portuguese (Brazil)": "Nome: {0}\nStatus: {1}\nAutores: {2}\nVersão: {3}", - "Elyrion": "r₼: {0}\n^ŦaŦ₺^: {1}\na₺Ŧţȱr: {2}\nƒƒƒƒƒƒƒ: {3}", - "German (Germany)": "Name: {0}\nStatus: {1}\nAutoren: {2}\nVersion: {3}" - }, "polymod_hub_dump": { "English": "DUMP DATA", "Russian": "ЗАДАМПИТЬ ДАННЫЕ", + "Turkish": "VERİLERİ DIŞA AKTAR", + "Spanish (Mexico)": "VOLCAR DATOS", + "French (France)": "EXTRAIRE LES DONNÉES", + "Polish": "ZRZUĆ DANE", + "Portuguese (Brazil)": "EXTRAIR DADOS", "German (Germany)": "DATENDUMP" }, "polymod_hub_dumped": { "English": "Dump completed successfully!\n\n{0}", "Russian": "Дамп завершен успешно!\n\n{0}", + "Turkish": "Veriler başarıyla dışa aktarıldı!\n\n{0}", + "Spanish (Mexico)": "¡Volcado completado con éxito!\n\n{0}", + "French (France)": "Extraction terminée avec succès!\n\n{0}", + "Polish": "Zrzut zakończony pomyślnie!\n\n{0}", + "Portuguese (Brazil)": "Extração concluída com sucesso!\n\n{0}", "German (Germany)": "Dump erfolgreich beendet!\n\n{0}" }, "polymod_hub_openfolder": { "English": "OPEN FOLDER", - "Russian": "ОТКРЫТЬ ПАПКУ" + "Russian": "ОТКРЫТЬ ПАПКУ", + "Turkish": "KLASÖRÜ AÇ", + "Spanish (Mexico)": "ABRIR CARPETA", + "French (France)": "OUVRIR LE DOSSIER", + "Polish": "OTWÓRZ FOLDER", + "Portuguese (Brazil)": "ABRIR PASTA", + "German (Germany)": "ORDNER ÖFFNEN" }, "polymod_cycle": { "English": "Dependency cycle detected", - "Russian": "Обнаружен цикл зависимостей" + "Russian": "Обнаружен цикл зависимостей", + "Turkish": "Bağımlılık döngüsü algılandı", + "Spanish (Mexico)": "Se detectó un ciclo de dependencias", + "French (France)": "Cycle de dépendances détecté", + "Polish": "Wykryto cykl zależności", + "Portuguese (Brazil)": "Ciclo de dependências detectado", + "German (Germany)": "Abhängigkeitszyklus erkannt" }, "polymod_cycle_description": { "English": "Unable to determine mod loading order!", "Russian": "Невозможно определить порядок загрузки модов!", + "Turkish": "Mod yükleme sırası belirlenemedi!", + "Spanish (Mexico)": "¡No se pudo determinar el orden de carga de los mods!", + "French (France)": "Impossible de déterminer l'ordre de chargement des mods!", + "Polish": "Nie można określić kolejności ładowania modów!", + "Portuguese (Brazil)": "Não foi possível determinar a ordem de carregamento dos mods!", "German (Germany)": "Mod - ladereihenfolge konnte nicht bestimmt werden!" }, "polymod_hub_mod_status_error": { @@ -121,17 +137,6 @@ "Elyrion": "#₺rr∑ŋŦ mȱΔ# ₼π₺þþţ∫ ȱriþiŋa∫ mȱΔ#!", "German (Germany)": "Einige aktuelle mods sind nicht mit Älteren kompatibel!" }, - "polymod_signature_maybe_incompatible": { - "English": "Current mods may not be compatible with original mods!", - "Russian": "Текущие моды могут быть несовместимы с оригинальными модами!", - "Turkish": "Mevcut modlar orijinal modlarla uyumlu olmayabilir!", - "Spanish (Mexico)": "Es posible que este mod no sea compatibile con el original!", - "French (France)": "Les mods actuels peuvent ne pas être compatibles avec les mods originaux!", - "Polish": "Obecne mody mogą nie być kompatybilne z oryginalnymi modami!", - "Portuguese (Brazil)": "É possível que os mods carregados não sejam compatíveis com os mods originais", - "Elyrion": "#₺rr∑ŋŦ mȱΔ# maỹ ₼π₺þþţ∫ ȱriþiŋa∫ mȱΔ#!", - "German (Germany)": "Einige aktuelle mods könnten mit Älteren inkompatibel sein!" - }, "polymod_signature_mismatch": { "English": "Signature mismatch", "Russian": "Несоответствие подписи", @@ -176,133 +181,205 @@ "Elyrion": "Δ∑o₺þ", "German (Germany)": "Debuggen" }, - "polymod_autoupdate": { - "English": "Auto-update", - "Russian": "Автообновление", - "Turkish": "Otomatik güncelleme", - "Spanish (Mexico)": "Actualización automática", - "French (France)": "MAJ auto", - "Polish": "Auto aktualizacja", - "Portuguese (Brazil)": "Atualização automática", - "Elyrion": "a₺Ŧȱ₺πΔaŦ∑", - "German (Germany)": "Auto Aktualisierung" - }, - "polymod_autoupdate_alpha": { - "English": "Include alphas", - "Russian": "Включить альфы", - "Elyrion": "iŋ#∫₺Δ∑ a∫πţaȓ" - }, - "polymod_autoupdate_description": { - "English": "New update available!", - "Russian": "Доступно новое обновление!", - "Elyrion": "ŋ∑~ ₺πΔaŦ∑ a‡ai∫ao∫∑" - }, - "polymod_autoupdate_update": { - "English": "Update", - "Russian": "Обновить", - "Elyrion": "₺πΔaŦ∑" - }, "polymod_hub_config": { "English": "CONFIG", "Russian": "КОНФИГ", - "Elyrion": "#ȱŋ₼iþ" - }, - "polymod_hub_config_enable": { - "English": "ENABLE {0}", - "Russian": "ВКЛЮЧИТЬ {0}", - "Elyrion": "∑ŋao∫∑ {0}" - }, - "polymod_hub_config_disable": { - "English": "DISABLE {0}", - "Russian": "ВЫКЛЮЧИТЬ {0}", - "Elyrion": "Δiȓao∫∑ {0}" - }, - "polymod_config_setto": { - "English": "{0} is set to {1}!", - "Russian": "{0} задан на {1}!", - "Elyrion": "{0} iȓ ȓ∑Ŧ Ŧȱ {1}!" + "Turkish": "AYARLAR", + "Spanish (Mexico)": "CONFIGURACIÓN", + "French (France)": "CONFIGURATION", + "Polish": "KONFIGURACJA", + "Portuguese (Brazil)": "CONFIGURAÇÕES", + "Elyrion": "#ȱŋ₼iþ", + "German (Germany)": "KONFIGURATION" }, "polymod_hub_hotreload": { - "English": "HOT RELOAD" - }, - "polymod_hotreload_success": { - "English": "Hot reload completed for the mod {0}!" - }, - "polymod_hotreload_failure": { - "English": "No mods for hot reload!", - "Russian": "Данные спрайтов не найдены!", - "Elyrion": "ŋȱ ȓπriŦ∑ iŋ₼ȱȓ ~∑r∑ ₼ȱ₺ŋΔ!" + "English": "HOT RELOAD", + "Russian": "ГОРЯЧАЯ ПЕРЕЗАГРУЗКА", + "Turkish": "ANINDA YENİDEN YÜKLE", + "Spanish (Mexico)": "RECARGA EN CALIENTE", + "French (France)": "RECHARGEMENT À CHAUD", + "Polish": "PRZEŁADOWANIE NA GORĄCO", + "Portuguese (Brazil)": "RECARGA A QUENTE", + "German (Germany)": "SOFORT NEU LADEN" }, "polymod_wc_vanillaonly": { "English": "{0} is only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", - "Russian": "{0} доступен только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера." + "Russian": "{0} доступен только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера.", + "Turkish": "{0} yalnızca orijinal Polytopia'da kullanılabilir. Başlatıcıda PolyMod'u devre dışı bırak veya oyunu başlatıcı olmadan başlat.", + "Spanish (Mexico)": "{0} solo está disponible en Polytopia sin mods. Desactiva PolyMod en el launcher o inicia el juego sin el launcher.", + "French (France)": "{0} n'est disponible que dans Polytopia sans mods. Désactivez PolyMod dans le launcher ou lancez le jeu sans le launcher.", + "Polish": "{0} jest dostępne tylko w niezmodowanej Polytopii. Wyłącz PolyMod w launcherze lub uruchom grę bez launchera.", + "Portuguese (Brazil)": "{0} só está disponível no Polytopia sem mods. Desative o PolyMod no launcher ou inicie o jogo sem o launcher.", + "German (Germany)": "{0} ist nur im unmodifizierten Polytopia verfügbar. Deaktiviere PolyMod im Launcher oder starte das Spiel ohne den Launcher." }, "polymod_achi_vanillaonly": { - "English": "Achievements are only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", - "Russian": "Достижения доступны только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера." - }, + "English": "{0} are only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", + "Russian": "{0} доступны только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера.", + "Turkish": "{0} yalnızca orijinal Polytopia'da kullanılabilir. Başlatıcıda PolyMod'u devre dışı bırak veya oyunu başlatıcı olmadan başlat.", + "Spanish (Mexico)": "{0} solo están disponibles en Polytopia sin mods. Desactiva PolyMod en el launcher o inicia el juego sin el launcher.", + "French (France)": "{0} ne sont disponibles que dans Polytopia sans mods. Désactivez PolyMod dans le launcher ou lancez le jeu sans le launcher.", + "Polish": "{0} są dostępne tylko w niezmodowanej Polytopii. Wyłącz PolyMod w launcherze lub uruchom grę bez launchera.", + "Portuguese (Brazil)": "{0} só estão disponíveis no Polytopia sem mods. Desative o PolyMod no launcher ou inicie o jogo sem o launcher.", + "German (Germany)": "{0} sind nur im unmodifizierten Polytopia verfügbar. Deaktiviere PolyMod im Launcher oder starte das Spiel ohne den Launcher." + }, "polymod_title_invalid": { "English": "Invalid Launch", - "Russian": "Неверный Запуск" + "Russian": "Неверный Запуск", + "Turkish": "Geçersiz Başlatma", + "Spanish (Mexico)": "Inicio no válido", + "French (France)": "Lancement invalide", + "Polish": "Nieprawidłowe uruchomienie", + "Portuguese (Brazil)": "Inicialização inválida", + "German (Germany)": "Ungültiger Start" }, "polymod_description_invalid": { "English": "PolyMod launch was invalid. Please, open the game via the PolyMod Launcher or proceed to our site to install it :)", - "Russian": "PolyMod запущен неккоректно. Пожалуйста, откройте игру через PolyMod Launcher или перейдите на наш сайт и установите его :)" + "Russian": "PolyMod запущен некорректно. Пожалуйста, откройте игру через PolyMod Launcher или перейдите на наш сайт и установите его :)", + "Turkish": "PolyMod geçersiz şekilde başlatıldı. Lütfen oyunu PolyMod Launcher ile aç veya yüklemek için sitemize git :)", + "Spanish (Mexico)": "PolyMod se inició de forma incorrecta. Abre el juego con el PolyMod Launcher o visita nuestro sitio para instalarlo :)", + "French (France)": "PolyMod a été lancé de manière incorrecte. Veuillez ouvrir le jeu via le PolyMod Launcher ou vous rendre sur notre site pour l'installer :)", + "Polish": "PolyMod został uruchomiony nieprawidłowo. Otwórz grę przez PolyMod Launcher lub przejdź na naszą stronę, aby go zainstalować :)", + "Portuguese (Brazil)": "O PolyMod foi iniciado de forma inválida. Abra o jogo pelo PolyMod Launcher ou acesse nosso site para instalá-lo :)", + "German (Germany)": "PolyMod wurde ungültig gestartet. Öffne das Spiel bitte über den PolyMod Launcher oder besuche unsere Website, um ihn zu installieren :)" }, "buttons_download_launcher": { "English": "OUR SITE", - "Russian": "НАШ САЙТ" + "Russian": "НАШ САЙТ", + "Turkish": "SİTEMİZ", + "Spanish (Mexico)": "NUESTRO SITIO", + "French (France)": "NOTRE SITE", + "Polish": "NASZA STRONA", + "Portuguese (Brazil)": "NOSSO SITE", + "German (Germany)": "UNSERE WEBSITE" }, "polymod_hub_summary": { "English": "{0} of {1} mods loaded.", - "Russian": "Загружено модов: {0} из {1}." + "Russian": "Загружено модов: {0} из {1}.", + "Turkish": "{1} moddan {0} tanesi yüklendi.", + "Spanish (Mexico)": "{0} de {1} mods cargados.", + "French (France)": "{0} mods sur {1} chargés.", + "Polish": "Załadowano modów: {0} z {1}.", + "Portuguese (Brazil)": "{0} de {1} mods carregados.", + "German (Germany)": "{0} von {1} Mods geladen." }, "polymod_hub_mods_none": { "English": "No mods are installed yet. Put mod archives into the Mods folder next to the game and restart it.", - "Russian": "Моды пока не установлены. Положите архивы модов в папку Mods рядом с игрой и перезапустите её." + "Russian": "Моды пока не установлены. Положите архивы модов в папку Mods рядом с игрой и перезапустите её.", + "Turkish": "Henüz yüklü mod yok. Mod arşivlerini oyunun yanındaki Mods klasörüne koy ve oyunu yeniden başlat.", + "Spanish (Mexico)": "Aún no hay mods instalados. Coloca los archivos de mods en la carpeta Mods junto al juego y reinícialo.", + "French (France)": "Aucun mod n'est encore installé. Placez les archives de mods dans le dossier Mods à côté du jeu, puis redémarrez-le.", + "Polish": "Nie zainstalowano jeszcze żadnych modów. Umieść archiwa modów w folderze Mods obok gry i uruchom ją ponownie.", + "Portuguese (Brazil)": "Nenhum mod instalado ainda. Coloque os arquivos dos mods na pasta Mods ao lado do jogo e reinicie-o.", + "German (Germany)": "Es sind noch keine Mods installiert. Lege Mod-Archive in den Ordner Mods neben dem Spiel und starte es neu." }, "polymod_hub_mod_authors": { "English": "by {0}", - "Russian": "от {0}" + "Russian": "от {0}", + "Turkish": "{0} tarafından", + "Spanish (Mexico)": "por {0}", + "French (France)": "par {0}", + "Polish": "autor: {0}", + "Portuguese (Brazil)": "por {0}", + "German (Germany)": "von {0}" }, "polymod_hub_mod_checksum": { "English": "checksum {0}", - "Russian": "контрольная сумма {0}" + "Russian": "контрольная сумма {0}", + "Turkish": "sağlama toplamı {0}", + "Spanish (Mexico)": "suma de verificación {0}", + "French (France)": "somme de contrôle {0}", + "Polish": "suma kontrolna {0}", + "Portuguese (Brazil)": "soma de verificação {0}", + "German (Germany)": "Prüfsumme {0}" }, "polymod_hub_checksum": { "English": "Global checksum: {0}", - "Russian": "Общая контрольная сумма: {0}" + "Russian": "Общая контрольная сумма: {0}", + "Turkish": "Genel sağlama toplamı: {0}", + "Spanish (Mexico)": "Suma de verificación global: {0}", + "French (France)": "Somme de contrôle globale: {0}", + "Polish": "Globalna suma kontrolna: {0}", + "Portuguese (Brazil)": "Soma de verificação global: {0}", + "German (Germany)": "Globale Prüfsumme: {0}" }, "polymod_hub_config_debug": { "English": "DEBUG", - "Russian": "ОТЛАДКА" + "Russian": "ОТЛАДКА", + "Turkish": "HATA AYIKLAMA", + "Spanish (Mexico)": "DEPURACIÓN", + "French (France)": "DÉBOGAGE", + "Polish": "DEBUGOWANIE", + "Portuguese (Brazil)": "DEPURAÇÃO", + "German (Germany)": "DEBUGGEN" }, "polymod_hub_config_coordinates": { "English": "COORDINATES", - "Russian": "КООРДИНАТЫ" + "Russian": "КООРДИНАТЫ", + "Turkish": "KOORDİNATLAR", + "Spanish (Mexico)": "COORDENADAS", + "French (France)": "COORDONNÉES", + "Polish": "WSPÓŁRZĘDNE", + "Portuguese (Brazil)": "COORDENADAS", + "German (Germany)": "KOORDINATEN" }, "polymod_debug_description": { "English": "Opens the developer console and writes verbose logs.", - "Russian": "Открывает консоль разработчика и включает подробные логи." + "Russian": "Открывает консоль разработчика и включает подробные логи.", + "Turkish": "Geliştirici konsolunu açar ve ayrıntılı günlük kaydı tutar.", + "Spanish (Mexico)": "Abre la consola de desarrollador y escribe registros detallados.", + "French (France)": "Ouvre la console de développement et écrit des journaux détaillés.", + "Polish": "Otwiera konsolę deweloperską i zapisuje szczegółowe logi.", + "Portuguese (Brazil)": "Abre o console de desenvolvedor e grava logs detalhados.", + "German (Germany)": "Öffnet die Entwicklerkonsole und schreibt ausführliche Logs." }, "polymod_coordinates": { "English": "Coordinates", - "Russian": "Координаты" + "Russian": "Координаты", + "Turkish": "Koordinatlar", + "Spanish (Mexico)": "Coordenadas", + "French (France)": "Coordonnées", + "Polish": "Współrzędne", + "Portuguese (Brazil)": "Coordenadas", + "German (Germany)": "Koordinaten" }, "polymod_coordinates_description": { "English": "Shows the coordinates of every tile on the map.", - "Russian": "Показывает координаты каждой клетки на карте." + "Russian": "Показывает координаты каждой клетки на карте.", + "Turkish": "Haritadaki her karenin koordinatlarını gösterir.", + "Spanish (Mexico)": "Muestra las coordenadas de cada casilla del mapa.", + "French (France)": "Affiche les coordonnées de chaque case de la carte.", + "Polish": "Pokazuje współrzędne każdego pola na mapie.", + "Portuguese (Brazil)": "Mostra as coordenadas de cada casa do mapa.", + "German (Germany)": "Zeigt die Koordinaten jedes Feldes auf der Karte." }, "polymod_on": { "English": "ON", - "Russian": "ВКЛ" + "Russian": "ВКЛ", + "Turkish": "AÇIK", + "Spanish (Mexico)": "ACTIVADO", + "French (France)": "ACTIVÉ", + "Polish": "WŁ.", + "Portuguese (Brazil)": "LIGADO", + "German (Germany)": "AN" }, "polymod_off": { "English": "OFF", - "Russian": "ВЫКЛ" + "Russian": "ВЫКЛ", + "Turkish": "KAPALI", + "Spanish (Mexico)": "DESACTIVADO", + "French (France)": "DÉSACTIVÉ", + "Polish": "WYŁ.", + "Portuguese (Brazil)": "DESLIGADO", + "German (Germany)": "AUS" }, "polymod_hotreload_unavailable": { "English": "Hot reload is not available yet.", - "Russian": "Горячая перезагрузка пока недоступна." + "Russian": "Горячая перезагрузка пока недоступна.", + "Turkish": "Anında yeniden yükleme henüz kullanılamıyor.", + "Spanish (Mexico)": "La recarga en caliente aún no está disponible.", + "French (France)": "Le rechargement à chaud n'est pas encore disponible.", + "Polish": "Przeładowanie na gorąco nie jest jeszcze dostępne.", + "Portuguese (Brazil)": "A recarga a quente ainda não está disponível.", + "German (Germany)": "Sofortiges Neuladen ist noch nicht verfügbar." } } \ No newline at end of file diff --git a/src/Api/Config.cs b/src/Api/Config.cs index 047a2f0..84c177d 100644 --- a/src/Api/Config.cs +++ b/src/Api/Config.cs @@ -16,7 +16,8 @@ namespace PolyMod.Api; /// /// /// The type of the config object. -public class Config where T : class +// should be public when i get through it +internal class Config where T : class { private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; private T? currentConfig; @@ -30,7 +31,8 @@ public class Config where T : class /// /// The mod name, normally the mod id. The config uses it as the file name or as the key in mods.json. /// The place on disk for the config. - public Config(string modName, ConfigTypes configType) + // should be public when i get through it + internal Config(string modName, ConfigTypes configType) { this.modName = modName; this.configType = configType; @@ -79,7 +81,8 @@ public Config(string modName, ConfigTypes configType) /// If there is a config in memory, for example a config that the constructor read from disk, the method keeps that config. /// /// The config object to use when there is no config in memory. - public void SetDefaultConfig(T defaultValue) + // should be public when i get through it + internal void SetDefaultConfig(T defaultValue) { defaultConfig = defaultValue; if (currentConfig is not null) return; @@ -92,7 +95,8 @@ public void SetDefaultConfig(T defaultValue) /// This method does not write to disk. Call to write the config to disk. /// /// The new config object. - public void Write(T config) + // should be public when i get through it + internal void Write(T config) { currentConfig = config; } @@ -101,7 +105,8 @@ public void Write(T config) /// /// The config object. Changes to it stay in memory until you call . /// There is no config in memory. This occurs when there is no config on disk and you did not call . - public T Get() + // should be public when i get through it + internal T Get() { return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); } @@ -111,7 +116,8 @@ public T Get() /// This method does not write to disk. Call after you edit the config. /// The action that changes the config object. /// There is no config in memory. This occurs when there is no config on disk and you did not call . - public void Edit(Action editor) + // should be public when i get through it + internal void Edit(Action editor) { editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); } @@ -122,7 +128,8 @@ public void Edit(Action editor) /// The function that gets the value from the config object. /// The value that gives. /// There is no config in memory. This occurs when there is no config on disk and you did not call . - public TResult Get(Func getter) + // should be public when i get through it + internal TResult Get(Func getter) { return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); } @@ -133,7 +140,8 @@ public TResult Get(Func getter) /// It keeps the values of other mods in mods.json. /// /// The config type is not a known value. - public void SaveChanges() + // should be public when i get through it + internal void SaveChanges() { switch (configType) { @@ -145,7 +153,7 @@ public void SaveChanges() var modsConfigText = File.ReadAllText(ExposedConfigPath); var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); - File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); + File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(indentedJsonOptions)); break; default: throw new ArgumentOutOfRangeException(); @@ -155,7 +163,8 @@ public void SaveChanges() /// /// The places on disk for a config. /// - public enum ConfigTypes + // should be public when i get through it + internal enum ConfigTypes { /// The config is in its own file, Mods/{modName}.json. PerMod, diff --git a/src/Api/GLDConfig.cs b/src/Api/GLDConfig.cs index 15bc345..7e0ee62 100644 --- a/src/Api/GLDConfig.cs +++ b/src/Api/GLDConfig.cs @@ -19,7 +19,8 @@ namespace PolyMod.Api; /// The users can change the values in mods.json. The changes apply the next time that PolyMod loads the patch. /// /// -public class GldConfigTemplate +// should be public when i get through it +internal class GldConfigTemplate { private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); @@ -32,7 +33,8 @@ public class GldConfigTemplate /// /// The text of the patch file. /// The mod id. The template uses it as the key of the mod section in mods.json. - public GldConfigTemplate(string templateText, string modName) + // should be public when i get through it + internal GldConfigTemplate(string templateText, string modName) { this.templateText = templateText; this.modName = modName; @@ -64,7 +66,8 @@ private void Load() /// If the template uses a key that is not in the config, the method writes the default value to mods.json. /// /// The rendered text, or null if the template has an error. The method writes the error to the log. - public string? Render() + // should be public when i get through it + internal string? Render() { if (!templateText.Contains("{{")) return templateText; var template = Template.Parse(templateText); @@ -109,7 +112,8 @@ private void Load() /// The method replaces the section of the mod and keeps the sections of other mods. /// If the file does not exist or does not contain a JSON object, the method makes a new file. /// - public void SaveChanges() + // should be public when i get through it + internal void SaveChanges() { JsonObject modsConfigJson; if (File.Exists(ConfigPath)) diff --git a/src/Api/PolyScript.cs b/src/Api/PolyScript.cs index 757b6a7..effd8ac 100644 --- a/src/Api/PolyScript.cs +++ b/src/Api/PolyScript.cs @@ -11,7 +11,8 @@ namespace PolyMod.Api; /// When PolyMod loads a mod assembly, it finds the first type in the assembly that is a subclass of this class. /// It makes an instance of that type, calls , and then calls . /// -public abstract class PolyScriptBase +// should be public when i get through it +internal abstract class PolyScriptBase { /// /// Gives the mod and the logger to the script. PolyMod calls this method before . @@ -24,12 +25,14 @@ public abstract class PolyScriptBase /// Starts the mod script. PolyMod calls this method one time, after it loads the mod assembly. /// Put the code that starts your mod here, for example the code that applies your Harmony patches. /// - public abstract void Load(); + // should be public when i get through it + internal abstract void Load(); /// /// Stops the mod script. PolyMod does not call this method at this time. /// - public abstract void Unload(); + // should be public when i get through it + internal abstract void Unload(); /// /// Makes a script. The constructor is internal, so only classes in PolyMod can be direct subclasses. @@ -47,7 +50,8 @@ internal PolyScriptBase() /// /// The type of the per-mod config object. /// The type of the exposed config object. -public abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class +// should be public when i get through it +internal abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class { /// /// Sets the and properties. @@ -76,12 +80,14 @@ internal override void Initialize(Mod mod, ManualLogSource logger) /// /// Does nothing. Override this method to stop your mod. PolyMod does not call this method at this time. /// - public override void Unload() { } + // should be public when i get through it + internal override void Unload() { } /// /// Gets the mod that the script belongs to. /// - public Mod Mod { get; private set; } = null!; + // should be public when i get through it + internal Mod Mod { get; private set; } = null!; /// /// Gets the per-mod config. PolyMod keeps it in the file Mods/{mod id}.json. /// Call before you read it. @@ -102,6 +108,7 @@ public override void Unload() { } /// The base class for a mod script that uses for the per-mod config and the exposed config. /// Make a subclass and override . /// -public abstract class PolyScript : PolyScript +// should be public when i get through it +internal abstract class PolyScript : PolyScript { } diff --git a/src/Loader.cs b/src/Loader.cs index 6cd40a9..943ff22 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -20,7 +20,7 @@ namespace PolyMod; /// /// The methods that register mods, sort them, load their files and apply their GLD data. /// -internal static class Loader +public static class Loader { private static readonly JsonSerializerOptions manifestJsonOptions = new() { @@ -354,7 +354,7 @@ ref manifest } if (Plugin.config.disabledMods.Contains(manifest.id)) { - Plugin.logger.LogError($"Mod {manifest.id} is disabled, skipping"); + Plugin.logger.LogInfo($"Mod {manifest.id} is disabled, skipping"); continue; } if (manifest.version == null) @@ -409,16 +409,15 @@ private static void ProcessModFile(string fullName, byte[] bytes, List /// Sorts the registered mods and loads their assemblies, sprite info files and language files. /// /// - /// The method uses , not . + /// The method uses . /// First, it sorts the mods with . If there is a dependency cycle, the method stops. /// For each mod with the status , it loads the .dll files, the sprite info files and the language files. /// A sprite info file has the name sprites.json or sprites_*.json. /// A language file has the name language.json or language_*.json. /// At the end, it calls Compatibility.ComputeChecksums. /// - /// A dictionary of mods. The method does not use this parameter. /// Set to true if the mods have a dependency cycle, false otherwise. - internal static void LoadMods(Dictionary mods, out bool dependencyCycle) + internal static void LoadMods(out bool dependencyCycle) { dependencyCycle = !SortMods(Registry.mods); if (dependencyCycle) return; @@ -694,7 +693,7 @@ public static void LoadTextureFile(Mod mod, Mod.File file) { string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); Texture2D texture2D = Visual.BuildTexture(file.bytes); - Registry.textures[name] = new KeyValuePair(texture2D, false); + Registry.textures[name] = texture2D; } /// @@ -1060,10 +1059,8 @@ internal static void ProcessFilesQueue() { try { - foreach (KeyValuePair keyValuePair in Registry.filesQueueToBeProcessedAfterGLDMerge) + foreach ((Mod mod, Mod.File file) in Registry.filesQueueToBeProcessedAfterGLDMerge) { - Mod mod = keyValuePair.Key; - Mod.File file = keyValuePair.Value; Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); if (prefabsMatch.Success) { diff --git a/src/Managers/Compatibility.cs b/src/Managers/Compatibility.cs index 8646f1f..524833b 100644 --- a/src/Managers/Compatibility.cs +++ b/src/Managers/Compatibility.cs @@ -222,7 +222,7 @@ private static void StartScreen_UI2_OnShow() { if (!Plugin.ValidLaunch && Application.platform != RuntimePlatform.Android) { - PopupManager.GetBasicPopupWithData( + BasicPopup invalidLaunchPopup = PopupManager.GetBasicPopupWithData( new( Localization.Get("polymod.title.invalid"), Localization.Get("polymod.description.invalid"), @@ -241,7 +241,9 @@ private static void StartScreen_UI2_OnShow() ) } ) - ).Show(); + ); + invalidLaunchPopup.IsUnskippable = true; + invalidLaunchPopup.Show(); void OpenSite() { diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 24b9caf..1395449 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -418,6 +418,7 @@ private static bool IsAchievementValid(ref bool __result, Achievement achievemen /// Applies the Harmony patches of this class, then registers and loads the mods. /// /// + /// First, the method makes the folder if it does not exist. /// The method adds the game itself as the mod polytopia with the status Success. /// Then it calls and . /// It keeps the dependency cycle result in . @@ -426,6 +427,7 @@ private static bool IsAchievementValid(ref bool __result, Achievement achievemen internal static void Init() { stopwatch.Start(); + Directory.CreateDirectory(Plugin.PERSISTENT_DATA_PATH); Harmony.CreateAndPatchAll(typeof(Main)); Mod.Manifest polytopia = new( "polytopia", @@ -437,7 +439,7 @@ internal static void Init() ); Registry.mods.Add(polytopia.id, new(polytopia, Mod.Status.Success, new())); Loader.RegisterMods(Registry.mods); - Loader.LoadMods(Registry.mods, out var cycle); + Loader.LoadMods(out var cycle); dependencyCycle = cycle; stopwatch.Stop(); } @@ -521,28 +523,28 @@ internal static void Load(GameLogicData gameLogicData, JObject json) Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); if (prefabsMatch.Success) { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); continue; } Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); if (unitPrefabMatch.Success) { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); continue; } Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); if (improvementPrefabMatch.Success) { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); continue; } Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); if (resourcePrefabMatch.Success) { - Registry.filesQueueToBeProcessedAfterGLDMerge.Add(mod, file); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); continue; } diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs index 841f1c6..9cd35eb 100644 --- a/src/Managers/Prefabs.cs +++ b/src/Managers/Prefabs.cs @@ -475,6 +475,7 @@ internal static void CreatePrefabs() /// Then it adds the visual parts from . /// The head position marker is the visual part with the name . /// If no visual part has this name, the method uses the first visual part that it made. + /// If the description has no visual parts, the method uses the SpriteContainer object. /// /// The method keeps the prefab when the scene changes. /// If is true, it adds the prefab to , otherwise to . @@ -513,7 +514,8 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) } } - unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; + unitInstance.headPositionMarker = headPositionMarker + ?? (visualParts.Count > 0 ? visualParts[0].visualPart.transform : spriteContainer); var svr = unitInstance.GetComponent(); svr.visualParts = visualParts.ToArray(); @@ -532,8 +534,8 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) /// Makes the visual parts of a custom unit prefab. /// /// - /// The method reverses the sequence of in the description itself. - /// Then it makes the visual parts in the new sequence with . + /// The method makes the visual parts with , from the last item of to the first. + /// It does not change the description. /// The first part gets the sorting order 0, and each next part gets a sorting order that is 1 more. /// The outline sorting order starts at minus the number of parts and increases by 1 for each part, to a maximum of -1. /// and replace these values when they are set. @@ -553,10 +555,9 @@ internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) int nextPartSortingOrder = 0; int nextOutlineSortingOrder = -visualPartInfos.Count; - var newVisualInfo = visualPartInfos; - newVisualInfo.Reverse(); - foreach (var info in newVisualInfo) + for (int i = visualPartInfos.Count - 1; i >= 0; i--) { + VisualPartInfo info = visualPartInfos[i]; parts.Add(CreateUnitVisualPart(info, spriteContainer, info.sortingOrderOverride ?? nextPartSortingOrder, info.outlineSortingOrderOverride ?? nextOutlineSortingOrder)); if (nextOutlineSortingOrder < -1) { diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 6c0e72d..c87a41a 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -1363,71 +1363,54 @@ internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, strin Registry.sprites[spriteName] = sprite; } - // Runs early: only touches your own textures, nothing from SpriteAtlasManager's lookup state. /// /// Makes and registers the sprites from mod textures. /// First, the method makes a sprite for each entry in . - /// It uses the texture with the sprite name, or else the texture with the origin name. + /// If the entry has an origin name, the method uses the texture with that name. Otherwise, it uses the texture with the sprite name. /// It skips an entry without a texture, and keeps entries for . - /// It marks the texture entry with the sprite name as processed in . - /// Then it makes a sprite with the default settings for each texture that is not processed. - /// A texture that only an origin name uses is not processed, so it also gets a sprite with its own name. + /// Then it makes a sprite with the default settings for each texture that does not have a registered sprite with the same name. + /// A texture that only an origin name uses therefore also gets a sprite with its own name. /// public static void CreateSprites() { - Plugin.logger.LogInfo($"Creating sprites with outer origin..."); + Plugin.logger.LogInfo("Creating sprites with outer origin..."); pendingInnerOriginSpriteInfos.Clear(); SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); const float defaultPixelsPerUnit = 2112f; - foreach (KeyValuePair spriteInfoPair in Registry.spriteInfos) + foreach (var (spriteName, spriteInfo) in Registry.spriteInfos) { - string spriteName = spriteInfoPair.Key; - SpriteInfo spriteInfo = spriteInfoPair.Value; - - bool isInnerOrigin = spriteInfo.spriteOrigin != null - && spriteInfo.spriteOrigin.originType == OriginType.Inner; - - if (isInnerOrigin) + if (spriteInfo.spriteOrigin?.originType == OriginType.Inner) { - pendingInnerOriginSpriteInfos.Add(spriteInfoPair); + pendingInnerOriginSpriteInfos.Add(new(spriteName, spriteInfo)); continue; } - KeyValuePair textureEntry; - if (!Registry.textures.TryGetValue(spriteName, out textureEntry)) // search texture - { - if (spriteInfo.spriteOrigin == null || - spriteInfo.spriteOrigin.originType != OriginType.Outer || - spriteInfo.spriteOrigin.name == null || - !Registry.textures.TryGetValue(spriteInfo.spriteOrigin.name, out textureEntry)) // search texture in outer sprite origin - { - continue; - } - } - + string textureName = spriteInfo.spriteOrigin?.name ?? spriteName; + if (!Registry.textures.TryGetValue(textureName, out Texture2D? texture)) + continue; Vector2 pivot = spriteInfo.pivot ?? GetPivotPreset(spriteName); float pixelsPerUnit = spriteInfo.pixelsPerUnit ?? defaultPixelsPerUnit; - bool transformToOutline = spriteInfo.transformToOutline; - float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; - Sprite sprite = BuildSpriteWithTexture(textureEntry.Key, pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); - Registry.textures[spriteName] = new KeyValuePair(textureEntry.Key, true); + Sprite sprite = BuildSpriteWithTexture( + texture, + pivot, + pixelsPerUnit, + spriteInfo.transformToOutline, + spriteInfo.gaussianBlurRadius + ); RegisterSprite(spriteAtlasManager, spriteName, sprite); } - foreach (KeyValuePair> texturePair in Registry.textures) + foreach (var (textureName, texture) in Registry.textures) { - if (texturePair.Value.Value) - { + if (Registry.sprites.ContainsKey(textureName)) continue; - } - string spriteName = texturePair.Key; - Sprite sprite = BuildSpriteWithTexture(texturePair.Value.Key, GetPivotPreset(spriteName), defaultPixelsPerUnit); - RegisterSprite(spriteAtlasManager, spriteName, sprite); + Sprite sprite = BuildSpriteWithTexture(texture, GetPivotPreset(textureName), defaultPixelsPerUnit); + RegisterSprite(spriteAtlasManager, textureName, sprite); } } @@ -1533,9 +1516,9 @@ private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) /// Makes and registers the sprites in , and then clears that list. /// For each entry, the method finds the game sprite with the origin name. /// If the game sprite does not exist, it writes a warning to the log and skips the entry. - /// If the entry has a pivot or pixels per unit, the method makes a new sprite with these settings. - /// Only a new sprite gets the outline and blur settings. - /// Without a pivot and pixels per unit, the method registers the game sprite with no changes. + /// If the entry has a pivot, pixels per unit, an outline or a blur, the method makes a new sprite with these settings. + /// A setting that the entry does not have comes from the game sprite. + /// Without these settings, the method registers the game sprite with no changes. /// public static void CreateInnerOriginSprites() { @@ -1559,10 +1542,11 @@ public static void CreateInnerOriginSprites() bool hasPivotOverride = spriteInfo.pivot != null; bool hasPixelsPerUnitOverride = spriteInfo.pixelsPerUnit != null; + bool hasEffect = spriteInfo.transformToOutline || spriteInfo.gaussianBlurRadius != null; Sprite sprite = originalSprite; - if (hasPivotOverride || hasPixelsPerUnitOverride) + if (hasPivotOverride || hasPixelsPerUnitOverride || hasEffect) { Vector2 normalizedOriginalPivot = new( originalSprite.pivot.x / originalSprite.rect.width, diff --git a/src/NullableFix.cs b/src/NullableFix.cs deleted file mode 100644 index 20b4278..0000000 --- a/src/NullableFix.cs +++ /dev/null @@ -1,52 +0,0 @@ -#nullable disable -// verify whether it is needed at all bruv, i tested one time quickly and it easily compiled -namespace System.Runtime.CompilerServices -{ - /// - /// A local copy of the attribute that the compiler writes to show the nullability of a type. - /// The compiler uses this copy when the referenced assemblies do not supply the attribute. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] - public sealed class NullableAttribute : System.Attribute - { - /// - /// Makes a new with one nullability flag. The constructor does not keep the value. - /// - /// The nullability flag for the type. - public NullableAttribute(byte b) { } - - /// - /// Makes a new with a nullability flag for each part of a type. The constructor does not keep the values. - /// - /// The nullability flags for the type and its type arguments. - public NullableAttribute(byte[] b) { } - } - - /// - /// A local copy of the attribute that the compiler writes to give the default nullability for a type or method. - /// The compiler uses this copy when the referenced assemblies do not supply the attribute. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false)] - public sealed class NullableContextAttribute : System.Attribute - { - /// - /// Makes a new . The constructor does not keep the value. - /// - /// The default nullability flag. - public NullableContextAttribute(byte b) { } - } - - /// - /// A local copy of the attribute that the compiler writes to a module when it keeps nullability data only for public members. - /// The compiler uses this copy when the referenced assemblies do not supply the attribute. - /// - [System.AttributeUsage(System.AttributeTargets.Module)] - public sealed class NullablePublicOnlyAttribute : System.Attribute - { - /// - /// Makes a new . The constructor does not keep the value. - /// - /// True if the module also has nullability data for internal members. - public NullablePublicOnlyAttribute(bool b) { } - } -} diff --git a/src/Plugin.cs b/src/Plugin.cs index bd62ba6..8d1ac47 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -206,7 +206,6 @@ public override void Load() /// It reads one line of JSON and sets , and from it. /// If the line is empty, the method stops and does not change these values. /// If an error occurs, the method sets to false. - /// In all cases other than an empty line, the method then sets to true. /// internal static void CaptureLaunchData() { @@ -230,7 +229,6 @@ internal static void CaptureLaunchData() { ValidLaunch = false; } - ValidLaunch = true; } /// diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs index ad0e87c..1ec55f3 100644 --- a/src/Prefabs/VisualPartInfo.cs +++ b/src/Prefabs/VisualPartInfo.cs @@ -99,7 +99,7 @@ public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) /// The sorting orders come from the SpriteRenderer of the visual part object and of the outline object. /// If an object has no SpriteRenderer, its sorting order is null. /// gets the world position of the visual part object. - /// gets the z component of the rotation quaternion, not an angle in degrees. + /// gets the world rotation of the visual part object around the z axis, in degrees. /// /// The visual part to copy. Its visual part object must not be null. public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) @@ -123,7 +123,7 @@ public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) } coordinates = visualPart.visualPart.transform.position; - rotation = visualPart.visualPart.transform.rotation.z; + rotation = visualPart.visualPart.transform.eulerAngles.z; defaultSpriteName = visualPart.DefaultSpriteName; tintable = visualPart.tintable; skinningLogic = visualPart.skinLogic; diff --git a/src/Registry.cs b/src/Registry.cs index de7f52d..1fa07a8 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -25,10 +25,8 @@ public static class Registry /// /// The textures from the PNG files of mods, keyed by the lowercase file name without the extension. - /// The value contains the texture and a flag. - /// The flag is true when PolyMod already made a sprite from the texture with a sprite info. /// - internal static Dictionary> textures = new(); // string = texture name, bool, whether texture was processed or not. reviwers, pls tell me how to improve + internal static Dictionary textures = new(); /// /// The audio sources of mod audio files, keyed by the lowercase file name without the extension. @@ -75,9 +73,9 @@ public static class Registry /// /// The prefab files that PolyMod loads after it merges the GLD patches. - /// The key is the mod and the value is the file. + /// Each entry contains the mod and one of its files. A mod can have more than one entry. /// - public static Dictionary filesQueueToBeProcessedAfterGLDMerge = new(); // I dont know whether I should do sum abt it + internal static List<(Mod mod, Mod.File file)> filesQueueToBeProcessedAfterGLDMerge = new(); /// /// Gets the mod sprite that is the best match for a base name, a tribe, a skin and a level. From 9fb4e322712fdf1eab4cbbaa6534592b9956d414 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Tue, 10 Nov 2026 20:04:10 +0100 Subject: [PATCH 36/42] removed comment from terrain renderer prefix --- src/Managers/Visual.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index c87a41a..123ba8f 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -525,7 +525,7 @@ private static string GetLandSpriteName(TileData tileData) /// If true, the renderer shows the sprite without color saturation. /// Always false, which skips the original method. [HarmonyPrefix] - [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] // Why prefix? I really hate repeating the logic. I would have to do the same bs 2 times.... anyway reviewers tell me ok? + [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile, TribeType climate, SkinType skin, bool shouldDesaturate) { From 7cc9e38c6c1d815efaf5f78688f312ab34719021 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 12 Nov 2026 15:28:41 +0100 Subject: [PATCH 37/42] new readme? idk --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/README.md b/README.md index 138e97f..8195979 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ ![](https://img.shields.io/codefactor/grade/github/PolyModdingTeam/PolyMod) ![](https://img.shields.io/github/actions/workflow/status/PolyModdingTeam/PolyMod/cicd.yml) +**The mod loader for The Battle of Polytopia.** + +PolyMod lets you play Polytopia with new tribes, units, buildings, skins and much more, made by the community. Mods are just folders or archives you drop into the game, and PolyMod takes care of the rest. Your vanilla game, saves and settings stay untouched. + | | x86 | ARM | |:-------:|:---:|:---:| | Windows | ✅ | ❌ | @@ -11,3 +15,47 @@ | MacOS | ❌ | ❌ | | Android | ➖ | 🚧 | | IOS | ➖ | ❌ | + +## Features + +- **Play with mods in a few clicks.** Browse and download mods right in the launcher or on our website, then start the game. +- **Keep your vanilla game safe.** Modded games use their own save data. Start the game without the launcher, and you get plain Polytopia. +- **Everything in one place.** The PolyMod Hub shows your mods, their status and config, and opens with **Ctrl + Tab** from anywhere in the game. +- **Made for modders.** Change the game logic with JSON patches, add your own sprites, translations and prefabs, or write code mods in C#. + +## Installation + +1. Download the **PolyMod Launcher** from [polymod.dev/download](https://polymod.dev/download/). +2. Install PolyMod with the launcher. +3. Start Polytopia from the launcher. + +That's it. The PolyMod button on the start screen opens the hub. + +### Installing mods + +The easiest way is to download mods directly in the launcher or on [polymod.dev](https://polymod.dev). + +You can also install a mod by hand: put it into the `Mods` folder next to the game and restart. A mod can be a folder, a `.zip` or a `.polymod` file. + +> [!NOTE] +> Modded multiplayer is not supported yet. Weekly challenges and achievements are only available in vanilla Polytopia, so they are turned off while PolyMod is active. + +## Making mods + +Want to make your own tribe, unit or skin? Everything you need is on the [wiki](https://github.com/PolyModdingTeam/PolyMod/wiki), and the community on [Discord](https://discord.gg/eWPdhWtfVy) is always happy to help. + +## Building from source + +You need the [.NET 8 SDK](https://dotnet.microsoft.com/download). + +```bash +git clone https://github.com/PolyModdingTeam/PolyMod.git +cd PolyMod +dotnet build src/PolyMod.csproj -c IL2CPP +``` + +Copy `src/bin/IL2CPP/net6.0/PolyMod.dll` into the `BepInEx/plugins` folder of your game. Run `dotnet test` to run the tests. + +## License + +PolyMod is licensed under [CC BY-NC-ND 4.0](LICENSE). From 9e636d54cd65b1729a6c15a1f23999627b4e2e32 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Thu, 12 Nov 2026 22:32:18 +0100 Subject: [PATCH 38/42] made get audio clip private --- src/Registry.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Registry.cs b/src/Registry.cs index 1fa07a8..ee60ea6 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -164,7 +164,7 @@ public static class Registry /// The tribe part of the audio name, or an empty string. /// The skin part of the audio name, or an empty string. /// The clip of the audio source that is the best match, or null if no audio source matches. - public static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") + private static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") { AudioSource? audioSource = null; baseName = baseName.ToLowerInvariant(); From b343b1280810a35ef9426b81ee935df3534ceafc Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Fri, 13 Nov 2026 20:00:23 +0100 Subject: [PATCH 39/42] new autoindexes: now each type has their own index --- src/Loader.cs | 31 +++++++++++++++++++------------ src/Managers/Loc.cs | 1 + src/Registry.cs | 39 +++++++++++++++++++++++++++++++++++---- 3 files changed, 55 insertions(+), 16 deletions(-) diff --git a/src/Loader.cs b/src/Loader.cs index 943ff22..d6ece97 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -103,12 +103,16 @@ internal record TypeMapping(Type type, bool shouldCreateCache = true); string skinId = skin.ToString(); if (!Enum.TryParse(skinId, ignoreCase: true, out _)) { - SkinType skinValue = (SkinType)Registry.autoidx; + int index = Registry.GetAutoIndex(typeof(SkinType)); + SkinType skinValue = (SkinType)index; + EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); - Registry.skinInfo.Add(new Visual.SkinInfo(Registry.autoidx, skinId, null)); - Plugin.logger.LogInfo("Created mapping for skinType with id " + skinId + " and index " + Registry.autoidx); - Registry.autoidx++; + + Registry.skinInfo.Add(new Visual.SkinInfo(index, skinId, null)); + Plugin.logger.LogInfo("Created mapping for skinType with id " + skinId + " and index " + index); + Registry.IncrementAutoIndex(typeof(SkinType)); + if(token["tribeAbilities"] != null) { JArray tribeAbilities = token["tribeAbilities"].Cast(); @@ -124,11 +128,14 @@ out TribeAbility.Type tribeAbilityType ) && tribeAbilityType == TribeAbility.Type.Flooded) { string tileEffectId = skinId.ToLowerInvariant() + "_flood"; - EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); - EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); - Visual.customFloodingSkins.Add((TileData.EffectType)Registry.autoidx, skinValue); - Plugin.logger.LogInfo("Created mapping for tileEffect with id " + tileEffectId + " and index " + Registry.autoidx); - Registry.autoidx++; + int autoidx = Registry.GetAutoIndex(typeof(TileData.EffectType)); + + TileData.EffectType effectType = (TileData.EffectType)autoidx; + EnumCache.AddMapping(tileEffectId, effectType); + EnumCache.AddMapping(tileEffectId, effectType); + Visual.customFloodingSkins.Add(effectType, skinValue); + Plugin.logger.LogInfo("Created mapping for tileEffect with id " + tileEffectId + " and index " + autoidx); + Registry.IncrementAutoIndex(typeof(TileData.EffectType)); } } } @@ -952,7 +959,7 @@ internal static void ProcessCustomTribes() /// The method does two passes over all entries of all data categories in the GLD. /// In the first pass, it uses only entries that have an idx, in categories with shouldCreateCache set to true. /// If the type of the category is not an enum, the method writes a warning to the log and ignores the entry. - /// If idx is -1, the method sets idx to the next value of . + /// If idx is -1, the method sets idx to the next free index of the enum type of the category, from . /// If allowUnsafeIndexes is true, the method also uses an entry with an idx larger than all existing enum values. /// The method ignores all other entries in the first pass. /// For each entry that it uses, it calls EnumCache.AddMapping two times. The first call adds the name, and the second call adds the type. @@ -986,8 +993,8 @@ internal static void CreateMappings(JObject rootObject) if ((int)token["idx"] == -1) { - token["idx"] = Registry.autoidx; - Registry.autoidx++; + token["idx"] = Registry.GetAutoIndex(targetType); + Registry.IncrementAutoIndex(targetType); } else if (Plugin.config.allowUnsafeIndexes) { diff --git a/src/Managers/Loc.cs b/src/Managers/Loc.cs index 46b1e47..9635ae5 100644 --- a/src/Managers/Loc.cs +++ b/src/Managers/Loc.cs @@ -30,6 +30,7 @@ public static class Loc /// It finds a custom enum value in the parts of the key, which are separated by dots. /// A custom enum value is a number that is not less than . /// The patch gets the enum name of this value from the enum caches of the type mappings in . + /// If more than one enum type has a name for the value, the patch uses the last of these types in . /// Then it replaces the number in the key with the enum name. /// If the key has more than one custom value, the patch uses only the last value. /// diff --git a/src/Registry.cs b/src/Registry.cs index ee60ea6..8077cc6 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -11,13 +11,44 @@ namespace PolyMod; /// public static class Registry { + // internal static int autoidx = Plugin.AUTOIDX_STARTS_FROM; + /// - /// The next free index for an automatically indexed enum value. - /// PolyMod uses this one counter for all enum types, which include tribes, units, skins and tile effects. - /// The counter starts at . + /// The next free index for automatically indexed enum values, keyed by the enum type. + /// Each enum type, for example tribes, units, skins and tile effects, has its own counter. + /// A counter starts at . + /// Values of different enum types can therefore be the same number. /// - internal static int autoidx = Plugin.AUTOIDX_STARTS_FROM; + internal static Dictionary autoindexes = new(); + /// + /// Gets the next free index for an automatically indexed value of an enum type. + /// The method does not change the counter. Call after you use the index. + /// If the type has no counter yet, the method makes one that starts at . + /// + /// The enum type. + /// The next free index for the type. + public static int GetAutoIndex(Type type) + { + if(!autoindexes.TryGetValue(type, out int value)) + { + autoindexes[type] = value = Plugin.AUTOIDX_STARTS_FROM; + } + return value; + } + + /// + /// Increases the next free index of an enum type by 1. + /// If the type has no counter yet, the method makes one that starts at and then increases it. + /// + /// The enum type. + public static void IncrementAutoIndex(Type type) + { + if(!autoindexes.ContainsKey(type)) + autoindexes[type] = Plugin.AUTOIDX_STARTS_FROM; + + autoindexes[type]++; + } /// /// The sprites that PolyMod made from mod textures, keyed by the lowercase sprite name. /// From 87ce26b2a62e2d11a0be59c40cc92faefcda6107 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Fri, 13 Nov 2026 20:11:16 +0100 Subject: [PATCH 40/42] removed config from api for now --- src/Api/Config.cs | 338 +++++++++++++++++++++--------------------- src/Api/GLDConfig.cs | 244 +++++++++++++++--------------- src/Api/PolyScript.cs | 54 ++++--- src/Loader.cs | 2 +- src/Managers/Main.cs | 18 +-- 5 files changed, 327 insertions(+), 329 deletions(-) diff --git a/src/Api/Config.cs b/src/Api/Config.cs index 84c177d..dc0ef25 100644 --- a/src/Api/Config.cs +++ b/src/Api/Config.cs @@ -1,174 +1,174 @@ -using System.Text.Json; -using System.Text.Json.Nodes; +// using System.Text.Json; +// using System.Text.Json.Nodes; -namespace PolyMod.Api; +// namespace PolyMod.Api; -/// -/// The config of a mod. It keeps the config object in memory and reads it from and writes it to a JSON file. -/// -/// -/// -/// To use a config, call first. Then use or . -/// Call to write your changes to disk. -/// -/// -/// The class uses System.Text.Json to read and write the config object. -/// -/// -/// The type of the config object. -// should be public when i get through it -internal class Config where T : class -{ - private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; - private T? currentConfig; - private readonly string modName; - private readonly ConfigTypes configType; - private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string perModConfigPath; - private T? defaultConfig; - /// - /// Makes a config for a mod and reads the config from disk if the config file exists. - /// - /// The mod name, normally the mod id. The config uses it as the file name or as the key in mods.json. - /// The place on disk for the config. - // should be public when i get through it - internal Config(string modName, ConfigTypes configType) - { - this.modName = modName; - this.configType = configType; - perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); - Load(); - } +// /// +// /// The config of a mod. It keeps the config object in memory and reads it from and writes it to a JSON file. +// /// +// /// +// /// +// /// To use a config, call first. Then use or . +// /// Call to write your changes to disk. +// /// +// /// +// /// The class uses System.Text.Json to read and write the config object. +// /// +// /// +// /// The type of the config object. +// // should be public when i get through it +// internal class Config where T : class +// { +// private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; +// private T? currentConfig; +// private readonly string modName; +// private readonly ConfigTypes configType; +// private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); +// private readonly string perModConfigPath; +// private T? defaultConfig; +// /// +// /// Makes a config for a mod and reads the config from disk if the config file exists. +// /// +// /// The mod name, normally the mod id. The config uses it as the file name or as the key in mods.json. +// /// The place on disk for the config. +// // should be public when i get through it +// internal Config(string modName, ConfigTypes configType) +// { +// this.modName = modName; +// this.configType = configType; +// perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); +// Load(); +// } - /// - /// Reads the config from disk into memory. - /// For , the method reads the file Mods/{modName}.json. - /// For , the method reads the value with the mod name as its key in mods.json. - /// If the file does not exist, the method does not change the config in memory. - /// - /// The config type is not a known value. - internal void Load() // can be called internally if config changes; gui config not implemented yet - { - switch (configType) - { - case ConfigTypes.PerMod: - { - if (!File.Exists(perModConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(perModConfigPath); - currentConfig = JsonSerializer.Deserialize(jsonText); - break; - } - case ConfigTypes.Exposed: - { - if (!File.Exists(ExposedConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(ExposedConfigPath); - currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); - break; - } - default: - throw new ArgumentOutOfRangeException(); - } - } - /// - /// Sets the default config. Call this method before you read or edit the config. - /// If there is no config in memory, the method uses the default config and writes it to disk. - /// If there is a config in memory, for example a config that the constructor read from disk, the method keeps that config. - /// - /// The config object to use when there is no config in memory. - // should be public when i get through it - internal void SetDefaultConfig(T defaultValue) - { - defaultConfig = defaultValue; - if (currentConfig is not null) return; - Write(defaultConfig); - SaveChanges(); - } +// /// +// /// Reads the config from disk into memory. +// /// For , the method reads the file Mods/{modName}.json. +// /// For , the method reads the value with the mod name as its key in mods.json. +// /// If the file does not exist, the method does not change the config in memory. +// /// +// /// The config type is not a known value. +// internal void Load() // can be called internally if config changes; gui config not implemented yet +// { +// switch (configType) +// { +// case ConfigTypes.PerMod: +// { +// if (!File.Exists(perModConfigPath)) +// { +// return; +// } +// var jsonText = File.ReadAllText(perModConfigPath); +// currentConfig = JsonSerializer.Deserialize(jsonText); +// break; +// } +// case ConfigTypes.Exposed: +// { +// if (!File.Exists(ExposedConfigPath)) +// { +// return; +// } +// var jsonText = File.ReadAllText(ExposedConfigPath); +// currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); +// break; +// } +// default: +// throw new ArgumentOutOfRangeException(); +// } +// } +// /// +// /// Sets the default config. Call this method before you read or edit the config. +// /// If there is no config in memory, the method uses the default config and writes it to disk. +// /// If there is a config in memory, for example a config that the constructor read from disk, the method keeps that config. +// /// +// /// The config object to use when there is no config in memory. +// // should be public when i get through it +// internal void SetDefaultConfig(T defaultValue) +// { +// defaultConfig = defaultValue; +// if (currentConfig is not null) return; +// Write(defaultConfig); +// SaveChanges(); +// } - /// - /// Replaces the full config object in memory. To change only some values, use . - /// This method does not write to disk. Call to write the config to disk. - /// - /// The new config object. - // should be public when i get through it - internal void Write(T config) - { - currentConfig = config; - } - /// - /// Gets the config object that is in memory. - /// - /// The config object. Changes to it stay in memory until you call . - /// There is no config in memory. This occurs when there is no config on disk and you did not call . - // should be public when i get through it - internal T Get() - { - return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); - } - /// - /// Calls an action on the config object that is in memory, so that the action can change the config. - /// - /// This method does not write to disk. Call after you edit the config. - /// The action that changes the config object. - /// There is no config in memory. This occurs when there is no config on disk and you did not call . - // should be public when i get through it - internal void Edit(Action editor) - { - editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Gets one value from the config object that is in memory. - /// - /// The type of the value. - /// The function that gets the value from the config object. - /// The value that gives. - /// There is no config in memory. This occurs when there is no config on disk and you did not call . - // should be public when i get through it - internal TResult Get(Func getter) - { - return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Writes the config object that is in memory to disk as indented JSON. - /// For , the method replaces the file Mods/{modName}.json. - /// For , the method replaces the value with the mod name as its key in mods.json. - /// It keeps the values of other mods in mods.json. - /// - /// The config type is not a known value. - // should be public when i get through it - internal void SaveChanges() - { - switch (configType) - { - case ConfigTypes.PerMod: - var perModJson = JsonSerializer.Serialize(currentConfig, indentedJsonOptions); - File.WriteAllText(perModConfigPath, perModJson); - break; - case ConfigTypes.Exposed: - var modsConfigText = File.ReadAllText(ExposedConfigPath); - var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); - modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); - File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(indentedJsonOptions)); - break; - default: - throw new ArgumentOutOfRangeException(); - } - } +// /// +// /// Replaces the full config object in memory. To change only some values, use . +// /// This method does not write to disk. Call to write the config to disk. +// /// +// /// The new config object. +// // should be public when i get through it +// internal void Write(T config) +// { +// currentConfig = config; +// } +// /// +// /// Gets the config object that is in memory. +// /// +// /// The config object. Changes to it stay in memory until you call . +// /// There is no config in memory. This occurs when there is no config on disk and you did not call . +// // should be public when i get through it +// internal T Get() +// { +// return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); +// } +// /// +// /// Calls an action on the config object that is in memory, so that the action can change the config. +// /// +// /// This method does not write to disk. Call after you edit the config. +// /// The action that changes the config object. +// /// There is no config in memory. This occurs when there is no config on disk and you did not call . +// // should be public when i get through it +// internal void Edit(Action editor) +// { +// editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); +// } +// /// +// /// Gets one value from the config object that is in memory. +// /// +// /// The type of the value. +// /// The function that gets the value from the config object. +// /// The value that gives. +// /// There is no config in memory. This occurs when there is no config on disk and you did not call . +// // should be public when i get through it +// internal TResult Get(Func getter) +// { +// return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); +// } +// /// +// /// Writes the config object that is in memory to disk as indented JSON. +// /// For , the method replaces the file Mods/{modName}.json. +// /// For , the method replaces the value with the mod name as its key in mods.json. +// /// It keeps the values of other mods in mods.json. +// /// +// /// The config type is not a known value. +// // should be public when i get through it +// internal void SaveChanges() +// { +// switch (configType) +// { +// case ConfigTypes.PerMod: +// var perModJson = JsonSerializer.Serialize(currentConfig, indentedJsonOptions); +// File.WriteAllText(perModConfigPath, perModJson); +// break; +// case ConfigTypes.Exposed: +// var modsConfigText = File.ReadAllText(ExposedConfigPath); +// var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); +// modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); +// File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(indentedJsonOptions)); +// break; +// default: +// throw new ArgumentOutOfRangeException(); +// } +// } - /// - /// The places on disk for a config. - /// - // should be public when i get through it - internal enum ConfigTypes - { - /// The config is in its own file, Mods/{modName}.json. - PerMod, - /// The config is a value in the shared mods.json file in the game folder, with the mod name as its key. - Exposed - } -} +// /// +// /// The places on disk for a config. +// /// +// // should be public when i get through it +// internal enum ConfigTypes +// { +// /// The config is in its own file, Mods/{modName}.json. +// PerMod, +// /// The config is a value in the shared mods.json file in the game folder, with the mod name as its key. +// Exposed +// } +// } diff --git a/src/Api/GLDConfig.cs b/src/Api/GLDConfig.cs index 7e0ee62..02bdb56 100644 --- a/src/Api/GLDConfig.cs +++ b/src/Api/GLDConfig.cs @@ -1,132 +1,132 @@ -using System.Text.Json; -using System.Text.Json.Nodes; -using Scriban; -using Scriban.Runtime; +// using System.Text.Json; +// using System.Text.Json.Nodes; +// using Scriban; +// using Scriban.Runtime; -namespace PolyMod.Api; +// namespace PolyMod.Api; -/// -/// A GLD patch template with config values. -/// PolyMod uses it for each patch.json and patch_*.json file of a mod. -/// -/// -/// -/// A patch file can use the Scriban template syntax. In the template, write {{ config "key" "default" }} to get a config value. -/// The function gets the value with that key from the section of the mod in mods.json, as text. -/// If the key does not exist, the function adds the key with the default value and gives the default value. -/// -/// -/// The users can change the values in mods.json. The changes apply the next time that PolyMod loads the patch. -/// -/// -// should be public when i get through it -internal class GldConfigTemplate -{ - private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); +// /// +// /// A GLD patch template with config values. +// /// PolyMod uses it for each patch.json and patch_*.json file of a mod. +// /// +// /// +// /// +// /// A patch file can use the Scriban template syntax. In the template, write {{ config "key" "default" }} to get a config value. +// /// The function gets the value with that key from the section of the mod in mods.json, as text. +// /// If the key does not exist, the function adds the key with the default value and gives the default value. +// /// +// /// +// /// The users can change the values in mods.json. The changes apply the next time that PolyMod loads the patch. +// /// +// /// +// // should be public when i get through it +// internal class GldConfigTemplate +// { +// private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string templateText; - private JsonObject currentConfig = new(); - private string modName; +// private readonly string templateText; +// private JsonObject currentConfig = new(); +// private string modName; - /// - /// Makes a template from the text of a patch file and reads the config values of the mod from mods.json. - /// - /// The text of the patch file. - /// The mod id. The template uses it as the key of the mod section in mods.json. - // should be public when i get through it - internal GldConfigTemplate(string templateText, string modName) - { - this.templateText = templateText; - this.modName = modName; - Load(); - } - /// - /// Reads the config values of the mod from mods.json. - /// If the file does not exist, or the mod does not have a JSON object in it, the method uses an empty config. - /// - private void Load() - { - if (File.Exists(ConfigPath)) - { - var json = File.ReadAllText(ConfigPath); - if (JsonNode.Parse(json) is JsonObject modsConfig - && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) - && modConfigNode is JsonObject modConfig) - { - currentConfig = modConfig; - return; - } - } - currentConfig = new JsonObject(); - } +// /// +// /// Makes a template from the text of a patch file and reads the config values of the mod from mods.json. +// /// +// /// The text of the patch file. +// /// The mod id. The template uses it as the key of the mod section in mods.json. +// // should be public when i get through it +// internal GldConfigTemplate(string templateText, string modName) +// { +// this.templateText = templateText; +// this.modName = modName; +// Load(); +// } +// /// +// /// Reads the config values of the mod from mods.json. +// /// If the file does not exist, or the mod does not have a JSON object in it, the method uses an empty config. +// /// +// private void Load() +// { +// if (File.Exists(ConfigPath)) +// { +// var json = File.ReadAllText(ConfigPath); +// if (JsonNode.Parse(json) is JsonObject modsConfig +// && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) +// && modConfigNode is JsonObject modConfig) +// { +// currentConfig = modConfig; +// return; +// } +// } +// currentConfig = new JsonObject(); +// } - /// - /// Renders the template with the config values of the mod. - /// If the text does not contain {{, the method gives the text without changes. - /// If the template uses a key that is not in the config, the method writes the default value to mods.json. - /// - /// The rendered text, or null if the template has an error. The method writes the error to the log. - // should be public when i get through it - internal string? Render() - { - if (!templateText.Contains("{{")) return templateText; - var template = Template.Parse(templateText); - var context = new TemplateContext(); - var scriptObject = new ScriptObject(); +// /// +// /// Renders the template with the config values of the mod. +// /// If the text does not contain {{, the method gives the text without changes. +// /// If the template uses a key that is not in the config, the method writes the default value to mods.json. +// /// +// /// The rendered text, or null if the template has an error. The method writes the error to the log. +// // should be public when i get through it +// internal string? Render() +// { +// if (!templateText.Contains("{{")) return templateText; +// var template = Template.Parse(templateText); +// var context = new TemplateContext(); +// var scriptObject = new ScriptObject(); - bool changedConfig = false; - scriptObject.Import("config", - new Func((key, defaultValue) => - { - if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) - { - return token.ToString(); - } +// bool changedConfig = false; +// scriptObject.Import("config", +// new Func((key, defaultValue) => +// { +// if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) +// { +// return token.ToString(); +// } - changedConfig = true; - currentConfig[key] = defaultValue; +// changedConfig = true; +// currentConfig[key] = defaultValue; - return defaultValue; - }) - ); - context.PushGlobal(scriptObject); - string? result; - try - { - result = template.Render(context); - } - catch (Exception e) - { - Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); - result = null; - } - if (changedConfig) - { - SaveChanges(); - } - return result; - } +// return defaultValue; +// }) +// ); +// context.PushGlobal(scriptObject); +// string? result; +// try +// { +// result = template.Render(context); +// } +// catch (Exception e) +// { +// Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); +// result = null; +// } +// if (changedConfig) +// { +// SaveChanges(); +// } +// return result; +// } - /// - /// Writes the config values of the mod to mods.json as indented JSON. - /// The method replaces the section of the mod and keeps the sections of other mods. - /// If the file does not exist or does not contain a JSON object, the method makes a new file. - /// - // should be public when i get through it - internal void SaveChanges() - { - JsonObject modsConfigJson; - if (File.Exists(ConfigPath)) - { - var modsConfigText = File.ReadAllText(ConfigPath); - modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); - } - else - { - modsConfigJson = new JsonObject(); - } +// /// +// /// Writes the config values of the mod to mods.json as indented JSON. +// /// The method replaces the section of the mod and keeps the sections of other mods. +// /// If the file does not exist or does not contain a JSON object, the method makes a new file. +// /// +// // should be public when i get through it +// internal void SaveChanges() +// { +// JsonObject modsConfigJson; +// if (File.Exists(ConfigPath)) +// { +// var modsConfigText = File.ReadAllText(ConfigPath); +// modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); +// } +// else +// { +// modsConfigJson = new JsonObject(); +// } - modsConfigJson[modName] = currentConfig; - File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); - } -} +// modsConfigJson[modName] = currentConfig; +// File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); +// } +// } diff --git a/src/Api/PolyScript.cs b/src/Api/PolyScript.cs index effd8ac..6d3c9d4 100644 --- a/src/Api/PolyScript.cs +++ b/src/Api/PolyScript.cs @@ -1,11 +1,11 @@ using BepInEx.Logging; -using Newtonsoft.Json.Linq; +// using Newtonsoft.Json.Linq; namespace PolyMod.Api; /// /// The base class of all mod scripts. Do not use this class directly. -/// To make a mod script, make a subclass of or . +/// To make a mod script, make a subclass of . /// /// /// When PolyMod loads a mod assembly, it finds the first type in the assembly that is a subclass of this class. @@ -42,28 +42,26 @@ internal PolyScriptBase() } } /// -/// The base class for a mod script with a typed per-mod config and a typed exposed config. +/// The base class for a mod script. /// /// /// Make a subclass and override . -/// Before PolyMod calls , it sets the , , , and properties. +/// Before PolyMod calls , it sets the and properties. /// -/// The type of the per-mod config object. -/// The type of the exposed config object. // should be public when i get through it -internal abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class +// internal abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class +internal abstract class PolyScript : PolyScriptBase { /// /// Sets the and properties. - /// Makes the per-mod config and the exposed config, with the mod id as the mod name. /// /// The mod that the script belongs to. /// The log source of the mod. internal override void Initialize(Mod mod, ManualLogSource logger) { Mod = mod; - Config = new Config(mod.id, Config.ConfigTypes.PerMod); - ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); + // Config = new Config(mod.id, Config.ConfigTypes.PerMod); + // ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); Logger = logger; } @@ -88,27 +86,27 @@ internal override void Unload() { } /// // should be public when i get through it internal Mod Mod { get; private set; } = null!; - /// - /// Gets the per-mod config. PolyMod keeps it in the file Mods/{mod id}.json. - /// Call before you read it. - /// - protected Config Config { get; private set; } = null!; - /// - /// Gets the exposed config. PolyMod keeps it in the shared mods.json file, with the mod id as its key. - /// Call before you read it. - /// - protected Config ExposedConfig { get; private set; } = null!; + // /// + // /// Gets the per-mod config. PolyMod keeps it in the file Mods/{mod id}.json. + // /// Call before you read it. + // /// + // protected Config Config { get; private set; } = null!; + // /// + // /// Gets the exposed config. PolyMod keeps it in the shared mods.json file, with the mod id as its key. + // /// Call before you read it. + // /// + // protected Config ExposedConfig { get; private set; } = null!; /// /// Gets the log source of the mod. Use it to write messages to the BepInEx log. /// protected ManualLogSource Logger { get; private set; } = null!; } -/// -/// The base class for a mod script that uses for the per-mod config and the exposed config. -/// Make a subclass and override . -/// -// should be public when i get through it -internal abstract class PolyScript : PolyScript -{ -} +// /// +// /// The base class for a mod script that uses for the per-mod config and the exposed config. +// /// Make a subclass and override . +// /// +// // should be public when i get through it +// internal abstract class PolyScript : PolyScript +// { +// } diff --git a/src/Loader.cs b/src/Loader.cs index d6ece97..51967b6 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -754,7 +754,7 @@ public static void LoadTextureFile(Mod mod, Mod.File file) /// /// The mod that contains the file. /// The audio file to load. - public static void LoadAudioFile(Mod mod, Mod.File file) + private static void LoadAudioFile(Mod mod, Mod.File file) { string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); try diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index 1395449..833af19 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -464,7 +464,7 @@ private static void Application_persistentDataPath_get(ref string __result) /// Then it reads the files of each mod and uses the file name or the file extension to select the action: /// /// localization.json and localization_*.json: calls . - /// patch.json and patch_*.json: renders the file as a and merges it into with . If the render gives null, the mod gets the status Error. + /// patch.json and patch_*.json: reads the file as JSON and merges it into with . /// prefabs, unitPrefab, improvementPrefab, and resourcePrefab JSON files: adds the file to . /// Files with the extension .png: calls . /// Files with the extension .bundle: calls . @@ -505,17 +505,17 @@ internal static void Load(GameLogicData gameLogicData, JObject json) if (patchMatch.Success) { var patchText = new StreamReader(new MemoryStream(file.bytes)).ReadToEnd(); - var template = new Api.GldConfigTemplate(patchText, mod.id); - var text = template.Render(); - if (text is null) - { - mod.status = Mod.Status.Error; - continue; - } + // var template = new Api.GldConfigTemplate(patchText, mod.id); + // var text = template.Render(); + // if (text is null) + // { + // mod.status = Mod.Status.Error; + // continue; + // } Loader.LoadGameLogicDataPatch( mod, json, - JObject.Parse(text) + JObject.Parse(patchText) ); continue; } From a48e7a73f4ccb11bf4097eca4929437e32d90542 Mon Sep 17 00:00:00 2001 From: Maksym Muraviov$ Date: Fri, 13 Nov 2026 20:42:03 +0100 Subject: [PATCH 41/42] made launch always valid until we drop launcher --- src/Plugin.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Plugin.cs b/src/Plugin.cs index 8d1ac47..e4a7598 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -229,6 +229,8 @@ internal static void CaptureLaunchData() { ValidLaunch = false; } + + ValidLaunch = true; // IN THIS 2.0 ALPHA LAUNCH IS ALWAYS VALID!!!!!!!!!!! } /// From e31cc0e3d526c68413170b626a3d02c837143c80 Mon Sep 17 00:00:00 2001 From: Lubyanoy Ivan Date: Fri, 13 Nov 2026 23:16:22 +0300 Subject: [PATCH 42/42] Smol README fixes --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8195979..13499c7 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ That's it. The PolyMod button on the start screen opens the hub. The easiest way is to download mods directly in the launcher or on [polymod.dev](https://polymod.dev). -You can also install a mod by hand: put it into the `Mods` folder next to the game and restart. A mod can be a folder, a `.zip` or a `.polymod` file. +You can also install a mod by hand: put it into the `Mods` folder next to the game and restart. > [!NOTE] > Modded multiplayer is not supported yet. Weekly challenges and achievements are only available in vanilla Polytopia, so they are turned off while PolyMod is active. @@ -51,7 +51,7 @@ You need the [.NET 8 SDK](https://dotnet.microsoft.com/download). ```bash git clone https://github.com/PolyModdingTeam/PolyMod.git cd PolyMod -dotnet build src/PolyMod.csproj -c IL2CPP +dotnet build ``` Copy `src/bin/IL2CPP/net6.0/PolyMod.dll` into the `BepInEx/plugins` folder of your game. Run `dotnet test` to run the tests.