diff --git a/PvZ Fusion Translator.sln.DotSettings.user b/PvZ Fusion Translator.sln.DotSettings.user index 8f0047e..ad79a6e 100644 --- a/PvZ Fusion Translator.sln.DotSettings.user +++ b/PvZ Fusion Translator.sln.DotSettings.user @@ -1,5 +1,6 @@  ForceIncluded ForceIncluded + ForceIncluded ForceIncluded ForceIncluded \ No newline at end of file diff --git a/Source/AssetStore/AudioStore.cs b/Source/AssetStore/AudioStore.cs index 639065a..77fb4d4 100644 --- a/Source/AssetStore/AudioStore.cs +++ b/Source/AssetStore/AudioStore.cs @@ -48,7 +48,7 @@ internal static class AudioStore } #if MELONLOADER var audioSourceType = typeof(AudioSource); - var sourceMethodName = "Play"; + const string SourceMethodName = "Play"; var prefixMethod = typeof(AudioStore).GetMethod(nameof(AudioPlayPatch), BindingFlags.Static | BindingFlags.Public); if (prefixMethod == null) @@ -58,13 +58,13 @@ internal static class AudioStore } _ = Core.Instance.HarmonyInstance.Patch( - AccessTools.Method(audioSourceType, sourceMethodName), - new HarmonyMethod(prefixMethod) + AccessTools.Method(audioSourceType, SourceMethodName), + new(prefixMethod) ); Core.Instance.HarmonyInstance.Patch( - AccessTools.Method(audioSourceType, sourceMethodName, [typeof(ulong)]), - new HarmonyMethod(prefixMethod) + AccessTools.Method(audioSourceType, SourceMethodName, [typeof(ulong)]), + new(prefixMethod) ); #endif } diff --git a/Source/Core.cs b/Source/Core.cs index 7d908d7..921e028 100644 --- a/Source/Core.cs +++ b/Source/Core.cs @@ -6,7 +6,7 @@ global using MelonLoader.Utils; global using Il2Cpp; global using Il2CppAlmanacData; global using Il2CppCore; -global using Il2CppGameLevel; +global using Il2CppGameLevel; // ReSharper disable once RedundantUsingDirective.Global global using Il2CppGameLevel.Abyss; global using Il2CppGameLevel.EventNodes; global using Il2CppGameLevel.RogueShooting; @@ -44,6 +44,7 @@ global using Il2CppPlantInfo = AlmanacData.PlantInfo; using PvZ_Fusion_Translator.AssetStore; using PvZ_Fusion_Translator.Patches.Managers; using PvZ_Fusion_Translator.Patches.Modes.Super_Editor; + #if MELONLOADER [assembly: MelonGame("LanPiaoPiao", "PlantsVsZombiesRH"), diff --git a/Source/FileLoader.cs b/Source/FileLoader.cs index fd413e3..6a42034 100644 --- a/Source/FileLoader.cs +++ b/Source/FileLoader.cs @@ -544,22 +544,20 @@ internal static class FileLoader } } - foreach (var filepath in Directory.EnumerateFiles(textureDir, "*.png", SearchOption.AllDirectories)) + foreach (var path in Directory.EnumerateFiles(textureDir, "*.png", SearchOption.AllDirectories) + .Where( + p => (!p.Contains("[Custom Textures]", StringComparison.OrdinalIgnoreCase) || + !Core.Instance.ConfigDefaultTextures.Value) && + (localToc.ContainsKey(p.Replace(basePath + "\\", "").Replace("\\", "/")) || + SerializeWithIndentation(localToc) == "{}") + )) { - if (filepath.Contains("[Custom Textures]", StringComparison.OrdinalIgnoreCase) && - Core.Instance.ConfigDefaultTextures.Value) - continue; - - if (!localToc.ContainsKey(filepath.Replace(basePath + "\\", "").Replace("\\", "/")) && - SerializeWithIndentation(localToc) != "{}") - continue; - if (ModFeatures.IsDebug) - Log.LogDebug("Loading File : " + filepath); + Log.LogDebug("Loading File : " + path); - var imageData = File.ReadAllBytes(filepath); - var texture2D = Utils.LoadImage(imageData); - TextureStore.TextureDict[Path.GetFileNameWithoutExtension(filepath)] = imageData; + var imageData = File.ReadAllBytes(path); + _ = Utils.LoadImage(imageData); + TextureStore.TextureDict[Path.GetFileNameWithoutExtension(path)] = imageData; } } @@ -570,6 +568,7 @@ internal static class FileLoader } } + // ReSharper disable once FunctionComplexityOverflow internal static void LoadLocalizedSprites(Utils.LanguageEnum? language = null) { var textureDir = GetAssetDir(AssetType.Sprites, language); @@ -580,14 +579,13 @@ internal static class FileLoader try { var trueTextureDir = GetAssetDir(AssetType.Textures, language); - var localToc = new Dictionary(); var localTocDir = Path.Combine(trueTextureDir, "Texture_TOC.json"); if (!File.Exists(localTocDir)) File.WriteAllText(localTocDir, "{}"); var localTocContent = File.ReadAllText(localTocDir); - localToc = System.Text.Json.JsonSerializer.Deserialize>(localTocContent); + var localToc = System.Text.Json.JsonSerializer.Deserialize>(localTocContent); var basePath = Core.ModDirectory; @@ -627,44 +625,42 @@ internal static class FileLoader { var downloadPath = Path.Combine(basePath, path); - var baseUrl = - $"https://raw.githubusercontent.com/Teyliu/PVZF-Translation/refs/heads/main/PvZ_Fusion_Translator/"; + const string BaseUrl = + "https://raw.githubusercontent.com/Teyliu/PVZF-Translation/refs/heads/main/PvZ_Fusion_Translator/"; - var url = baseUrl + path; + var url = $"{BaseUrl}{path}"; var imageData = Utils.GetByteDataFromWeb(url).Result; - if (imageData != null) - { - var fileName = Path.GetFileName(downloadPath); - var texture2D = Utils.LoadImage(imageData); - TextureStore.SpriteDict[fileName] = imageData; + if (imageData == null) + continue; - if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) - Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); + var fileName = Path.GetFileName(downloadPath); + _ = Utils.LoadImage(imageData); + TextureStore.SpriteDict[fileName] = imageData; - File.WriteAllBytes(downloadPath, imageData); - } + if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) + Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); + + File.WriteAllBytes(downloadPath, imageData); } } } - foreach (var filepath in Directory.EnumerateFiles(textureDir, "*.png", SearchOption.AllDirectories)) + foreach (var path in Directory.EnumerateFiles(textureDir, "*.png", SearchOption.AllDirectories) + .Where( + p => (!p.Contains("[Custom Textures]", StringComparison.OrdinalIgnoreCase) || + !Core.Instance.ConfigDefaultTextures.Value) && + (localToc.ContainsKey(p.Replace(basePath + "\\", "").Replace("\\", "/")) || + SerializeWithIndentation(localToc) == "{}") + )) { - if (filepath.Contains("[Custom Textures]", StringComparison.OrdinalIgnoreCase) && - Core.Instance.ConfigDefaultTextures.Value) - continue; - - if (!localToc.ContainsKey(filepath.Replace(basePath + "\\", "").Replace("\\", "/")) && - SerializeWithIndentation(localToc) != "{}") - continue; - if (ModFeatures.IsDebug) - Log.LogDebug("Loading File (Sprite): " + filepath); + Log.LogDebug("Loading File (Sprite): " + path); - var imageData = File.ReadAllBytes(filepath); - var texture2D = Utils.LoadImage(imageData); - TextureStore.SpriteDict[Path.GetFileNameWithoutExtension(filepath)] = imageData; + var imageData = File.ReadAllBytes(path); + _ = Utils.LoadImage(imageData); + TextureStore.SpriteDict[Path.GetFileNameWithoutExtension(path)] = imageData; } } @@ -692,14 +688,13 @@ internal static class FileLoader try { var trueTextureDir = Path.Combine(Core.ModDirectory, "[Custom Textures]"); - var localToc = new Dictionary(); var localTocDir = Path.Combine(trueTextureDir, "Default_TOC.json"); if (!File.Exists(localTocDir)) File.WriteAllText(localTocDir, "{}"); var localTocContent = File.ReadAllText(localTocDir); - localToc = System.Text.Json.JsonSerializer.Deserialize>(localTocContent); + var localToc = System.Text.Json.JsonSerializer.Deserialize>(localTocContent); var basePath = Core.ModDirectory; @@ -739,24 +734,23 @@ internal static class FileLoader { var downloadPath = Path.Combine(basePath, path); - var baseUrl = - $"https://raw.githubusercontent.com/Teyliu/PVZF-Translation/refs/heads/main/PvZ_Fusion_Translator/"; + const string BaseUrl = "https://raw.githubusercontent.com/Teyliu/PVZF-Translation/refs/heads/main/PvZ_Fusion_Translator/"; - var url = baseUrl + path; + var url = $"{BaseUrl}{path}"; var imageData = Utils.GetByteDataFromWeb(url).Result; - if (imageData != null) - { - var fileName = Path.GetFileName(downloadPath); - var texture2D = Utils.LoadImage(imageData); - TextureStore.TextureDict[fileName] = imageData; + if (imageData == null) + continue; - if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) - Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); + var fileName = Path.GetFileName(downloadPath); + _ = Utils.LoadImage(imageData); + TextureStore.TextureDict[fileName] = imageData; - File.WriteAllBytes(downloadPath, imageData); - } + if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) + Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); + + File.WriteAllBytes(downloadPath, imageData); } } } @@ -772,7 +766,7 @@ internal static class FileLoader continue; var imageData = File.ReadAllBytes(filepath); - var texture2D = Utils.LoadImage(imageData); + _ = Utils.LoadImage(imageData); TextureStore.TextureDict[Path.GetFileNameWithoutExtension(filepath)] = imageData; } } @@ -794,14 +788,13 @@ internal static class FileLoader try { var trueTextureDir = Path.Combine(Core.ModDirectory, "[Custom Textures]"); - var localToc = new Dictionary(); var localTocDir = Path.Combine(trueTextureDir, "Custom_TOC.json"); if (!File.Exists(localTocDir)) File.WriteAllText(localTocDir, "{}"); var localTocContent = File.ReadAllText(localTocDir); - localToc = System.Text.Json.JsonSerializer.Deserialize>(localTocContent); + var localToc = System.Text.Json.JsonSerializer.Deserialize>(localTocContent); var basePath = Core.ModDirectory; @@ -821,13 +814,7 @@ internal static class FileLoader foreach (var pair in textureToc) { - if (!localToc.TryGetValue(pair.Key, out var value)) - { - toDownload.Add(pair.Key); - continue; - } - - if (pair.Value != value) + if (!localToc.TryGetValue(pair.Key, out var value) || pair.Value != value) { toDownload.Add(pair.Key); continue; @@ -844,24 +831,24 @@ internal static class FileLoader { var downloadPath = Path.Combine(basePath, path); - var baseUrl = - $"https://raw.githubusercontent.com/Teyliu/PVZF-Translation/refs/heads/main/PvZ_Fusion_Translator/"; + const string BaseUrl = + "https://raw.githubusercontent.com/Teyliu/PVZF-Translation/refs/heads/main/PvZ_Fusion_Translator/"; - var url = baseUrl + path; + var url = $"{BaseUrl}{path}"; var imageData = Utils.GetByteDataFromWeb(url).Result; - if (imageData != null) - { - var fileName = Path.GetFileName(downloadPath); - var texture2D = Utils.LoadImage(imageData); - TextureStore.TextureDict[fileName] = imageData; + if (imageData == null) + continue; - if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) - Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); + var fileName = Path.GetFileName(downloadPath); + _ = Utils.LoadImage(imageData); + TextureStore.TextureDict[fileName] = imageData; - File.WriteAllBytes(downloadPath, imageData); - } + if (!Directory.Exists(Path.GetDirectoryName(downloadPath))) + Directory.CreateDirectory(Path.GetDirectoryName(downloadPath)); + + File.WriteAllBytes(downloadPath, imageData); } } } @@ -873,7 +860,7 @@ internal static class FileLoader continue; var imageData = File.ReadAllBytes(filepath); - var texture2D = Utils.LoadImage(imageData); + _ = Utils.LoadImage(imageData); TextureStore.TextureDict[Path.GetFileNameWithoutExtension(filepath)] = imageData; } } @@ -934,31 +921,23 @@ internal static class FileLoader var almanacDir = GetAssetDir(AssetType.Almanac, Utils.Language); if (AlmanacPlantMenu_Patch.AlmanacJson != "") - { - var plantAlmanac = SerializeWithIndentation(AlmanacPlantMenu_Patch.AlmanacJson); - File.WriteAllText( Path.Combine(almanacDir, "LawnStringsTranslate.json"), AlmanacPlantMenu_Patch.AlmanacJson ); - } if (AlmanacZombieMenu_Patch.AlmanacJson != "") - { - var zombieAlmanac = SerializeWithIndentation(AlmanacZombieMenu_Patch.AlmanacJson); - File.WriteAllText( Path.Combine(almanacDir, "ZombieStringsTranslate.json"), AlmanacZombieMenu_Patch.AlmanacJson ); - } - if (AlmanacSelectMenu_Patch.DetailStrings != new Dictionary()) - { - var detailStrings = SerializeWithIndentation(AlmanacSelectMenu_Patch.DetailStrings); + if (AlmanacSelectMenu_Patch.DetailStrings == new Dictionary()) + return; - File.WriteAllText(Path.Combine(almanacDir, "DetailStringsTranslate.json"), detailStrings); - } + var detailStrings = SerializeWithIndentation(AlmanacSelectMenu_Patch.DetailStrings); + + File.WriteAllText(Path.Combine(almanacDir, "DetailStringsTranslate.json"), detailStrings); } public static string SerializeWithIndentation(T value, int size = 4, char indentChar = ' ') @@ -992,10 +971,8 @@ internal static class FileLoader File.WriteAllText(Path.Combine(dumpDir, "ZombieStrings.json"), zombieStrings); //File.WriteAllText(Path.Combine(dumpDir, "AbyssBuffData.json"), AbyssBuffData); - // dump iz tips - var izDump = DumpIZStrings(); - var izLevelData = izDump.Item1; - var izLevelDataDump = izDump.Item2; + // Dump IZ tips. + var (_, izLevelDataDump) = DumpIZStrings(); File.WriteAllText( Path.Combine(dumpDir, "tips_iz.json"), @@ -1009,10 +986,8 @@ internal static class FileLoader ) ); - // dump fusion showcase tips - var fusionShowcaseDump = DumpFSStrings(); - var fusionShowcaseData = fusionShowcaseDump.Item1; - var fusionShowcaseDataDump = fusionShowcaseDump.Item2; + // Dump fusion showcase tips. + var (_, fusionShowcaseDataDump) = DumpFSStrings(); File.WriteAllText( Path.Combine(dumpDir, "tips_fs.json"), @@ -1026,7 +1001,7 @@ internal static class FileLoader ) ); - // dump almanac mechanics + // Dump almanac mechanics. var (_, detailStrings) = DumpDetailStrings(); File.WriteAllText( @@ -1042,7 +1017,7 @@ internal static class FileLoader ); } - public static ValueTuple, Dictionary> DumpIZStrings() + public static (Il2CppArrayBase, Dictionary) DumpIZStrings() { var izLevelData = Resources.LoadAll("izleveldata"); var izLevelDataDump = new Dictionary(); diff --git a/Source/ModFeatures.cs b/Source/ModFeatures.cs index c0c411d..2b7335e 100644 --- a/Source/ModFeatures.cs +++ b/Source/ModFeatures.cs @@ -9,23 +9,18 @@ public static class ModFeatures ReloadStrings, ReloadTextures, ExportLevelStrings, } - private class ModFeature + private sealed class ModFeature(string name, ModType modType, KeyCode keyCode, bool defaultValue = false) { - public string Name { get; private set; } + // ReSharper disable once UnusedMember.Local + public string Name { get; private set; } = name; - public ModType ModType { get; private set; } + // ReSharper disable once MemberCanBePrivate.Local + public ModType ModType { get; } = modType; - public KeyCode KeyCode { get; private set; } + public KeyCode KeyCode { get; } = keyCode; - public bool IsActive { get; set; } - - public ModFeature(string name, ModType modType, KeyCode keyCode, bool defaultValue = false) - { - Name = name; - ModType = modType; - KeyCode = keyCode; - IsActive = defaultValue; - } + // ReSharper disable once UnusedMember.Local + public bool IsActive { get; set; } = defaultValue; public void ToggleFeature() { @@ -40,22 +35,20 @@ public static class ModFeatures Core.ShowToast("Textures Reloaded!"); return; case ModType.ExportLevelStrings: - { var customMenu = UnityEngine.Object.FindObjectOfType(); if (!customMenu) return; - if (customMenu.isActiveAndEnabled) - { - Patches.Modes.Super_Editor.GameLevel.LevelManager_Patch - .ExportLevelStrings(customMenu.LevelData); + if (!customMenu.isActiveAndEnabled) + return; - Core.ShowToast("Dumped level strings!"); - } + Patches.Modes.Super_Editor.GameLevel.LevelManager_Patch + .ExportLevelStrings(customMenu.LevelData); + Core.ShowToast("Dumped level strings!"); return; - } + default: return; } } } @@ -68,7 +61,7 @@ public static class ModFeatures public static bool IsMultiLanguage { get; } = IsDefined("PVZ_FUSION_TRANSLATOR_MULTI_LANGUAGE", true); - private static Dictionary s_featureLists = new() + private static readonly Dictionary s_featureLists = new() { { ModType.ReloadStrings, new("Reload Strings", ModType.ReloadStrings, KeyCode.Home, true) }, { ModType.ReloadTextures, new("Reload Textures", ModType.ReloadTextures, KeyCode.End, true) }, @@ -80,21 +73,19 @@ public static class ModFeatures public static void ToggleFeature(ModType modType) { - if (!s_featureLists.ContainsKey(modType)) - return; - - s_featureLists[modType].ToggleFeature(); + if (s_featureLists.TryGetValue(modType, out var list)) + list.ToggleFeature(); } public static void OnLateUpdate() { - foreach (var (type, feature) in s_featureLists) - if (feature.KeyCode != KeyCode.None && Enum.IsDefined(typeof(KeyCode), feature.KeyCode)) + foreach (var (_, feature) in s_featureLists) + if (feature.KeyCode != KeyCode.None && Enum.IsDefined(feature.KeyCode)) if (Input.GetKeyDown(feature.KeyCode)) feature.ToggleFeature(); } - static bool IsDefined(string env, bool fallback = false) + private static bool IsDefined(string env, bool fallback = false) { var ret = Environment.GetEnvironmentVariable(env)?.ToUpperInvariant() is not "FALSE" and not "0" and var value && diff --git a/Source/Utils.cs b/Source/Utils.cs index 5a85263..6958efd 100644 --- a/Source/Utils.cs +++ b/Source/Utils.cs @@ -201,7 +201,7 @@ public static class Utils .GetComponent(); newGoBackText.autoSizeTextContainer = true; - newGoBackText.text = StringStore.TranslateText(text, false); + newGoBackText.text = StringStore.TranslateText(text); newGoBackText.font = fontAsset; newGoBackText.color = color; } @@ -261,9 +261,6 @@ public static class Utils public static string GetZombieNameFromAlmanac(ZombieType theZombieType, bool removeTags = false) { var theZombieName = ""; - - var currentLanguage = Language.ToString(); - var json = AlmanacZombieMenu_Patch.AlmanacJson; var zombieData = JsonUtility.FromJson(json); @@ -276,30 +273,26 @@ public static class Utils return theZombieName; } +#pragma warning disable CA2211 public static Dictionary> PlantIndices = new(); public static Dictionary PlantIndiceString = new(); - +#pragma warning restore CA2211 public static void RegisterPlantIndices() { PlantIndices = new(); PlantIndiceString = new(); - string originalJson; - string translatedJson; - var currentLanguage = Language.ToString(); - var almanacDir = FileLoader.GetAssetDir(FileLoader.AssetType.Almanac, Language); var dumpDir = FileLoader.GetAssetDir(FileLoader.AssetType.Dumps); var originalPath = Path.Combine(dumpDir, "LawnStrings.json"); - var path = Path.Combine(almanacDir, "LawnStringsTranslate.json"); if (!File.Exists(originalPath)) Log.LogError($"LawnStrings.json file not found at path: {originalPath}"); else try { - originalJson = File.ReadAllText(originalPath); - translatedJson = AlmanacPlantMenu_Patch.AlmanacJson; + var originalJson = File.ReadAllText(originalPath); + var translatedJson = AlmanacPlantMenu_Patch.AlmanacJson; var originalPlantData = JsonUtility.FromJson(originalJson); var translatedPlantData = JsonUtility.FromJson(translatedJson); @@ -315,17 +308,12 @@ public static class Utils if (info.seedType == originalPlantInfo.seedType) translatedPlantInfo = info; - if (translatedPlantInfo != null) - if (translatedPlantInfo.name != null) - { - var temp = new KeyValuePair( - translatedPlantInfo.seedType, - translatedPlantInfo.name - ); + if (translatedPlantInfo is not { name: not null }) + continue; - PlantIndices.Add(originalPlantInfo.seedType, temp); - PlantIndiceString[originalPlantInfo.name] = translatedPlantInfo.name; - } + KeyValuePair temp = new(translatedPlantInfo.seedType, translatedPlantInfo.name); + PlantIndices.Add(originalPlantInfo.seedType, temp); + PlantIndiceString[originalPlantInfo.name] = translatedPlantInfo.name; } } catch (Exception e) @@ -334,49 +322,32 @@ public static class Utils } } - public static void TryAdd(Dictionary dict, TA key, TB val) - { - if (dict.ContainsKey(key)) - dict[key] = val; - else - dict.Add(key, val); - } + public static void TryAdd(Dictionary dict, TA key, TB val) => dict[key] = val; - public static void TryAdd(SortedDictionary dict, TA key, TB val) - { - if (dict.ContainsKey(key)) - dict[key] = val; - else - dict.Add(key, val); - } + public static void TryAdd(SortedDictionary dict, TA key, TB val) => dict[key] = val; public static AssetBundle GetAssetBundle(Assembly assembly, string assetBundlePath, bool log = false) { try { - if (assembly != null) - { - var manifestResourceStream = - assembly.GetManifestResourceStream($"PvZ_Fusion_Translator.Resources.{assetBundlePath}"); + if (assembly == null) + throw new($"AssetBundle {assetBundlePath} was null."); - using (manifestResourceStream) - { - if (manifestResourceStream == null) - throw new("Stream was null."); + using var manifestResourceStream = + assembly.GetManifestResourceStream($"PvZ_Fusion_Translator.Resources.{assetBundlePath}"); - var array = new byte[manifestResourceStream.Length]; - _ = manifestResourceStream.Read(array, 0, array.Length); - var assetBundle = AssetBundle.LoadFromMemory(array); - ArgumentNullException.ThrowIfNull(assetBundle, "assetBundle"); + if (manifestResourceStream == null) + throw new("Stream was null."); - if (log) - Log.LogDebug($"AssetBundle {assetBundlePath} has successfully been loaded."); + var array = new byte[manifestResourceStream.Length]; + _ = manifestResourceStream.Read(array, 0, array.Length); + var assetBundle = AssetBundle.LoadFromMemory(array); + ArgumentNullException.ThrowIfNull(assetBundle); - return assetBundle; - } - } + if (log) + Log.LogDebug($"AssetBundle {assetBundlePath} has successfully been loaded."); - throw new($"AssetBundle {assetBundlePath} was null."); + return assetBundle; } catch (Exception value) { @@ -389,50 +360,45 @@ public static class Utils var assetBundle = AssetBundle.LoadFromFile(path); return assetBundle; } - - /*public static Dictionary> recipeLinks = new Dictionary>(); +#if false + public static readonly Dictionary> recipeLinks = new(); public static void RegisterRecipeLinks() { recipeLinks.Clear(); Il2CppSystem.Array mixData = MixData.data.Cast(); - int rows = mixData.GetLength(0); - int columns = mixData.GetLength(1); + var rows = mixData.GetLength(0); + var columns = mixData.GetLength(1); - foreach (PlantType plantType in Enum.GetValues(typeof(PlantType))) + foreach (var seedType in from PlantType plantType in Enum.GetValues(typeof(PlantType)) select (int)plantType) { - int seedType = (int)plantType; - recipeLinks.Add(seedType, new()); if (seedType > 0) - { - foreach (PlantType checkType in Enum.GetValues(typeof(PlantType))) + foreach (var checks in Enum.GetValues(typeof(PlantType)) + .Cast() + .Where(checkType => checkType > 0) + .Select( + int[] (checkType) => + [ + mixData.GetValue(seedType, (int)checkType).Unbox(), + mixData.GetValue((int)checkType, seedType).Unbox(), + ] + )) { - if (checkType > 0) - { - int[] checks = [mixData.GetValue(seedType, (int)checkType).Unbox(), mixData.GetValue((int)checkType, seedType).Unbox()]; + if (checks[0] != 0) + recipeLinks[seedType].Add(checks[0]); - if (checks[0] != 0) - { - recipeLinks[seedType].Add(checks[0]); - } - - if (checks[1] != 0) - { - recipeLinks[seedType].Add(checks[1]); - } - } + if (checks[1] != 0) + recipeLinks[seedType].Add(checks[1]); } - } - if (recipeLinks[seedType].Count > 0) - { - Log.LogDebug($"Found {recipeLinks[seedType].Count} fusions for {seedType}!"); - } - } - }*/ + if (recipeLinks[seedType].Count > 0) + Log.LogDebug($"Found {recipeLinks[seedType].Count} fusions for {seedType}!"); + } + } +#endif public static readonly Regex UntranslatedRegex = new("\\p{IsCJKUnifiedIdeographs}+"); public static bool CheckForUntranslatedText(string text) @@ -488,11 +454,9 @@ public static class Utils if (isLog) Log.LogInfo($"Attempting to read {url}"); - var client = new HttpClient(); - try { - var dataRequest = await client.GetAsync(url); + var dataRequest = await s_client.GetAsync(url); if (dataRequest.StatusCode == System.Net.HttpStatusCode.OK) { @@ -526,11 +490,9 @@ public static class Utils if (isLog) Log.LogInfo($"Attempting to read {url}"); - var client = new HttpClient(); - try { - var dataRequest = await client.GetAsync(url); + var dataRequest = await s_client.GetAsync(url); if (dataRequest.StatusCode == System.Net.HttpStatusCode.OK) { @@ -564,19 +526,15 @@ public static class Utils if (isLog) Log.LogInfo($"Attempting to read {url}"); - var client = new HttpClient(); - - using var request = new HttpRequestMessage - { - Method = HttpMethod.Get, - RequestUri = new(url), - }; + using var request = new HttpRequestMessage(); + request.Method = HttpMethod.Get; + request.RequestUri = new(url); request.Headers.Add("Accept", "*/*"); request.Headers.Add("Accept-Encoding", "gzip, deflate, br"); request.Headers.Add("User-Agent", "TranslatorMod"); - var dataRequest = await client.SendAsync(request); + var dataRequest = await s_client.SendAsync(request); if (dataRequest.StatusCode == System.Net.HttpStatusCode.OK) { @@ -602,7 +560,7 @@ public static class Utils var res = 0; var gameVersionParts = gameVersion.Split('.'); - var startingPower = (int)Math.Max(gameVersionParts.Length, 3); + var startingPower = Math.Max(gameVersionParts.Length, 3); for (var i = 0; i < startingPower; i++) { @@ -637,7 +595,7 @@ public static class Utils RegisterPlantIndices(); Zombie_Patch.LoadHpStrings(); } - +#pragma warning disable CA2211 // ReSharper disable once NotAccessedField.Global public static LanguageEnum OldLanguage; public static LanguageEnum Language; @@ -698,6 +656,8 @@ public static class Utils { ToggleEnum.SwapLocal, "Change Translation\nSource" }, }; + private static readonly HttpClient s_client = new(); +#pragma warning restore CA2211 public enum ToggleEnum { Textures,