diff --git a/BetterUI/BetterUI.csproj b/BetterUI/BetterUI.csproj index 4d4cae7..286bc17 100644 --- a/BetterUI/BetterUI.csproj +++ b/BetterUI/BetterUI.csproj @@ -11,10 +11,11 @@ BetterUI BetterUI v4.8 - 9 + 12 512 true + enable none @@ -71,7 +72,7 @@ False - $(GameDir)\unstripped_corlib\Mono.Security.dll + $(GameDir)\valheim_Data\Managed\Mono.Security.dll False @@ -88,247 +89,247 @@ False - $(GameDir)\unstripped_corlib\UnityEngine.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.dll False - $(GameDir)\unstripped_corlib\UnityEngine.AccessibilityModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.AccessibilityModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.AIModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.AIModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.AndroidJNIModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.AndroidJNIModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.AnimationModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.AnimationModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ARModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ARModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.AssetBundleModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.AssetBundleModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.AudioModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.AudioModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ClothModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ClothModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ClusterInputModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ClusterInputModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ClusterRendererModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ClusterRendererModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.CoreModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.CoreModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.CrashReportingModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.CrashReportingModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.DirectorModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.DirectorModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.DSPGraphModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.DSPGraphModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.GameCenterModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.GameCenterModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.GridModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.GridModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.HotReloadModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.HotReloadModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ImageConversionModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ImageConversionModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.IMGUIModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.IMGUIModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.InputLegacyModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.InputLegacyModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.InputModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.InputModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.JSONSerializeModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.JSONSerializeModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.LocalizationModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.LocalizationModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ParticleSystemModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ParticleSystemModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.PerformanceReportingModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.PerformanceReportingModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.Physics2DModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.Physics2DModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.PhysicsModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.PhysicsModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ProfilerModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ProfilerModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.ScreenCaptureModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.ScreenCaptureModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.SharedInternalsModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.SharedInternalsModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.SpriteMaskModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.SpriteMaskModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.SpriteShapeModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.SpriteShapeModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.StreamingModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.StreamingModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.SubstanceModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.SubstanceModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.SubsystemsModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.SubsystemsModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.TerrainModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.TerrainModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.TerrainPhysicsModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.TerrainPhysicsModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.TextCoreModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.TextCoreModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.TextRenderingModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.TextRenderingModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.TilemapModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.TilemapModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.TLSModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.TLSModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UI.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UI.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UIElementsModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UIElementsModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UIModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UIModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UmbraModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UmbraModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UNETModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UNETModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityAnalyticsModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityAnalyticsModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityConnectModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityConnectModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityTestProtocolModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityTestProtocolModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityWebRequestAssetBundleModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityWebRequestAssetBundleModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityWebRequestAudioModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityWebRequestAudioModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityWebRequestModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityWebRequestModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityWebRequestTextureModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityWebRequestTextureModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.UnityWebRequestWWWModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.UnityWebRequestWWWModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.VehiclesModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.VehiclesModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.VFXModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.VFXModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.VideoModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.VideoModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.VRModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.VRModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.WindModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.WindModule.dll False - $(GameDir)\unstripped_corlib\UnityEngine.XRModule.dll + $(GameDir)\valheim_Data\Managed\UnityEngine.XRModule.dll False @@ -374,6 +375,7 @@ - xcopy "$(TargetDir)" "$(GameDir)\Bepinex\plugins\$(ProjectName)\" /q /s /y /i + xcopy "$(TargetDir)" "$(GameDir)\BepInEx\plugins\$(ProjectName)\" /q /s /y /i + xcopy "$(TargetDir)" "C:\Users\crypt\AppData\Roaming\com.kesomannen.gale\valheim\profiles\AzuMods_All\BepInEx\plugins\$(ProjectName)\" /q /s /y /i \ No newline at end of file diff --git a/BetterUI/Changelog.txt b/BetterUI/Changelog.txt index 0bf1f6a..c40ecd2 100644 --- a/BetterUI/Changelog.txt +++ b/BetterUI/Changelog.txt @@ -1,4 +1,5 @@ ####v2.4.4 +####v2.4.4 - Fix for game version 0.217.14 (JuniorAndria) ####v2.4.3 - Required updates for Valheim version 0.216.9 diff --git a/BetterUI/GameClasses/EnemyHud.cs b/BetterUI/GameClasses/EnemyHud.cs index 28b90bf..4695a5c 100644 --- a/BetterUI/GameClasses/EnemyHud.cs +++ b/BetterUI/GameClasses/EnemyHud.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Reflection.Emit; using System.Runtime.CompilerServices; - +using TMPro; using UnityEngine; using UnityEngine.UI; @@ -46,13 +46,13 @@ static void ShowHudPostfix(ref EnemyHud __instance, ref Character c, ref bool __ return; } - var hpRoot = (hudData.m_gui.transform.Find("Health") as RectTransform); + RectTransform hpRoot = (hudData.m_gui.transform.Find("Health") as RectTransform); if (c.IsPlayer()) { if (Main.showPlayerHPText.Value) { - var hpText = UnityEngine.Object.Instantiate(hudData.m_name, hudData.m_name.transform.parent); + TextMeshProUGUI hpText = UnityEngine.Object.Instantiate(hudData.m_name, hudData.m_name.transform.parent); hpText.name = PlayerHpPrefix; hpText.rectTransform.anchoredPosition = new Vector2(hpText.rectTransform.anchoredPosition.x, 3.5f); hpText.text = $"{hudData.m_character.GetHealth():0}/{hudData.m_character.GetMaxHealth():0}"; @@ -71,7 +71,7 @@ static void ShowHudPostfix(ref EnemyHud __instance, ref Character c, ref bool __ if (Main.showEnemyHPText.Value) { // Edits to Boss HP Bar - var hpText = UnityEngine.Object.Instantiate(hudData.m_name, hudData.m_name.transform.parent); + TextMeshProUGUI hpText = UnityEngine.Object.Instantiate(hudData.m_name, hudData.m_name.transform.parent); hpText.name = BossHpPrefix; hpText.rectTransform.anchoredPosition = new Vector2(hpText.rectTransform.anchoredPosition.x, 0.0f); // orig.y = 21f hpText.text = $"{hudData.m_character.GetHealth():0} / {hudData.m_character.GetMaxHealth():0}"; @@ -86,13 +86,13 @@ static void ShowHudPostfix(ref EnemyHud __instance, ref Character c, ref bool __ hudData.m_name.fontSize = Main.enemyNameTextSize.Value; if (Main.enemyLevelStyle.Value != 0) { - hudData.m_name.text = hudData.m_name.text.Insert(0, $"Lv.{c.m_level} "); + hudData.m_name.text = hudData.m_name.text.Insert(0, $"Lv.{c.m_level} "); } if (Main.showEnemyHPText.Value) { hpRoot.sizeDelta = new Vector2(hpRoot.sizeDelta.x, hpRoot.sizeDelta.y * 3f); - var hpText = UnityEngine.Object.Instantiate(hudData.m_name, hudData.m_name.transform.parent); + TextMeshProUGUI hpText = UnityEngine.Object.Instantiate(hudData.m_name, hudData.m_name.transform.parent); hpText.name = EnemyHpPrefix; hpText.rectTransform.anchoredPosition = new Vector2(hpText.rectTransform.anchoredPosition.x, 7.0f); // orig.y = 21f hpText.text = $"{hudData.m_character.GetHealth():0}/{hudData.m_character.GetMaxHealth():0}"; @@ -135,7 +135,7 @@ static void UpdateHudsPostfix(ref EnemyHud __instance) Character character = null; foreach (KeyValuePair keyValuePair in __instance.m_huds) { - var value = keyValuePair.Value; + EnemyHud.HudData value = keyValuePair.Value; if (!value.m_character || !__instance.TestShow(value.m_character, true)) { @@ -149,13 +149,13 @@ static void UpdateHudsPostfix(ref EnemyHud __instance) { if (value.m_character.IsPlayer()) { - if (Main.showPlayerHPText.Value && _hpTextCache.TryGetValue(value, out var hpText)) { + if (Main.showPlayerHPText.Value && _hpTextCache.TryGetValue(value, out TextMeshProUGUI hpText)) { hpText.text = $"{value.m_character.GetHealth():0}/{value.m_character.GetMaxHealth():0}"; } } else if (value.m_character.IsBoss()) { - if (Main.showEnemyHPText.Value && _hpTextCache.TryGetValue(value, out var hpText)) { + if (Main.showEnemyHPText.Value && _hpTextCache.TryGetValue(value, out TextMeshProUGUI hpText)) { hpText.text = $"{value.m_character.GetHealth():0} / {value.m_character.GetMaxHealth():0}"; } } @@ -171,13 +171,13 @@ static void UpdateHudsPostfix(ref EnemyHud __instance) } - if (Main.showEnemyHPText.Value && _hpTextCache.TryGetValue(value, out var hpText)) { + if (Main.showEnemyHPText.Value && _hpTextCache.TryGetValue(value, out TextMeshProUGUI hpText)) { hpText.text = $"{value.m_character.GetHealth():0}/{value.m_character.GetMaxHealth():0}"; } if (Main.enemyLevelStyle.Value != 0) { - value.m_name.text = value.m_name.text.Insert(0, $"Lv.{value.m_character.m_level} "); + value.m_name.text = value.m_name.text.Insert(0, $"Lv.{value.m_character.m_level} "); } if (Main.enemyLevelStyle.Value == Main.EnemyLevelStyle.PrefixLevelNumber) @@ -224,8 +224,8 @@ public static void ShowLocalPlayerEnemyHudConfigChanged() { if (Player.m_localPlayer && EnemyHud.m_instance && EnemyHud.m_instance.m_huds.TryGetValue(Player.m_localPlayer, out EnemyHud.HudData hudData)) { - UnityEngine.Object.Destroy(hudData.m_gui); - EnemyHud.m_instance.m_huds.Remove(Player.m_localPlayer); + UnityEngine.Object.Destroy(hudData.m_gui); + EnemyHud.m_instance.m_huds.Remove(Player.m_localPlayer); } } } diff --git a/BetterUI/GameClasses/FejdStartup.cs b/BetterUI/GameClasses/FejdStartup.cs index 190688a..bc4acdc 100644 --- a/BetterUI/GameClasses/FejdStartup.cs +++ b/BetterUI/GameClasses/FejdStartup.cs @@ -7,24 +7,24 @@ namespace BetterUI.GameClasses { - [HarmonyPatch] - public static class BetterFejdStartup - { - [HarmonyPostfix] - [HarmonyPatch(typeof(FejdStartup), "SetupGui")] - private static void AddWaterMark(ref FejdStartup __instance) + [HarmonyPatch] + public static class BetterFejdStartup { - Patches.CustomWatermark.Apply(__instance); - } + [HarmonyPostfix] + [HarmonyPatch(typeof(FejdStartup), "SetupGui")] + private static void AddWaterMark(ref FejdStartup __instance) + { + Patches.CustomWatermark.Apply(__instance); + } - [HarmonyPostfix] - [HarmonyPatch(typeof(FejdStartup), "UpdateCharacterList")] - private static void ShowCharacterStats(ref FejdStartup __instance) - { - if (Main.showCustomCharInfo.Value) - { - Patches.CharacterStats.Show(__instance); - } + [HarmonyPostfix] + [HarmonyPatch(typeof(FejdStartup), "UpdateCharacterList")] + private static void ShowCharacterStats(ref FejdStartup __instance) + { + if (Main.showCustomCharInfo.Value) + { + Patches.CharacterStats.Show(__instance); + } + } } - } -} +} \ No newline at end of file diff --git a/BetterUI/GameClasses/HotkeyBar.cs b/BetterUI/GameClasses/HotkeyBar.cs index 9fba437..5b71f22 100644 --- a/BetterUI/GameClasses/HotkeyBar.cs +++ b/BetterUI/GameClasses/HotkeyBar.cs @@ -36,7 +36,7 @@ private static void PatchHotkeyBar(ref HotkeyBar __instance, ref Player player) // would be better if this could be done reliably in an Awake/ Start, but I'm not in the mood to look for one if (element.m_icon.gameObject.GetComponent() == null) { - var origScaleComp = element.m_icon.gameObject.AddComponent(); + ItemIconUpdater origScaleComp = element.m_icon.gameObject.AddComponent(); origScaleComp.Setup(element.m_icon); } diff --git a/BetterUI/GameClasses/Hud.cs b/BetterUI/GameClasses/Hud.cs index 09076b6..bff2401 100644 --- a/BetterUI/GameClasses/Hud.cs +++ b/BetterUI/GameClasses/Hud.cs @@ -100,7 +100,7 @@ private static void Update(Hud __instance) Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Now editing: {(Groups)activeLayer}"); } - float gameScale = GameObject.Find("LoadingGUI").GetComponent().scaleFactor; + float gameScale = GuiScaler.m_largeGuiScale; Vector3 mousePos = Input.mousePosition; // Select element / move element float scrollPos = Input.GetAxis("Mouse ScrollWheel"); // Change scale @@ -132,7 +132,7 @@ private static void Update(Hud __instance) } } - var mousePositionChange = (mousePos - lastMousePos) / gameScale; + Vector3 mousePositionChange = (mousePos - lastMousePos) / gameScale; if (Helpers.CheckHeldKey(Main.modKeyPrimary.Value) && rectList.Count > 0) { @@ -140,7 +140,7 @@ private static void Update(Hud __instance) { if (Helpers.CheckHeldKey(Main.modKeySecondary.Value)) { - var scaledMousePositionChange = mousePositionChange / (new Vector2(Screen.currentResolution.width, Screen.currentResolution.height) / 10); + Vector2 scaledMousePositionChange = mousePositionChange / (new Vector2(Screen.currentResolution.width, Screen.currentResolution.height) / 10); CustomHud.UpdateScaleAndDimensions(currentlyDragging, scaledMousePositionChange, scrollPos); } @@ -187,7 +187,7 @@ private static void Update(Hud __instance) } else { - foreach (var item in rectList) + foreach (KeyValuePair item in rectList) { if (RectTransformUtility.RectangleContainsScreenPoint(item.Value, mousePos)) { diff --git a/BetterUI/GameClasses/InventoryGrid.cs b/BetterUI/GameClasses/InventoryGrid.cs index 6fc6c4c..c942149 100644 --- a/BetterUI/GameClasses/InventoryGrid.cs +++ b/BetterUI/GameClasses/InventoryGrid.cs @@ -10,7 +10,7 @@ public static class BetterInventoryGrid [HarmonyPatch(typeof(InventoryGrid), "UpdateGui")] private static void PatchInventory(ref InventoryGrid __instance, ref Player player, ItemDrop.ItemData dragItem) { - var width = __instance.m_inventory.GetWidth(); + int width = __instance.m_inventory.GetWidth(); InventoryGrid.Element element; int index; @@ -32,7 +32,7 @@ private static void PatchInventory(ref InventoryGrid __instance, ref Player play // would be better if this could be done reliably in an Awake/ Start, but I'm not in the mood to look for one if (element.m_icon.gameObject.GetComponent() == null) { - var origScaleComp = element.m_icon.gameObject.AddComponent(); + ItemIconUpdater origScaleComp = element.m_icon.gameObject.AddComponent(); origScaleComp.Setup(element.m_icon); } diff --git a/BetterUI/GameClasses/ItemDrop.cs b/BetterUI/GameClasses/ItemDrop.cs index 220998d..e89ea46 100644 --- a/BetterUI/GameClasses/ItemDrop.cs +++ b/BetterUI/GameClasses/ItemDrop.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using BepInEx.Bootstrap; using HarmonyLib; namespace BetterUI.GameClasses @@ -20,7 +21,7 @@ private static bool PatchHoverText(ref ItemDrop __instance, ref string __result) text = string.Concat(new object[] { text, - " (", + " (", Patches.Stars.HoverText(__instance.m_itemData.m_quality), ") " }); @@ -29,7 +30,7 @@ private static bool PatchHoverText(ref ItemDrop __instance, ref string __result) { text = text + " x" + __instance.m_itemData.m_stack.ToString(); } - __result = Localization.instance.Localize(text + "\n[$KEY_Use] $inventory_pickup"); + __result = Localization.instance.Localize(text + "\n[$KEY_Use] $inventory_pickup"); return false; } @@ -37,12 +38,13 @@ private static bool PatchHoverText(ref ItemDrop __instance, ref string __result) static class ItemData { [HarmonyPrefix] - [HarmonyPatch(typeof(ItemDrop.ItemData), "GetTooltip", new Type[] { typeof(ItemDrop.ItemData), typeof(int), typeof(bool), typeof(float) })] + [HarmonyPatch(typeof(ItemDrop.ItemData), nameof(ItemDrop.ItemData.GetTooltip), new Type[] { typeof(ItemDrop.ItemData), typeof(int), typeof(bool), typeof(float), typeof(int) })] public static bool PatchTooltip(ref string __result, ItemDrop.ItemData item, int qualityLevel, bool crafting) { - if (!Main.showCustomTooltips.Value) return true; + if (!Main.showCustomTooltips.Value || Chainloader.PluginInfos.ContainsKey("randyknapp.mods.epicloot")) return true; __result = Patches.BetterTooltip.Create(item, qualityLevel, crafting); return false; // https://harmony.pardeike.net/articles/patching-prefix.html#changing-the-result-and-skipping-the-original + } } } diff --git a/BetterUI/GameClasses/SkillsDialog.cs b/BetterUI/GameClasses/SkillsDialog.cs index 08c6839..fcff8e6 100644 --- a/BetterUI/GameClasses/SkillsDialog.cs +++ b/BetterUI/GameClasses/SkillsDialog.cs @@ -1,23 +1,46 @@ using HarmonyLib; +using TMPro; using UnityEngine.UI; namespace BetterUI.GameClasses { - [HarmonyPatch] - public static class BetterSkillsDialog + [HarmonyPatch(typeof(SkillsDialog), nameof(SkillsDialog.Setup))] + static class SkillsDialogSetupPatch { - [HarmonyPostfix] - [HarmonyPatch(typeof(SkillsDialog), "Setup")] - private static void ChangeGUI(ref SkillsDialog __instance, ref Player player) + static void Postfix(SkillsDialog __instance, Player player) { - __instance.gameObject.SetActive(true); + if (__instance == null || player == null) + { + BetterUI.Main.log.LogError("SkillsDialog or Player instance is null."); + return; + } + + try + { + __instance.gameObject?.SetActive(true); + } + catch + { + BetterUI.Main.log.LogError("Failed to set SkillsDialog active."); + } + if (Main.showCharacterXP.Value) { - Utils.FindChild(__instance.transform, "topic").GetComponent().text = $"Level: {Patches.XP.level:0} Progress: {string.Format("{0:0%}", Patches.XP.LevelProgressPercentage)}"; + TMP_Text topicText = Utils.FindChild(__instance.transform, "topic")?.GetComponent(); + if (topicText != null) + { + topicText.text = $"Level: {Patches.XP.level:0} Progress: {Patches.XP.LevelProgressPercentage:0%}"; + } + else + { + BetterUI.Main.log.LogError("Topic text component is null."); + } } - if (!Main.customSkillUI.Value) return; - Patches.SkillUI.UpdateDialog(__instance, player); + if (Main.customSkillUI.Value) + { + Patches.SkillUI.UpdateDialog(__instance, player); + } } } -} +} \ No newline at end of file diff --git a/BetterUI/Main.cs b/BetterUI/Main.cs index d464469..43e6b34 100644 --- a/BetterUI/Main.cs +++ b/BetterUI/Main.cs @@ -21,7 +21,7 @@ public const string MODNAME = "BetterUI", AUTHOR = "MK", GUID = AUTHOR + "_" + MODNAME, - VERSION = "2.4.4"; + VERSION = "2.5.9"; internal static ManualLogSource log; internal readonly Harmony harmony; @@ -131,24 +131,24 @@ public void Awake() // Player HUD RESTART sectionName = "1 - Player HUD (Requires Logout)"; - var editingDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", nameof(enablePlayerHudEditing)), true); + bool editingDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", nameof(enablePlayerHudEditing)), true); enablePlayerHudEditing = Config.Bind(sectionName, nameof(enablePlayerHudEditing), editingDefault, "Enable the ability to edit the player HUD by pressing a hotkey."); - var healthDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomHealthBar"), false); + bool healthDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomHealthBar"), false); healthDefault |= GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD (Requires Logout)", "useCustomHealthBar"), false); customHealthBar = Config.Bind(sectionName, nameof(customHealthBar), healthDefault ? CustomBarState.on0Degrees : CustomBarState.off, $"Resizable, rotatable HP bar. This bar will always be the same size and will not get longer when you eat. Will also disable the default food bar, so {nameof(customFoodBar)} will be enabled automatically."); customHealthBar.SettingChanged += (_, _) => CustomHealthBar_SettingChanged(); RemoveOldConfigValue(new ConfigDefinition("1 - Player HUD", "healthBarRotation")); RemoveOldConfigValue(new ConfigDefinition(sectionName, "customHealthBarRotation")); - var staminaDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomStaminaBar"), false); + bool staminaDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomStaminaBar"), false); staminaDefault |= GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "useCustomStaminaBar"), false); customStaminaBar = Config.Bind(sectionName, nameof(customStaminaBar), staminaDefault ? CustomBarState.on0Degrees : CustomBarState.off, "Resizable, rotatable stamina bar. This bar will always be visible and will not get longer when you eat."); customStaminaBar.SettingChanged += (_, _) => CustomStaminaBar_SettingChanged(); RemoveOldConfigValue(new ConfigDefinition("1 - Player HUD", "staminaBarRotation")); RemoveOldConfigValue(new ConfigDefinition(sectionName, "customStaminaBarRotation")); - var foodDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomFoodBar"), false); + bool foodDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomFoodBar"), false); foodDefault |= GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "useCustomFoodBar"), false); customFoodBar = Config.Bind(sectionName, nameof(customFoodBar), foodDefault ? CustomBarState.on0Degrees : CustomBarState.off, $"Resizable, rotatable food bar. Requires {nameof(customHealthBar)}."); // if the customHealthBar is enabled the vanilla food bar is removed. If the customeFoodBAr is disabled, enable it so the user doesn't end up with no food bar. @@ -160,7 +160,7 @@ public void Awake() RemoveOldConfigValue(new ConfigDefinition("1 - Player HUD", "foodBarRotation")); RemoveOldConfigValue(new ConfigDefinition(sectionName, "customFoodBarRotation")); - var eitrDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomEitrBar"), false); + bool eitrDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("1 - Player HUD", "useCustomEitrBar"), false); customEitrBar = Config.Bind(sectionName, nameof(customEitrBar), eitrDefault ? CustomBarState.on0Degrees : CustomBarState.off, "Resizable, rotatable eitr bar. If you don't know what this is yet, just keep it disabled. This bar will always be visible and will not get longer when you eat."); customEitrBar.SettingChanged += (_, _) => CustomEitrBar_SettingChanged(); RemoveOldConfigValue(new ConfigDefinition(sectionName, "customSpoilerBarRotation")); @@ -169,15 +169,15 @@ public void Awake() // Character Inventory sectionName = "2 - Character Inventory"; - var wasColorOnDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "showDurabilityColor"), true); - var colorDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "durabilityColorPalette"), 0); + bool wasColorOnDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "showDurabilityColor"), true); + int colorDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "durabilityColorPalette"), 0); durabilityBarColorPalette = Config.Bind(sectionName, nameof(durabilityBarColorPalette), IntToDurabilityBarStyle(wasColorOnDefault, colorDefault), "Change durability bar colors. Options: 0 = Green, Yellow, Orange, Red, 1 = White, Light Yellow, Light Cyan, Blue."); showItemStars = Config.Bind(sectionName, nameof(showItemStars), true, "Show item quality as stars."); showCustomCharInfo = Config.Bind(sectionName, nameof(showCustomCharInfo), true, "Show Deaths, Builds, and Crafts stats on character selection screen. Also shows the Kills stat if something increases it (the base game doesn't)."); - showCustomTooltips = Config.Bind(sectionName, nameof(showCustomTooltips), true, "Show more info on inventory item tooltips. Disable this if using Epic Loot."); + showCustomTooltips = Config.Bind(sectionName, nameof(showCustomTooltips), true, "Show more info on inventory item tooltips. Automatically disabled this if using Epic Loot for compatibility."); showCombinedItemStats = Config.Bind(sectionName, nameof(showCombinedItemStats), true, "Show all item stats when mouse is hovered over armor amount."); @@ -207,7 +207,7 @@ public void Awake() timeLeftHoverTextBeeHive = Config.Bind(sectionName, nameof(timeLeftHoverTextBeeHive), TimeLeftStyle.MinutesSecondsLeft, "Select duration display. Disabled = Default, PercentageDone = % Done, MinutesSecondsLeft = min:sec left."); - var chestStyleDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "chestHasRoomStyle"), 2); + int chestStyleDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "chestHasRoomStyle"), 2); chestHasRoomHoverText = Config.Bind(sectionName, nameof(chestHasRoomHoverText), IntToChestHasRoomStyle(chestStyleDefault), "Select how chest emptiness is displayed. Disabled = Default | Percentage = % | ItemsSlashMaxRoom= used / total slots. | AmountOfFreeSlots = count of free slots."); // @@ -227,7 +227,7 @@ public void Awake() // Character XP RESTART sectionName = "5 - Character XP (Requires Logout)"; - var expBarDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("5 - Character XP", nameof(showCharacterXpBar)), true); + bool expBarDefault = GetOldOrDefaultConfigValue(new ConfigDefinition("5 - Character XP", nameof(showCharacterXpBar)), true); showCharacterXpBar = Config.Bind(sectionName, nameof(showCharacterXpBar), expBarDefault, "Show Character XP bar on the bottom of the screen. Character XP must be enabled."); // @@ -240,7 +240,7 @@ public void Awake() showEnemyHPText = Config.Bind(sectionName, nameof(showEnemyHPText), true, "Show the text with HP amount on enemy health bars."); - var enemyLevelStyleDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "enemyLvlStyle"), 0); + int enemyLevelStyleDefault = GetOldOrDefaultConfigValue(new ConfigDefinition(sectionName, "enemyLvlStyle"), 0); enemyLevelStyle = Config.Bind(sectionName, nameof(enemyLevelStyle), IntToEnemyLevelStyle(enemyLevelStyleDefault), "Choose how enemy level is shown."); enemyNameTextSize = Config.Bind(sectionName, nameof(enemyNameTextSize), 14, "Font size of the name on the enemy."); @@ -281,6 +281,8 @@ public void Awake() { PrintOrphanedEntries(); } + + this.Logger.LogInfo("BetterUI (Forever Maintained Version) loaded"); } private DurabilityBarStyle IntToDurabilityBarStyle(bool wasColorPaletteOn, int selectedColorPalette) @@ -388,13 +390,13 @@ public bool TryGetOldConfigValue(ConfigDefinition configDefinition, ref T old { if (!TomlTypeConverter.CanConvert(typeof(T))) { - throw new ArgumentException(string.Format("Type {0} is not supported by the config system. Supported types: {1}", typeof(T), string.Join(", ", (from x in TomlTypeConverter.GetSupportedTypes() select x.Name).ToArray()))); + throw new ArgumentException($"Type {typeof(T)} is not supported by the config system. Supported types: {string.Join(", ", (from x in TomlTypeConverter.GetSupportedTypes() select x.Name).ToArray())}"); } try { - var iolock = AccessTools.FieldRefAccess("_ioLock").Invoke(Config); - var orphanedEntries = (Dictionary)AccessTools.PropertyGetter(typeof(ConfigFile), "OrphanedEntries").Invoke(Config, new object[0]); + object iolock = AccessTools.FieldRefAccess("_ioLock").Invoke(Config); + Dictionary orphanedEntries = (Dictionary)AccessTools.PropertyGetter(typeof(ConfigFile), "OrphanedEntries").Invoke(Config, new object[0]); lock (iolock) { @@ -413,7 +415,7 @@ public bool TryGetOldConfigValue(ConfigDefinition configDefinition, ref T old } catch (Exception e) { - Debug.LogWarning($"Error getting orphaned entry: {e.StackTrace}"); + BetterUI.Main.log.LogWarning($"Error getting orphaned entry: {e.StackTrace}"); } return false; @@ -423,8 +425,8 @@ public void PrintOrphanedEntries() { try { - var iolock = AccessTools.FieldRefAccess("_ioLock").Invoke(Config); - var orphanedEntries = (Dictionary)AccessTools.PropertyGetter(typeof(ConfigFile), "OrphanedEntries").Invoke(Config, new object[0]); + object iolock = AccessTools.FieldRefAccess("_ioLock").Invoke(Config); + Dictionary orphanedEntries = (Dictionary)AccessTools.PropertyGetter(typeof(ConfigFile), "OrphanedEntries").Invoke(Config, new object[0]); if (orphanedEntries.Count == 0) { @@ -433,17 +435,17 @@ public void PrintOrphanedEntries() lock (iolock) { - Debug.Log("printing orphaned config values"); + BetterUI.Main.log.LogInfo("printing orphaned config values"); - foreach (var item in orphanedEntries) + foreach (KeyValuePair item in orphanedEntries) { - Debug.Log($"{item.Key.Section},{item.Key.Key}: {item.Value}"); + BetterUI.Main.log.LogInfo($"{item.Key.Section},{item.Key.Key}: {item.Value}"); } } } catch (Exception e) { - Debug.LogWarning($"Error logging orphaned entries: {e.StackTrace}"); + BetterUI.Main.log.LogWarning($"Error logging orphaned entries: {e.StackTrace}"); } } diff --git a/BetterUI/Package/README.md b/BetterUI/Package/README.md index d22e4d3..fab0dc5 100644 --- a/BetterUI/Package/README.md +++ b/BetterUI/Package/README.md @@ -1,27 +1,24 @@ -[

](https://valheim.thunderstore.io/package/thedefside/BetterUI_Reforged) +[

](https://valheim.thunderstore.io/package/BetterUI_ForeverMaintained/BetterUI_ForeverMaintained/) -# BetterUI: Reforged for Valheim +# BetterUI: Forever Maintained for Valheim This mod updates the game UI with few subtle edits. You are able to edit and select what updates you want to use. # Support -Join our Discord! https://discord.gg/vSEjCNF48K -## Table of Contents -1. [Features](#Features) -2. [Changelog](#Changelog) -3. [Installation](#Installation) -4. [FAQ](#FAQ) -5. [Thanks](#Thanks) +### Azumatt + +`DISCORD:` Azumatt#2625 + +`STEAM:` https://steamcommunity.com/id/azumatt/ + +For Questions or Comments, find me in my discord: + + ## Features -#### Add stats to the character select screen - - Kills (if IG ever starts counting these) - - Deaths - - Crafts - - Builds #### Customizable Player HUD - Makes player HUD elements movemable @@ -61,10 +58,9 @@ Join our Discord! https://discord.gg/vSEjCNF48K ## Changelog -v2.4.4 - - Fix for game version 0.217.14 (JuniorAndria) +- Fixed some tooltip stuff, boss hud PR accepted, skills dialog fixes -Full Changelog: https://github.com/thedefside/BetterUI/blob/main/BetterUI/Changelog.txt +Full Changelog can be found on the wiki tab for this mod here: [https://valheim.thunderstore.io/package/BetterUI_ForeverMaintained/BetterUI_ForeverMaintained/wiki/](https://valheim.thunderstore.io/package/BetterUI_ForeverMaintained/BetterUI_ForeverMaintained/wiki/) ## Installation diff --git a/BetterUI/Package/icon.png b/BetterUI/Package/icon.png index f8222af..7101e99 100644 Binary files a/BetterUI/Package/icon.png and b/BetterUI/Package/icon.png differ diff --git a/BetterUI/Package/icon.psd b/BetterUI/Package/icon.psd new file mode 100644 index 0000000..2a95ad8 Binary files /dev/null and b/BetterUI/Package/icon.psd differ diff --git a/BetterUI/Package/icon_orig.png b/BetterUI/Package/icon_orig.png new file mode 100644 index 0000000..f8222af Binary files /dev/null and b/BetterUI/Package/icon_orig.png differ diff --git a/BetterUI/Package/manifest.json b/BetterUI/Package/manifest.json index 4d83f93..c93134d 100644 --- a/BetterUI/Package/manifest.json +++ b/BetterUI/Package/manifest.json @@ -1,9 +1,9 @@ { - "name": "BetterUI_Reforged", - "description": "Masa's BetterUI mod updated with bug fixes and new features", - "version_number": "2.4.3", - "website_url": "https://github.com/thedefside/BetterUI", + "name": "BetterUI_ForeverMaintained", + "description": "BetterUI once again fixed up for the masses. This time, it won't be abandoned.", + "version_number": "2.5.9", + "website_url": "https://valheim.thunderstore.io/package/BetterUI_ForeverMaintained/BetterUI_ForeverMaintained/source/", "dependencies": [ - "denikson-BepInExPack_Valheim-5.4.2100" + "denikson-BepInExPack_Valheim-5.4.2202" ] } \ No newline at end of file diff --git a/BetterUI/Patches/Compatibility.cs b/BetterUI/Patches/Compatibility.cs index 79b211b..5cf3e2d 100644 --- a/BetterUI/Patches/Compatibility.cs +++ b/BetterUI/Patches/Compatibility.cs @@ -1,43 +1,42 @@ using UnityEngine; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +static class Compatibility { - static class Compatibility - { public static class QuickSlotsHotkeyBar { - private static readonly string originalPath = "QuickSlotsHotkeyBar"; - private static readonly string parent = "hudroot"; - public static bool isUsing = false; - - /// - /// Unachor the QuickSlotsHotkeyBar so it can be moved during customization(F7). - /// - public static void Unanchor(Hud hud) - { - Transform parentTransform = Hud.instance.transform.Find(parent); - Transform quickSlots = parentTransform.Find(originalPath); + private static readonly string originalPath = "QuickSlotsHotkeyBar"; + private static readonly string parent = "hudroot"; + public static bool isUsing = false; - if (quickSlots) + /// + /// Unachor the QuickSlotsHotkeyBar so it can be moved during customization(F7). + /// + public static void Unanchor(Hud hud) { - isUsing = true; - //Removes the component stopping us from moving the QuickSlotsHotkeyBar. - GameObject.Destroy(quickSlots.GetComponent("ConfigPositionedElement")); - // No rotation for now, as objects are created and edited all the time on runtime... - /* - int rot = 90 - (Main.staminaBarRotation.Value / 90 % 4 * 90); - Vector3 oldRot = quickSlots.localEulerAngles; - quickSlots.localEulerAngles = new Vector3(0, 0, -rot); + Transform parentTransform = Hud.instance.transform.Find(parent); + Transform quickSlots = parentTransform.Find(originalPath); + + if (quickSlots) + { + isUsing = true; + //Removes the component stopping us from moving the QuickSlotsHotkeyBar. + GameObject.Destroy(quickSlots.GetComponent("ConfigPositionedElement")); + // No rotation for now, as objects are created and edited all the time on runtime... + /* + int rot = 90 - (Main.staminaBarRotation.Value / 90 % 4 * 90); + Vector3 oldRot = quickSlots.localEulerAngles; + quickSlots.localEulerAngles = new Vector3(0, 0, -rot); - foreach (Transform child in quickSlots) - { - Helpers.DebugLine($"Editing: {child}.\n{child.localEulerAngles}\n{quickSlots.localEulerAngles}"); - child.localEulerAngles = oldRot; - } - */ - //quickSlots.SetParent(parentTransform, false); + foreach (Transform child in quickSlots) + { + Helpers.DebugLine($"Editing: {child}.\n{child.localEulerAngles}\n{quickSlots.localEulerAngles}"); + child.localEulerAngles = oldRot; + } + */ + //quickSlots.SetParent(parentTransform, false); + } } - } } - } -} +} \ No newline at end of file diff --git a/BetterUI/Patches/CustomBars.cs b/BetterUI/Patches/CustomBars.cs index 8c70316..e6a8e57 100644 --- a/BetterUI/Patches/CustomBars.cs +++ b/BetterUI/Patches/CustomBars.cs @@ -1,469 +1,469 @@ using System; using System.Collections.Generic; +using TMPro; using UnityEngine; using UnityEngine.UI; using static BetterUI.Main; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +internal class CustomBars { - internal class CustomBars + public static class BarHelper { - public static class BarHelper - { - public static float StepSize => Hud.instance.m_healthPanel.sizeDelta.x; + public static float StepSize => Hud.instance.m_healthPanel.sizeDelta.x; - public const float scalingFactor = 0.6f; - public const int padding = 0; + public const float scalingFactor = 0.6f; + public const int padding = 0; - public static void BaseCreate(string objectName, string origBarName, ref RectTransform root, ref GuiBar slowBar, ref GuiBar fastBar, ref Text barText) + public static void BaseCreate(string objectName, string origBarName, ref RectTransform root, ref GuiBar slowBar, ref GuiBar fastBar, ref TMP_Text barText) + { + // we've obviously already done this before if it's not null + if (root != null) { - // we've obviously already done this before if it's not null - if (root != null) - { - return; - } + return; + } - // Hide original bar - Hud.instance.transform.Find("hudroot").Find(origBarName).gameObject.SetActive(false); + // Hide original bar + Hud.instance.transform.Find("hudroot").Find(origBarName).gameObject.SetActive(false); - root = UnityEngine.Object.Instantiate(Hud.instance.m_healthBarRoot, Hud.instance.transform.Find("hudroot")); - root.gameObject.name = objectName; + root = UnityEngine.Object.Instantiate(Hud.instance.m_healthBarRoot, Hud.instance.transform.Find("hudroot")); + root.gameObject.name = objectName; - fastBar = root.Find("fast").GetComponent(); - slowBar = root.Find("slow").GetComponent(); + fastBar = root.Find("fast").GetComponent(); + slowBar = root.Find("slow").GetComponent(); - var fastBarHealthText = fastBar.transform.Find("bar").Find("HealthText"); - fastBarHealthText.gameObject.SetActive(false); - barText = UnityEngine.Object.Instantiate(fastBarHealthText.GetComponent(), root); - barText.gameObject.AddComponent(); - barText.gameObject.SetActive(true); + Transform fastBarHealthText = fastBar.transform.Find("bar").Find("HealthText"); + fastBarHealthText.gameObject.SetActive(false); + barText = UnityEngine.Object.Instantiate(fastBarHealthText.GetComponent(), root); + barText.gameObject.AddComponent(); + barText.gameObject.SetActive(true); - // Resize to a more "slim" rectangle - authors preference - root.Find("border").localScale = new Vector3(1f, scalingFactor, 1f); - root.Find("bkg").localScale = new Vector3(1f, scalingFactor, 1f); + // Resize to a more "slim" rectangle - authors preference + root.Find("border").localScale = new Vector3(1f, scalingFactor, 1f); + root.Find("bkg").localScale = new Vector3(1f, scalingFactor, 1f); - fastBar.transform.localScale = new Vector3(1f, scalingFactor, 1f); - slowBar.transform.localScale = new Vector3(1f, scalingFactor, 1f); - } + fastBar.transform.localScale = new Vector3(1f, scalingFactor, 1f); + slowBar.transform.localScale = new Vector3(1f, scalingFactor, 1f); + } - public static void UpdateRotation(int configRotation, ref RectTransform root, ref Text barText) - { - //configRotation = (configRotation + 180) % 360; + public static void UpdateRotation(int configRotation, ref RectTransform root, ref TMP_Text barText) + { + //configRotation = (configRotation + 180) % 360; - root.localEulerAngles = new Vector3(0, 0, configRotation); - barText.transform.localEulerAngles = new Vector3(0, 0, -configRotation); - } + root.localEulerAngles = new Vector3(0, 0, configRotation); + barText.transform.localEulerAngles = new Vector3(0, 0, -configRotation); + } - public static void HealthStyleUpdate(float max, float current, ref GuiBar slowBar, ref GuiBar fastBar, ref Text barText) - { - fastBar.SetMaxValue(max); - fastBar.SetValue(current); - slowBar.SetMaxValue(max); - slowBar.SetValue(current); + public static void HealthStyleUpdate(float max, float current, ref GuiBar slowBar, ref GuiBar fastBar, ref TMP_Text barText) + { + fastBar.SetMaxValue(max); + fastBar.SetValue(current); + slowBar.SetMaxValue(max); + slowBar.SetValue(current); - barText.fontSize = Main.customBarTextSize.Value; - barText.text = $"{Mathf.CeilToInt(current)}/{Mathf.CeilToInt(max)}"; - } + barText.fontSize = Main.customBarTextSize.Value; + barText.text = $"{Mathf.CeilToInt(current)}/{Mathf.CeilToInt(max)}"; + } - public static void StaminaStyleUpdate(float max, float current, ref GuiBar slowBar, ref GuiBar fastBar, ref Text barText) - { - fastBar.SetValue(current / max); - slowBar.SetValue(current / max); + public static void StaminaStyleUpdate(float max, float current, ref GuiBar slowBar, ref GuiBar fastBar, ref TMP_Text barText) + { + fastBar.SetValue(current / max); + slowBar.SetValue(current / max); - barText.fontSize = Main.customBarTextSize.Value; - barText.text = $"{Mathf.CeilToInt(current)}/{Mathf.CeilToInt(max)}"; - } + barText.fontSize = Main.customBarTextSize.Value; + barText.text = $"{Mathf.CeilToInt(current)}/{Mathf.CeilToInt(max)}"; + } - public static CustomBarState IncrementRotation(CustomBarState state) + public static CustomBarState IncrementRotation(CustomBarState state) + { + switch (state) { - switch (state) - { - case CustomBarState.on0Degrees: - return CustomBarState.on90Degrees; + case CustomBarState.on0Degrees: + return CustomBarState.on90Degrees; - case CustomBarState.on90Degrees: - return CustomBarState.on180Degrees; + case CustomBarState.on90Degrees: + return CustomBarState.on180Degrees; - case CustomBarState.on180Degrees: - return CustomBarState.on270Degrees; + case CustomBarState.on180Degrees: + return CustomBarState.on270Degrees; - case CustomBarState.on270Degrees: - return CustomBarState.on0Degrees; + case CustomBarState.on270Degrees: + return CustomBarState.on0Degrees; - default: - return state; - } + default: + return state; } + } - public static CustomBarState DecrementRotation(CustomBarState state) + public static CustomBarState DecrementRotation(CustomBarState state) + { + switch (state) { - switch (state) - { - case CustomBarState.on0Degrees: - return CustomBarState.on270Degrees; + case CustomBarState.on0Degrees: + return CustomBarState.on270Degrees; - case CustomBarState.on90Degrees: - return CustomBarState.on0Degrees; + case CustomBarState.on90Degrees: + return CustomBarState.on0Degrees; - case CustomBarState.on180Degrees: - return CustomBarState.on0Degrees; + case CustomBarState.on180Degrees: + return CustomBarState.on0Degrees; - case CustomBarState.on270Degrees: - return CustomBarState.on180Degrees; + case CustomBarState.on270Degrees: + return CustomBarState.on180Degrees; - default: - return state; - } + default: + return state; } } + } - public static class HealthBar - { - public const string objectName = "BetterUI_HPBar"; - internal static RectTransform root; - internal static GuiBar slowBar; - internal static GuiBar fastBar; - internal static Text barText; + public static class HealthBar + { + public const string objectName = "BetterUI_HPBar"; + internal static RectTransform root; + internal static GuiBar slowBar; + internal static GuiBar fastBar; + internal static TMP_Text barText; - public static void UpdateRotation() + public static void UpdateRotation() + { + if (root == null || Main.customHealthBar.Value == Main.CustomBarState.off) { - if (root == null || Main.customHealthBar.Value == Main.CustomBarState.off) - { - return; - } - - BarHelper.UpdateRotation((int)Main.customHealthBar.Value, ref root, ref barText); + return; } - public static void Create() + BarHelper.UpdateRotation((int)Main.customHealthBar.Value, ref root, ref barText); + } + + public static void Create() + { + try { - try - { - BarHelper.BaseCreate(objectName, "healthpanel", ref root, ref slowBar, ref fastBar, ref barText); - UpdateRotation(); + BarHelper.BaseCreate(objectName, "healthpanel", ref root, ref slowBar, ref fastBar, ref barText); + UpdateRotation(); - // go to a good default position that can get overriden by the editing feature if needed - // go up and left - root.position += new Vector3(-BarHelper.StepSize / 4, BarHelper.StepSize / 4); - } - catch (Exception e) - { - Debug.LogError($"{nameof(HealthBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); - } + // go to a good default position that can get overriden by the editing feature if needed + // go up and left + root.position += new Vector3(-BarHelper.StepSize / 4, BarHelper.StepSize / 4); } - - public static void Update(float max, float current) + catch (Exception e) { - try - { - if (root != null) - { - BarHelper.HealthStyleUpdate(max, current, ref slowBar, ref fastBar, ref barText); - } - } - catch (Exception e) - { - Debug.LogError($"{nameof(HealthBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); - } + BetterUI.Main.log.LogError($"{nameof(HealthBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); } } - public static class StaminaBar + public static void Update(float max, float current) { - public const string objectName = "BetterUI_StaminaBar"; - internal static RectTransform root; - internal static GuiBar slowBar; - internal static GuiBar fastBar; - internal static Text barText; - - public static void UpdateRotation() + try { - if (root == null || Main.customStaminaBar.Value == Main.CustomBarState.off) + if (root != null) { - return; + BarHelper.HealthStyleUpdate(max, current, ref slowBar, ref fastBar, ref barText); } + } + catch (Exception e) + { + BetterUI.Main.log.LogError($"{nameof(HealthBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); + } + } + } + + public static class StaminaBar + { + public const string objectName = "BetterUI_StaminaBar"; + internal static RectTransform root; + internal static GuiBar slowBar; + internal static GuiBar fastBar; + internal static TMP_Text barText; - BarHelper.UpdateRotation((int)Main.customStaminaBar.Value, ref root, ref barText); + public static void UpdateRotation() + { + if (root == null || Main.customStaminaBar.Value == Main.CustomBarState.off) + { + return; } - public static void Create() + BarHelper.UpdateRotation((int)Main.customStaminaBar.Value, ref root, ref barText); + } + + public static void Create() + { + try { - try - { - BarHelper.BaseCreate(objectName, "staminapanel", ref root, ref slowBar, ref fastBar, ref barText); - UpdateRotation(); + BarHelper.BaseCreate(objectName, "staminapanel", ref root, ref slowBar, ref fastBar, ref barText); + UpdateRotation(); - fastBar.m_originalColor = Hud.instance.m_staminaBar2Fast.m_bar.GetComponent().color; - slowBar.m_originalColor = Hud.instance.m_staminaBar2Slow.m_bar.GetComponent().color; - fastBar.ResetColor(); - slowBar.ResetColor(); + fastBar.m_originalColor = Hud.instance.m_staminaBar2Fast.m_bar.GetComponent().color; + slowBar.m_originalColor = Hud.instance.m_staminaBar2Slow.m_bar.GetComponent().color; + fastBar.ResetColor(); + slowBar.ResetColor(); - fastBar.m_smoothDrain = Hud.instance.m_staminaBar2Fast.m_smoothDrain; - fastBar.m_changeDelay = Hud.instance.m_staminaBar2Fast.m_changeDelay; - fastBar.m_smoothSpeed = Hud.instance.m_staminaBar2Fast.m_smoothSpeed; + fastBar.m_smoothDrain = Hud.instance.m_staminaBar2Fast.m_smoothDrain; + fastBar.m_changeDelay = Hud.instance.m_staminaBar2Fast.m_changeDelay; + fastBar.m_smoothSpeed = Hud.instance.m_staminaBar2Fast.m_smoothSpeed; - // go to a good default position that can get overriden by the editing feature if needed - // go left - root.position -= new Vector3(BarHelper.StepSize / 4, 0); + // go to a good default position that can get overriden by the editing feature if needed + // go left + root.position -= new Vector3(BarHelper.StepSize / 4, 0); - if (Main.customHealthBar.Value != Main.CustomBarState.off) - { - // hold positon - root.position -= new Vector3(0, BarHelper.padding); - } - else - { - // go up - root.position += new Vector3(0, BarHelper.StepSize / 4); - } + if (Main.customHealthBar.Value != Main.CustomBarState.off) + { + // hold positon + root.position -= new Vector3(0, BarHelper.padding); } - catch (Exception e) + else { - Debug.LogError($"{nameof(StaminaBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); + // go up + root.position += new Vector3(0, BarHelper.StepSize / 4); } } - - public static void Update(float max, float current) + catch (Exception e) { - try - { - if (root != null) - { - BarHelper.StaminaStyleUpdate(max, current, ref slowBar, ref fastBar, ref barText); - } - } - catch (Exception e) - { - Debug.LogError($"{nameof(StaminaBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); - } + BetterUI.Main.log.LogError($"{nameof(StaminaBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); } } - public static class EitrBar + public static void Update(float max, float current) { - public const string objectName = "BetterUI_EitrBar"; - internal static RectTransform root; - internal static GuiBar slowBar; - internal static GuiBar fastBar; - internal static Text barText; - - public static void UpdateRotation() + try { - if (root == null || Main.customEitrBar.Value == Main.CustomBarState.off) + if (root != null) { - return; + BarHelper.StaminaStyleUpdate(max, current, ref slowBar, ref fastBar, ref barText); } + } + catch (Exception e) + { + BetterUI.Main.log.LogError($"{nameof(StaminaBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); + } + } + } - BarHelper.UpdateRotation((int)Main.customEitrBar.Value, ref root, ref barText); + public static class EitrBar + { + public const string objectName = "BetterUI_EitrBar"; + internal static RectTransform root; + internal static GuiBar slowBar; + internal static GuiBar fastBar; + internal static TMP_Text barText; + + public static void UpdateRotation() + { + if (root == null || Main.customEitrBar.Value == Main.CustomBarState.off) + { + return; } - public static void Create() + BarHelper.UpdateRotation((int)Main.customEitrBar.Value, ref root, ref barText); + } + + public static void Create() + { + try { - try - { - BarHelper.BaseCreate("BetterUI_EitrBar", "eitrpanel", ref root, ref slowBar, ref fastBar, ref barText); - UpdateRotation(); + BarHelper.BaseCreate("BetterUI_EitrBar", "eitrpanel", ref root, ref slowBar, ref fastBar, ref barText); + UpdateRotation(); - fastBar.m_originalColor = Hud.instance.m_eitrBarFast.m_bar.GetComponent().color; - slowBar.m_originalColor = Hud.instance.m_eitrBarSlow.m_bar.GetComponent().color; - fastBar.ResetColor(); - slowBar.ResetColor(); + fastBar.m_originalColor = Hud.instance.m_eitrBarFast.m_bar.GetComponent().color; + slowBar.m_originalColor = Hud.instance.m_eitrBarSlow.m_bar.GetComponent().color; + fastBar.ResetColor(); + slowBar.ResetColor(); - fastBar.m_smoothDrain = Hud.instance.m_eitrBarFast.m_smoothDrain; - fastBar.m_changeDelay = Hud.instance.m_eitrBarFast.m_changeDelay; - fastBar.m_smoothSpeed = Hud.instance.m_eitrBarFast.m_smoothSpeed; + fastBar.m_smoothDrain = Hud.instance.m_eitrBarFast.m_smoothDrain; + fastBar.m_changeDelay = Hud.instance.m_eitrBarFast.m_changeDelay; + fastBar.m_smoothSpeed = Hud.instance.m_eitrBarFast.m_smoothSpeed; - // go to a good default position that can get overriden by the editing feature if needed - // go left - root.position -= new Vector3(BarHelper.StepSize / 4, 0); + // go to a good default position that can get overriden by the editing feature if needed + // go left + root.position -= new Vector3(BarHelper.StepSize / 4, 0); - if (Main.customHealthBar.Value != Main.CustomBarState.off) - { - // hold position - root.position -= new Vector3(0, BarHelper.padding); + if (Main.customHealthBar.Value != Main.CustomBarState.off) + { + // hold position + root.position -= new Vector3(0, BarHelper.padding); - if (Main.customStaminaBar.Value != Main.CustomBarState.off) - { - // go down - root.position -= new Vector3(0, BarHelper.StepSize / 4 + BarHelper.padding); - } - } - else + if (Main.customStaminaBar.Value != Main.CustomBarState.off) { - // go up - root.position += new Vector3(0, BarHelper.StepSize / 4); + // go down + root.position -= new Vector3(0, BarHelper.StepSize / 4 + BarHelper.padding); } } - catch (Exception e) + else { - Debug.LogError($"{nameof(EitrBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); + // go up + root.position += new Vector3(0, BarHelper.StepSize / 4); } } + catch (Exception e) + { + BetterUI.Main.log.LogError($"{nameof(EitrBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); + } + } - public static void Update(float max, float current) + public static void Update(float max, float current) + { + try { - try - { - if (root != null) - { - BarHelper.StaminaStyleUpdate(max, current, ref slowBar, ref fastBar, ref barText); - } - } - catch (Exception e) + if (root != null) { - Debug.LogError($"{nameof(EitrBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); + BarHelper.StaminaStyleUpdate(max, current, ref slowBar, ref fastBar, ref barText); } } + catch (Exception e) + { + BetterUI.Main.log.LogError($"{nameof(EitrBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); + } } + } - public static class FoodBar - { - public const string objectName = "BetterUI_FoodBar"; - private static RectTransform foodPanel; - private static RectTransform foodBarRoot; - private static RectTransform foodBaseBar; + public static class FoodBar + { + public const string objectName = "BetterUI_FoodBar"; + private static RectTransform foodPanel; + private static RectTransform foodBarRoot; + private static RectTransform foodBaseBar; - private static Image[] foodBars; - private static Image[] foodIcons; - private static Text[] foodTimes; - private static Transform[] foodTransforms; + private static Image[] foodBars; + private static Image[] foodIcons; + private static TMP_Text[] foodTimes; + private static Transform[] foodTransforms; - public static void UpdateRotation() + public static void UpdateRotation() + { + if (foodPanel == null || Main.customFoodBar.Value == Main.CustomBarState.off) { - if (foodPanel == null || Main.customFoodBar.Value == Main.CustomBarState.off) - { - return; - } + return; + } - int rot = ((int)Main.customFoodBar.Value + 270) % 360; - foodPanel.localEulerAngles = new Vector3(0, 0, rot); + int rot = ((int)Main.customFoodBar.Value + 270) % 360; + foodPanel.localEulerAngles = new Vector3(0, 0, rot); - foreach (var item in foodTransforms) - { - item.localEulerAngles = new Vector3(0, 0, -rot); - } + foreach (Transform item in foodTransforms) + { + item.localEulerAngles = new Vector3(0, 0, -rot); } + } - public static void Create() + public static void Create() + { + try { - try + // we've obviously already done this before if it's not null + if (foodPanel != null) { - // we've obviously already done this before if it's not null - if (foodPanel != null) - { - return; - } + return; + } - // original food panel gets hidden by hiding the original health bar, so if the user doesn't use that feature, then they would have two food bars - if (Main.customHealthBar.Value == Main.CustomBarState.off) - { - Debug.LogWarning($"{nameof(Main.customFoodBar)} requires {nameof(Main.customHealthBar)}. No custom food bar will be created. Activate {nameof(Main.customHealthBar)} and log out and back in to use {nameof(Main.customFoodBar)}."); - return; - } + // original food panel gets hidden by hiding the original health bar, so if the user doesn't use that feature, then they would have two food bars + if (Main.customHealthBar.Value == Main.CustomBarState.off) + { + BetterUI.Main.log.LogWarning($"{nameof(Main.customFoodBar)} requires {nameof(Main.customHealthBar)}. No custom food bar will be created. Activate {nameof(Main.customHealthBar)} and log out and back in to use {nameof(Main.customFoodBar)}."); + return; + } - foodPanel = UnityEngine.Object.Instantiate(Hud.instance.m_healthPanel, Hud.instance.transform.Find("hudroot")); - foodPanel.gameObject.name = objectName; - foodPanel.gameObject.SetActive(true); + foodPanel = UnityEngine.Object.Instantiate(Hud.instance.m_healthPanel, Hud.instance.transform.Find("hudroot")); + foodPanel.gameObject.name = objectName; + foodPanel.gameObject.SetActive(true); - foodBarRoot = foodPanel.Find("Food").GetComponent(); - foodBaseBar = foodBarRoot.Find("baseBar").GetComponent(); + foodBarRoot = foodPanel.Find("Food").GetComponent(); + foodBaseBar = foodBarRoot.Find("baseBar").GetComponent(); - foodBars = new Image[Hud.instance.m_foodBars.Length]; - foodIcons = new Image[Hud.instance.m_foodIcons.Length]; - foodTimes = new Text[Hud.instance.m_foodTime.Length]; - foodTransforms = new Transform[Hud.instance.m_foodTime.Length]; + foodBars = new Image[Hud.instance.m_foodBars.Length]; + foodIcons = new Image[Hud.instance.m_foodIcons.Length]; + foodTimes = new TMP_Text[Hud.instance.m_foodTime.Length]; + foodTransforms = new Transform[Hud.instance.m_foodTime.Length]; - for (int i = 0; i < Hud.instance.m_foodBars.Length; i++) - { - foodBars[i] = foodBarRoot.Find(Hud.instance.m_foodBars[i].name).GetComponent(); - foodTransforms[i] = foodPanel.Find($"food{i}"); - foodIcons[i] = foodTransforms[i].Find($"foodicon{i}").GetComponent(); - foodTimes[i] = foodTransforms[i].Find($"time").GetComponent(); - } + for (int i = 0; i < Hud.instance.m_foodBars.Length; i++) + { + foodBars[i] = foodBarRoot.Find(Hud.instance.m_foodBars[i].name).GetComponent(); + foodTransforms[i] = foodPanel.Find($"food{i}"); + foodIcons[i] = foodTransforms[i].Find($"foodicon{i}").GetComponent(); + foodTimes[i] = foodTransforms[i].Find($"time").GetComponent(); + } - UpdateRotation(); + UpdateRotation(); - // Stuff to remove / hide - foodPanel.Find("Health").gameObject.SetActive(false); - foodPanel.Find("darken").gameObject.SetActive(false); - foodPanel.Find("healthicon").gameObject.SetActive(false); + // Stuff to remove / hide + foodPanel.Find("Health").gameObject.SetActive(false); + foodPanel.Find("darken").gameObject.SetActive(false); + foodPanel.Find("healthicon").gameObject.SetActive(false); - // hide the fork icon. mistlands renamed this one, probably from editor dropping a new version into the scene (might also explain why the armor icon had a fork icon) - foodPanel.Find("foodicon (1)").gameObject.SetActive(false); + // hide the fork icon. mistlands renamed this one, probably from editor dropping a new version into the scene (might also explain why the armor icon had a fork icon) + foodPanel.Find("foodicon (1)").gameObject.SetActive(false); - foodPanel.position = Hud.instance.m_gpRoot.position; - foodPanel.position += new Vector3(-foodPanel.sizeDelta.x / 4, foodPanel.sizeDelta.x / 2); - } - catch (Exception e) - { - Debug.LogError($"{nameof(FoodBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); - } + foodPanel.position = Hud.instance.m_gpRoot.position; + foodPanel.position += new Vector3(-foodPanel.sizeDelta.x / 4, foodPanel.sizeDelta.x / 2); } + catch (Exception e) + { + BetterUI.Main.log.LogError($"{nameof(FoodBar)}.{nameof(Create)}() {e.Message} {e.StackTrace}"); + } + } - // based on HUD.UpdateFood() - public static void Update(Player player) + // based on HUD.UpdateFood() + public static void Update(Player player) + { + try { - try + if (foodPanel != null) { - if (foodPanel != null) + List foods = player.GetFoods(); + float baseHP = player.GetBaseFoodHP() / 25f * 32f; + foodBaseBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, baseHP); + float barLength = baseHP; + + for (int i = 0; i < Hud.instance.m_foodBars.Length; i++) { - List foods = player.GetFoods(); - float baseHP = player.GetBaseFoodHP() / 25f * 32f; - foodBaseBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, baseHP); - float barLength = baseHP; + Image foodBar = foodBars[i]; + Image foodIcon = foodIcons[i]; + TMP_Text foodTime = foodTimes[i]; - for (int i = 0; i < Hud.instance.m_foodBars.Length; i++) + if (i < foods.Count) { - Image foodBar = foodBars[i]; - Image foodIcon = foodIcons[i]; - Text foodTime = foodTimes[i]; + foodBar.gameObject.SetActive(true); + Player.Food food = foods[i]; + foodIcon.gameObject.SetActive(true); + foodIcon.sprite = food.m_item.GetIcon(); - if (i < foods.Count) + if (food.CanEatAgain()) { - foodBar.gameObject.SetActive(true); - Player.Food food = foods[i]; - foodIcon.gameObject.SetActive(true); - foodIcon.sprite = food.m_item.GetIcon(); - - if (food.CanEatAgain()) - { - foodIcon.color = new Color(1f, 1f, 1f, 0.7f + Mathf.Sin(Time.time * 5f) * 0.3f); - } - else - { - foodIcon.color = Color.white; - } - - foodTime.gameObject.SetActive(true); - foodTime.fontSize = customFoodBarTextSize.Value; - - if (food.m_time >= 60f) - { - foodTime.text = Mathf.CeilToInt(food.m_time / 60f) + "m"; - foodTime.color = Color.white; - } - else - { - foodTime.text = Mathf.FloorToInt(food.m_time) + "s"; - foodTime.color = new Color(1f, 1f, 1f, 0.4f + Mathf.Sin(Time.time * 10f) * 0.6f); - } + foodIcon.color = new Color(1f, 1f, 1f, 0.7f + Mathf.Sin(Time.time * 5f) * 0.3f); } else { - foodBar.gameObject.SetActive(false); - foodIcon.gameObject.SetActive(false); - foodTime.gameObject.SetActive(false); + foodIcon.color = Color.white; } - } - float size = Mathf.Ceil(player.GetMaxHealth() / 25f * 32f); - foodBarRoot.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, size); + foodTime.gameObject.SetActive(true); + foodTime.fontSize = customFoodBarTextSize.Value; + + if (food.m_time >= 60f) + { + foodTime.text = Mathf.CeilToInt(food.m_time / 60f) + "m"; + foodTime.color = Color.white; + } + else + { + foodTime.text = Mathf.FloorToInt(food.m_time) + "s"; + foodTime.color = new Color(1f, 1f, 1f, 0.4f + Mathf.Sin(Time.time * 10f) * 0.6f); + } + } + else + { + foodBar.gameObject.SetActive(false); + foodIcon.gameObject.SetActive(false); + foodTime.gameObject.SetActive(false); + } } + + float size = Mathf.Ceil(player.GetMaxHealth() / 25f * 32f); + foodBarRoot.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, size); } - catch (Exception e) - { - Debug.LogError($"{nameof(FoodBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); - } + } + catch (Exception e) + { + BetterUI.Main.log.LogError($"{nameof(FoodBar)}.{nameof(Update)}() {e.Message} {e.StackTrace}"); } } } diff --git a/BetterUI/Patches/CustomHud.cs b/BetterUI/Patches/CustomHud.cs index 28ceb56..83174ff 100644 --- a/BetterUI/Patches/CustomHud.cs +++ b/BetterUI/Patches/CustomHud.cs @@ -1,345 +1,385 @@ using System; using System.Collections.Generic; +using TMPro; using UnityEngine; using UnityEngine.UI; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +internal static class CustomHud { - internal static class CustomHud + public static List elements; + public static Dictionary roots = new Dictionary(); + public static Dictionary templates = new Dictionary(); + private static Transform hudRoot; + private static Transform invRoot; + private static Transform baseRoot; + public static readonly string templateSuffix = "_template"; + + // In the future give users ability to add new elements? + private static readonly Element[] supportedElements = { - public static List elements; - public static Dictionary roots = new Dictionary(); - public static Dictionary templates = new Dictionary(); - private static Transform hudRoot; - private static Transform invRoot; - private static Transform baseRoot; - public static readonly string templateSuffix = "_template"; - - // In the future give users ability to add new elements? - private static readonly Element[] supportedElements = - { - new Element("HotKeyBar", Groups.HudRoot), - new Element("BuildHud", Groups.HudRoot, "BuildHud/SelectedInfo"), - new Element("MiniMap", Groups.HudRoot, "MiniMap/small"), - new Element("GuardianPower", Groups.HudRoot), - new Element("StatusEffects", Groups.HudRoot), - new Element("SaveIcon", Groups.HudRoot), - new Element("BadConnectionIcon", Groups.HudRoot), - new Element("BuildHints", Groups.HudRoot, "KeyHints/BuildHints"), - new Element("CombatHints", Groups.HudRoot, "KeyHints/CombatHints"), - new Element("Player", Groups.Inventory, "Player", "PlayerInventory"), - new Element("Container", Groups.Inventory, "Container", "ChestContainer"), - new Element("Info", Groups.Inventory, "Info", "UITab"), - new Element("Crafting", Groups.Inventory, "Crafting", "CraftingWindow"), - new Element(CustomBars.HealthBar.objectName, Groups.HudRoot, CustomBars.HealthBar.objectName, "HP Bar"), - new Element(CustomBars.FoodBar.objectName, Groups.HudRoot, CustomBars.FoodBar.objectName, "Food Bar"), - new Element(CustomBars.StaminaBar.objectName, Groups.HudRoot, CustomBars.StaminaBar.objectName, "Stamina Bar"), - new Element(CustomBars.EitrBar.objectName, Groups.HudRoot, CustomBars.EitrBar.objectName, "Eitr Bar"), - new Element("QuickSlots", Groups.HudRoot, "QuickSlotsHotkeyBar", "QuickSlots") - //new Element("QuickSlotsHotkeyBar", Groups.HudRoot, "healthpanel/Health/QuickSlotsHotkeyBar", "QuickSlotsHotkey"), - //new Element("QuickSlotGrid", Groups.Inventory, "Player/QuickSlotGrid", "QuickSlots"), - //new Element("EquipmentSlotGrid", Groups.Inventory, "Player/EquipmentSlotGrid", "EquipmentSlots"), + new Element("HotKeyBar", Groups.HudRoot), + new Element("BuildHud", Groups.HudRoot, "BuildHud/SelectedInfo"), + new Element("MiniMap", Groups.HudRoot, "MiniMap/small"), + new Element("GuardianPower", Groups.HudRoot), + new Element("StatusEffects", Groups.HudRoot), + new Element("SaveIcon", Groups.HudRoot), + new Element("BadConnectionIcon", Groups.HudRoot), + new Element("BuildHints", Groups.HudRoot, "KeyHints/BuildHints"), + new Element("CombatHints", Groups.HudRoot, "KeyHints/CombatHints"), + new Element("Player", Groups.Inventory, "Player", "PlayerInventory"), + new Element("Container", Groups.Inventory, "Container", "ChestContainer"), + new Element("Info", Groups.Inventory, "Info", "UITab"), + new Element("Crafting", Groups.Inventory, "Crafting", "CraftingWindow"), + new Element(CustomBars.HealthBar.objectName, Groups.HudRoot, CustomBars.HealthBar.objectName, "HP Bar"), + new Element(CustomBars.FoodBar.objectName, Groups.HudRoot, CustomBars.FoodBar.objectName, "Food Bar"), + new Element(CustomBars.StaminaBar.objectName, Groups.HudRoot, CustomBars.StaminaBar.objectName, "Stamina Bar"), + new Element(CustomBars.EitrBar.objectName, Groups.HudRoot, CustomBars.EitrBar.objectName, "Eitr Bar"), + new Element("QuickSlots", Groups.HudRoot, "QuickSlotsHotkeyBar", "QuickSlots"), + new Element("BossHud", Groups.HudRoot, "EnemyHud/HudRoot/HudBaseBoss", "Boss Health Bar") + //new Element("QuickSlotsHotkeyBar", Groups.HudRoot, "healthpanel/Health/QuickSlotsHotkeyBar", "QuickSlotsHotkey"), + //new Element("QuickSlotGrid", Groups.Inventory, "Player/QuickSlotGrid", "QuickSlots"), + //new Element("EquipmentSlotGrid", Groups.Inventory, "Player/EquipmentSlotGrid", "EquipmentSlots"), }; - // If new items are added to mandatory items, check if user has them - if not add them. - public static void Load(Hud hud) + // If new items are added to mandatory items, check if user has them - if not add them. + public static void Load(Hud hud) + { + try { - try - { - hudRoot = hud.transform.Find("hudroot"); - invRoot = InventoryGui.instance.transform.Find("root"); // Issue, this element is hidden when inventory is closed - baseRoot = MessageHud.instance.transform; // This layer will be projected over other UI elements + hudRoot = hud.transform.Find("hudroot"); + invRoot = InventoryGui.instance.transform.Find("root"); // Issue, this element is hidden when inventory is closed + baseRoot = MessageHud.instance.transform; // This layer will be projected over other UI elements - roots[Groups.HudRoot] = hudRoot; - roots[Groups.Inventory] = invRoot; + roots[Groups.HudRoot] = hudRoot; + roots[Groups.Inventory] = invRoot; - if (Main.uiData.Value == "none" || Main.uiData.Value == "") + if (Main.uiData.Value == "none" || Main.uiData.Value == "") + { + Helpers.DebugLine($"User has no uiData. Creating basic template."); + elements = new List(); + } + else + { + try { - Helpers.DebugLine($"User has no uiData. Creating basic template."); - elements = new List(); + byte[] bytes = Convert.FromBase64String(Main.uiData.Value); + elements = (List)bytes.DeSerialize(); // Risky, as we trust the data is valid? + Helpers.DebugLine($"User has {elements.Count} ui elements set."); } - else + catch { - try - { - byte[] bytes = Convert.FromBase64String(Main.uiData.Value); - elements = (List)bytes.DeSerialize(); // Risky, as we trust the data is valid? - Helpers.DebugLine($"User has {elements.Count} ui elements set."); - } - catch - { - Helpers.DebugLine($"FAILED to DeSerialize uiData: {Main.uiData.Value}"); - } + Helpers.DebugLine($"FAILED to DeSerialize uiData: {Main.uiData.Value}"); + } - foreach (var item in elements) - { - item.OnAfterDeserialize(); - } + foreach (HudElement item in elements) + { + item.OnAfterDeserialize(); } + } - if (elements.Count < supportedElements.Length) + if (elements.Count < supportedElements.Length) + { + foreach (Element e in supportedElements) { - foreach (Element e in supportedElements) + // Element does not exist in users uiData, add it. + if (!elements.Exists(he => he.Name == e.Name)) { - // Element does not exist in users uiData, add it. - if (!elements.Exists(he => he.Name == e.Name)) - { - Helpers.DebugLine($"Adding to elements: {e.Name}"); - elements.Add(new HudElement(e.Name, e.DisplayName, e.Group, e.LocationPath, Vector2.zero)); + Helpers.DebugLine($"Adding to elements: {e.Name} with path: {e.LocationPath}"); + elements.Add(new HudElement(e.Name, e.DisplayName, e.Group, e.LocationPath, Vector2.zero)); - if (elements.Count == supportedElements.Length) break; - } + if (elements.Count == supportedElements.Length) break; } } - else if (elements.Count > supportedElements.Length) - { - // We have more elements than supported? Are there duplicates, how? - Helpers.DebugLine($"Seems that your UI might be corrupted!", true, true); - } - - CreateTemplates(); } - catch (Exception e) + else if (elements.Count > supportedElements.Length) { - Helpers.DebugLine($"Issue while CustomHud Load. {e.Message}", true, true); + // We have more elements than supported? Are there duplicates, how? + Helpers.DebugLine($"Seems that your UI might be corrupted!", true, true); } - } - public static void Save() + CreateTemplates(); + } + catch (Exception e) { - try - { - // Before saving, check if unset elements -> no need to save them. - elements.RemoveAll(e => e.Position == Vector2.zero); - byte[] bytes = elements.Serialize(); - Helpers.DebugLine($"uiData bytes: {bytes.Length}"); - string base64String = Convert.ToBase64String(bytes); - Main.uiData.Value = base64String; - } - catch (Exception e) - { - Helpers.DebugLine($"FAILED to Save: {e.Message}"); - } + Helpers.DebugLine($"Issue while CustomHud Load. {e.Message}", true, true); } + } - public static void ShowTemplates(bool show, int activeLayer) + public static void Save() + { + try + { + // Before saving, check if unset elements -> no need to save them. + elements.RemoveAll(e => e.Position == Vector2.zero); + byte[] bytes = elements.Serialize(); + Helpers.DebugLine($"uiData bytes: {bytes.Length}"); + string base64String = Convert.ToBase64String(bytes); + Main.uiData.Value = base64String; + } + catch (Exception e) { - // Try to find reason on using this? - //roots.TryGetValue((Groups)activeLayer, out Transform activeTemplate); + Helpers.DebugLine($"FAILED to Save: {e.Message}"); + } + } - foreach (HudElement e in elements) + public static void ShowTemplates(bool show, int activeLayer) + { + // Try to find reason on using this? + //roots.TryGetValue((Groups)activeLayer, out Transform activeTemplate); + + foreach (HudElement e in elements) + { + if ((Groups)activeLayer == e.Group) { - if ((Groups)activeLayer == e.Group) + RectTransform rt = LocateTemplateRect(e.Name); + if (rt) { - RectTransform rt = LocateTemplateRect(e.Name); - if (rt) - { - rt.gameObject.SetActive(show); - } + rt.gameObject.SetActive(show); } - else + } + else + { + RectTransform rt = LocateTemplateRect(e.Name); + if (rt) { - RectTransform rt = LocateTemplateRect(e.Name); - if (rt) - { - rt.gameObject.SetActive(false); - } + rt.gameObject.SetActive(false); } } - - if (!show) Save(); } - public static void UpdatePosition(string name, Vector2 posChange) - { - HudElement element = elements.Find(e => e.Name == name); + if (!show) Save(); + } - if (element.Name == name) - { - element.Position += posChange; + public static void UpdatePosition(string name, Vector2 posChange) + { + HudElement element = elements.Find(e => e.Name == name); - if (element.Group == Groups.Inventory) - { - var newPos = (Vector2)Camera.main.ScreenToViewportPoint(posChange); + if (element.Name == name) + { + element.Position += posChange; - element.AnchorMin += newPos; - element.AnchorMax += newPos; - } + if (element.Group == Groups.Inventory) + { + Vector2 newPos = (Vector2)Camera.main.ScreenToViewportPoint(posChange); - // Update element & template position - PositionTemplate(element); + element.AnchorMin += newPos; + element.AnchorMax += newPos; } + + // Update element & template position + PositionTemplate(element); } + } - public static void UpdateScaleAndDimensions(string name, Vector2 dimensionChanges, float scaleChange) - { - HudElement element = elements.Find(e => e.Name == name); + public static void UpdateScaleAndDimensions(string name, Vector2 dimensionChanges, float scaleChange) + { + HudElement element = elements.Find(e => e.Name == name); - if (element.Name == name) + if (element.Name == name) + { + if (scaleChange != 0f) { - if (scaleChange != 0f) - { - element.ChangeScale(scaleChange); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{element.DisplayName} size: {element.Scale}"); - } - - if (dimensionChanges != Vector2.zero) - { - element.ChangeXDims(dimensionChanges.x); - element.ChangeYDims(dimensionChanges.y); - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{element.DisplayName} dimensions: ({element.XDimensions},{element.YDimensions})"); - // Update element & template position - PositionTemplate(element); - } + element.ChangeScale(scaleChange); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{element.DisplayName} size: {element.Scale}"); } - else + + if (dimensionChanges != Vector2.zero) { - Helpers.DebugLine($"Invalid call when updating element: {name}", true, true); + element.ChangeXDims(dimensionChanges.x); + element.ChangeYDims(dimensionChanges.y); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{element.DisplayName} dimensions: ({element.XDimensions},{element.YDimensions})"); + // Update element & template position + PositionTemplate(element); } } + else + { + Helpers.DebugLine($"Invalid call when updating element: {name}", true, true); + } + } - private static void PositionTemplate(HudElement e) + private static void PositionTemplate(HudElement e) + { + try { - try + RectTransform rt = LocateRectTransform(e.Group, e.Path); // Original object + RectTransform tt = LocateTemplateRect(e.Name); // Your generated template + //Helpers.DebugLine($"{rt} {rt.anchorMin} {e.GetPosition()}"); + if (rt) { - RectTransform rt = LocateRectTransform(e.Group, e.Path); // Original object - RectTransform tt = LocateTemplateRect(e.Name); // Your generated template - //Helpers.DebugLine($"{rt} {rt.anchorMin} {e.GetPosition()}"); - if (rt) + // Add special handling for BossHud + if (e.Name == "BossHud") { - if (e.Group == Groups.Inventory) - { - float gameScale = GameObject.Find("LoadingGUI").GetComponent().scaleFactor; - //Helpers.DebugLine($"\n{e.GetPosition()}\n{gameScale}\n{Camera.main.ViewportToScreenPoint(e.GetAnchorMin())}\n{tt.position}"); - //Helpers.DebugLine($"\n{e.GetPosition() / gameScale}"); - // Original object are moved by anchors - Vector3 cPos = Camera.main.ViewportToScreenPoint(e.AnchorMax); - Vector2 ePos = e.Position; - - rt.anchorMin = e.AnchorMin; - rt.anchorMax = e.AnchorMax; - tt.anchoredPosition = e.Position / gameScale; - } - else + // Update the original template that gets cloned + rt.anchoredPosition = e.Position; + rt.localScale = new Vector3(e.Scale * e.XDimensions, e.Scale * e.YDimensions); + + // Update any existing boss huds in the scene + EnemyHud enemyHud = EnemyHud.m_instance; + if (enemyHud != null) { - rt.anchoredPosition = e.Position; - tt.anchoredPosition = e.Position; //rt.anchoredPosition; + foreach (var hudPair in enemyHud.m_huds) + { + if (hudPair.Key.IsBoss()) + { + var bossRT = hudPair.Value.m_gui.GetComponent(); + if (bossRT) + { + bossRT.anchoredPosition = e.Position; + bossRT.localScale = new Vector3(e.Scale * e.XDimensions, e.Scale * e.YDimensions); + } + } + } } + } - rt.localScale = new Vector3(e.Scale * e.XDimensions, e.Scale * e.YDimensions); - tt.localScale = rt.localScale; + if (e.Group == Groups.Inventory) + { + float gameScale = GuiScaler.m_largeGuiScale; + //Helpers.DebugLine($"\n{e.GetPosition()}\n{gameScale}\n{Camera.main.ViewportToScreenPoint(e.GetAnchorMin())}\n{tt.position}"); + //Helpers.DebugLine($"\n{e.GetPosition() / gameScale}"); + // Original object are moved by anchors + Vector3 cPos = Camera.main.ViewportToScreenPoint(e.AnchorMax); + Vector2 ePos = e.Position; + + rt.anchorMin = e.AnchorMin; + rt.anchorMax = e.AnchorMax; + tt.anchoredPosition = e.Position / gameScale; } - } - catch - { - Helpers.DebugLine($"PositionTemplate Catch: {e.Name}"); + else + { + rt.anchoredPosition = e.Position; + tt.anchoredPosition = e.Position; //rt.anchoredPosition; + } + + rt.localScale = new Vector3(e.Scale * e.XDimensions, e.Scale * e.YDimensions); + tt.localScale = rt.localScale; } } + catch + { + Helpers.DebugLine($"PositionTemplate Catch: {e.Name}"); + } + } - public static RectTransform LocateRectTransform(Groups group, string path) + public static RectTransform LocateRectTransform(Groups group, string path) + { + try { - try - { - roots.TryGetValue(group, out Transform parent); - // We change parent to Inventory root - if (group == Groups.Inventory) parent = InventoryGui.instance.transform.Find("root"); + roots.TryGetValue(group, out Transform parent); + // We change parent to Inventory root + if (group == Groups.Inventory) parent = InventoryGui.instance.transform.Find("root"); - return parent.Find(path).GetComponent(); - } - catch + // Special case for BossHud + if (path.StartsWith("EnemyHud/")) { - return null; + Transform ingameGui = hudRoot.parent.parent; + Transform enemyHud = ingameGui.Find(path); + if (enemyHud != null) + { + return enemyHud.GetComponent(); + } } - } - public static RectTransform LocateTemplateRect(string name) + return parent.Find(path).GetComponent(); + } + catch { - try - { - return baseRoot.Find($"{name}{templateSuffix}").GetComponent(); - } - catch - { - Helpers.DebugLine($"Unable to find template for {name}", true, true); - return null; - } + return null; } + } - public static void PositionTemplates() + public static RectTransform LocateTemplateRect(string name) + { + try + { + return baseRoot.Find($"{name}{templateSuffix}").GetComponent(); + } + catch { - foreach (HudElement e in elements) PositionTemplate(e); + Helpers.DebugLine($"Unable to find template for {name}", true, true); + return null; } + } - private static void CreateTemplates() + public static void PositionTemplates() + { + foreach (HudElement e in elements) PositionTemplate(e); + } + + private static void CreateTemplates() + { + List unusedElements = new List(); + foreach (HudElement e in elements) { - List unusedElements = new List(); - foreach (HudElement e in elements) + try { - try + RectTransform rt = LocateRectTransform(e.Group, e.Path); + if (e.Position == Vector2.zero) { - RectTransform rt = LocateRectTransform(e.Group, e.Path); - if (e.Position == Vector2.zero) + if (e.Group == Groups.Inventory) { - if (e.Group == Groups.Inventory) - { - e.Position = rt.anchoredPosition; - // This elements depend on anchors, set these - e.AnchorMin = rt.anchorMin; - e.AnchorMax = rt.anchorMax; - } - else - { - e.Position = rt.anchoredPosition; - } + e.Position = rt.anchoredPosition; + // This elements depend on anchors, set these + e.AnchorMin = rt.anchorMin; + e.AnchorMax = rt.anchorMax; + } + else + { + e.Position = rt.anchoredPosition; } - AddTemplateToHud(e, rt); - } - catch - { - unusedElements.Add(e); } + + AddTemplateToHud(e, rt); } - // Remove unused elements from main ElementList - if (unusedElements.Count > 0) + catch { - Helpers.DebugLine($"Removing {unusedElements.Count} unused elements."); - foreach (HudElement e in unusedElements) - { - Helpers.DebugLine($"Remove {e.DisplayName} as not used."); - elements.Remove(e); - } + unusedElements.Add(e); } } - private static void AddTemplateToHud(HudElement element, RectTransform rt) + // Remove unused elements from main ElementList + if (unusedElements.Count > 0) { - // Should we add these to their own elements? Based on their group? - // roots.TryGetValue(Groups.HudRoot, out Transform templateRoot); // Everything on hudRoot - // roots.TryGetValue(element.group, out Transform templateRoot); - - Transform go = UnityEngine.Object.Instantiate(hudRoot.Find("BuildHud/SelectedInfo"), baseRoot); - go.gameObject.name = $"{element.Name}{templateSuffix}"; - go.Find("selected_piece").gameObject.SetActive(false); - go.Find("requirements").gameObject.SetActive(false); - - Text t = go.gameObject.AddComponent(); - t.text = $"{element.DisplayName}"; - t.font = Resources.GetBuiltinResource("Arial.ttf"); - t.fontSize = 20; - t.alignment = TextAnchor.MiddleCenter; - go.gameObject.SetActive(false); // Have it hidden when added - - RectTransform templateRT = go.GetComponent(); - templateRT.pivot = rt.pivot; - templateRT.anchorMin = rt.anchorMin; - templateRT.anchorMax = rt.anchorMax; - templateRT.offsetMin = rt.offsetMin; - templateRT.offsetMax = rt.offsetMax; - templateRT.sizeDelta = rt.sizeDelta; - templateRT.anchoredPosition = rt.anchoredPosition; - templateRT.position = rt.position; - templateRT.localEulerAngles = rt.localEulerAngles; - t.resizeTextForBestFit = true; + Helpers.DebugLine($"Removing {unusedElements.Count} unused elements."); + foreach (HudElement e in unusedElements) + { + Helpers.DebugLine($"Remove {e.DisplayName} as not used."); + elements.Remove(e); + } } } + + private static void AddTemplateToHud(HudElement element, RectTransform rt) + { + // Should we add these to their own elements? Based on their group? + // roots.TryGetValue(Groups.HudRoot, out Transform templateRoot); // Everything on hudRoot + // roots.TryGetValue(element.group, out Transform templateRoot); + + Transform go = UnityEngine.Object.Instantiate(hudRoot.Find("BuildHud/SelectedInfo"), baseRoot); + go.gameObject.name = $"{element.Name}{templateSuffix}"; + go.Find("selected_piece").gameObject.SetActive(false); + go.Find("requirements").gameObject.SetActive(false); + + TextMeshProUGUI t = go.gameObject.AddComponent(); + t.text = $"{element.DisplayName}"; + t.font = Hud.instance.m_pieceDescription.font; + t.fontSize = 20; + t.alignment = TextAlignmentOptions.CenterGeoAligned; + go.gameObject.SetActive(false); // Have it hidden when added + + RectTransform templateRT = go.GetComponent(); + templateRT.pivot = rt.pivot; + templateRT.anchorMin = rt.anchorMin; + templateRT.anchorMax = rt.anchorMax; + templateRT.offsetMin = rt.offsetMin; + templateRT.offsetMax = rt.offsetMax; + templateRT.sizeDelta = rt.sizeDelta; + templateRT.anchoredPosition = rt.anchoredPosition; + templateRT.position = rt.position; + templateRT.localEulerAngles = rt.localEulerAngles; + t.enableAutoSizing = true; + } } \ No newline at end of file diff --git a/BetterUI/Patches/Helpers.cs b/BetterUI/Patches/Helpers.cs index b8f199f..4a1db7a 100644 --- a/BetterUI/Patches/Helpers.cs +++ b/BetterUI/Patches/Helpers.cs @@ -8,119 +8,117 @@ using System.Threading.Tasks; using UnityEngine; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +public static class ObjectSerialize { - public static class ObjectSerialize - { public static byte[] Serialize(this object obj) { - if (obj == null) - { - return null; - } - - using (var memoryStream = new MemoryStream()) - { - var binaryFormatter = new BinaryFormatter(); - binaryFormatter.Serialize(memoryStream, obj); - var compressed = Compress(memoryStream.ToArray()); - return compressed; - } + if (obj == null) + { + return null; + } + + using (MemoryStream memoryStream = new MemoryStream()) + { + BinaryFormatter binaryFormatter = new BinaryFormatter(); + binaryFormatter.Serialize(memoryStream, obj); + byte[] compressed = Compress(memoryStream.ToArray()); + return compressed; + } } public static object DeSerialize(this byte[] arrBytes) { - using (var memoryStream = new MemoryStream()) - { - var binaryFormatter = new BinaryFormatter(); - var decompressed = Decompress(arrBytes); + using (MemoryStream memoryStream = new MemoryStream()) + { + BinaryFormatter binaryFormatter = new BinaryFormatter(); + byte[] decompressed = Decompress(arrBytes); - memoryStream.Write(decompressed, 0, decompressed.Length); - memoryStream.Seek(0, SeekOrigin.Begin); + memoryStream.Write(decompressed, 0, decompressed.Length); + memoryStream.Seek(0, SeekOrigin.Begin); - return binaryFormatter.Deserialize(memoryStream); - } + return binaryFormatter.Deserialize(memoryStream); + } } public static byte[] Compress(byte[] input) { - byte[] compressesData; + byte[] compressesData; - using (var outputStream = new MemoryStream()) - { - using (var zip = new GZipStream(outputStream, CompressionMode.Compress)) + using (MemoryStream outputStream = new MemoryStream()) { - zip.Write(input, 0, input.Length); + using (GZipStream zip = new GZipStream(outputStream, CompressionMode.Compress)) + { + zip.Write(input, 0, input.Length); + } + + compressesData = outputStream.ToArray(); } - compressesData = outputStream.ToArray(); - } - return compressesData; + return compressesData; } public static byte[] Decompress(byte[] input) { - byte[] decompressedData; + byte[] decompressedData; - using (var outputStream = new MemoryStream()) - { - using (var inputStream = new MemoryStream(input)) + using (MemoryStream outputStream = new MemoryStream()) { - using (var zip = new GZipStream(inputStream, CompressionMode.Decompress)) - { - zip.CopyTo(outputStream); - } + using (MemoryStream inputStream = new MemoryStream(input)) + { + using (GZipStream zip = new GZipStream(inputStream, CompressionMode.Decompress)) + { + zip.CopyTo(outputStream); + } + } + + decompressedData = outputStream.ToArray(); } - decompressedData = outputStream.ToArray(); - } - - return decompressedData; + return decompressedData; } - } +} - class Helpers - { +class Helpers +{ public static string Repeat(string value, int count) { - return new StringBuilder(value.Length * count).Insert(0, value, count).ToString(); + return new StringBuilder(value.Length * count).Insert(0, value, count).ToString(); } public static string TimeString(double val1, double val2) { - TimeSpan t = TimeSpan.FromSeconds(val1 - val2); - return t.Hours > 0 ? - string.Format("{0:D2}h {1:D2}m {2:D2}s", t.Hours, t.Minutes, t.Seconds) : t.Minutes > 0 ? - string.Format("{0:D2}m {1:D2}s", t.Minutes, t.Seconds) : string.Format("{0:D2}s", t.Seconds); + TimeSpan t = TimeSpan.FromSeconds(val1 - val2); + return t.Hours > 0 ? $"{t.Hours:D2}h {t.Minutes:D2}m {t.Seconds:D2}s" + : t.Minutes > 0 ? $"{t.Minutes:D2}m {t.Seconds:D2}s" : $"{t.Seconds:D2}s"; } public static string TimeString(double seconds) { - TimeSpan t = TimeSpan.FromSeconds(seconds); - return t.Hours > 0 ? - string.Format("{0:D2}h {1:D2}m {2:D2}s", t.Hours, t.Minutes, t.Seconds) : t.Minutes > 0 ? - string.Format("{0:D2}m {1:D2}s", t.Minutes, t.Seconds) : string.Format("{0:D2}s", t.Seconds); + TimeSpan t = TimeSpan.FromSeconds(seconds); + return t.Hours > 0 ? $"{t.Hours:D2}h {t.Minutes:D2}m {t.Seconds:D2}s" + : t.Minutes > 0 ? $"{t.Minutes:D2}m {t.Seconds:D2}s" : $"{t.Seconds:D2}s"; } public static void DebugLine(string str = "", bool pref = true, bool warn = false) { - if (Main.isDebug.Value) - { - if (warn) Main.log.LogWarning($"{(pref ? $"[{typeof(Main).Namespace}] " : "")}{str}"); - else Main.log.LogInfo($"{(pref ? $"[{typeof(Main).Namespace}] " : "")}{str}"); - } + if (Main.isDebug.Value) + { + if (warn) Main.log.LogWarning($"{(pref ? $"[{typeof(Main).Namespace}] " : "")}{str}"); + else Main.log.LogInfo($"{(pref ? $"[{typeof(Main).Namespace}] " : "")}{str}"); + } } public static bool CheckHeldKey(KeyCode key) { - try - { - return Input.GetKey(key); - } - catch - { - return false; - } + try + { + return Input.GetKey(key); + } + catch + { + return false; + } } - } -} +} \ No newline at end of file diff --git a/BetterUI/Patches/HoverText.cs b/BetterUI/Patches/HoverText.cs index 59ea13c..5384131 100644 --- a/BetterUI/Patches/HoverText.cs +++ b/BetterUI/Patches/HoverText.cs @@ -1,231 +1,234 @@ using UnityEngine; using static BetterUI.Main; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +static class HoverText { - static class HoverText - { - private static readonly string useKey = "[$KEY_Use]"; - private static readonly string _containerBase = "[$KEY_Use] $piece_container_open"; + private static readonly string useKey = "[$KEY_Use]"; + + private static readonly string _containerBase = "[$KEY_Use] $piece_container_open"; + // [E] Cook item - private static readonly string _cookItem = "[$KEY_Use] $piece_cstand_cook"; + private static readonly string _cookItem = "[$KEY_Use] $piece_cstand_cook"; + // [1-8] Cook Item - private static readonly string _selectItem = "[1-8] $piece_cstand_cook"; + private static readonly string _selectItem = "[1-8] $piece_cstand_cook"; private static readonly string overCookColor = "red"; - private static readonly string smelterRoof = "$piece_smelter_reqroof"; + private static readonly string smelterRoof = "$piece_smelter_reqroof"; public static bool PatchFermenter(Fermenter fermenter, ref string hoverText) { - switch (fermenter.GetStatus()) - { - case Fermenter.Status.Fermenting: - string contentName = fermenter.GetContentName(); - if (fermenter.m_exposed) // Why do we need to re-check? Ain't Fermenter.Status.Exposed enough? - Wack original code. - { - hoverText = Localization.instance.Localize(fermenter.m_name + " ( " + contentName + ", $piece_fermenter_exposed )"); - return false; - } - string time = Main.timeLeftHoverTextFermenter.Value == Main.TimeLeftStyle.PercentageDone ? - $"{fermenter.GetFermentationTime() / fermenter.m_fermentationDuration:P0}" : - Helpers.TimeString(fermenter.m_fermentationDuration - fermenter.GetFermentationTime()); - - hoverText = Localization.instance.Localize($"{contentName}\n$piece_fermenter_fermenting: {time}"); - return false; - - case Fermenter.Status.Ready: - string contentName2 = fermenter.GetContentName(); - hoverText = Localization.instance.Localize($"{fermenter.m_name}, $piece_fermenter_ready \n{contentName2}\n[$KEY_Use] $piece_fermenter_tap"); - return false; - - default: - return true; - } - } - - public static void PatchBeeHive(Beehive beeHive, ref string hoverText) + switch (fermenter.GetStatus()) { - int honeyLevel = beeHive.GetHoneyLevel(); + case Fermenter.Status.Fermenting: + string contentName = fermenter.GetContentName(); + if (fermenter.m_exposed) // Why do we need to re-check? Ain't Fermenter.Status.Exposed enough? - Wack original code. + { + hoverText = Localization.instance.Localize(fermenter.m_name + " ( " + contentName + ", $piece_fermenter_exposed )"); + return false; + } - var timeLeft = string.Empty; + string time = Main.timeLeftHoverTextFermenter.Value == Main.TimeLeftStyle.PercentageDone ? $"{fermenter.GetFermentationTime() / fermenter.m_fermentationDuration:P0}" : Helpers.TimeString(fermenter.m_fermentationDuration - fermenter.GetFermentationTime()); - if (honeyLevel < beeHive.m_maxHoney) - { - float num = beeHive.m_nview.GetZDO().GetFloat("product"); + hoverText = Localization.instance.Localize($"{contentName}\n$piece_fermenter_fermenting: {time}"); + return false; - float durationUntilDone = beeHive.m_secPerUnit - num; + case Fermenter.Status.Ready: + string contentName2 = fermenter.GetContentName(); + hoverText = Localization.instance.Localize($"{fermenter.m_name}, $piece_fermenter_ready \n{contentName2}\n[$KEY_Use] $piece_fermenter_tap"); + return false; - if (Main.timeLeftHoverTextBeeHive.Value == Main.TimeLeftStyle.PercentageDone) - { - timeLeft = $"{num / beeHive.m_secPerUnit:P0}, "; - } - else - { - timeLeft = $"{Helpers.TimeString(durationUntilDone)}, "; - } - } + default: + return true; + } + } - if (honeyLevel > 0) + public static void PatchBeeHive(Beehive beeHive, ref string hoverText) + { + int honeyLevel = beeHive.GetHoneyLevel(); + + string timeLeft = string.Empty; + + if (honeyLevel < beeHive.m_maxHoney) + { + float num = beeHive.m_nview.GetZDO().GetFloat("product"); + + float durationUntilDone = beeHive.m_secPerUnit - num; + + if (Main.timeLeftHoverTextBeeHive.Value == Main.TimeLeftStyle.PercentageDone) { - hoverText = Localization.instance.Localize($"{beeHive.m_name} ( {timeLeft}{beeHive.m_honeyItem.m_itemData.m_shared.m_name} x {honeyLevel} ) \n[$KEY_Use] $piece_beehive_extract"); + timeLeft = $"{num / beeHive.m_secPerUnit:P0}, "; } else { - hoverText = Localization.instance.Localize($"{beeHive.m_name} ( {timeLeft}$piece_container_empty ) \n[$KEY_Use] $piece_beehive_check"); + timeLeft = $"{Helpers.TimeString(durationUntilDone)}, "; } } + if (honeyLevel > 0) + { + hoverText = Localization.instance.Localize($"{beeHive.m_name} ( {timeLeft}{beeHive.m_honeyItem.m_itemData.m_shared.m_name} x {honeyLevel} ) \n[$KEY_Use] $piece_beehive_extract"); + } + else + { + hoverText = Localization.instance.Localize($"{beeHive.m_name} ( {timeLeft}$piece_container_empty ) \n[$KEY_Use] $piece_beehive_check"); + } + } + public static bool PatchPlant(Plant plant, ref string hoverText) { - switch (plant.m_status) - { - case Plant.Status.Healthy: - string time = Main.timeLeftHoverTextPlant.Value == Main.TimeLeftStyle.PercentageDone ? - $"{plant.TimeSincePlanted() / plant.GetGrowTime():P0}" : - Helpers.TimeString(plant.GetGrowTime() - plant.TimeSincePlanted()); - - hoverText = Localization.instance.Localize($"{plant.m_name}\n{time}"); - return false; - - default: - return true; - } + switch (plant.m_status) + { + case Plant.Status.Healthy: + string time = Main.timeLeftHoverTextPlant.Value == Main.TimeLeftStyle.PercentageDone ? $"{plant.TimeSincePlanted() / plant.GetGrowTime():P0}" : Helpers.TimeString(plant.GetGrowTime() - plant.TimeSincePlanted()); + + hoverText = Localization.instance.Localize($"{plant.m_name}\n{time}"); + return false; + + default: + return true; + } } public static string PatchContainer(Container container) { - /* - string room = Main.chestHasRoomStyle.Value == 1 ? - $"{container.m_inventory.SlotsUsedPercentage():F0}%" : - $"{container.m_inventory.NrOfItems()}/{container.m_inventory.GetWidth() * container.m_inventory.GetHeight()}"; - */ + /* + string room = Main.chestHasRoomStyle.Value == 1 ? + $"{container.m_inventory.SlotsUsedPercentage():F0}%" : + $"{container.m_inventory.NrOfItems()}/{container.m_inventory.GetWidth() * container.m_inventory.GetHeight()}"; + */ string room; - switch (Main.chestHasRoomHoverText.Value) - { - case ChestHasRoomStyle.Percentage: - room = $"{container.m_inventory.SlotsUsedPercentage():F0}%"; - break; - case ChestHasRoomStyle.ItemsSlashMaxRoom: - room = $"{container.m_inventory.NrOfItems()}/{container.m_inventory.GetWidth() * container.m_inventory.GetHeight()}"; - break; - case ChestHasRoomStyle.AmountOfFreeSlots: - room = $"{container.m_inventory.GetEmptySlots()}"; - break; - default: - room = $"{container.m_inventory.SlotsUsedPercentage():F0}%"; - break; - } - return Localization.instance.Localize($"{container.m_name} ( {room} )\n{_containerBase}"); + switch (Main.chestHasRoomHoverText.Value) + { + case ChestHasRoomStyle.Percentage: + room = $"{container.m_inventory.SlotsUsedPercentage():F0}%"; + break; + case ChestHasRoomStyle.ItemsSlashMaxRoom: + room = $"{container.m_inventory.NrOfItems()}/{container.m_inventory.GetWidth() * container.m_inventory.GetHeight()}"; + break; + case ChestHasRoomStyle.AmountOfFreeSlots: + room = $"{container.m_inventory.GetEmptySlots()}"; + break; + default: + room = $"{container.m_inventory.SlotsUsedPercentage():F0}%"; + break; + } + + return Localization.instance.Localize($"{container.m_name} ( {room} )\n{_containerBase}"); } public static bool PatchCookingStation(CookingStation cookingStation, ref string hoverText) { - if (cookingStation.m_nview.IsOwner()) - { - string cookingItems = ""; - int items = 0; - - for (int i = 0; i < cookingStation.m_slots.Length; i++) + if (cookingStation.m_nview.IsOwner()) { - cookingStation.GetSlot(i, out string text, out float num, out CookingStation.Status status); - if (text != "" && text != cookingStation.m_overCookedItem.name) - { - CookingStation.ItemConversion itemConversion = cookingStation.GetItemConversion(text); - if (text != null) + string cookingItems = ""; + int items = 0; + + for (int i = 0; i < cookingStation.m_slots.Length; i++) { - items++; - if (num > itemConversion.m_cookTime) // Item overCooking - { - string time = Main.timeLeftHoverTextCookingStation.Value == Main.TimeLeftStyle.PercentageDone ? $"{num / (itemConversion.m_cookTime * 2f):P0}" : Helpers.TimeString(itemConversion.m_cookTime * 2f - num); - cookingItems += $"\n{cookingStation.m_overCookedItem.GetHoverName()}: {time}"; - } - else - { - string time = Main.timeLeftHoverTextCookingStation.Value == Main.TimeLeftStyle.PercentageDone ? $"{num / itemConversion.m_cookTime:P0}" : Helpers.TimeString(itemConversion.m_cookTime - num); - cookingItems += $"\n{itemConversion.m_to.GetHoverName()}: {time}"; - } + cookingStation.GetSlot(i, out string text, out float num, out CookingStation.Status status); + if (text != "" && text != cookingStation.m_overCookedItem.name) + { + CookingStation.ItemConversion itemConversion = cookingStation.GetItemConversion(text); + if (text != null) + { + items++; + if (num > itemConversion.m_cookTime) // Item overCooking + { + string time = Main.timeLeftHoverTextCookingStation.Value == Main.TimeLeftStyle.PercentageDone ? $"{num / (itemConversion.m_cookTime * 2f):P0}" : Helpers.TimeString(itemConversion.m_cookTime * 2f - num); + cookingItems += $"\n{cookingStation.m_overCookedItem.GetHoverName()}: {time}"; + } + else + { + string time = Main.timeLeftHoverTextCookingStation.Value == Main.TimeLeftStyle.PercentageDone ? $"{num / itemConversion.m_cookTime:P0}" : Helpers.TimeString(itemConversion.m_cookTime - num); + cookingItems += $"\n{itemConversion.m_to.GetHoverName()}: {time}"; + } + } + } + } + + if (items > 0) + { + hoverText = items >= cookingStation.m_slots.Length ? Localization.instance.Localize($"{cookingStation.m_name}{cookingItems}") : Localization.instance.Localize($"{cookingStation.m_name}\n{_cookItem}\n{_selectItem}{cookingItems}"); + return false; // Overwrite games default string } - } - } - if (items > 0) - { - hoverText = items >= cookingStation.m_slots.Length ? - Localization.instance.Localize($"{cookingStation.m_name}{cookingItems}") : - Localization.instance.Localize($"{cookingStation.m_name}\n{_cookItem}\n{_selectItem}{cookingItems}"); - return false; // Overwrite games default string } - } - return true; + + return true; } public static void PatchSmelter(Smelter smelter) { - if (smelter.m_emptyOreSwitch && smelter.m_spawnStack) - { - int processedQueueSize = smelter.GetProcessedQueueSize(); - smelter.m_emptyOreSwitch.m_hoverText = $"{smelter.m_name} {processedQueueSize} $piece_smelter_ready \n{useKey} {smelter.m_emptyOreTooltip}"; - } - int queueSize = smelter.GetQueueSize(); - smelter.m_addOreSwitch.m_hoverText = $"{smelter.m_name} ({queueSize}/{smelter.m_maxOre}) "; - - if (queueSize > 0) // This codeline is run every tick when windmill is on!! - { - Debug.Log($"{smelter.GetBakeTimer()}, {smelter.m_secPerProduct}, {queueSize}"); - - smelter.m_addOreSwitch.m_hoverText += $"{Helpers.TimeString(smelter.m_secPerProduct * queueSize - smelter.GetBakeTimer())}"; - // 8sec - 10sec (30sec) - // 9sec - 10sec (30sec) - } - - if (smelter.m_requiresRoof && !smelter.m_haveRoof && Mathf.Sin(Time.time * 10f) > 0f) - { - Switch addOreSwitch = smelter.m_addOreSwitch; - addOreSwitch.m_hoverText += $" {smelterRoof}"; - } - Switch addOreSwitch2 = smelter.m_addOreSwitch; - addOreSwitch2.m_hoverText = $"{addOreSwitch2.m_hoverText} \n{useKey} {smelter.m_addOreTooltip}"; + if (smelter.m_emptyOreSwitch && smelter.m_spawnStack) + { + int processedQueueSize = smelter.GetProcessedQueueSize(); + smelter.m_emptyOreSwitch.m_hoverText = $"{smelter.m_name} {processedQueueSize} $piece_smelter_ready \n{useKey} {smelter.m_emptyOreTooltip}"; + } + + int queueSize = smelter.GetQueueSize(); + smelter.m_addOreSwitch.m_hoverText = $"{smelter.m_name} ({queueSize}/{smelter.m_maxOre}) "; + + if (queueSize > 0) // This codeline is run every tick when windmill is on!! + { + BetterUI.Main.log.LogInfo($"{smelter.GetBakeTimer()}, {smelter.m_secPerProduct}, {queueSize}"); + + smelter.m_addOreSwitch.m_hoverText += $"{Helpers.TimeString(smelter.m_secPerProduct * queueSize - smelter.GetBakeTimer())}"; + // 8sec - 10sec (30sec) + // 9sec - 10sec (30sec) + } + + if (smelter.m_requiresRoof && !smelter.m_haveRoof && Mathf.Sin(Time.time * 10f) > 0f) + { + Switch addOreSwitch = smelter.m_addOreSwitch; + addOreSwitch.m_hoverText += $" {smelterRoof}"; + } + + Switch addOreSwitch2 = smelter.m_addOreSwitch; + addOreSwitch2.m_hoverText = $"{addOreSwitch2.m_hoverText} \n{useKey} {smelter.m_addOreTooltip}"; } private static void CalculateSmelterBakeTime(Smelter smelter) { - double deltaTime = smelter.GetDeltaTime(); - float accumulator = smelter.GetAccumulator(); - accumulator += (float)deltaTime; - float power = smelter.m_windmill ? smelter.m_windmill.GetPowerOutput() : 1f; - - while (accumulator >= 1f) - { - accumulator -= 1f; - float fuel = smelter.GetFuel(); - string queuedOre = smelter.GetQueuedOre(); - if ((smelter.m_maxFuel == 0 || fuel > 0f) && queuedOre != "" && smelter.m_secPerProduct > 0f && (!smelter.m_requiresRoof || smelter.m_haveRoof)) + double deltaTime = smelter.GetDeltaTime(); + float accumulator = smelter.GetAccumulator(); + accumulator += (float)deltaTime; + float power = smelter.m_windmill ? smelter.m_windmill.GetPowerOutput() : 1f; + + while (accumulator >= 1f) { - float speed = 1f * power; - if (smelter.m_maxFuel > 0) - { - float usage = smelter.m_secPerProduct / (float)smelter.m_fuelPerProduct; - fuel -= speed / usage; - if (fuel < 0f) fuel = 0f; - smelter.SetFuel(fuel); - } - float bakeTime = smelter.GetBakeTimer(); - bakeTime += speed; - smelter.SetBakeTimer(bakeTime); - if (bakeTime > smelter.m_secPerProduct) - { - smelter.SetBakeTimer(0f); - smelter.RemoveOneOre(); - smelter.QueueProcessed(queuedOre); - } + accumulator -= 1f; + float fuel = smelter.GetFuel(); + string queuedOre = smelter.GetQueuedOre(); + if ((smelter.m_maxFuel == 0 || fuel > 0f) && queuedOre != "" && smelter.m_secPerProduct > 0f && (!smelter.m_requiresRoof || smelter.m_haveRoof)) + { + float speed = 1f * power; + if (smelter.m_maxFuel > 0) + { + float usage = smelter.m_secPerProduct / (float)smelter.m_fuelPerProduct; + fuel -= speed / usage; + if (fuel < 0f) fuel = 0f; + smelter.SetFuel(fuel); + } + + float bakeTime = smelter.GetBakeTimer(); + bakeTime += speed; + smelter.SetBakeTimer(bakeTime); + if (bakeTime > smelter.m_secPerProduct) + { + smelter.SetBakeTimer(0f); + smelter.RemoveOneOre(); + smelter.QueueProcessed(queuedOre); + } + } } - } - if (smelter.GetQueuedOre() == "" || ((float)smelter.m_maxFuel > 0f && smelter.GetFuel() == 0f)) - { - smelter.SpawnProcessed(); - } + if (smelter.GetQueuedOre() == "" || ((float)smelter.m_maxFuel > 0f && smelter.GetFuel() == 0f)) + { + smelter.SpawnProcessed(); + } - smelter.SetAccumulator(accumulator); + smelter.SetAccumulator(accumulator); } - } } \ No newline at end of file diff --git a/BetterUI/Patches/HudElement.cs b/BetterUI/Patches/HudElement.cs index 52c5b1b..c51de65 100644 --- a/BetterUI/Patches/HudElement.cs +++ b/BetterUI/Patches/HudElement.cs @@ -1,156 +1,220 @@ using System; using UnityEngine; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +[Serializable] +public class HudElement { - [Serializable] - public class HudElement - { - // the serialization is NOT done with the unity serializer, so private members ARE serialized, and SerializeField, ISerializationCallbackReceiver and FormerlySerializedAs do not work + // the serialization is NOT done with the unity serializer, so private members ARE serialized, and SerializeField, ISerializationCallbackReceiver and FormerlySerializedAs do not work - private readonly string name; - private readonly string displayName; - private readonly string path; + private readonly string name; + private readonly string displayName; + private readonly string path; - /// - /// Layer Group where the element belongs - /// - private readonly Groups group; + /// + /// Layer Group where the element belongs + /// + private readonly Groups group; - private float x; - private float y; - private float scale; + private float x; + private float y; + private float scale; - // DO NOT rename this field. keep it as 'dimensions'. The deserialization used is NOT unity deserialization, so FormerlySerializedAs does NOT work - private float dimensions; + // DO NOT rename this field. keep it as 'dimensions'. The deserialization used is NOT unity deserialization, so FormerlySerializedAs does NOT work + private float dimensions; - private float xDimensions; + private float xDimensions; - // AnchorMin - private float anchorMinX; + // AnchorMin + private float anchorMinX; - private float anchorMinY; + private float anchorMinY; - // AnchorMax - private float anchorMaxX; + // AnchorMax + private float anchorMaxX; - private float anchorMaxY; + private float anchorMaxY; - public HudElement(string name, string displayName, Groups group, string path, Vector2 position, float scale = 1f, float xDimensions = 1f, float yDimensions = 1f) - { - this.name = name; - this.displayName = displayName; - this.path = path; - this.group = group; - - this.x = position.x; - this.y = position.y; - this.scale = scale; - this.xDimensions = xDimensions; - this.dimensions = yDimensions; - } - - // intentionally no setter - public string Name { get => this.name; } - public string DisplayName { get => this.displayName; } - public string Path { get => this.path; } - public Groups Group { get => this.group; } + public HudElement(string name, string displayName, Groups group, string path, Vector2 position, float scale = 1f, float xDimensions = 1f, float yDimensions = 1f) + { + this.name = name; + this.displayName = displayName; + this.path = path; + this.group = group; + + this.x = position.x; + this.y = position.y; + this.scale = scale; + this.xDimensions = xDimensions; + this.dimensions = yDimensions; + } - public Vector2 Position { get => new Vector2(this.x, this.y); set { this.x = value.x; this.y = value.y; } } + // intentionally no setter + public string Name + { + get => this.name; + } - public Vector2 AnchorMin { get => new Vector2(anchorMinX, anchorMinY); set { this.anchorMinX = value.x; this.anchorMinY = value.y; } } - public Vector2 AnchorMax { get => new Vector2(anchorMaxX, anchorMaxY); set { this.anchorMaxX = value.x; this.anchorMaxY = value.y; } } + public string DisplayName + { + get => this.displayName; + } - public float Scale { get => this.scale; } + public string Path + { + get => this.path; + } - public float XDimensions { get => this.xDimensions; } - public float YDimensions { get => this.dimensions; } + public Groups Group + { + get => this.group; + } - // scale == 0 is intentionally still allowed - public void ChangeScale(float change) + public Vector2 Position + { + get => new Vector2(this.x, this.y); + set { - scale = (float)Math.Round(Mathf.Abs(scale + change), 1); + this.x = value.x; + this.y = value.y; } + } - public void ChangeXDims(float change) + public Vector2 AnchorMin + { + get => new Vector2(anchorMinX, anchorMinY); + set { - xDimensions = Mathf.Max(0.1f, (float)Math.Round(Mathf.Abs(xDimensions + change), 2)); + this.anchorMinX = value.x; + this.anchorMinY = value.y; } + } - public void ChangeYDims(float change) + public Vector2 AnchorMax + { + get => new Vector2(anchorMaxX, anchorMaxY); + set { - dimensions = Mathf.Max(0.1f, (float)Math.Round(Mathf.Abs(dimensions + change), 2)); + this.anchorMaxX = value.x; + this.anchorMaxY = value.y; } + } - // called manually in CustomHud.Load because unitys ISerializationCallbackReceiver does not work with the used deserializer - public void OnAfterDeserialize() - { - // this especially catches backwards compatibility, because all older setups will have xDimensions == 0 (default values do not work with the deserializer), so keep this as xDimensions = 1f; - if (xDimensions < 0.1f) - { - xDimensions = 1f; - } - - if (dimensions < 0.1f) - { - dimensions = 1f; - } - } + public float Scale + { + get => this.scale; } - public readonly struct Element + public float XDimensions { - /// - /// Used as an unique value, unique name to the element. - /// If no path is given, this needs to be the elements path as well. - /// - private readonly string name; // We see this as unique. Might cause issues later on? + get => this.xDimensions; + } - /// - /// Use custom name on the template when user edits HUD - /// - private readonly string displayName; + public float YDimensions + { + get => this.dimensions; + } - /// - /// On what layer group should the element be editable. This is as well the parent element where path is related. - /// - private readonly Groups group; + // scale == 0 is intentionally still allowed + public void ChangeScale(float change) + { + scale = (float)Math.Round(Mathf.Abs(scale + change), 1); + } - /// - /// Path of the element. Relative to parent. - /// - private readonly string locationPath; + public void ChangeXDims(float change) + { + xDimensions = Mathf.Max(0.1f, (float)Math.Round(Mathf.Abs(xDimensions + change), 2)); + } - public string Name { get => name; } - public string DisplayName { get => displayName; } - public Groups Group { get => group; } - public string LocationPath { get => locationPath; } + public void ChangeYDims(float change) + { + dimensions = Mathf.Max(0.1f, (float)Math.Round(Mathf.Abs(dimensions + change), 2)); + } - public Element(string name, Groups group, string locationPath = "", string displayName = "") + // called manually in CustomHud.Load because unitys ISerializationCallbackReceiver does not work with the used deserializer + public void OnAfterDeserialize() + { + // this especially catches backwards compatibility, because all older setups will have xDimensions == 0 (default values do not work with the deserializer), so keep this as xDimensions = 1f; + if (xDimensions < 0.1f) + { + xDimensions = 1f; + } + + if (dimensions < 0.1f) { - this.name = name; - this.group = group; - this.locationPath = locationPath == "" ? name : locationPath; - this.displayName = displayName == "" ? name : displayName; + dimensions = 1f; } } +} - public enum Groups +public readonly struct Element +{ + /// + /// Used as an unique value, unique name to the element. + /// If no path is given, this needs to be the elements path as well. + /// + private readonly string name; // We see this as unique. Might cause issues later on? + + /// + /// Use custom name on the template when user edits HUD + /// + private readonly string displayName; + + /// + /// On what layer group should the element be editable. This is as well the parent element where path is related. + /// + private readonly Groups group; + + /// + /// Path of the element. Relative to parent. + /// + private readonly string locationPath; + + public string Name { - HudRoot, - Inventory, - Other // Is this enough, or should we just specify everything? + get => name; } - public enum ParentRoot + public string DisplayName { - Hud, - Inventory, - HudMessage, - TopLeftMessage, - Chat, - EnemyHud, - Store, - Menu + get => displayName; } + + public Groups Group + { + get => group; + } + + public string LocationPath + { + get => locationPath; + } + + public Element(string name, Groups group, string locationPath = "", string displayName = "") + { + this.name = name; + this.group = group; + this.locationPath = locationPath == "" ? name : locationPath; + this.displayName = displayName == "" ? name : displayName; + } +} + +public enum Groups +{ + HudRoot, + Inventory, + Other // Is this enough, or should we just specify everything? +} + +public enum ParentRoot +{ + Hud, + Inventory, + HudMessage, + TopLeftMessage, + Chat, + EnemyHud, + Store, + Menu } \ No newline at end of file diff --git a/BetterUI/Patches/ItemIconUpdater.cs b/BetterUI/Patches/ItemIconUpdater.cs index f0a523b..690e862 100644 --- a/BetterUI/Patches/ItemIconUpdater.cs +++ b/BetterUI/Patches/ItemIconUpdater.cs @@ -1,25 +1,24 @@ using UnityEngine; using UnityEngine.UI; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +internal class ItemIconUpdater : MonoBehaviour { - internal class ItemIconUpdater : MonoBehaviour - { - private Vector3 origScale; - private Image icon; + private Vector3 origScale; + private Image icon; - public void Setup(Image icon) - { - this.icon = icon; - this.origScale = icon.transform.localScale; - IconScaleSize_SettingChanged(); + public void Setup(Image icon) + { + this.icon = icon; + this.origScale = icon.transform.localScale; + IconScaleSize_SettingChanged(); - Main.iconScaleSize.SettingChanged += (_, _) => IconScaleSize_SettingChanged(); - } + Main.iconScaleSize.SettingChanged += (_, _) => IconScaleSize_SettingChanged(); + } - private void IconScaleSize_SettingChanged() - { - icon.transform.localScale = origScale * Mathf.Max(Main.iconScaleSize.Value, 0.1f); - } + private void IconScaleSize_SettingChanged() + { + icon.transform.localScale = origScale * Mathf.Max(Main.iconScaleSize.Value, 0.1f); } } \ No newline at end of file diff --git a/BetterUI/Patches/Items.cs b/BetterUI/Patches/Items.cs index 6b59a76..ca746c0 100644 --- a/BetterUI/Patches/Items.cs +++ b/BetterUI/Patches/Items.cs @@ -4,316 +4,325 @@ using System.Text; using System.Threading.Tasks; using HarmonyLib; +using TMPro; using UnityEngine; using UnityEngine.UI; -namespace BetterUI.Patches +namespace BetterUI.Patches; + +public static class ElementHelper { - public static class ElementHelper + public static void UpdateElement(GuiBar durabilityBar, Image icon, ItemDrop.ItemData item) { - public static void UpdateElement(GuiBar durabilityBar, Image icon, ItemDrop.ItemData item) + if (Main.durabilityBarColorPalette.Value != Main.DurabilityBarStyle.Disabled && item.m_shared.m_useDurability) { - if (Main.durabilityBarColorPalette.Value != Main.DurabilityBarStyle.Disabled && item.m_shared.m_useDurability) + if (item.m_durability <= 0f) { - if (item.m_durability <= 0f) - { - // Item has no durability, original code will handle this - } - else // Item has durability left - { - DurabilityBar.UpdateColor(durabilityBar, item.GetDurabilityPercentage()); - } + // Item has no durability, original code will handle this + } + else // Item has durability left + { + DurabilityBar.UpdateColor(durabilityBar, item.GetDurabilityPercentage()); } } } +} - static class DurabilityBar - { +static class DurabilityBar +{ private static readonly Color[] normal = new Color[] { - new Color(0.11765f, 0.72941f, 0.03529f, 1f), // Green - new Color(0.72941f, 0.72941f, 0.03529f, 1f), // Yellow - new Color(0.72941f, 0.34902f, 0.03529f, 1f), // Orange - new Color(0.72941f, 0.03529f, 0.03529f, 1f) // Red + new Color(0.11765f, 0.72941f, 0.03529f, 1f), // Green + new Color(0.72941f, 0.72941f, 0.03529f, 1f), // Yellow + new Color(0.72941f, 0.34902f, 0.03529f, 1f), // Orange + new Color(0.72941f, 0.03529f, 0.03529f, 1f) // Red }; + private static readonly Color[] protanopia = new Color[] { - new Color(1f, 1f, 1f, 1f), // Green -> White - new Color(0.878f, 1f, 0f, 1f), // Yellow -> Light Yellow - new Color(0.192f, 0.859f, 0.573f, 1f), // Orange -> Light Cyan - new Color(0.11f, 0.435f, 0.973f, 1f) // Red -> Blue + new Color(1f, 1f, 1f, 1f), // Green -> White + new Color(0.878f, 1f, 0f, 1f), // Yellow -> Light Yellow + new Color(0.192f, 0.859f, 0.573f, 1f), // Orange -> Light Cyan + new Color(0.11f, 0.435f, 0.973f, 1f) // Red -> Blue }; private static readonly Array[] colorArray = new Array[] { - normal, - protanopia + normal, + protanopia }; private static readonly Color[] activeColor = colorArray[(int)Main.durabilityBarColorPalette.Value] as Color[]; public static void UpdateColor(GuiBar durabilityBar, float durability) { - durabilityBar.SetValue(durability); - // Might be to update items colorbar? This is from original code. - durabilityBar.ResetColor(); - // Between 1f - 0f - switch (durability) - { - case float n when (n >= 0.75f): - // Color green - durabilityBar.SetColor(activeColor[0]); - break; - case float n when (n >= 0.50f): - // Color yellow - durabilityBar.SetColor(activeColor[1]); - break; - case float n when (n >= 0.25f): - // Color Orange - durabilityBar.SetColor(activeColor[2]); - break; - case float n when (n >= 0f): - // Color Red - durabilityBar.SetColor(activeColor[3]); - break; - } + durabilityBar.SetValue(durability); + // Might be to update items colorbar? This is from original code. + durabilityBar.ResetColor(); + // Between 1f - 0f + switch (durability) + { + case float n when (n >= 0.75f): + // Color green + durabilityBar.SetColor(activeColor[0]); + break; + case float n when (n >= 0.50f): + // Color yellow + durabilityBar.SetColor(activeColor[1]); + break; + case float n when (n >= 0.25f): + // Color Orange + durabilityBar.SetColor(activeColor[2]); + break; + case float n when (n >= 0f): + // Color Red + durabilityBar.SetColor(activeColor[3]); + break; + } } - } +} - static class Stars - { +static class Stars +{ private static Color starColor = new(1.0f, 0.85882f, 0.23137f, 1.0f); public static void Draw(InventoryGrid.Element element, int quality_lvl) { - string stars; - if(quality_lvl >= 5) // Fix for modded items... - { - stars = $"{quality_lvl}x \u2605"; // Could be ★x5 or ★x99999 - element.m_quality.alignment = TextAnchor.MiddleRight; - element.m_quality.rectTransform.sizeDelta = new Vector2(60f, 20f); - if (quality_lvl > 99998) stars = $"MODDED \u2605"; // For them wack guys - } else - { - stars = Helpers.Repeat("\u2605", quality_lvl); - element.m_quality.rectTransform.sizeDelta = new Vector2(quality_lvl * 10f, 20f); - } - - UnityEngine.Object.Destroy(element.m_quality.GetComponent()); - element.m_quality.text = $"{stars}"; - element.m_quality.color = starColor; - - // Parent size = 64x64, quality size = 20x20, top-right (0,0) -> (-4f,-10f) - element.m_quality.rectTransform.anchoredPosition = new Vector2(-4f, -6f); - - // TODO: Spawned items might break this, as they could have 99 stars. - // Possible fix, after x amount switch to: ★x[amount] = ★x99 + string stars; + element.m_quality.textWrappingMode = TextWrappingModes.PreserveWhitespaceNoWrap; + if (quality_lvl >= 5) // Fix for modded items... + { + stars = $"{quality_lvl}x \u2605"; // Could be ★x5 or ★x99999 + element.m_quality.alignment = TextAlignmentOptions.MidlineRight; + element.m_quality.rectTransform.sizeDelta = new Vector2(60f, 20f); + if (quality_lvl > 99998) stars = $"MODDED \u2605"; // For them wack guys + } + else + { + stars = Helpers.Repeat("\u2605", quality_lvl); + element.m_quality.rectTransform.sizeDelta = new Vector2(quality_lvl * 10f, 20f); + } + + UnityEngine.Object.Destroy(element.m_quality.GetComponent()); + element.m_quality.text = $"{stars}"; + element.m_quality.color = starColor; + + // Parent size = 64x64, quality size = 20x20, top-right (0,0) -> (-4f,-10f) + element.m_quality.rectTransform.anchoredPosition = new Vector2(-4f, -6f); + + // TODO: Spawned items might break this, as they could have 99 stars. + // Possible fix, after x amount switch to: ★x[amount] = ★x99 } + public static string HoverText(int quality_lvl) { - if ( quality_lvl >= 5) // Fix modded items - { - return $"{quality_lvl}x\u2605"; - } else if (quality_lvl > 99999) // For them HC Modders - { - return $"Modded"; - } else return Helpers.Repeat("\u2605", quality_lvl); + if (quality_lvl >= 5) // Fix modded items + { + return $"{quality_lvl}x\u2605"; + } + else if (quality_lvl > 99999) // For them HC Modders + { + return $"Modded"; + } + else return Helpers.Repeat("\u2605", quality_lvl); } - } - - static class InventoryArmorTooltip - { +} + +static class InventoryArmorTooltip +{ // Should we just inherit from UITooltip and add our own stuff? public static UITooltip tooltip = null; - public static Text m_armor = null; + public static TMP_Text m_armor = null; public static void Awake(InventoryGui ig) { - Transform baContainer = ig.m_armor.transform.parent; - - // Save old values - Transform background = Utils.FindChild(baContainer, "bkg"); - Transform icon = Utils.FindChild(baContainer, "armor_icon"); - Transform text = Utils.FindChild(baContainer, "ac_text"); - - GameObject prefab = ig.m_containerGrid.m_elementPrefab; - if (prefab == null) return; - // Create an copy of Inventory Element, Important Components = Image, Tooltip - GameObject InventoryElement = UnityEngine.Object.Instantiate(prefab, baContainer); - - // Deactivate stuff - InventoryElement.transform.Find("equiped").GetComponent().enabled = false; - InventoryElement.transform.Find("queued").GetComponent().enabled = false; - InventoryElement.transform.Find("icon").GetComponent().enabled = false; - InventoryElement.transform.Find("amount").GetComponent().enabled = false; - InventoryElement.transform.Find("durability").gameObject.SetActive(false); - InventoryElement.transform.Find("binding").GetComponent().enabled = false; - InventoryElement.transform.Find("quality").GetComponent().enabled = false; - InventoryElement.transform.Find("selected").gameObject.SetActive(false); - InventoryElement.transform.Find("noteleport").GetComponent().enabled = false; - InventoryElement.transform.Find("foodicon").GetComponent().enabled = false; - - // Delete components - UnityEngine.Object.Destroy(InventoryElement.GetComponent()); - UnityEngine.Object.Destroy(InventoryElement.GetComponent