using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Hooked.Fishing; using Hooked.UI; using JetBrains.Annotations; using LocalizationManager; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UIManager; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.U2D; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Callbacks; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Hooked")] [assembly: AssemblyDescription("A Stardew Valley style fishing minigame for Valheim.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("Hooked")] [assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")] [assembly: AssemblyFileVersion("1.1.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LocalizationManager { [PublicAPI] public class Localizer { private static readonly Dictionary>> PlaceholderProcessors; private static readonly Dictionary> loadedTexts; private static readonly ConditionalWeakTable localizationLanguage; private static readonly List> localizationObjects; private static BaseUnityPlugin? _plugin; private static readonly List fileExtensions; private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } public static event Action? OnLocalizationComplete; private static void UpdatePlaceholderText(Localization localization, string key) { localizationLanguage.TryGetValue(localization, out string value); string text = loadedTexts[value][key]; if (PlaceholderProcessors.TryGetValue(key, out Dictionary> value2)) { text = value2.Aggregate(text, (string current, KeyValuePair> kv) => current.Replace("{" + kv.Key + "}", kv.Value())); } localization.AddWord(key, text); } public static void AddPlaceholder(string key, string placeholder, ConfigEntry config, Func? convertConfigValue = null) where T : notnull { if (convertConfigValue == null) { convertConfigValue = (T val) => val.ToString(); } if (!PlaceholderProcessors.ContainsKey(key)) { PlaceholderProcessors[key] = new Dictionary>(); } config.SettingChanged += delegate { UpdatePlaceholder(); }; if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage())) { UpdatePlaceholder(); } void UpdatePlaceholder() { PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value); UpdatePlaceholderText(Localization.instance, key); } } public static void AddText(string key, string text) { List> list = new List>(); foreach (WeakReference localizationObject in localizationObjects) { if (localizationObject.TryGetTarget(out var target)) { Dictionary dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)]; if (!target.m_translations.ContainsKey(key)) { dictionary[key] = text; target.AddWord(key, text); } } else { list.Add(localizationObject); } } foreach (WeakReference item in list) { localizationObjects.Remove(item); } } public static void Load() { _ = plugin; } public static void LoadLocalizationLater(Localization __instance) { LoadLocalization(Localization.instance, __instance.GetSelectedLanguage()); } public static void SafeCallLocalizeComplete() { Localizer.OnLocalizationComplete?.Invoke(); } private static void LoadLocalization(Localization __instance, string language) { if (!localizationLanguage.Remove(__instance)) { localizationObjects.Add(new WeakReference(__instance)); } localizationLanguage.Add(__instance, language); Dictionary dictionary = new Dictionary(); foreach (string item in from f in Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath), plugin.Info.Metadata.Name + ".*", SearchOption.AllDirectories) where fileExtensions.IndexOf(Path.GetExtension(f)) >= 0 select f) { string[] array = Path.GetFileNameWithoutExtension(item).Split(new char[1] { '.' }); if (array.Length >= 2) { string text = array[1]; if (dictionary.ContainsKey(text)) { Debug.LogWarning((object)("Duplicate key " + text + " found for " + plugin.Info.Metadata.Name + ". The duplicate file found at " + item + " will be skipped.")); } else { dictionary[text] = item; } } } byte[] array2 = LoadTranslationFromAssembly("English"); if (array2 == null) { throw new Exception("Found no English localizations in mod " + plugin.Info.Metadata.Name + ". Expected an embedded resource translations/English.json or translations/English.yml."); } Dictionary dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize>(Encoding.UTF8.GetString(array2)); if (dictionary2 == null) { throw new Exception("Localization for mod " + plugin.Info.Metadata.Name + " failed: Localization file was empty."); } string text2 = null; if (language != "English") { if (dictionary.TryGetValue(language, out var value)) { text2 = File.ReadAllText(value); } else { byte[] array3 = LoadTranslationFromAssembly(language); if (array3 != null) { text2 = Encoding.UTF8.GetString(array3); } } } if (text2 == null && dictionary.TryGetValue("English", out var value2)) { text2 = File.ReadAllText(value2); } if (text2 != null) { foreach (KeyValuePair item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize>(text2) ?? new Dictionary()) { dictionary2[item2.Key] = item2.Value; } } loadedTexts[language] = dictionary2; foreach (KeyValuePair item3 in dictionary2) { UpdatePlaceholderText(__instance, item3.Key); } } static Localizer() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Expected O, but got Unknown PlaceholderProcessors = new Dictionary>>(); loadedTexts = new Dictionary>(); localizationLanguage = new ConditionalWeakTable(); localizationObjects = new List>(); fileExtensions = new List(2) { ".json", ".yml" }; Harmony val = new Harmony("org.bepinex.helpers.LocalizationManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalization", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "SetupGui", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalizationLater", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "SafeCallLocalizeComplete", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static byte[]? LoadTranslationFromAssembly(string language) { foreach (string fileExtension in fileExtensions) { byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension); if (array != null) { return array; } } return null; } public static byte[]? ReadEmbeddedFileBytes(string resourceFileName, Assembly? containingAssembly = null) { using MemoryStream memoryStream = new MemoryStream(); if ((object)containingAssembly == null) { containingAssembly = Assembly.GetCallingAssembly(); } string text = containingAssembly.GetManifestResourceNames().FirstOrDefault((string str) => str.EndsWith(resourceFileName, StringComparison.Ordinal)); if (text != null) { containingAssembly.GetManifestResourceStream(text)?.CopyTo(memoryStream); } return (memoryStream.Length == 0L) ? null : memoryStream.ToArray(); } } public static class LocalizationManagerVersion { public const string Version = "1.4.1"; } } namespace Hooked { [BepInPlugin("Azumatt.Hooked", "Hooked", "1.1.0")] public class HookedPlugin : BaseUnityPlugin { public enum Toggle { On = 1, Off = 0 } public enum BarAnchor { Left, Right } public enum TutorialMode { Always, Beginner, Never } public enum DifficultyPreset { Relaxed, Casual, Normal, Challenging, Brutal } internal const string ModName = "Hooked"; internal const string ModVersion = "1.1.0"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.Hooked"; private static readonly string ConfigFileName = "Azumatt.Hooked.cfg"; private static readonly string ConfigFileFullPath; internal static string ConnectionError; public static readonly ManualLogSource HookedLogger; private static readonly ConfigSync ConfigSync; private static HookedPlugin self; private readonly Harmony harmony = new Harmony("Azumatt.Hooked"); private static readonly Dictionary DefaultBiomeLoot; private static ConfigEntry serverConfigLocked; public static ConfigEntry minigameEnabled; public static ConfigEntry difficulty; public static ConfigEntry biteProximityBonus; public static ConfigEntry autoHook; public static ConfigEntry barHeightBase; public static ConfigEntry barHeightPerLevel; public static ConfigEntry startingProgress; public static ConfigEntry firstCatchProgress; public static ConfigEntry fillRate; public static ConfigEntry drainRate; public static ConfigEntry barGravity; public static ConfigEntry inBarGravityScale; public static ConfigEntry difficultyScale; public static ConfigEntry escapeDifficultyBonus; public static ConfigEntry reelInFrom; public static ConfigEntry minLineLength; public static ConfigEntry lineBreaks; public static ConfigEntry biteRangeBonus; public static ConfigEntry beginnerAssist; public static ConfigEntry beginnerSkillLevel; public static ConfigEntry beginnerDifficultyScale; public static ConfigEntry beginnerDrainScale; public static ConfigEntry beginnerBarBonus; public static ConfigEntry fishOverrides; public static ConfigEntry flexibleBait; public static ConfigEntry baitTackle; public static ConfigEntry lunkers; public static ConfigEntry lunkerChance; public static ConfigEntry lunkerSkillBonus; public static ConfigEntry lunkerTierBonus; public static ConfigEntry lunkerDifficultyBonus; public static ConfigEntry lunkerWanderScale; public static ConfigEntry lunkerSkillScale; public static ConfigEntry lunkerQualityBonus; public static ConfigEntry lunkerTreasure; public static ConfigEntry lunkerTreasureRolls; public static ConfigEntry depthRewards; public static ConfigEntry shallowDepth; public static ConfigEntry fullDepth; public static ConfigEntry depthTreasureBonus; public static ConfigEntry depthSizeBonus; public static ConfigEntry depthSkillBonus; public static ConfigEntry depthLunkerBonus; public static ConfigEntry freshCatch; public static ConfigEntry freshCatchNeedsPerfect; public static ConfigEntry freshCatchDuration; public static ConfigEntry freshCatchCarryWeight; public static ConfigEntry freshCatchStaminaRegen; public static ConfigEntry freshCatchEitrRegen; public static ConfigEntry sizeFromSkill; public static ConfigEntry qualityFromSize; public static ConfigEntry qualityLossSteps; public static ConfigEntry perfectUpgradesQuality; public static ConfigEntry skillGainScale; public static ConfigEntry skillGainOnLoss; public static ConfigEntry skillFillBonus; public static ConfigEntry treasureEnabled; public static ConfigEntry treasureChance; public static ConfigEntry treasureSkillBonus; public static ConfigEntry treasureTierBonus; public static ConfigEntry treasureFillRate; public static ConfigEntry treasureDrainRate; public static ConfigEntry treasureRollsMin; public static ConfigEntry treasureRollsMax; public static ConfigEntry treasureLoot; public static ConfigEntry treasureGuard; public static ConfigEntry treasureBlocklist; public static ConfigEntry treasureKnownOnly; public static ConfigEntry treasureBiomeLoot; public static ConfigEntry treasureBiomeAddsToBase; public static readonly Dictionary> treasureBiomeTables; public static ConfigEntry staminaScale; public static ConfigEntry reelStaminaScale; public static ConfigEntry fishFinder; public static ConfigEntry soundEnabled; public static ConfigEntry soundVolume; public static ConfigEntry reelClipNames; public static ConfigEntry shakeStrength; public static ConfigEntry uiScale; public static ConfigEntry fishIconScale; public static ConfigEntry tutorial; public static ConfigEntry uiAnchor; public static ConfigEntry uiOffsetX; public static ConfigEntry uiOffsetY; public void Awake() { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Expected O, but got Unknown //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Expected O, but got Unknown //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Expected O, but got Unknown //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Expected O, but got Unknown //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Expected O, but got Unknown //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Expected O, but got Unknown //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Expected O, but got Unknown //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Expected O, but got Unknown //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Expected O, but got Unknown //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Expected O, but got Unknown //IL_0356: Unknown result type (might be due to invalid IL or missing references) //IL_0361: Expected O, but got Unknown //IL_038e: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Expected O, but got Unknown //IL_03c6: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Expected O, but got Unknown //IL_0434: Unknown result type (might be due to invalid IL or missing references) //IL_043f: Expected O, but got Unknown //IL_046c: Unknown result type (might be due to invalid IL or missing references) //IL_0477: Expected O, but got Unknown //IL_04a4: Unknown result type (might be due to invalid IL or missing references) //IL_04af: Expected O, but got Unknown //IL_04dc: Unknown result type (might be due to invalid IL or missing references) //IL_04e7: Expected O, but got Unknown //IL_05cc: Unknown result type (might be due to invalid IL or missing references) //IL_05d7: Expected O, but got Unknown //IL_061f: Unknown result type (might be due to invalid IL or missing references) //IL_062a: Expected O, but got Unknown //IL_0657: Unknown result type (might be due to invalid IL or missing references) //IL_0662: Expected O, but got Unknown //IL_06aa: Unknown result type (might be due to invalid IL or missing references) //IL_06b5: Expected O, but got Unknown //IL_06e2: Unknown result type (might be due to invalid IL or missing references) //IL_06ed: Expected O, but got Unknown //IL_071a: Unknown result type (might be due to invalid IL or missing references) //IL_0725: Expected O, but got Unknown //IL_0752: Unknown result type (might be due to invalid IL or missing references) //IL_075d: Expected O, but got Unknown //IL_078a: Unknown result type (might be due to invalid IL or missing references) //IL_0795: Expected O, but got Unknown //IL_07c2: Unknown result type (might be due to invalid IL or missing references) //IL_07cd: Expected O, but got Unknown //IL_07ee: Unknown result type (might be due to invalid IL or missing references) //IL_07f9: Expected O, but got Unknown //IL_0836: Unknown result type (might be due to invalid IL or missing references) //IL_0841: Expected O, but got Unknown //IL_0889: Unknown result type (might be due to invalid IL or missing references) //IL_0894: Expected O, but got Unknown //IL_08c1: Unknown result type (might be due to invalid IL or missing references) //IL_08cc: Expected O, but got Unknown //IL_08f9: Unknown result type (might be due to invalid IL or missing references) //IL_0904: Expected O, but got Unknown //IL_0931: Unknown result type (might be due to invalid IL or missing references) //IL_093c: Expected O, but got Unknown //IL_0969: Unknown result type (might be due to invalid IL or missing references) //IL_0974: Expected O, but got Unknown //IL_09a1: Unknown result type (might be due to invalid IL or missing references) //IL_09ac: Expected O, but got Unknown //IL_0a0f: Unknown result type (might be due to invalid IL or missing references) //IL_0a1a: Expected O, but got Unknown //IL_0a47: Unknown result type (might be due to invalid IL or missing references) //IL_0a52: Expected O, but got Unknown //IL_0a7f: Unknown result type (might be due to invalid IL or missing references) //IL_0a8a: Expected O, but got Unknown //IL_0ab7: Unknown result type (might be due to invalid IL or missing references) //IL_0ac2: Expected O, but got Unknown //IL_0b0a: Unknown result type (might be due to invalid IL or missing references) //IL_0b15: Expected O, but got Unknown //IL_0b42: Unknown result type (might be due to invalid IL or missing references) //IL_0b4d: Expected O, but got Unknown //IL_0b7a: Unknown result type (might be due to invalid IL or missing references) //IL_0b85: Expected O, but got Unknown //IL_0bb2: Unknown result type (might be due to invalid IL or missing references) //IL_0bbd: Expected O, but got Unknown //IL_0bea: Unknown result type (might be due to invalid IL or missing references) //IL_0bf5: Expected O, but got Unknown //IL_0c17: Unknown result type (might be due to invalid IL or missing references) //IL_0c22: Expected O, but got Unknown //IL_0c44: Unknown result type (might be due to invalid IL or missing references) //IL_0c4f: Expected O, but got Unknown //IL_0d95: Unknown result type (might be due to invalid IL or missing references) //IL_0d9a: Unknown result type (might be due to invalid IL or missing references) //IL_0db7: Unknown result type (might be due to invalid IL or missing references) //IL_0df9: Unknown result type (might be due to invalid IL or missing references) //IL_0e48: Unknown result type (might be due to invalid IL or missing references) //IL_0e53: Expected O, but got Unknown //IL_0e80: Unknown result type (might be due to invalid IL or missing references) //IL_0e8b: Expected O, but got Unknown //IL_0f28: Unknown result type (might be due to invalid IL or missing references) //IL_0f33: Expected O, but got Unknown //IL_0f60: Unknown result type (might be due to invalid IL or missing references) //IL_0f6b: Expected O, but got Unknown //IL_0f98: Unknown result type (might be due to invalid IL or missing references) //IL_0fa3: Expected O, but got Unknown //IL_0fd0: Unknown result type (might be due to invalid IL or missing references) //IL_0fdb: Expected O, but got Unknown //IL_1023: Unknown result type (might be due to invalid IL or missing references) //IL_102e: Expected O, but got Unknown //IL_105b: Unknown result type (might be due to invalid IL or missing references) //IL_1066: Expected O, but got Unknown self = this; Localizer.Load(); bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "Only server admins can change synced settings."); ConfigSync.AddLockingConfigEntry(serverConfigLocked); minigameEnabled = config("2 - Minigame", "Enabled", Toggle.On, "Runs the bobber-bar fight. Off uses vanilla line pulling."); difficulty = config("2 - Minigame", "Difficulty", DifficultyPreset.Normal, "Fight preset. Normal leaves the settings below alone."); biteProximityBonus = config("2 - Minigame", "Bite Proximity Bonus", 0.2f, new ConfigDescription("Extra bite chance at point-blank range. 0 keeps vanilla odds.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); autoHook = config("2 - Minigame", "Auto Hook", Toggle.On, "Hooks fish as soon as they bite."); barHeightBase = config("2 - Minigame", "Bar Height", 96, new ConfigDescription("Green bar height at Fishing 0.", (AcceptableValueBase)(object)new AcceptableValueRange(32, 400), Array.Empty())); barHeightPerLevel = config("2 - Minigame", "Bar Height Per Level", 8, new ConfigDescription("Bar height gained per 10 Fishing.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 40), Array.Empty())); startingProgress = config("2 - Minigame", "Starting Progress", 0.3f, new ConfigDescription("Catch meter at the start of each fight.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 0.9f), Array.Empty())); firstCatchProgress = config("2 - Minigame", "First Catch Progress", 0.1f, new ConfigDescription("Catch meter for this character's first fish. Match Starting Progress to disable.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 0.9f), Array.Empty())); fillRate = config("2 - Minigame", "Fill Rate", 0.002f, new ConfigDescription("Catch meter gained per 1/60s inside the bar.", (AcceptableValueBase)(object)new AcceptableValueRange(0.0002f, 0.02f), Array.Empty())); drainRate = config("2 - Minigame", "Drain Rate", 0.003f, new ConfigDescription("Catch meter lost per 1/60s outside the bar.", (AcceptableValueBase)(object)new AcceptableValueRange(0.0002f, 0.02f), Array.Empty())); barGravity = config("2 - Minigame", "Bar Gravity", 0.25f, new ConfigDescription("Strength of the bar's rise and fall.", (AcceptableValueBase)(object)new AcceptableValueRange(0.05f, 1f), Array.Empty())); skillFillBonus = config("2 - Minigame", "Skill Fill Bonus", 2f, new ConfigDescription("Fill rate multiplier at Fishing 100.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 5f), Array.Empty())); inBarGravityScale = config("2 - Minigame", "In Bar Gravity Scale", 0.6f, new ConfigDescription("Bar gravity while the fish is inside. Lower is steadier.", (AcceptableValueBase)(object)new AcceptableValueRange(0.1f, 1f), Array.Empty())); difficultyScale = config("2 - Minigame", "Difficulty Scale", 1f, new ConfigDescription("Scales derived fish difficulty. Overrides ignore it.", (AcceptableValueBase)(object)new AcceptableValueRange(0.1f, 3f), Array.Empty())); escapeDifficultyBonus = config("2 - Minigame", "Escape Difficulty Bonus", 15f, new ConfigDescription("Difficulty added while the fish thrashes.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 60f), Array.Empty())); reelInFrom = config("2 - Minigame", "Reel In From", 0.75f, new ConfigDescription("Catch meter where the float starts coming in.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); minLineLength = config("2 - Minigame", "Minimum Line Length", 4f, new ConfigDescription("Closest the float comes before the catch, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange(0.5f, 25f), Array.Empty())); biteRangeBonus = config("2 - Minigame", "Bite Range Bonus", 4f, new ConfigDescription("Hook range added at Fishing 100, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 20f), Array.Empty())); lineBreaks = config("2 - Minigame", "Line Breaks", Toggle.On, "Breaks the line past the rod's maximum range."); beginnerAssist = config("2 - Minigame", "Beginner Assist", Toggle.On, "Enables the early bar and drain help."); beginnerSkillLevel = config("2 - Minigame", "Beginner Skill Level", 10f, new ConfigDescription("Fishing level where beginner help and tutorial stop.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 100f), Array.Empty())); beginnerDifficultyScale = config("2 - Minigame", "Beginner Difficulty Scale", 1f, new ConfigDescription("Difficulty multiplier at Fishing 0. 1 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange(0.1f, 1f), Array.Empty())); beginnerDrainScale = config("2 - Minigame", "Beginner Drain Scale", 0.67f, new ConfigDescription("Drain multiplier at Fishing 0.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); beginnerBarBonus = config("2 - Minigame", "Beginner Bar Bonus", 40f, new ConfigDescription("Bar height added at Fishing 0.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 200f), Array.Empty())); fishOverrides = config("3 - Fish", "Overrides", "", "Fish1=60:Dart, Fish3=85. Patterns: Mixed, Dart, Smooth, Sinker, Floater."); fishOverrides.SettingChanged += delegate { FishTuning.ParseOverrides(fishOverrides.Value); }; FishTuning.ParseOverrides(fishOverrides.Value); flexibleBait = config("3 - Fish / Bait", "Flexible Bait", Toggle.On, "After you discover the required bait, any fishing bait can hook that fish. The equipped bait is still spent."); baitTackle = config("3 - Fish / Bait", "Bait Benefits", Toggle.On, "Trophy-crafted bait gives its fixed fishing benefit."); sizeFromSkill = config("4 - Rewards", "Size From Skill", Toggle.On, "Fishing skill and deep water can add one or two quality levels."); qualityFromSize = config("4 - Rewards", "Misses Lower Quality", Toggle.On, "Time outside the bar can lower fish quality."); qualityLossSteps = config("4 - Rewards", "Quality Loss Steps", 4, new ConfigDescription("Number of 0.8s misses that remove one quality level.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 40), Array.Empty())); perfectUpgradesQuality = config("4 - Rewards", "Perfect Upgrades Quality", Toggle.On, "Perfect catches gain one quality level."); skillGainScale = config("4 - Rewards", "Skill Gain Scale", 1f, new ConfigDescription("Fishing XP multiplier.", (AcceptableValueBase)(object)new AcceptableValueRange(0.01f, 4f), Array.Empty())); skillGainOnLoss = config("4 - Rewards", "Skill Gain On Loss", 0.5f, new ConfigDescription("XP share paid on escape, scaled by peak meter.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); lunkers = config("4 - Rewards / Lunkers", "Enabled", Toggle.On, "Enables rare, harder fish with better rewards."); lunkerChance = config("4 - Rewards / Lunkers", "Chance", 0.03f, new ConfigDescription("Base chance per hooked fish.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); lunkerSkillBonus = config("4 - Rewards / Lunkers", "Skill Bonus", 0.05f, new ConfigDescription("Chance added at Fishing 100.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); lunkerTierBonus = config("4 - Rewards / Lunkers", "Tier Bonus", 0.04f, new ConfigDescription("Chance added for the hardest fish.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); lunkerDifficultyBonus = config("4 - Rewards / Lunkers", "Difficulty Bonus", 15f, new ConfigDescription("Difficulty added to lunkers.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 40f), Array.Empty())); lunkerWanderScale = config("4 - Rewards / Lunkers", "Wander Scale", 1f, new ConfigDescription("Lunker target-change rate. 1 leaves it alone.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 5f), Array.Empty())); lunkerSkillScale = config("4 - Rewards / Lunkers", "Skill Scale", 5f, new ConfigDescription("Lunker XP multiplier.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 20f), Array.Empty())); lunkerQualityBonus = config("4 - Rewards / Lunkers", "Quality Bonus", 1, new ConfigDescription("Quality levels added to lunkers.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 4), Array.Empty())); lunkerTreasure = config("4 - Rewards / Lunkers", "Guaranteed Treasure", Toggle.On, "Lunkers always carry treasure."); lunkerTreasureRolls = config("4 - Rewards / Lunkers", "Treasure Rolls", 1, new ConfigDescription("Extra loot rolls in a lunker chest.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 10), Array.Empty())); depthRewards = config("4 - Rewards / Depth", "Enabled", Toggle.On, "Enables rewards for deeper water."); shallowDepth = config("4 - Rewards / Depth", "Shallow Depth", 5f, new ConfigDescription("Water depth where bonuses start, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 50f), Array.Empty())); fullDepth = config("4 - Rewards / Depth", "Full Depth", 15f, new ConfigDescription("Water depth where bonuses max out, in meters.", (AcceptableValueBase)(object)new AcceptableValueRange(2f, 100f), Array.Empty())); depthTreasureBonus = config("4 - Rewards / Depth", "Treasure Bonus", 0.08f, new ConfigDescription("Treasure chance added at full depth.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); depthSizeBonus = config("4 - Rewards / Depth", "Size Bonus", 0.25f, new ConfigDescription("Quality-roll chance added at full depth.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); depthSkillBonus = config("4 - Rewards / Depth", "Skill Bonus", 0.25f, new ConfigDescription("XP bonus at full depth. 0.25 means 25%.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 2f), Array.Empty())); depthLunkerBonus = config("4 - Rewards / Depth", "Lunker Bonus", 0.02f, new ConfigDescription("Lunker chance added at full depth.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); freshCatch = config("4 - Rewards / Fresh Catch", "Enabled", Toggle.On, "Enables the Fresh Catch buff."); freshCatchNeedsPerfect = config("4 - Rewards / Fresh Catch", "Requires Perfect", Toggle.On, "Requires a Perfect catch or lunker."); freshCatchDuration = config("4 - Rewards / Fresh Catch", "Duration", 300f, new ConfigDescription("Buff duration in seconds. Lunkers double it.", (AcceptableValueBase)(object)new AcceptableValueRange(10f, 3600f), Array.Empty())); freshCatchCarryWeight = config("4 - Rewards / Fresh Catch", "Carry Weight", 50f, new ConfigDescription("Carry weight added by the buff.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 300f), Array.Empty())); freshCatchStaminaRegen = config("4 - Rewards / Fresh Catch", "Stamina Regen", 1.1f, new ConfigDescription("Stamina regeneration multiplier. 1.1 means 10% faster.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 2f), Array.Empty())); freshCatchEitrRegen = config("4 - Rewards / Fresh Catch", "Eitr Regen", 1f, new ConfigDescription("Eitr regeneration multiplier. 1 leaves it alone.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 2f), Array.Empty())); treasureEnabled = config("5 - Treasure", "Enabled", Toggle.On, "Enables treasure in the bobber bar."); treasureChance = config("5 - Treasure", "Chance", 0.15f, new ConfigDescription("Base chance per hooked fish.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); treasureSkillBonus = config("5 - Treasure", "Skill Bonus", 0.15f, new ConfigDescription("Chance added at Fishing 100.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); treasureTierBonus = config("5 - Treasure", "Tier Bonus", 0.1f, new ConfigDescription("Chance added for the hardest fish.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty())); treasureFillRate = config("5 - Treasure", "Fill Rate", 0.0135f, new ConfigDescription("Treasure meter gained per 1/60s inside the bar.", (AcceptableValueBase)(object)new AcceptableValueRange(0.001f, 0.1f), Array.Empty())); treasureDrainRate = config("5 - Treasure", "Drain Rate", 0.01f, new ConfigDescription("Treasure meter lost per 1/60s outside the bar.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 0.1f), Array.Empty())); treasureRollsMin = config("5 - Treasure", "Rolls Min", 1, new ConfigDescription("Minimum loot rolls per chest.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 10), Array.Empty())); treasureRollsMax = config("5 - Treasure", "Rolls Max", 2, new ConfigDescription("Maximum loot rolls per chest.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 10), Array.Empty())); treasureLoot = config("5 - Treasure", "Loot", "Coins:20:60:30, FishingBait:5:15:25, Amber:1:3:20, AmberPearl:1:2:8, Ruby:1:1:4", "Prefab:min:max:weight, comma separated."); treasureGuard = config("5 - Treasure", "Block Progression Items", Toggle.On, "Blocks non-teleportable items and trophies."); treasureBlocklist = config("5 - Treasure", "Blocklist", "", "Extra blocked prefab names, comma separated."); treasureKnownOnly = config("5 - Treasure", "Known Items Only", Toggle.On, "Limits loot to items this character knows. Falls back to base loot if none qualify."); treasureLoot.SettingChanged += delegate { Treasure.Invalidate(); }; treasureGuard.SettingChanged += delegate { Treasure.Invalidate(); }; treasureBlocklist.SettingChanged += delegate { Treasure.Invalidate(); }; treasureBiomeLoot = config("5 - Treasure / Biome", "Biome Tables", Toggle.On, "Uses a loot table for the float's biome."); treasureBiomeAddsToBase = config("5 - Treasure / Biome", "Adds To Base", Toggle.On, "Adds biome loot to base loot. Off replaces it."); foreach (KeyValuePair item in DefaultBiomeLoot) { ConfigEntry val = config("5 - Treasure / Biome", ((object)item.Key/*cast due to .constrained prefix*/).ToString(), item.Value, $"Prefab:min:max:weight for {item.Key}. Blank uses base loot."); val.SettingChanged += delegate { Treasure.Invalidate(); }; treasureBiomeTables[item.Key] = val; } staminaScale = config("6 - Stamina", "Hooked Drain Scale", 1f, new ConfigDescription("Rod stamina drain while a fish is hooked.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 5f), Array.Empty())); reelStaminaScale = config("6 - Stamina", "Reel Drain Scale", 1f, new ConfigDescription("Rod pull cost while reeling.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 5f), Array.Empty())); fishFinder = config("7 - Interface", "Fish Finder", Toggle.On, "Shows nearby fish that can take the equipped bait.", synchronizedSetting: false); reelClipNames = config("7 - Interface", "Reel Clip", "", "Reel audio clip names, comma separated. Blank uses defaults.", synchronizedSetting: false); tutorial = config("7 - Interface", "Tutorial", TutorialMode.Beginner, "Control hint beside the bar. Beginner stops at Beginner Skill Level.", synchronizedSetting: false); soundEnabled = config("7 - Interface", "Sound", Toggle.On, "Enables Hooked's reel, bounce and result sounds.", synchronizedSetting: false); soundVolume = config("7 - Interface", "Sound Volume", 0.7f, new ConfigDescription("Hooked sound volume.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 1f), Array.Empty()), synchronizedSetting: false); shakeStrength = config("7 - Interface", "Shake Strength", 3f, new ConfigDescription("Screen shake in pixels. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 12f), Array.Empty()), synchronizedSetting: false); uiScale = config("7 - Interface", "Scale", 0.85f, new ConfigDescription("Bobber-bar UI scale.", (AcceptableValueBase)(object)new AcceptableValueRange(0.4f, 2f), Array.Empty()), synchronizedSetting: false); fishIconScale = config("7 - Interface", "Fish Icon Scale", 1.25f, new ConfigDescription("Fish icon scale.", (AcceptableValueBase)(object)new AcceptableValueRange(0.5f, 3f), Array.Empty()), synchronizedSetting: false); uiAnchor = config("7 - Interface", "Anchor", BarAnchor.Right, "Side of the player used by the bar.", synchronizedSetting: false); uiOffsetX = config("7 - Interface", "Offset X", 0f, new ConfigDescription("Horizontal offset in pixels.", (AcceptableValueBase)(object)new AcceptableValueRange(-800f, 800f), Array.Empty()), synchronizedSetting: false); uiOffsetY = config("7 - Interface", "Offset Y", 0f, new ConfigDescription("Vertical offset in pixels.", (AcceptableValueBase)(object)new AcceptableValueRange(-500f, 500f), Array.Empty()), synchronizedSetting: false); UIRoot.Init(HookedLogger, harmony); harmony.PatchAll(Assembly.GetExecutingAssembly()); SetupWatcher(); if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; ((BaseUnityPlugin)this).Config.Save(); } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { HookedLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { HookedLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); HookedLogger.LogError((object)"Please check your config entries for spelling and format!"); } } internal static ConfigEntry config(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry val2 = ((BaseUnityPlugin)self).Config.Bind(group, name, value, val); ConfigSync.AddConfigEntry(val2).SynchronizedConfig = synchronizedSetting; return val2; } internal static ConfigEntry config(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } static HookedPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; ConnectionError = ""; HookedLogger = Logger.CreateLogSource("Hooked"); ConfigSync = new ConfigSync("Azumatt.Hooked") { DisplayName = "Hooked", CurrentVersion = "1.1.0", MinimumRequiredVersion = "1.1.0", ModRequired = false }; self = null; DefaultBiomeLoot = new Dictionary { [(Biome)1] = "Feathers:2:8:20, Dandelion:1:3:15, Resin:5:15:20, Mushroom:1:3:15, Raspberry:5:10:10", [(Biome)8] = "GreydwarfEye:3:8:25, Resin:8:20:20, Thistle:2:5:20, BoneFragments:3:8:15, Ruby:1:1:5, FishingBaitForest:5:15:15", [(Biome)2] = "Guck:2:6:20, Ooze:2:5:20, Bloodbag:2:6:20, WitheredBone:1:2:10, Root:1:3:10, Chain:1:1:5, FishingBaitSwamp:5:15:15", [(Biome)4] = "Obsidian:3:8:20, FreezeGland:2:5:20, WolfFang:1:4:15, Crystal:1:3:15, SilverNecklace:1:1:4, OnionSeeds:1:3:10, FishingBaitCave:5:15:15", [(Biome)16] = "Needle:3:8:20, Barley:2:6:20, Flax:2:6:20, Cloudberry:3:8:15, LinenThread:1:3:10, FishingBaitPlains:5:15:15", [(Biome)512] = "Sap:1:3:20, YggdrasilWood:2:6:20, RoyalJelly:1:3:15, Softtissue:2:5:15, Carapace:1:3:10, Eitr:1:2:5, FishingBaitMistlands:5:15:15", [(Biome)32] = "CharredBone:2:6:20, Blackwood:3:8:20, MorgenHeart:1:1:4, FishingBaitAshlands:5:15:15", [(Biome)64] = "FreezeGland:2:5:20, Crystal:1:3:15, FishingBaitDeepNorth:5:15:15", [(Biome)256] = "Chitin:2:6:20, SerpentScale:1:3:15, SerpentMeat:1:2:10, Coins:30:80:20, FishingBaitOcean:5:15:15" }; serverConfigLocked = null; minigameEnabled = null; difficulty = null; biteProximityBonus = null; autoHook = null; barHeightBase = null; barHeightPerLevel = null; startingProgress = null; firstCatchProgress = null; fillRate = null; drainRate = null; barGravity = null; inBarGravityScale = null; difficultyScale = null; escapeDifficultyBonus = null; reelInFrom = null; minLineLength = null; lineBreaks = null; biteRangeBonus = null; beginnerAssist = null; beginnerSkillLevel = null; beginnerDifficultyScale = null; beginnerDrainScale = null; beginnerBarBonus = null; fishOverrides = null; flexibleBait = null; baitTackle = null; lunkers = null; lunkerChance = null; lunkerSkillBonus = null; lunkerTierBonus = null; lunkerDifficultyBonus = null; lunkerWanderScale = null; lunkerSkillScale = null; lunkerQualityBonus = null; lunkerTreasure = null; lunkerTreasureRolls = null; depthRewards = null; shallowDepth = null; fullDepth = null; depthTreasureBonus = null; depthSizeBonus = null; depthSkillBonus = null; depthLunkerBonus = null; freshCatch = null; freshCatchNeedsPerfect = null; freshCatchDuration = null; freshCatchCarryWeight = null; freshCatchStaminaRegen = null; freshCatchEitrRegen = null; sizeFromSkill = null; qualityFromSize = null; qualityLossSteps = null; perfectUpgradesQuality = null; skillGainScale = null; skillGainOnLoss = null; skillFillBonus = null; treasureEnabled = null; treasureChance = null; treasureSkillBonus = null; treasureTierBonus = null; treasureFillRate = null; treasureDrainRate = null; treasureRollsMin = null; treasureRollsMax = null; treasureLoot = null; treasureGuard = null; treasureBlocklist = null; treasureKnownOnly = null; treasureBiomeLoot = null; treasureBiomeAddsToBase = null; treasureBiomeTables = new Dictionary>(); staminaScale = null; reelStaminaScale = null; fishFinder = null; soundEnabled = null; soundVolume = null; reelClipNames = null; shakeStrength = null; uiScale = null; fishIconScale = null; tutorial = null; uiAnchor = null; uiOffsetX = null; uiOffsetY = null; } } } namespace Hooked.UI { public class BobberBarAudio { public static string[] ReelClips = new string[2] { "Ui_Click_01", "UI_Build_Default_01" }; public static string[] GrabClips = new string[3] { "Fishing_PoleCastLine1", "UI_Equip_Start_M_01", "Ui_Click_01" }; public static string[] BounceClips = new string[1] { "Ui_Click_01" }; public static string[] TreasureUpClips = new string[3] { "Fishing_BaitSplash1", "UI_TreasurePile_Place_01", "Ui_Click_01" }; public static string[] TreasureWonClips = new string[3] { "UI_TreasurePile_Place_01", "UI_Craft_Finish_01", "UI_LevelUp_S_01" }; public static string[] CaughtClips = new string[2] { "UI_Craft_Finish_01", "UI_Pickup_M_01" }; public static string[] PerfectClips = new string[2] { "UI_LevelUp_S_01", "UI_Craft_Finish_01" }; public static string[] LostClips = new string[2] { "Fishing_LineSnap3", "UI_Drop_M_01" }; private const float FastClickInterval = 0.07f; private const float SlowClickInterval = 0.3f; private const float WinningPitch = 1.25f; private const float LosingPitch = 0.8f; private const float ClickVolumeScale = 0.3f; private readonly AudioSource ratchet = Source(host); private readonly AudioSource oneShot = Source(host); private AudioClip? reelClip; private float clickTimer; private bool wasReeling; private bool wasAtEdge; private bool wasTreasureVisible; private bool wasTreasureCaught; private static bool Enabled { get { if (HookedPlugin.soundEnabled.Value == HookedPlugin.Toggle.On) { return HookedPlugin.soundVolume.Value > 0f; } return false; } } public BobberBarAudio(GameObject host) { } public void Begin() { wasReeling = false; wasTreasureVisible = false; wasTreasureCaught = false; wasAtEdge = true; clickTimer = 0f; if (reelClip == null) { reelClip = ResolveReel(); } } public void Track(BobberBar model) { if (Enabled) { Ratchet(model.FishInBar); if (model.Reeling && !wasReeling) { Play(GrabClips); } bool flag = model.BarPosition <= 0.01f || model.BarPosition >= 568f - model.BarHeight - 0.01f; if (flag && !wasAtEdge) { Play(BounceClips, 0.5f); } if (model.TreasureVisible && !wasTreasureVisible) { Play(TreasureUpClips); } if (model.TreasureCaught && !wasTreasureCaught) { Play(TreasureWonClips); } wasReeling = model.Reeling; wasAtEdge = flag; wasTreasureVisible = model.TreasureVisible; wasTreasureCaught = model.TreasureCaught; } } public void Finish(BarResult result, bool perfect) { Stop(); switch (result) { case BarResult.Caught: Play(perfect ? PerfectClips : CaughtClips); break; case BarResult.Lost: Play(LostClips); break; default: throw new ArgumentOutOfRangeException("result", result, null); case BarResult.Running: break; } } public void Stop() { ratchet.Stop(); } private void Ratchet(bool winning) { if (!((Object)(object)reelClip == (Object)null)) { clickTimer -= Time.deltaTime; if (!(clickTimer > 0f)) { clickTimer = (winning ? 0.07f : 0.3f); ratchet.pitch = (winning ? 1.25f : 0.8f) + Random.Range(-0.05f, 0.05f); ratchet.PlayOneShot(reelClip, HookedPlugin.soundVolume.Value * 0.3f); } } } private static AudioClip? ResolveReel() { string value = HookedPlugin.reelClipNames.Value; string[] array = ((value.Trim().Length > 0) ? value.Split(new char[1] { ',' }) : ReelClips); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { AudioClip val = GameAssets.Clip(array2[i].Trim()); if (val != null) { HookedPlugin.HookedLogger.LogDebug((object)("Reel click using clip '" + ((Object)val).name + "'")); return val; } } HookedPlugin.HookedLogger.LogWarning((object)("No reel clip resolved, the reel will be silent. Tried: " + string.Join(", ", array))); return null; } private void Play(string[] candidates, float volumeScale = 1f) { AudioClip val = GameAssets.FirstClip(candidates); if (val != null) { oneShot.PlayOneShot(val, HookedPlugin.soundVolume.Value * volumeScale); } } private static AudioSource Source(GameObject host) { AudioSource val = host.AddComponent(); val.playOnAwake = false; val.loop = false; val.spatialBlend = 0f; val.volume = 1f; if ((Object)(object)AudioMan.instance != (Object)null) { val.outputAudioMixerGroup = AudioMan.instance.m_guiMixer; } return val; } } public class BobberBarView : MonoBehaviour { public static string[] TreasureIconItems = new string[4] { "Coins", "Amber", "Ruby", "AmberPearl" }; public static string[] PanelSprites = new string[4] { "woodpanel_512x512", "panel_bkg_128_transparent", "panel_bkg_128", "panel_bkg" }; public static string[] BorderSprites = new string[2] { "panel_border_128", "panel_border_bw_128" }; public static string[] SunkenSprites = new string[3] { "InputFieldBackground", "item_background_sunken", "item_background" }; private const float FrameWidth = 108f; private const float FramePadding = 12f; private const float TrackX = 14f; private const float TrackWidth = 48f; private const float BarWidth = 36f; private const float MeterX = 74f; private const float MeterWidth = 20f; private const float MarkerSize = 40f; private const float MarkerCenterOffset = 24f; private const float ChestMeterWidth = 40f; private const float ChestMeterHeight = 8f; private const float ScreenOffsetX = 0.104f; private const float ScreenOffsetY = -0.139f; private const float ResultShakeSeconds = 0.5f; private const float FadeSeconds = 0.25f; private const float PerfectFadeSeconds = 0.7f; private const float BorderThickness = 2f; private const float SliceShrink = 2f; private static readonly Color BorderColor = new Color(0.55f, 0.45f, 0.3f, 0.55f); private static readonly Color FrameBackColor = new Color(0f, 0f, 0f, 0.85f); private static readonly Color ChannelColor = new Color(0.04f, 0.05f, 0.07f, 0.85f); private static readonly Color BarColor = new Color(0.33f, 0.85f, 0.36f, 0.85f); private static readonly Color MeterBackColor = new Color(0.03f, 0.04f, 0.05f, 0.9f); private static readonly Color ChestMeterBackColor = new Color(0.41f, 0.41f, 0.41f, 0.5f); private static readonly Color ChestMeterColor = new Color(1f, 0.65f, 0f, 1f); private static readonly Color TreasureColor = new Color(0.93f, 0.78f, 0.31f, 1f); private static readonly Color LunkerColor = new Color(1f, 0.85f, 0.45f, 1f); private static readonly Color EmptyColor = new Color(0.92f, 0.24f, 0.2f, 1f); private static readonly Color FullColor = new Color(0.34f, 0.92f, 0.36f, 1f); private static BobberBarView? instance; private static Sprite? treasureIcon; private RectTransform frame; private RectTransform track; private RectTransform bar; private RectTransform fish; private RectTransform treasure; private RectTransform chestMeter; private RectTransform chestFill; private RectTransform catchMeter; private RectTransform catchFill; private Image catchFillImage; private Image fishImage; private Image treasureImage; private CanvasGroup perfectBadge; private GameObject lunkerBadge; private GameObject tutorial; private Text tutorialText; private CanvasGroup group; private BobberBarAudio audio; private float scale; private float trackPixels; private Vector2 anchor; private float outroTimer; private float perfectAlpha; private bool chestShown; private bool chestMeterShown; public static void Show(FishingSession session) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) if (!UIRoot.IsReady) { HookedPlugin.HookedLogger.LogWarning((object)"GUI root isn't up yet, running this catch without a bar."); return; } if (instance == null) { instance = Build(); } ((Component)instance).gameObject.SetActive(true); instance.fishImage.sprite = session.Icon; ((Graphic)instance.fishImage).color = (((Object)(object)session.Icon == (Object)null) ? TreasureColor : (session.Lunker ? LunkerColor : Color.white)); instance.lunkerBadge.SetActive(session.Lunker); instance.DressTreasure(); instance.chestShown = false; instance.chestMeterShown = false; ((Component)instance.treasure).gameObject.SetActive(false); ((Component)instance.chestMeter).gameObject.SetActive(false); ((Component)instance.perfectBadge).gameObject.SetActive(true); instance.perfectAlpha = 1f; instance.perfectBadge.alpha = 1f; instance.outroTimer = 0f; instance.group.alpha = 1f; instance.DressTutorial(session); instance.Layout(session.Bar); instance.audio.Begin(); } public static void Finish(BarResult result, bool perfect) { if (!((Object)(object)instance == (Object)null)) { if (result == BarResult.Running) { Hide(); return; } instance.outroTimer = 0.75f; instance.perfectBadge.alpha = ((result == BarResult.Caught && perfect) ? 1f : 0f); instance.tutorial.SetActive(false); instance.audio.Finish(result, perfect); } } public static void Hide() { if ((Object)(object)instance != (Object)null) { instance.audio.Stop(); instance.outroTimer = 0f; ((Component)instance).gameObject.SetActive(false); } } private void Update() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) if (outroTimer > 0f) { Outro(); return; } FishingSession active = FishingSession.Active; if (active == null) { Hide(); return; } BobberBar bobberBar = active.Bar; float value = HookedPlugin.shakeStrength.Value; bar.anchoredPosition = new Vector2(0f, (0f - bobberBar.BarPosition) * scale) + (bobberBar.FishInBar ? Vector2.zero : Jitter(value)); fish.anchoredPosition = new Vector2(0f, (0f - (bobberBar.FishPosition + 24f)) * scale) + (bobberBar.FishInBar ? Jitter(value) : Vector2.zero); catchFill.sizeDelta = new Vector2(0f, trackPixels * bobberBar.Progress); ((Graphic)catchFillImage).color = Color.Lerp(EmptyColor, FullColor, bobberBar.Progress); float num = (bobberBar.Perfect ? 1f : Mathf.Max(0f, perfectAlpha - Time.deltaTime / 0.7f)); if (!Mathf.Approximately(num, perfectAlpha)) { perfectAlpha = num; perfectBadge.alpha = num; } audio.Track(bobberBar); if (bobberBar.HasTreasure) { bool treasureVisible = bobberBar.TreasureVisible; bool flag = bobberBar.TreasureInBar && !bobberBar.TreasureCaught; if (treasureVisible != chestShown) { chestShown = treasureVisible; ((Component)treasure).gameObject.SetActive(treasureVisible); } treasure.anchoredPosition = new Vector2(0f, (0f - (bobberBar.TreasurePosition + 24f)) * scale) + (flag ? Jitter(value * 2f) : Vector2.zero); ((Transform)treasure).localScale = Vector3.one * Mathf.Max(0.01f, bobberBar.TreasureScale); bool flag2 = treasureVisible && bobberBar.TreasureProgress > 0f && !bobberBar.TreasureCaught; if (flag2 != chestMeterShown) { chestMeterShown = flag2; ((Component)chestMeter).gameObject.SetActive(flag2); } chestMeter.anchoredPosition = new Vector2(0f, (0f - bobberBar.TreasurePosition) * scale); chestFill.offsetMax = new Vector2(-40f * scale * (1f - bobberBar.TreasureProgress), 0f); } } private void Outro() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) outroTimer -= Time.deltaTime; if (outroTimer <= 0f) { Hide(); return; } RectTransform val = (RectTransform)((Component)this).transform; bool flag = outroTimer > 0.25f; val.anchoredPosition = anchor + (flag ? Jitter(HookedPlugin.shakeStrength.Value) : Vector2.zero); group.alpha = (flag ? 1f : (outroTimer / 0.25f)); } private void DressTreasure() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (treasureIcon == null) { treasureIcon = FindTreasureIcon(); } treasureImage.sprite = treasureIcon; ((Graphic)treasureImage).color = (((Object)(object)treasureIcon == (Object)null) ? TreasureColor : Color.white); } private void DressTutorial(FishingSession session) { bool flag = HookedPlugin.tutorial.Value switch { HookedPlugin.TutorialMode.Always => true, HookedPlugin.TutorialMode.Beginner => session.SkillLevel < HookedPlugin.beginnerSkillLevel.Value, _ => false, }; tutorial.SetActive(flag); if (flag) { tutorialText.text = Localization.instance.Localize("[$KEY_Block] $hooked_tut_raise\n$hooked_tut_lower\n\n$hooked_tut_keep\n$hooked_tut_perfect"); } } private static Sprite? FindTreasureIcon() { if ((Object)(object)ObjectDB.instance == (Object)null) { return null; } string[] treasureIconItems = TreasureIconItems; foreach (string text in treasureIconItems) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text); if (itemPrefab != null) { ItemDrop component = itemPrefab.GetComponent(); if (component != null) { return component.m_itemData.GetIcon(); } } } return null; } private static Vector2 Jitter(float strength) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (!(strength <= 0f)) { return new Vector2(Random.Range(0f - strength, strength), Random.Range(0f - strength, strength)); } return Vector2.zero; } private void Layout(BobberBar model) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02fe: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Expected O, but got Unknown float num = (float)Screen.height / 616f; scale = Mathf.Min(HookedPlugin.uiScale.Value, num); trackPixels = 568f * scale; RectTransform val = (RectTransform)((Component)this).transform; bool flag = HookedPlugin.uiAnchor.Value == HookedPlugin.BarAnchor.Left; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(0.5f, 0.5f); val.anchorMax = val2; val.anchorMin = val2; val.pivot = new Vector2(0.5f, 0.5f); val.sizeDelta = new Vector2(108f * scale, trackPixels + 24f * scale); anchor = new Vector2((flag ? (-1f) : 1f) * 0.104f * (float)Screen.width + HookedPlugin.uiOffsetX.Value, -0.139f * (float)Screen.height + HookedPlugin.uiOffsetY.Value); val.anchoredPosition = anchor; Column(frame, 0f, 108f * scale, 0f); Column(track, 14f * scale, 48f * scale, 12f * scale); Column(catchMeter, 74f * scale, 20f * scale, 12f * scale); bar.sizeDelta = new Vector2(36f * scale, model.BarHeight * scale); treasure.sizeDelta = new Vector2(40f * scale, 40f * scale); chestMeter.sizeDelta = new Vector2(40f * scale, 8f * scale); float num2 = 40f * HookedPlugin.fishIconScale.Value * scale; fish.sizeDelta = new Vector2(num2, num2); RectTransform val3 = (RectTransform)((Component)perfectBadge).transform; val3.anchoredPosition = new Vector2(54f * scale, 0.6f); val3.sizeDelta = new Vector2(108f * scale, 28f); RectTransform val4 = (RectTransform)lunkerBadge.transform; val4.anchoredPosition = new Vector2(54f * scale, -0.6f); val4.sizeDelta = new Vector2(108f * scale, 28f); RectTransform val5 = (RectTransform)tutorial.transform; ((Vector2)(ref val2))..ctor(flag ? 1f : 0f, 0.5f); val5.anchorMax = val2; val5.anchorMin = val2; val5.pivot = new Vector2(flag ? 0f : 1f, 0.5f); val5.anchoredPosition = new Vector2(flag ? 16f : (-16f), 0f); UILayout.ClampToCanvas(val5); } private static BobberBarView Build() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("Hooked_BobberBar", new Type[1] { typeof(RectTransform) }); val.transform.SetParent(UIRoot.Front, false); BobberBarView bobberBarView = val.AddComponent(); bobberBarView.group = val.AddComponent(); bobberBarView.group.interactable = false; bobberBarView.group.blocksRaycasts = false; bobberBarView.audio = new BobberBarAudio(val); bobberBarView.frame = Plate("Frame", val.transform); Styler.Lit(((Component)bobberBarView.frame).gameObject); bobberBarView.track = ((Graphic)Sunken("Track", (Transform)(object)bobberBarView.frame)).rectTransform; bobberBarView.bar = Marker("Bar", (Transform)(object)bobberBarView.track, BarColor, centered: false); bobberBarView.chestMeter = Marker("ChestMeter", (Transform)(object)bobberBarView.track, ChestMeterBackColor, centered: false); bobberBarView.chestFill = ((Graphic)Rect("Fill", (Transform)(object)bobberBarView.chestMeter, ChestMeterColor)).rectTransform; Stretch(bobberBarView.chestFill); bobberBarView.treasure = Marker("Treasure", (Transform)(object)bobberBarView.track, TreasureColor, centered: true); bobberBarView.treasureImage = ((Component)bobberBarView.treasure).GetComponent(); bobberBarView.treasureImage.preserveAspect = true; bobberBarView.fish = Marker("Fish", (Transform)(object)bobberBarView.track, Color.white, centered: true); bobberBarView.fishImage = ((Component)bobberBarView.fish).GetComponent(); bobberBarView.fishImage.preserveAspect = true; bobberBarView.catchMeter = ((Graphic)Sunken("CatchMeter", (Transform)(object)bobberBarView.frame)).rectTransform; bobberBarView.catchFill = ((Graphic)Rect("Fill", (Transform)(object)bobberBarView.catchMeter, Color.white)).rectTransform; bobberBarView.catchFill.anchorMin = new Vector2(0f, 0f); bobberBarView.catchFill.anchorMax = new Vector2(1f, 0f); bobberBarView.catchFill.pivot = new Vector2(0.5f, 0f); bobberBarView.catchFill.anchoredPosition = Vector2.zero; bobberBarView.catchFill.sizeDelta = Vector2.zero; bobberBarView.catchFillImage = ((Component)bobberBarView.catchFill).GetComponent(); RectTransform val2 = Badge("PerfectBadge", val.transform, "$hooked_perfect", GameColors.Orange, new Vector2(0f, 1f), new Vector2(0.5f, 0f)); bobberBarView.perfectBadge = ((Component)val2).gameObject.AddComponent(); bobberBarView.lunkerBadge = ((Component)Badge("LunkerBadge", val.transform, "$hooked_lunker", LunkerColor, new Vector2(0f, 0f), new Vector2(0.5f, 1f))).gameObject; RectTransform val3 = Plate("Tutorial", val.transform); Styler.Lit(((Component)val3).gameObject); val3.sizeDelta = new Vector2(270f, 170f); bobberBarView.tutorial = ((Component)val3).gameObject; bobberBarView.tutorialText = UIFactory.Text("Text", (Transform)(object)val3, "", TextRole.Label, 16, (TextAnchor)3); ((Graphic)bobberBarView.tutorialText).raycastTarget = false; Skin.Outline(((Component)bobberBarView.tutorialText).gameObject); Stretch(((Graphic)bobberBarView.tutorialText).rectTransform, 18f); return bobberBarView; } private static RectTransform Badge(string name, Transform parent, string key, Color color, Vector2 anchor, Vector2 pivot) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) RectTransform val = Plate(name, parent); Vector2 anchorMin = (val.anchorMax = anchor); val.anchorMin = anchorMin; val.pivot = pivot; Text obj = UIFactory.Text("Text", (Transform)(object)val, Localization.instance.Localize(key), TextRole.Title, 20, (TextAnchor)4); ((Graphic)obj).color = color; ((Graphic)obj).raycastTarget = false; obj.horizontalOverflow = (HorizontalWrapMode)1; Skin.Outline(((Component)obj).gameObject); Stretch(((Graphic)obj).rectTransform); return val; } internal static RectTransform Plate(string name, Transform parent) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) Image val = Rect(name, parent, FrameBackColor); if (name == "Frame") { Skinned(val, PanelSprites, Color.white); return ((Graphic)val).rectTransform; } Image obj = Rect("Border", ((Component)val).transform, BorderColor); Skinned(obj, BorderSprites, Color.white); Stretch(((Graphic)obj).rectTransform); return ((Graphic)val).rectTransform; } private static Image Sunken(string name, Transform parent) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Image obj = Rect(name, parent, ChannelColor); Skinned(obj, SunkenSprites); return obj; } private static void Skinned(Image image, string[] candidates, Color? tint = null) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Sprite val = GameAssets.FirstSprite(candidates); if (val != null) { image.sprite = val; image.type = (Type)1; image.pixelsPerUnitMultiplier = 2f; if (tint.HasValue) { Color valueOrDefault = tint.GetValueOrDefault(); ((Graphic)image).color = valueOrDefault; } } } private static Image Rect(string name, Transform parent, Color color) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name, new Type[3] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image) }); val.transform.SetParent(parent, false); Image component = val.GetComponent(); ((Graphic)component).color = color; ((Graphic)component).material = null; ((Graphic)component).raycastTarget = false; return component; } private static RectTransform Marker(string name, Transform parent, Color color, bool centered) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) RectTransform rectTransform = ((Graphic)Rect(name, parent, color)).rectTransform; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(0.5f, 1f); rectTransform.anchorMax = val; rectTransform.anchorMin = val; rectTransform.pivot = new Vector2(0.5f, centered ? 0.5f : 1f); return rectTransform; } internal static void Stretch(RectTransform rect, float inset = 0f) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one; rect.offsetMin = new Vector2(inset, inset); rect.offsetMax = new Vector2(0f - inset, 0f - inset); } private static void Column(RectTransform rect, float offsetX, float width, float inset) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) rect.anchorMin = new Vector2(0f, 0f); rect.anchorMax = new Vector2(0f, 1f); rect.pivot = new Vector2(0f, 0.5f); rect.sizeDelta = new Vector2(width, (0f - inset) * 2f); rect.anchoredPosition = new Vector2(offsetX, 0f); } } public class CastStatusView : MonoBehaviour { private struct Reading { public bool Incoming; public int Interested; public int InRange; public int TooShallow; public float Nearest; } private const float PollSeconds = 0.4f; private const float ScreenOffsetX = 0.104f; private const float ScreenOffsetY = -0.139f; private static readonly Color Incoming = new Color(0.45f, 0.95f, 0.45f, 1f); private static readonly Color Nearby = new Color(0.78f, 0.86f, 0.72f, 1f); private static readonly Color WrongBait = new Color(1f, 0.75f, 0.35f, 1f); private static readonly Color Empty = new Color(0.78f, 0.78f, 0.78f, 1f); private static CastStatusView? instance; private Text label; private CanvasGroup group; private float timer; private bool shown; public static void Ensure() { if ((Object)(object)instance == (Object)null && UIRoot.IsReady) { instance = Build(); } } private void Update() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) timer -= Time.deltaTime; if (timer > 0f) { return; } timer = 0.4f; if (HookedPlugin.fishFinder.Value != HookedPlugin.Toggle.Off && !((Object)(object)Player.m_localPlayer == (Object)null) && FishingSession.Active == null) { FishingFloat val = LocalFloat(); if (val != null) { if (!val.IsInWater() || (Object)(object)val.GetCatch() != (Object)null) { Show(visible: false); return; } Reading reading = Count(val); Show(visible: true); Layout(); if (reading.Incoming) { ((Graphic)label).color = Incoming; label.text = Localization.instance.Localize("$hooked_finder_incoming"); } else if (reading.TooShallow > 0 && reading.Interested == 0) { ((Graphic)label).color = WrongBait; label.text = Localization.instance.Localize("$hooked_finder_shallow"); } else if (reading.Interested > 0) { ((Graphic)label).color = Nearby; label.text = Localization.instance.Localize("$hooked_finder_nearby", new string[2] { reading.Interested.ToString(), Mathf.RoundToInt(reading.Nearest).ToString() }); } else if (reading.InRange > 0) { ((Graphic)label).color = WrongBait; label.text = Localization.instance.Localize("$hooked_finder_wrongbait", new string[1] { reading.InRange.ToString() }); } else { ((Graphic)label).color = Empty; label.text = Localization.instance.Localize("$hooked_finder_empty"); } return; } } Show(visible: false); } private static Reading Count(FishingFloat bobber) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) Reading result = default(Reading); string bait = bobber.GetBait(); Character owner = bobber.GetOwner(); Player player = (Player)(object)((owner is Player) ? owner : null); Vector3 position = ((Component)bobber).transform.position; float range = bobber.m_range; float num = Waters.Depth(position); foreach (IMonoUpdater instance in Fish.Instances) { Fish val = (Fish)(object)((instance is Fish) ? instance : null); if (val == null || (Object)(object)((Component)val).transform == (Object)null) { continue; } if ((Object)(object)val.m_waypointFF == (Object)(object)bobber) { result.Incoming = true; } float num2 = Vector3.Distance(((Component)val).transform.position, position); if (num2 > range) { continue; } result.InRange++; if (!BaitTackle.Accepts(val, bait, player)) { continue; } if (num < val.m_minDepth) { result.TooShallow++; continue; } if (result.Interested == 0 || num2 < result.Nearest) { result.Nearest = num2; } result.Interested++; } return result; } private static FishingFloat? LocalFloat() { foreach (FishingFloat allInstance in FishingFloat.GetAllInstances()) { if ((Object)(object)allInstance != (Object)null && (Object)(object)allInstance.GetOwner() == (Object)(object)Player.m_localPlayer) { return allInstance; } } return null; } private void Show(bool visible) { if (visible != shown) { shown = visible; group.alpha = (visible ? 1f : 0f); } } private void Layout() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown RectTransform val = (RectTransform)((Component)this).transform; bool flag = HookedPlugin.uiAnchor.Value == HookedPlugin.BarAnchor.Left; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(0.5f, 0.5f); val.anchorMax = val2; val.anchorMin = val2; val.pivot = new Vector2(0.5f, 0.5f); val.sizeDelta = new Vector2(230f, 34f); val.anchoredPosition = new Vector2((flag ? (-1f) : 1f) * 0.104f * (float)Screen.width + HookedPlugin.uiOffsetX.Value, -0.139f * (float)Screen.height + HookedPlugin.uiOffsetY.Value); UILayout.ClampToCanvas(val); } private static CastStatusView Build() { RectTransform val = BobberBarView.Plate("Hooked_CastStatus", UIRoot.Front); Styler.Lit(((Component)val).gameObject); CastStatusView castStatusView = ((Component)val).gameObject.AddComponent(); castStatusView.group = ((Component)val).gameObject.AddComponent(); castStatusView.group.interactable = false; castStatusView.group.blocksRaycasts = false; castStatusView.group.alpha = 0f; castStatusView.label = UIFactory.Text("Text", (Transform)(object)val, "", TextRole.Label, 16, (TextAnchor)4); ((Graphic)castStatusView.label).raycastTarget = false; castStatusView.label.horizontalOverflow = (HorizontalWrapMode)1; Skin.Outline(((Component)castStatusView.label).gameObject); BobberBarView.Stretch(((Graphic)castStatusView.label).rectTransform, 6f); return castStatusView; } } } namespace Hooked.Fishing { public readonly struct Tackle { public readonly float BarBonus; public readonly float DrainScale; public readonly float ClingStrength; public readonly float BounceScale; public readonly float DoubleChance; public readonly int QualityBonus; public readonly bool TreasureHunter; public Tackle(float barBonus = 0f, float drainScale = 1f, float clingStrength = 0f, float bounceScale = 1f, float doubleChance = 0f, int qualityBonus = 0, bool treasureHunter = false) { BarBonus = barBonus; DrainScale = drainScale; ClingStrength = clingStrength; BounceScale = bounceScale; DoubleChance = doubleChance; QualityBonus = qualityBonus; TreasureHunter = treasureHunter; } } public static class BaitTackle { public static readonly Tackle Plain = default(Tackle); private static readonly Dictionary Baits = new Dictionary(StringComparer.Ordinal) { ["FishingBaitForest"] = new Tackle(24f), ["FishingBaitSwamp"] = new Tackle(0f, 2f / 3f), ["FishingBaitCave"] = new Tackle(0f, 1f, 0f, 1f, 0f, 1), ["FishingBaitOcean"] = new Tackle(0f, 1f, 0f, 0.1f), ["FishingBaitPlains"] = new Tackle(0f, 1f, 0.2f), ["FishingBaitMistlands"] = new Tackle(0f, 1f, 0f, 1f, 0f, 0, treasureHunter: true), ["FishingBaitAshlands"] = new Tackle(0f, 1f, 0f, 1f, 0.25f), ["FishingBaitDeepNorth"] = new Tackle(24f, 2f / 3f) }; public static Tackle For(string? bait) { if (HookedPlugin.baitTackle.Value == HookedPlugin.Toggle.Off || bait == null) { return Plain; } if (!Baits.TryGetValue(bait, out var value)) { return Plain; } return value; } public static bool Accepts(Fish fish, string? bait, Player? player) { if (bait == null) { return false; } if (IsNative(fish, bait)) { return true; } if (HookedPlugin.flexibleBait.Value == HookedPlugin.Toggle.On && (Object)(object)player != (Object)null) { return UnlockedChance(fish, player) > 0f; } return false; } public static bool IsNative(Fish fish, string? bait) { if (bait == null) { return false; } foreach (BaitSetting bait2 in fish.m_baits) { if ((Object)(object)bait2.m_bait != (Object)null && ((Object)bait2.m_bait).name == bait) { return true; } } return false; } public static float UnlockedChance(Fish fish, Player player) { float num = 0f; foreach (BaitSetting bait in fish.m_baits) { if ((Object)(object)bait.m_bait != (Object)null && player.IsKnownMaterial(bait.m_bait.m_itemData.m_shared.m_name)) { num = Mathf.Max(num, bait.m_chance); } } return num; } } public enum FishMotion { Mixed, Dart, Smooth, Sinker, Floater } public enum BarResult { Running, Caught, Lost } public class BobberBar { public const float TrackHeight = 568f; public const float FishTrackHeight = 548f; public const float MinDifficulty = 15f; public const float MaxDifficulty = 100f; private const float StepSeconds = 1f / 60f; private const float SizeReductionSeconds = 0.8f; public float Difficulty; public float Gravity = 0.25f; public float InBarGravityScale = 0.6f; public float FillRate = 0.002f; public float DrainRate = 0.003f; public float TreasureFillRate = 0.0135f; public float TreasureDrainRate = 0.01f; public bool TreasureProtectsFish; public float WanderScale = 1f; public float Cling; public float Bounce = 1f; public readonly FishMotion Motion; public readonly float BarHeight; public readonly bool HasTreasure; private float fishSpeed; private float fishTarget; private float floaterSinker; private float barSpeed; private float treasureTimer; private float sizeTimer = 0.8f; private float accumulator; private bool fishHasBeenInBar; public float FishPosition { get; private set; } = 508f; public float BarPosition { get; private set; } public float Progress { get; private set; } public float PeakProgress { get; private set; } public float TreasurePosition { get; private set; } public float TreasureProgress { get; private set; } public float TreasureScale { get; private set; } public bool TreasureCaught { get; private set; } public bool TreasureVisible => TreasureScale > 0f; public bool TreasureInBar { get; private set; } public bool FishInBar { get; private set; } public bool Reeling { get; private set; } public bool Perfect { get; private set; } = true; public BarResult Result { get; private set; } public int SizeLossSteps { get; private set; } public BobberBar(float difficulty, FishMotion motion, float barHeight, bool treasure, float startProgress) { Difficulty = Mathf.Clamp(difficulty, 15f, 100f); Motion = motion; BarHeight = Mathf.Clamp(barHeight, 16f, 568f); HasTreasure = treasure; BarPosition = 568f - BarHeight; Progress = Mathf.Clamp01(startProgress); fishTarget = (100f - Difficulty) / 100f * 548f; treasureTimer = Random.Range(1f, 3f); } public void Update(bool reeling, float deltaTime) { if (Result != BarResult.Running) { return; } accumulator += Mathf.Min(deltaTime, 0.25f); while (accumulator >= 1f / 60f) { accumulator -= 1f / 60f; MoveFish(); MoveBar(reeling); MoveTreasure(); Score(); if (Result != BarResult.Running) { break; } } } private void MoveFish() { if (Chance(Difficulty * ((Motion == FishMotion.Smooth) ? 20f : 1f) / 4000f * WanderScale) && (Motion != FishMotion.Smooth || fishTarget < 0f)) { float num = 548f - FishPosition; float num2 = Mathf.Min(99f, Difficulty + (float)Random.Range(10, 45)) / 100f; fishTarget = FishPosition + (float)Random.Range(-(int)FishPosition, (int)num) * num2; } floaterSinker = Motion switch { FishMotion.Floater => Mathf.Max(floaterSinker - 0.01f, -1.5f), FishMotion.Sinker => Mathf.Min(floaterSinker + 0.01f, 1.5f), _ => floaterSinker, }; if (Mathf.Abs(FishPosition - fishTarget) > 3f && fishTarget >= 0f) { float num3 = (fishTarget - FishPosition) / ((float)Random.Range(10, 30) + (100f - Mathf.Min(100f, Difficulty))); fishSpeed += (num3 - fishSpeed) / 5f; } else if (Motion != FishMotion.Smooth && Chance(Difficulty / 2000f * WanderScale)) { fishTarget = FishPosition + (float)(Chance(0.5f) ? Random.Range(-100, -51) : Random.Range(50, 101)); } else { fishTarget = -1f; } if (Motion == FishMotion.Dart && Chance(Difficulty / 1000f * WanderScale)) { int num4 = (int)Difficulty * 2; fishTarget = FishPosition + (float)(Chance(0.5f) ? Random.Range(-100 - num4, -51) : Random.Range(50, 101 + num4)); } fishTarget = Mathf.Clamp(fishTarget, -1f, 548f); FishPosition = Mathf.Clamp(FishPosition + fishSpeed + floaterSinker, 0f, 532f); } private void MoveBar(bool reeling) { Reeling = reeling; FishInBar = FishPosition + 12f <= BarPosition - 32f + BarHeight && FishPosition - 16f >= BarPosition - 32f; if (FishPosition >= 548f - BarHeight && BarPosition >= 568f - BarHeight - 4f) { FishInBar = true; } float num = (reeling ? (0f - Gravity) : Gravity); if (reeling && (BarPosition <= 0f || BarPosition >= 568f - BarHeight)) { barSpeed = 0f; } if (FishInBar) { num *= InBarGravityScale; if (Cling > 0f) { barSpeed += ((FishPosition + 16f < BarPosition + BarHeight / 2f) ? (0f - Cling) : Cling); } } barSpeed += num; BarPosition += barSpeed; if (BarPosition + BarHeight > 568f) { BarPosition = 568f - BarHeight; barSpeed = (0f - barSpeed) * 2f / 3f * Bounce; } else if (BarPosition < 0f) { BarPosition = 0f; barSpeed = (0f - barSpeed) * 2f / 3f; } } private void MoveTreasure() { if (!HasTreasure) { return; } float num = treasureTimer; treasureTimer -= 1f / 60f; if (treasureTimer > 0f) { return; } if (TreasureScale < 1f && !TreasureCaught) { if (num > 0f) { bool num2 = BarPosition > 284f; float num3 = (num2 ? 8f : Mathf.Min(528f, BarPosition + BarHeight)); float num4 = (num2 ? (BarPosition - 20f) : 500f); TreasurePosition = Random.Range(Mathf.Min(num3, num4), Mathf.Max(num3, num4)); } TreasureScale = Mathf.Min(1f, TreasureScale + 0.1f); } TreasureInBar = TreasurePosition + 12f <= BarPosition - 32f + BarHeight && TreasurePosition - 16f >= BarPosition - 32f; if (TreasureInBar && !TreasureCaught) { TreasureProgress += TreasureFillRate; if (TreasureProgress >= 1f) { TreasureProgress = 1f; TreasureCaught = true; } } else if (TreasureCaught) { TreasureScale = Mathf.Max(0f, TreasureScale - 0.1f); } else { TreasureProgress = Mathf.Max(0f, TreasureProgress - TreasureDrainRate); } } private void Score() { if (FishInBar) { Progress += FillRate; fishHasBeenInBar = true; } else if (!TreasureProtectsFish || !TreasureInBar || TreasureCaught) { if (fishHasBeenInBar) { Perfect = false; } sizeTimer -= 1f / 60f; if (sizeTimer <= 0f) { sizeTimer = 0.8f; int sizeLossSteps = SizeLossSteps + 1; SizeLossSteps = sizeLossSteps; } Progress -= DrainRate; } Progress = Mathf.Clamp01(Progress); PeakProgress = Mathf.Max(PeakProgress, Progress); float progress = Progress; BarResult result = ((progress <= 0f) ? BarResult.Lost : ((progress >= 1f) ? BarResult.Caught : Result)); Result = result; } private static bool Chance(float probability) { return Random.value < probability; } } public readonly struct FishProfile { public readonly float Difficulty; public readonly FishMotion Motion; public FishProfile(float difficulty, FishMotion motion) { Difficulty = difficulty; Motion = motion; } } public static class FishTuning { private readonly struct Override { public readonly float Difficulty; public readonly FishMotion? Motion; public Override(float difficulty, FishMotion? motion) { Difficulty = difficulty; Motion = motion; } } private const float EasiestEscapeStamina = 10f; private const float HardestEscapeStamina = 50f; private const float EasiestDifficulty = 32f; private const float DifficultyCurve = 1.35f; private static readonly Dictionary Overrides = new Dictionary(StringComparer.OrdinalIgnoreCase); public static FishProfile For(Fish fish) { string prefabName = Utils.GetPrefabName(((Component)fish).gameObject); if (!Overrides.TryGetValue(prefabName, out var value)) { return new FishProfile(Difficulty(fish), Motion(fish)); } return new FishProfile(value.Difficulty, value.Motion ?? Motion(fish)); } private static float Difficulty(Fish fish) { ItemDrop component = ((Component)fish).GetComponent(); int num = ((component == null) ? 1 : Mathf.Max(1, component.m_itemData.m_quality)); float num2 = ((fish.m_escapeStaminaUse > 0f) ? fish.m_escapeStaminaUse : (fish.m_staminaUse * 2.5f)); float num3 = Mathf.InverseLerp(10f, 50f, num2); return Mathf.Clamp((Mathf.Lerp(32f, 100f, Mathf.Pow(num3, 1.35f)) + (float)(num - 1) * 5f) * HookedPlugin.difficultyScale.Value, 15f, 100f); } private static FishMotion Motion(Fish fish) { if (fish.m_minDepth >= 4f) { return FishMotion.Sinker; } if (fish.m_maxDepth <= 2f) { return FishMotion.Floater; } if (fish.m_speed >= 8f) { return FishMotion.Dart; } if (!(fish.m_speed <= 2.5f)) { return FishMotion.Mixed; } return FishMotion.Smooth; } public static void ParseOverrides(string config) { Overrides.Clear(); string[] array = config.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length == 0) { continue; } string[] array2 = text.Split(new char[1] { '=' }); if (array2.Length != 2 || array2[0].Trim().Length == 0) { HookedPlugin.HookedLogger.LogWarning((object)("Ignoring fish override '" + text + "': expected 'PrefabName=difficulty' or 'PrefabName=difficulty:pattern'.")); continue; } string[] array3 = array2[1].Split(new char[1] { ':' }); if (!float.TryParse(array3[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { HookedPlugin.HookedLogger.LogWarning((object)("Ignoring fish override '" + text + "': '" + array3[0].Trim() + "' is not a number.")); continue; } FishMotion? motion = null; if (array3.Length > 1) { if (!Enum.TryParse(array3[1].Trim(), ignoreCase: true, out var result2)) { HookedPlugin.HookedLogger.LogWarning((object)("Ignoring fish override '" + text + "': '" + array3[1].Trim() + "' is not a swim pattern.")); continue; } motion = result2; } Overrides[array2[0].Trim()] = new Override(Mathf.Clamp(result, 15f, 100f), motion); } } } public static class FreshCatch { private static SE_Stats? effect; public static void Apply(Player player, Sprite? icon, bool perfect, bool lunker) { if (HookedPlugin.freshCatch.Value != HookedPlugin.Toggle.Off && !((Object)(object)icon == (Object)null) && (HookedPlugin.freshCatchNeedsPerfect.Value != HookedPlugin.Toggle.On || perfect || lunker)) { if ((Object)(object)effect == (Object)null) { effect = Build(); } ((StatusEffect)effect).m_icon = icon; ((StatusEffect)effect).m_ttl = HookedPlugin.freshCatchDuration.Value * (lunker ? 2f : 1f); effect.m_addMaxCarryWeight = HookedPlugin.freshCatchCarryWeight.Value; effect.m_staminaRegenMultiplier = HookedPlugin.freshCatchStaminaRegen.Value; effect.m_eitrRegenMultiplier = HookedPlugin.freshCatchEitrRegen.Value; ((Character)player).GetSEMan().RemoveStatusEffect(((StatusEffect)effect).NameHash(), true); ((Character)player).GetSEMan().AddStatusEffect((StatusEffect)(object)effect, false, 0, 0f); } } private static SE_Stats Build() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) SE_Stats obj = ScriptableObject.CreateInstance(); ((Object)obj).name = "Hooked_FreshCatch"; ((StatusEffect)obj).m_name = "$hooked_freshcatch"; ((StatusEffect)obj).m_tooltip = "$hooked_freshcatch_tooltip"; ((StatusEffect)obj).m_startMessage = "$hooked_freshcatch_start"; ((StatusEffect)obj).m_startMessageType = (MessageType)1; return obj; } } public static class FishPatches { [HarmonyPatch(typeof(Fish), "TestBate")] private static class FlexibleBait { private static void Postfix(Fish __instance, FishingFloat ff, ref bool __result) { if (!__result && HookedPlugin.flexibleBait.Value != HookedPlugin.Toggle.Off && !BaitTackle.IsNative(__instance, ff.GetBait())) { Character owner = ff.GetOwner(); Player val = (Player)(object)((owner is Player) ? owner : null); if (val != null && Random.value < BaitTackle.UnlockedChance(__instance, val)) { __result = true; } } } } [HarmonyPatch(typeof(Fish), "FindFloat")] private static class ProximityBite { private static void Postfix(Fish __instance, ref FishingFloat __result) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__result != (Object)null || HookedPlugin.biteProximityBonus.Value <= 0f) { return; } foreach (FishingFloat allInstance in FishingFloat.GetAllInstances()) { if ((Object)(object)allInstance == (Object)null || !allInstance.IsInWater() || (Object)(object)allInstance.GetCatch() != (Object)null || allInstance.m_range <= 0f) { continue; } float num = Vector3.Distance(((Component)__instance).transform.position, ((Component)allInstance).transform.position); if (!(num > allInstance.m_range)) { float num2 = 1f - num / allInstance.m_range; if (Random.value < HookedPlugin.biteProximityBonus.Value * num2 * num2) { __result = allInstance; break; } } } } } } public static class FishingFloatPatches { [HarmonyPatch(typeof(FishingFloat), "SetCatch")] private static class HookMinigame { private static void Postfix(FishingFloat __instance, Fish fish) { if ((Object)(object)fish != (Object)null) { FishingSession.Start(__instance, fish); } } } [HarmonyPatch(typeof(FishingFloat), "Setup")] private static class WidenBiteRange { private static void Postfix(FishingFloat __instance, Character owner) { if ((Object)(object)owner != (Object)null) { __instance.m_range += owner.GetSkillFactor((SkillType)104) * HookedPlugin.biteRangeBonus.Value; } CastStatusView.Ensure(); } } [HarmonyPatch(typeof(FishingFloat), "RPC_Nibble")] private static class AutoHook { private static void Postfix(FishingFloat __instance, bool correctBait) { if (HookedPlugin.autoHook.Value != HookedPlugin.Toggle.Off && correctBait && (Object)(object)__instance.m_nview != (Object)null && __instance.m_nview.IsValid() && __instance.m_nview.IsOwner()) { __instance.TryToHook(); } } } [HarmonyPatch(typeof(FishingFloat), "FixedUpdate")] private static class DriveFloat { private static bool Prefix(FishingFloat __instance) { FishingSession active = FishingSession.Active; if (active == null || !active.Owns(__instance) || !__instance.m_nview.IsOwner()) { return true; } active.PhysicsStep(); return false; } } [HarmonyPatch(typeof(FishingFloat), "OnDestroy")] private static class DropSession { private static void Postfix(FishingFloat __instance) { FishingSession.Ended(__instance); } } } public class FishingSession { public readonly FishingFloat Float; public readonly Fish Fish; public readonly BobberBar Bar; public readonly Sprite? Icon; public readonly float SkillLevel; public readonly bool Lunker; public readonly Biome Biome; public readonly float Depth; private readonly Player player; private readonly ItemDrop? drop; private readonly Tackle tackle; private readonly DifficultyTuning preset; private readonly string fishPrefab; private readonly float baseDifficulty; private readonly float rewardDifficulty; private readonly float skillFactor; private readonly float depthFactor; private readonly float tierFactor; private readonly float startLineLength; private readonly int startQuality; private Transform? rodTop; private bool finished; private bool won; private const string FirstCatchKey = "Hooked.FirstCatch"; public static FishingSession? Active { get; private set; } public static void Start(FishingFloat fishingFloat, Fish fish) { if (HookedPlugin.minigameEnabled.Value != HookedPlugin.Toggle.Off && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)fishingFloat.GetOwner() != (Object)(object)Player.m_localPlayer)) { Active?.End(); Active = new FishingSession(fishingFloat, fish, Player.m_localPlayer); BobberBarView.Show(Active); if (Active.Lunker) { fishingFloat.Message("$hooked_lunker_hooked", true); } } } public static void Ended(FishingFloat fishingFloat) { if ((Object)(object)Active?.Float == (Object)(object)fishingFloat) { Active.End(); } } public bool Owns(FishingFloat fishingFloat) { return (Object)(object)Float == (Object)(object)fishingFloat; } private FishingSession(FishingFloat fishingFloat, Fish fish, Player player) { //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) Float = fishingFloat; Fish = fish; this.player = player; fishPrefab = Utils.GetPrefabName(((Component)fish).gameObject); drop = ((Component)fish).GetComponent(); Icon = (((Object)(object)drop == (Object)null) ? null : drop.m_itemData.GetIcon()); startQuality = (((Object)(object)drop == (Object)null) ? 1 : Mathf.Max(1, drop.m_itemData.m_quality)); startLineLength = fishingFloat.m_lineLength; FishProfile fishProfile = FishTuning.For(fish); preset = Presets.Current; skillFactor = ((Character)player).GetSkillFactor((SkillType)104); SkillLevel = skillFactor * 100f; tackle = BaitTackle.For(fishingFloat.GetBait()); Vector3 position = ((Component)fishingFloat).transform.position; Biome = Waters.Biome(position); Depth = Waters.Depth(position); depthFactor = ((HookedPlugin.depthRewards.Value == HookedPlugin.Toggle.Off) ? 0f : Mathf.InverseLerp(HookedPlugin.shallowDepth.Value, Mathf.Max(HookedPlugin.shallowDepth.Value + 1f, HookedPlugin.fullDepth.Value), Depth)); tierFactor = Mathf.InverseLerp(15f, 100f, fishProfile.Difficulty); rewardDifficulty = fishProfile.Difficulty; Lunker = RollLunker(); float num = BeginnerAssist(skillFactor); baseDifficulty = Mathf.Max(15f, (fishProfile.Difficulty * preset.Difficulty + (Lunker ? HookedPlugin.lunkerDifficultyBonus.Value : 0f)) * Mathf.Lerp(1f, HookedPlugin.beginnerDifficultyScale.Value, num)); float barHeight = (float)HookedPlugin.barHeightBase.Value + skillFactor * 10f * (float)HookedPlugin.barHeightPerLevel.Value + num * HookedPlugin.beginnerBarBonus.Value + tackle.BarBonus + preset.BarBonus; bool num2 = Lunker && HookedPlugin.lunkerTreasure.Value == HookedPlugin.Toggle.On && HookedPlugin.treasureEnabled.Value == HookedPlugin.Toggle.On; float bonus = (tackle.TreasureHunter ? (HookedPlugin.treasureChance.Value / 3f) : 0f) + depthFactor * HookedPlugin.depthTreasureBonus.Value + tierFactor * HookedPlugin.treasureTierBonus.Value; bool treasure = num2 || Treasure.Roll(skillFactor, bonus); Bar = new BobberBar(baseDifficulty, fishProfile.Motion, barHeight, treasure, StartingProgress(player)) { Gravity = HookedPlugin.barGravity.Value, InBarGravityScale = HookedPlugin.inBarGravityScale.Value * ((tackle.ClingStrength > 0f) ? 0.5f : 1f), Cling = tackle.ClingStrength, Bounce = tackle.BounceScale, FillRate = HookedPlugin.fillRate.Value * Mathf.Lerp(1f, HookedPlugin.skillFillBonus.Value, skillFactor) * preset.Fill, DrainRate = HookedPlugin.drainRate.Value * Mathf.Lerp(1f, HookedPlugin.beginnerDrainScale.Value, num) * tackle.DrainScale * preset.Drain, TreasureFillRate = HookedPlugin.treasureFillRate.Value, TreasureDrainRate = HookedPlugin.treasureDrainRate.Value, TreasureProtectsFish = tackle.TreasureHunter, WanderScale = (Lunker ? HookedPlugin.lunkerWanderScale.Value : 1f) }; } private static float StartingProgress(Player player) { if (player.m_customData.ContainsKey("Hooked.FirstCatch")) { return HookedPlugin.startingProgress.Value; } return Mathf.Min(HookedPlugin.firstCatchProgress.Value, HookedPlugin.startingProgress.Value); } private bool RollLunker() { if (HookedPlugin.lunkers.Value == HookedPlugin.Toggle.Off) { return false; } float num = HookedPlugin.lunkerChance.Value + skillFactor * HookedPlugin.lunkerSkillBonus.Value + depthFactor * HookedPlugin.depthLunkerBonus.Value + tierFactor * HookedPlugin.lunkerTierBonus.Value; return Random.value < num; } public void PhysicsStep() { //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) float fixedDeltaTime = Time.fixedDeltaTime; if ((Object)(object)player != (Object)null && (Object)(object)rodTop == (Object)null) { rodTop = Float.GetRodTop((Character)(object)player); } if ((Object)(object)player == (Object)null || (Object)(object)rodTop == (Object)null) { Release(""); return; } if (((Character)player).InAttack() || ((Character)player).IsDrawingBow() || ((Character)player).IsDead()) { Float.ReturnBait(); Release(""); return; } float num = Mathf.Lerp(Float.m_hookedStaminaPerSec, Float.m_hookedStaminaPerSecMaxSkill, skillFactor); ((Character)player).UseStamina(num * HookedPlugin.staminaScale.Value * fixedDeltaTime); bool flag = Reeling(player); if (flag) { float num2 = Float.m_pullStaminaUse + Fish.GetStaminaUse() * (float)startQuality; ((Character)player).UseStamina(Mathf.Lerp(num2, num2 * Float.m_pullStaminaUseMaxSkillMultiplier, skillFactor) * HookedPlugin.reelStaminaScale.Value * fixedDeltaTime); } if (!((Character)player).HaveStamina(0f)) { Release("$msg_fishing_lost"); return; } Bar.Difficulty = Mathf.Clamp(baseDifficulty + (Fish.IsEscaping() ? (HookedPlugin.escapeDifficultyBonus.Value * preset.Escape) : 0f), 15f, 100f); Bar.Update(flag, fixedDeltaTime); float num3 = Mathf.Max(HookedPlugin.minLineLength.Value, Float.m_maxDistance - Float.m_breakDistance); float num4 = Mathf.Min(startLineLength, num3); float num5 = Mathf.InverseLerp(HookedPlugin.reelInFrom.Value, 1f, Bar.Progress); float num6 = Mathf.Lerp(num4, Mathf.Min(HookedPlugin.minLineLength.Value, num4), num5); if (num6 > Float.m_lineLength || !Fish.IsOutOfWater()) { Float.m_lineLength = num6; } Vector3 val = rodTop.position - ((Component)Float).transform.position; float magnitude = ((Vector3)(ref val)).magnitude; Float.m_rodLine.SetSlack((1f - Utils.LerpStep(Float.m_lineLength / 2f, Float.m_lineLength, magnitude)) * Float.m_maxLineSlack); if (HookedPlugin.lineBreaks.Value == HookedPlugin.Toggle.On && magnitude > Float.m_maxDistance) { Float.m_lineBreakEffect.Create(((Component)Float).transform.position, Quaternion.identity, (Transform)null, 1f, -1); Release("$msg_fishing_linebroke"); return; } Utils.Pull(Float.m_body, ((Component)Fish).transform.position, 0.5f, Float.m_moveForce, 0.5f, 0.3f, false, false, 1f); Utils.Pull(Float.m_body, rodTop.position, Float.m_lineLength, Float.m_moveForce, 1f, 0.3f, false, false, 1f); switch (Bar.Result) { case BarResult.Caught: Win(); break; case BarResult.Lost: Release("$msg_fishing_lost"); break; default: throw new ArgumentOutOfRangeException(); case BarResult.Running: break; } } private void Win() { //IL_0115: Unknown result type (might be due to invalid IL or missing references) int num = startQuality + SizeBonus(); if (HookedPlugin.qualityFromSize.Value == HookedPlugin.Toggle.On) { num -= Bar.SizeLossSteps / Mathf.Max(1, HookedPlugin.qualityLossSteps.Value); } if (Bar.Perfect && HookedPlugin.perfectUpgradesQuality.Value == HookedPlugin.Toggle.On) { num++; } if (Lunker) { num += HookedPlugin.lunkerQualityBonus.Value; } num += tackle.QualityBonus; num = (((Object)(object)drop == (Object)null) ? num : Mathf.Clamp(num, 1, Mathf.Max(1, drop.m_itemData.m_shared.m_maxQuality))); if ((Object)(object)drop != (Object)null) { drop.SetQuality(num); drop.Save(); } string text = FishingFloat.Catch(Fish, (Character)(object)player); BeachIfNoRoom(); if (SecondFish(num)) { text += " x2"; } if (Bar.TreasureCaught) { string text2 = Treasure.Award(player, Biome, Lunker ? HookedPlugin.lunkerTreasureRolls.Value : 0); if (text2 != null && text2.Length > 0) { text = text + " & " + text2; } } if (Bar.Perfect) { text = "$hooked_perfect " + text; } if (Lunker) { text = "$hooked_lunker " + text; } won = true; player.m_customData["Hooked.FirstCatch"] = "1"; ((Character)player).RaiseSkill((SkillType)104, Experience(num) * HookedPlugin.skillGainScale.Value); FreshCatch.Apply(player, Icon, Bar.Perfect, Lunker); Release(text); } private bool SecondFish(int quality) { if (Lunker || tackle.DoubleChance <= 0f || Random.value >= tackle.DoubleChance) { return false; } if (((Humanoid)player).GetInventory().AddItem(fishPrefab, 1, quality, 0, player.GetPlayerID(), player.GetPlayerName(), false) != null) { return true; } if (!((Object)(object)ZNetScene.instance == (Object)null)) { GameObject prefab = ZNetScene.instance.GetPrefab(fishPrefab); if (prefab != null) { Loot.Give(player, prefab, 1); return true; } } return false; } private void BeachIfNoRoom() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)Fish == (Object)null) && !((Object)(object)Fish.m_nview == (Object)null) && Fish.m_nview.IsValid()) { Vector3 position = Loot.DropSpot(player); ((Component)Fish).transform.position = position; Fish.m_body.position = position; Fish.m_body.linearVelocity = Vector3.zero; } } private int SizeBonus() { if (HookedPlugin.sizeFromSkill.Value == HookedPlugin.Toggle.Off || Random.value >= skillFactor + depthFactor * HookedPlugin.depthSizeBonus.Value) { return 0; } if (!(Random.value < 0.4f)) { return 1; } return 2; } private float Experience(int quality) { float num = Mathf.Max(1f, (float)quality * 3f + rewardDifficulty / 3f); if (Bar.TreasureCaught) { num += num * 1.2f; } if (Bar.Perfect) { num += num * 1.4f; } if (Lunker) { num *= HookedPlugin.lunkerSkillScale.Value; } return num * Mathf.Lerp(1f, 1f + HookedPlugin.depthSkillBonus.Value, depthFactor); } private void RaiseSkillForLoss() { float num = HookedPlugin.skillGainOnLoss.Value * Bar.PeakProgress; if (num > 0f) { ((Character)player).RaiseSkill((SkillType)104, Experience(startQuality) * num * HookedPlugin.skillGainScale.Value); } } private void Release(string message) { if (!finished) { finished = true; if (!won) { RaiseSkillForLoss(); } if (message.Length > 0) { Float.Message(message, true); } Float.SetCatch((Fish)null); if ((Object)(object)Fish != (Object)null) { Fish.OnHooked((FishingFloat)null); } Float.m_nview.Destroy(); End(); } } private void End() { if (Active == this) { Active = null; } BobberBarView.Finish(Bar.Result, Bar.Perfect); } private static float BeginnerAssist(float skillFactor) { if (HookedPlugin.beginnerAssist.Value == HookedPlugin.Toggle.Off || HookedPlugin.beginnerSkillLevel.Value <= 0f) { return 0f; } return 1f - Mathf.Clamp01(skillFactor * 100f / HookedPlugin.beginnerSkillLevel.Value); } private static bool Reeling(Player player) { if (((Character)player).TakeInput()) { if (!ZInput.GetButton("Block")) { return ZInput.GetButton("JoyBlock"); } return true; } return false; } } public static class Loot { public static Vector3 DropSpot(Player player) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) return ((Component)player).transform.position + ((Component)player).transform.forward * 2f + Vector3.up; } public static void Give(Player player, GameObject prefab, int amount) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)prefab == (Object)null) && amount > 0 && (!((Humanoid)player).GetInventory().CanAddItem(prefab, amount) || !((Humanoid)player).GetInventory().AddItem(prefab, amount))) { ItemDrop component = Object.Instantiate(prefab, DropSpot(player), Quaternion.Euler(0f, (float)Random.Range(0, 360), 0f)).GetComponent(); if (component != null) { component.SetStack(amount); } ((Character)player).Message((MessageType)1, Localization.instance.Localize("$inventory_full"), 0, (Sprite)null); } } } public readonly struct DifficultyTuning { public readonly float Difficulty; public readonly float BarBonus; public readonly float Fill; public readonly float Drain; public readonly float Escape; public DifficultyTuning(float difficulty, float barBonus, float fill, float drain, float escape) { Difficulty = difficulty; BarBonus = barBonus; Fill = fill; Drain = drain; Escape = escape; } } public static class Presets { public static DifficultyTuning Current => For(HookedPlugin.difficulty.Value); private static DifficultyTuning For(HookedPlugin.DifficultyPreset preset) { return preset switch { HookedPlugin.DifficultyPreset.Relaxed => new DifficultyTuning(0.7f, 48f, 1.35f, 0.55f, 0.35f), HookedPlugin.DifficultyPreset.Casual => new DifficultyTuning(0.88f, 24f, 1.15f, 0.8f, 0.7f), HookedPlugin.DifficultyPreset.Challenging => new DifficultyTuning(1f, -14f, 0.95f, 1.15f, 1.2f), HookedPlugin.DifficultyPreset.Brutal => new DifficultyTuning(1f, -26f, 0.9f, 1.3f, 1.45f), _ => new DifficultyTuning(1f, 0f, 1f, 1f, 1f), }; } } public static class Treasure { private readonly struct Entry { public readonly GameObject Prefab; public readonly string Name; public readonly int Min; public readonly int Max; public readonly float Weight; public Entry(GameObject prefab, string name, int min, int max, float weight) { Prefab = prefab; Name = name; Min = min; Max = max; Weight = weight; } } private static readonly List Table = new List(); private static readonly Dictionary> BiomeTables = new Dictionary>(); private static readonly List Pool = new List(); private static bool parsed; public static void Invalidate() { parsed = false; } public static bool Roll(float skillFactor, float bonus) { if (HookedPlugin.treasureEnabled.Value == HookedPlugin.Toggle.Off) { return false; } return Random.value < HookedPlugin.treasureChance.Value + skillFactor * HookedPlugin.treasureSkillBonus.Value + bonus; } public static string Award(Player player, Biome biome, int rollBonus) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!parsed) { ParseTables(); } float weight = FillPool(player, biome); if (Pool.Count == 0) { return ""; } List list = new List(); int num = Random.Range(HookedPlugin.treasureRollsMin.Value, HookedPlugin.treasureRollsMax.Value + 1) + rollBonus; for (int i = 0; i < num; i++) { Entry? entry = Pick(weight); if (entry.HasValue) { Entry valueOrDefault = entry.GetValueOrDefault(); int num2 = Random.Range(valueOrDefault.Min, valueOrDefault.Max + 1); if (num2 > 0) { list.Add($"{num2}x {valueOrDefault.Name}"); Loot.Give(player, valueOrDefault.Prefab, num2); } } } return string.Join(" & ", list); } private static float FillPool(Player player, Biome biome) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) Pool.Clear(); bool knownOnly = HookedPlugin.treasureKnownOnly.Value == HookedPlugin.Toggle.On; List value; List list = ((HookedPlugin.treasureBiomeLoot.Value == HookedPlugin.Toggle.On && BiomeTables.TryGetValue(biome, out value)) ? value : null); bool num = list == null || HookedPlugin.treasureBiomeAddsToBase.Value == HookedPlugin.Toggle.On; float num2 = 0f; if (num) { num2 += Take(Table, player, knownOnly); } if (list != null) { num2 += Take(list, player, knownOnly); } if (Pool.Count > 0) { return num2; } return Take(Table, player, knownOnly: false); } private static float Take(List source, Player player, bool knownOnly) { float num = 0f; foreach (Entry item in source) { if (!knownOnly || player.IsMaterialKnown(item.Name)) { Pool.Add(item); num += item.Weight; } } return num; } private static Entry? Pick(float weight) { float num = Random.Range(0f, weight); foreach (Entry item in Pool) { num -= item.Weight; if (num <= 0f) { return item; } } return null; } private static void ParseTables() { //IL_008c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNetScene.instance == (Object)null) { return; } parsed = true; string[] blocklist = HookedPlugin.treasureBlocklist.Value.Split(new char[1] { ',' }); Parse(HookedPlugin.treasureLoot.Value, blocklist, Table); BiomeTables.Clear(); foreach (KeyValuePair> treasureBiomeTable in HookedPlugin.treasureBiomeTables) { List list = new List(); Parse(treasureBiomeTable.Value.Value, blocklist, list); if (list.Count > 0) { BiomeTables[treasureBiomeTable.Key] = list; } } } private static void Parse(string config, string[] blocklist, List into) { into.Clear(); string[] array = config.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length == 0) { continue; } string[] array2 = text.Split(new char[1] { ':' }); if (array2.Length != 4) { HookedPlugin.HookedLogger.LogWarning((object)("Ignoring treasure entry '" + text + "': expected 'Prefab:min:max:weight'.")); continue; } string text2 = array2[0].Trim(); GameObject prefab = ZNetScene.instance.GetPrefab(text2); if (!((Object)(object)prefab == (Object)null)) { ItemDrop component = prefab.GetComponent(); if (component != null) { string text3 = Blocked(component, text2, blocklist); int value; int value2; float value3; if (text3 != null) { HookedPlugin.HookedLogger.LogWarning((object)("Refusing treasure entry '" + text + "': " + text3 + ".")); } else if (!Number(array2[1], out value) || !Number(array2[2], out value2) || !Weight(array2[3], out value3)) { HookedPlugin.HookedLogger.LogWarning((object)("Ignoring treasure entry '" + text + "': min, max and weight all have to be numbers.")); } else { into.Add(new Entry(prefab, component.m_itemData.m_shared.m_name, value, Mathf.Max(value, value2), value3)); } continue; } } HookedPlugin.HookedLogger.LogWarning((object)("Ignoring treasure entry '" + text + "': no item prefab named '" + text2 + "'.")); } } private static string? Blocked(ItemDrop drop, string prefabName, string[] blocklist) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Invalid comparison between Unknown and I4 for (int i = 0; i < blocklist.Length; i++) { if (string.Equals(blocklist[i].Trim(), prefabName, StringComparison.OrdinalIgnoreCase)) { return "it is on the blocklist"; } } if (HookedPlugin.treasureGuard.Value == HookedPlugin.Toggle.Off) { return null; } if (!drop.m_itemData.m_shared.m_teleportable) { return "it cannot go through a portal, which is how the game marks progression material"; } if ((int)drop.m_itemData.m_shared.m_itemType != 13) { return null; } return "trophies summon bosses"; } private static bool Number(string text, out int value) { return int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value); } private static bool Weight(string text, out float value) { return float.TryParse(text.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out value); } } public static class Waters { public static Biome Biome(Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) Biome val = Heightmap.FindBiome(point); if ((int)val != 0) { return val; } return (Biome)256; } public static float Depth(Vector3 point) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZoneSystem.instance == (Object)null) { return 0f; } float num = Floating.GetLiquidLevel(point, 1f, (LiquidType)10); if (num < -1000f) { num = ZoneSystem.instance.m_waterLevel; } return Mathf.Max(0f, num - ZoneSystem.instance.GetGroundHeight(point)); } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy, string>((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } namespace UIManager { internal static class UIRoot { private static Harmony _harmony; private static bool _initialized; private static ButtonSfx _sfxTemplate; private static UIRootHost _host; public const int FrontSortingOrder = 2000; public static Transform Front { get; private set; } public static Transform Back { get; private set; } public static bool IsReady => (Object)(object)Front != (Object)null; public static bool IsHeadless => (int)SystemInfo.graphicsDeviceType == 4; public static int UILayer { get { int num = LayerMask.NameToLayer("UI"); if (num < 0) { return 5; } return num; } } internal static UIRootHost Host { get { EnsureHost(); return _host; } } public static event Action OnReady; public static void Init(ManualLogSource log = null, Harmony harmony = null) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) if (!_initialized) { _initialized = true; if (log != null) { UILog.Use(log); } if (IsHeadless) { UILog.Debug("headless - skipping GUI setup"); return; } string text = "uimanager." + typeof(UIRoot).Assembly.GetName().Name.ToLowerInvariant(); _harmony = (Harmony)(((object)harmony) ?? ((object)new Harmony(text))); _harmony.PatchAll(typeof(UIRoot)); _harmony.PatchAll(typeof(InputBlocker)); _harmony.PatchAll(typeof(UIPanels)); SceneManager.sceneLoaded += OnSceneLoaded; EnsureHost(); TryCreateGui(); } } private static void EnsureHost() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown if (!((Object)(object)_host != (Object)null)) { GameObject val = new GameObject("UIManager.Host [" + typeof(UIRoot).Assembly.GetName().Name + "]") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val); _host = val.AddComponent(); } } private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (!(((Scene)(ref scene)).name != "start") || !(((Scene)(ref scene)).name != "main")) { GameAssets.Index(force: true); if ((Object)(object)_host != (Object)null) { ((MonoBehaviour)_host).StartCoroutine(WaitAndCreate()); } } } private static IEnumerator WaitAndCreate() { for (int i = 0; i < 300; i++) { if (IsReady) { break; } TryCreateGui(); if (IsReady) { break; } yield return null; } } [HarmonyPatch(typeof(FejdStartup), "SetupGui")] [HarmonyPostfix] private static void FejdStartupSetupGuiPostfix() { TryCreateGui(); } [HarmonyPatch(typeof(Game), "Start")] [HarmonyPostfix] private static void GameStartPostfix() { TryCreateGui(); } public static void TryCreateGui() { if (IsReady || IsHeadless) { return; } Transform val = FindGuiRoot(); if ((Object)(object)val == (Object)null) { return; } GameAssets.Index(force: true); VanillaUI.Harvest(force: true); string name = typeof(UIRoot).Assembly.GetName().Name; Back = CreateCanvas("UIManager.Back [" + name + "]", 0, val).transform; Back.SetAsFirstSibling(); Front = CreateCanvas("UIManager.Front [" + name + "]", 2000, val).transform; Front.SetAsLastSibling(); UILog.Debug("GUI canvases created under " + UIExtensions.PathOf(val)); try { UIRoot.OnReady?.Invoke(); } catch (Exception e) { UILog.Error("a UIRoot.OnReady handler threw", e); } } private static void SetLayerRecursively(GameObject target, int layer) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)target == (Object)null) { return; } target.layer = layer; foreach (Transform item in target.transform) { SetLayerRecursively(((Component)item).gameObject, layer); } } private static Transform FindGuiRoot() { GameObject val = GameObject.Find("GuiRoot/GUI"); if ((Object)(object)val != (Object)null) { return val.transform; } GameObject val2 = GameObject.Find("_GameMain/LoadingGUI"); if ((Object)(object)val2 != (Object)null) { return val2.transform; } return null; } private static GameObject CreateCanvas(string name, int sortingOrder, Transform parent) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Expected O, but got Unknown GameObject val = new GameObject(name, new Type[5] { typeof(RectTransform), typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster), typeof(GuiPixelFix) }) { layer = UILayer }; val.transform.SetParent(parent, false); RectTransform val2 = (RectTransform)val.transform; val2.anchorMin = Vector2.zero; val2.anchorMax = Vector2.one; val2.offsetMin = Vector2.zero; val2.offsetMax = Vector2.zero; ((Transform)val2).localScale = Vector3.one; Canvas component = val.GetComponent(); component.renderMode = (RenderMode)0; component.overrideSorting = true; component.sortingOrder = sortingOrder; component.additionalShaderChannels = (AdditionalCanvasShaderChannels)25; val.GetComponent().referencePixelsPerUnit = 50f; return val; } public static GameObject Instantiate(GameObject prefab, Transform parent = null, bool style = true, StyleOptions options = null) { if ((Object)(object)prefab == (Object)null) { UILog.Error("cannot instantiate a null prefab"); return null; } if ((Object)(object)parent == (Object)null) { parent = Front; } if ((Object)(object)parent == (Object)null) { UILog.Error("the GUI is not up yet - hook UIRoot.OnReady before instantiating '" + ((Object)prefab).name + "'"); return null; } GameObject val = Object.Instantiate(prefab, parent, false); ((Object)val).name = ((Object)prefab).name; SetLayerRecursively(val, UILayer); if (style) { Styler.Apply(val, options); } return val; } public static Canvas RaiseAbove(GameObject target, int extra = 100) { if ((Object)(object)target == (Object)null) { return null; } Canvas obj = target.GetComponent() ?? target.AddComponent(); obj.overrideSorting = true; obj.sortingOrder = 2000 + extra; if ((Object)(object)target.GetComponent() == (Object)null) { target.AddComponent(); } return obj; } public static ButtonSfx FindSfxTemplate() { if ((Object)(object)_sfxTemplate != (Object)null) { return _sfxTemplate; } ButtonSfx[] array = Resources.FindObjectsOfTypeAll(); foreach (ButtonSfx val in array) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val.m_sfxPrefab == (Object)null)) { _sfxTemplate = val; break; } } return _sfxTemplate; } public static Coroutine Run(IEnumerator routine) { EnsureHost(); return ((MonoBehaviour)_host).StartCoroutine(routine); } } internal class UIRootHost : MonoBehaviour { private void Update() { InputBlocker.Tick(); UIPanels.Tick(); } } internal static class GameAssets { private static readonly Dictionary SpriteIndex = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary> SpriteDuplicates = new Dictionary>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary FontIndex = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary TmpFontIndex = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary MaterialIndex = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary ClipIndex = new Dictionary(StringComparer.OrdinalIgnoreCase); private static int _indexedFrame = -1; public static bool TrustedOnly; public static bool IsIndexed => _indexedFrame >= 0; public static int SpriteCount => SpriteIndex.Count; public static IEnumerable SpriteNames => SpriteIndex.Keys; public static IEnumerable FontNames => FontIndex.Keys; public static IEnumerable TmpFontNames => TmpFontIndex.Keys; public static IEnumerable AllSprites => SpriteIndex.Values; public static void Index(bool force = false) { if (force || _indexedFrame != Time.frameCount) { SpriteIndex.Clear(); SpriteDuplicates.Clear(); FontIndex.Clear(); TmpFontIndex.Clear(); MaterialIndex.Clear(); ClipIndex.Clear(); Sprite[] array = Resources.FindObjectsOfTypeAll(); for (int i = 0; i < array.Length; i++) { AddSprite(array[i]); } IndexAtlases(); Font[] array2 = Resources.FindObjectsOfTypeAll(); foreach (Font val in array2) { Put((IDictionary)FontIndex, ((Object)(object)val != (Object)null) ? ((Object)val).name : null, val); } TMP_FontAsset[] array3 = Resources.FindObjectsOfTypeAll(); foreach (TMP_FontAsset val2 in array3) { Put((IDictionary)TmpFontIndex, ((Object)(object)val2 != (Object)null) ? ((Object)val2).name : null, val2); } Material[] array4 = Resources.FindObjectsOfTypeAll(); foreach (Material val3 in array4) { Put((IDictionary)MaterialIndex, ((Object)(object)val3 != (Object)null) ? ((Object)val3).name : null, val3); } AudioClip[] array5 = Resources.FindObjectsOfTypeAll(); foreach (AudioClip val4 in array5) { Put((IDictionary)ClipIndex, ((Object)(object)val4 != (Object)null) ? ((Object)val4).name : null, val4); } _indexedFrame = Time.frameCount; UILog.Debug($"indexed {SpriteIndex.Count} sprites, {FontIndex.Count} fonts, {TmpFontIndex.Count} TMP fonts, {MaterialIndex.Count} materials, {ClipIndex.Count} clips"); } } private static void IndexAtlases() { SpriteAtlas[] array = Resources.FindObjectsOfTypeAll(); foreach (SpriteAtlas val in array) { if ((Object)(object)val == (Object)null || val.spriteCount <= 0) { continue; } try { Sprite[] array2 = (Sprite[])(object)new Sprite[val.spriteCount]; val.GetSprites(array2); Sprite[] array3 = array2; for (int j = 0; j < array3.Length; j++) { AddSprite(array3[j]); } } catch (Exception ex) { UILog.Debug("could not read atlas '" + ((Object)val).name + "': " + ex.Message); } } } private static void AddSprite(Sprite sprite) { if ((Object)(object)sprite == (Object)null) { return; } string text = ((Object)sprite).name; if (text.EndsWith("(Clone)", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - 7); } if (string.IsNullOrEmpty(text)) { return; } if (!SpriteIndex.ContainsKey(text)) { SpriteIndex[text] = sprite; } else if (!((Object)(object)SpriteIndex[text] == (Object)(object)sprite)) { if (!SpriteDuplicates.TryGetValue(text, out var value)) { value = (SpriteDuplicates[text] = new List()); } if (!value.Contains(sprite)) { value.Add(sprite); } } } private static void Put(IDictionary index, string name, T value) where T : Object { if (!((Object)(object)value == (Object)null) && !string.IsNullOrEmpty(name) && !index.ContainsKey(name)) { index[name] = value; } } public static Sprite Sprite(string name) { TryGetSprite(name, out var sprite); return sprite; } public static bool TryGetSprite(string name, out Sprite sprite) { sprite = null; if (string.IsNullOrEmpty(name)) { return false; } if (VanillaUI.TryGetSprite(name, out sprite)) { return true; } if (TrustedOnly) { return false; } if (!IsIndexed) { Index(); } if (SpriteIndex.TryGetValue(name, out sprite) && (Object)(object)sprite != (Object)null) { return true; } Index(force: true); if (SpriteIndex.TryGetValue(name, out sprite)) { return (Object)(object)sprite != (Object)null; } return false; } public static IList SpritesNamed(string name) { List list = new List(); if (TryGetSprite(name, out var sprite)) { list.Add(sprite); } if (SpriteDuplicates.TryGetValue(name, out var value)) { list.AddRange(value); } return list; } public static Sprite FirstSprite(params string[] candidates) { for (int i = 0; i < candidates.Length; i++) { if (TryGetSprite(candidates[i], out var sprite)) { return sprite; } } return null; } public static Font Font(string name) { if (string.IsNullOrEmpty(name)) { return null; } Font val = VanillaUI.Font(name); if ((Object)(object)val != (Object)null) { return val; } if (TrustedOnly) { return null; } if (!IsIndexed) { Index(); } if (FontIndex.TryGetValue(name, out var value) && (Object)(object)value != (Object)null) { return value; } Index(force: true); if (!FontIndex.TryGetValue(name, out value)) { return null; } return value; } public static Font FirstFont(params string[] candidates) { for (int i = 0; i < candidates.Length; i++) { Font val = Font(candidates[i]); if ((Object)(object)val != (Object)null) { return val; } } return null; } public static TMP_FontAsset TmpFont(string name) { if (string.IsNullOrEmpty(name)) { return null; } TMP_FontAsset val = VanillaUI.TmpFont(name); if ((Object)(object)val != (Object)null) { return val; } if (TrustedOnly) { return null; } if (!IsIndexed) { Index(); } if (TmpFontIndex.TryGetValue(name, out var value) && (Object)(object)value != (Object)null) { return value; } Index(force: true); if (!TmpFontIndex.TryGetValue(name, out value)) { return null; } return value; } public static TMP_FontAsset FirstTmpFont(params string[] candidates) { for (int i = 0; i < candidates.Length; i++) { TMP_FontAsset val = TmpFont(candidates[i]); if ((Object)(object)val != (Object)null) { return val; } } return null; } public static TMP_FontAsset AnyTmpFont() { if (!IsIndexed) { Index(); } foreach (TMP_FontAsset value in TmpFontIndex.Values) { if ((Object)(object)value != (Object)null) { return value; } } return null; } public static Material Material(string name) { if (string.IsNullOrEmpty(name)) { return null; } if (!IsIndexed) { Index(); } if (!MaterialIndex.TryGetValue(name, out var value)) { return null; } return value; } public static AudioClip Clip(string name) { if (string.IsNullOrEmpty(name)) { return null; } if (!IsIndexed) { Index(); } if (!ClipIndex.TryGetValue(name, out var value)) { return null; } return value; } public static AudioClip FirstClip(params string[] candidates) { for (int i = 0; i < candidates.Length; i++) { AudioClip val = Clip(candidates[i]); if ((Object)(object)val != (Object)null) { return val; } } return null; } public static IEnumerable Search(string term, int limit = 60) { if (!IsIndexed) { Index(); } if (string.IsNullOrEmpty(term)) { return SpriteIndex.Keys.OrderBy((string k) => k).Take(limit); } return (from k in SpriteIndex.Keys where k.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0 orderby k select k).Take(limit); } } internal static class VanillaUI { private static readonly Dictionary Sprites = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary Fonts = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary TmpFonts = new Dictionary(StringComparer.OrdinalIgnoreCase); private static Material _uiMaterial; private static TMP_FontAsset _primaryTmpFont; private static TMP_FontAsset _titleTmpFont; private static Font _primaryFont; private static Scrollbar _scrollbar; private static ScrollRect _scrollRect; private static int _scrollbarScore; private static int _harvestedFrame = -1; private static readonly Dictionary _tmpFontUse = new Dictionary(); private static readonly Dictionary _fontUse = new Dictionary(); private static float _largestText; private static readonly HashSet StockSprites = new HashSet(StringComparer.OrdinalIgnoreCase) { "UISprite", "Knob", "Checkmark", "UIMask", "DropdownArrow", "InputFieldBackground" }; public static bool IsHarvested => _harvestedFrame >= 0; public static int SpriteCount => Sprites.Count; public static Material UiMaterial { get { Harvest(); return _uiMaterial; } } public static TMP_FontAsset PrimaryTmpFont { get { Harvest(); return _primaryTmpFont; } } public static TMP_FontAsset TitleTmpFont { get { Harvest(); if (!((Object)(object)_titleTmpFont != (Object)null)) { return _primaryTmpFont; } return _titleTmpFont; } } public static Font PrimaryFont { get { Harvest(); return _primaryFont; } } public static Scrollbar ScrollbarTemplate { get { Harvest(); if (!((Object)(object)_scrollbar != (Object)null)) { return null; } return _scrollbar; } } public static ScrollRect ScrollRectTemplate { get { Harvest(); if (!((Object)(object)_scrollRect != (Object)null)) { return null; } return _scrollRect; } } public static IEnumerable SpriteNames { get { Harvest(); return Sprites.Keys; } } public static void Harvest(bool force = false) { if ((!force && _harvestedFrame >= 0) || (!force && _harvestedFrame == Time.frameCount)) { return; } Sprites.Clear(); Fonts.Clear(); TmpFonts.Clear(); _uiMaterial = null; _scrollbar = null; _scrollRect = null; _scrollbarScore = 0; _primaryTmpFont = null; _titleTmpFont = null; _primaryFont = null; Dictionary dictionary = new Dictionary(); _tmpFontUse.Clear(); _fontUse.Clear(); _largestText = 0f; bool flag = false; foreach (GameObject item in Roots()) { if (!((Object)(object)item == (Object)null)) { flag = true; Collect(item, dictionary); } } if (!flag) { return; } foreach (KeyValuePair item2 in dictionary) { if (!((Object)(object)item2.Key == (Object)null) && ((Object)item2.Key).name.StartsWith("litpanel", StringComparison.OrdinalIgnoreCase)) { _uiMaterial = item2.Key; break; } } int num = 0; if ((Object)(object)_uiMaterial == (Object)null) { foreach (KeyValuePair item3 in dictionary) { if (!((Object)(object)item3.Key == (Object)null) && item3.Value > num) { num = item3.Value; _uiMaterial = item3.Key; } } } _primaryTmpFont = MostUsed(_tmpFontUse); _primaryFont = MostUsed(_fontUse); _harvestedFrame = Time.frameCount; UILog.Debug($"harvested {Sprites.Count} sprites, {Fonts.Count} fonts, {TmpFonts.Count} TMP fonts from the game UI; " + "material '" + (((Object)(object)_uiMaterial != (Object)null) ? ((Object)_uiMaterial).name : "none") + "', scrollbar '" + (((Object)(object)_scrollbar != (Object)null) ? UIExtensions.PathOf(((Component)_scrollbar).transform) : "none") + "' " + $"(score {_scrollbarScore}), " + "body font '" + (((Object)(object)_primaryTmpFont != (Object)null) ? ((Object)_primaryTmpFont).name : "none") + "', title font '" + (((Object)(object)_titleTmpFont != (Object)null) ? ((Object)_titleTmpFont).name : "none") + "'"); } private static T MostUsed(Dictionary counts) where T : Object { T result = default(T); int num = 0; foreach (KeyValuePair count in counts) { if (!((Object)(object)count.Key == (Object)null) && count.Value > num) { num = count.Value; result = count.Key; } } return result; } public static IEnumerable RootObjects() { return Roots(); } private static IEnumerable Roots() { yield return Instance((Component)(object)FejdStartup.instance); yield return Instance((Component)(object)InventoryGui.instance); yield return Instance((Component)(object)Menu.instance); yield return Instance((Component)(object)Hud.instance); yield return Instance((Component)(object)StoreGui.instance); yield return Instance((Component)(object)TextViewer.instance); yield return Instance((Component)(object)Minimap.instance); } private static GameObject Instance(Component component) { if (!((Object)(object)component != (Object)null)) { return null; } return component.gameObject; } private static void Collect(GameObject root, IDictionary materialUse) { Image[] componentsInChildren = root.GetComponentsInChildren(true); foreach (Image val in componentsInChildren) { if (!((Object)(object)val == (Object)null)) { if ((Object)(object)val.sprite != (Object)null) { Put((IDictionary)Sprites, ((Object)val.sprite).name, val.sprite); } Material material = ((Graphic)val).material; if ((Object)(object)material != (Object)null && (Object)(object)material != (Object)(object)Graphic.defaultGraphicMaterial) { materialUse[material] = ((!materialUse.TryGetValue(material, out var value)) ? 1 : (value + 1)); } } } Text[] componentsInChildren2 = root.GetComponentsInChildren(true); foreach (Text val2 in componentsInChildren2) { if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.font == (Object)null)) { Put((IDictionary)Fonts, ((Object)val2.font).name, val2.font); _fontUse[val2.font] = ((!_fontUse.TryGetValue(val2.font, out var value2)) ? 1 : (value2 + 1)); } } TMP_Text[] componentsInChildren3 = root.GetComponentsInChildren(true); foreach (TMP_Text val3 in componentsInChildren3) { if (!((Object)(object)val3 == (Object)null) && !((Object)(object)val3.font == (Object)null)) { Put((IDictionary)TmpFonts, ((Object)val3.font).name, val3.font); _tmpFontUse[val3.font] = ((!_tmpFontUse.TryGetValue(val3.font, out var value3)) ? 1 : (value3 + 1)); if (val3.fontSize > _largestText) { _largestText = val3.fontSize; _titleTmpFont = val3.font; } } } if ((Object)(object)_scrollRect == (Object)null) { ScrollRect[] componentsInChildren4 = root.GetComponentsInChildren(true); foreach (ScrollRect val4 in componentsInChildren4) { if (!((Object)(object)val4 == (Object)null)) { _scrollRect = val4; break; } } } Scrollbar[] componentsInChildren5 = root.GetComponentsInChildren(true); foreach (Scrollbar scrollbar in componentsInChildren5) { int num = ScoreScrollbar(scrollbar); if (num > _scrollbarScore) { _scrollbarScore = num; _scrollbar = scrollbar; } } } private static int ScoreScrollbar(Scrollbar scrollbar) { if ((Object)(object)scrollbar == (Object)null || (Object)(object)scrollbar.handleRect == (Object)null) { return 0; } Image val = (Image)(((object)((Component)scrollbar.handleRect).GetComponent()) ?? ((object)/*isinst with value type is only supported in some contexts*/)); if ((Object)(object)val == (Object)null || (Object)(object)val.sprite == (Object)null) { return 0; } if (StockSprites.Contains(((Object)val.sprite).name)) { return 0; } int num = 5; if ((Object)(object)((Graphic)val).material != (Object)null && (Object)(object)((Graphic)val).material != (Object)(object)Graphic.defaultGraphicMaterial) { num += 2; } Image component = ((Component)scrollbar).GetComponent(); if ((Object)(object)component != (Object)null && (Object)(object)component.sprite != (Object)null && !StockSprites.Contains(((Object)component.sprite).name)) { num += 2; } if ((Object)(object)((Component)scrollbar).GetComponentInParent() != (Object)null) { num++; } return num; } private static void Put(IDictionary index, string name, T value) where T : Object { if (!((Object)(object)value == (Object)null) && !string.IsNullOrEmpty(name) && !index.ContainsKey(name)) { index[name] = value; } } public static bool TryGetSprite(string name, out Sprite sprite) { sprite = null; if (string.IsNullOrEmpty(name)) { return false; } Harvest(); if (Sprites.TryGetValue(name, out sprite)) { return (Object)(object)sprite != (Object)null; } return false; } public static Font Font(string name) { if (string.IsNullOrEmpty(name)) { return null; } Harvest(); if (!Fonts.TryGetValue(name, out var value)) { return null; } return value; } public static TMP_FontAsset TmpFont(string name) { if (string.IsNullOrEmpty(name)) { return null; } Harvest(); if (!TmpFonts.TryGetValue(name, out var value)) { return null; } return value; } } internal class ModBundle : IDisposable { private static readonly Dictionary Cache = new Dictionary(StringComparer.OrdinalIgnoreCase); public AssetBundle Bundle { get; private set; } public string Name { get; private set; } public IEnumerable AssetNames { get { if (!((Object)(object)Bundle != (Object)null)) { return Enumerable.Empty(); } return Bundle.GetAllAssetNames(); } } private ModBundle(string name, AssetBundle bundle) { Name = name; Bundle = bundle; } public static ModBundle FromEmbeddedResource(string fileName, Assembly assembly = null) { if (Cache.TryGetValue(fileName, out var value) && (Object)(object)value.Bundle != (Object)null) { return value; } assembly = assembly ?? Assembly.GetCallingAssembly(); string[] manifestResourceNames = assembly.GetManifestResourceNames(); string text = manifestResourceNames.FirstOrDefault((string n) => n.EndsWith(fileName, StringComparison.OrdinalIgnoreCase)); if (text == null) { UILog.Error("no embedded resource ending in '" + fileName + "' in " + assembly.GetName().Name + ". Found: " + ((manifestResourceNames.Length == 0) ? "none" : string.Join(", ", manifestResourceNames))); return null; } byte[] array; using (Stream stream = assembly.GetManifestResourceStream(text)) { if (stream == null) { UILog.Error("could not open embedded resource '" + text + "'"); return null; } using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); array = memoryStream.ToArray(); } AssetBundle val = AssetBundle.LoadFromMemory(array); if ((Object)(object)val == (Object)null) { UILog.Error("'" + text + "' is not a valid AssetBundle for this Unity version"); return null; } ModBundle modBundle = new ModBundle(fileName, val); Cache[fileName] = modBundle; UILog.Debug($"loaded bundle '{fileName}' with {val.GetAllAssetNames().Length} assets"); return modBundle; } public static ModBundle FromFile(string path) { if (!File.Exists(path)) { UILog.Error("no bundle at '" + path + "'"); return null; } string fileName = Path.GetFileName(path); if (Cache.TryGetValue(fileName, out var value) && (Object)(object)value.Bundle != (Object)null) { return value; } AssetBundle val = AssetBundle.LoadFromFile(path); if ((Object)(object)val == (Object)null) { UILog.Error("'" + path + "' is not a valid AssetBundle"); return null; } ModBundle modBundle = new ModBundle(fileName, val); Cache[fileName] = modBundle; return modBundle; } public T Load(string assetName) where T : Object { if ((Object)(object)Bundle == (Object)null) { return default(T); } T val = Bundle.LoadAsset(assetName); if ((Object)(object)val == (Object)null) { UILog.Error("bundle '" + Name + "' has no " + typeof(T).Name + " called '" + assetName + "'"); } return val; } public GameObject Prefab(string prefabName) { return this.Load(prefabName); } public GameObject Instantiate(string prefabName, Transform parent = null, bool style = true, StyleOptions options = null) { GameObject val = Prefab(prefabName); if (!((Object)(object)val == (Object)null)) { return UIRoot.Instantiate(val, parent, style, options); } return null; } public void Dispose() { if (!((Object)(object)Bundle == (Object)null)) { Cache.Remove(Name); Bundle.Unload(false); Bundle = null; } } } [Serializable] internal class SpriteRecord { public string name; public string file; public string texture; public int width; public int height; public float pixelsPerUnit; public float[] border = new float[4]; public float[] pivot = new float[2]; } [Serializable] internal class DumpManifest { public string generated; public string unityVersion; public List sprites = new List(); public List fonts = new List(); public List tmpFonts = new List(); public List materials = new List(); } internal static class AssetDump { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Func <>9__2_0; public static Func <>9__2_1; public static ConsoleEvent <>9__8_0; public static ConsoleEvent <>9__8_1; public static ConsoleEvent <>9__8_2; public static Func <>9__8_4; public static Func <>9__8_5; public static ConsoleEvent <>9__8_3; internal string b__2_0(string n) { return n; } internal string b__2_1(string n) { return n; } internal void b__8_0(ConsoleEventArgs args) { string filter = ((args.Length > 1) ? args[1] : null); args.Context.AddString(Dump(filter)); } internal void b__8_1(ConsoleEventArgs args) { if (args.Length < 2) { args.Context.AddString("usage: uim_find "); return; } List list = GameAssets.Search(args[1]).ToList(); args.Context.AddString((list.Count == 0) ? ("no sprite matches " + args[1]) : string.Join("\n", list.ToArray())); } internal void b__8_2(ConsoleEventArgs args) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown if ((Object)(object)UIRoot.Front == (Object)null) { args.Context.AddString("the GUI is not up yet"); return; } bool flag = false; foreach (Transform item in UIRoot.Front) { Transform val = item; if (((Component)val).gameObject.activeInHierarchy) { flag = true; string text = UILayout.Report(((Component)val).gameObject); args.Context.AddString(text); UILog.Info(Environment.NewLine + text); } } if (!flag) { args.Context.AddString("no visible windows on the UIManager canvas"); } } internal void b__8_3(ConsoleEventArgs args) { args.Context.AddString("Font: " + string.Join(", ", GameAssets.FontNames.OrderBy((string n) => n).ToArray())); args.Context.AddString("TMP: " + string.Join(", ", GameAssets.TmpFontNames.OrderBy((string n) => n).ToArray())); } internal string b__8_4(string n) { return n; } internal string b__8_5(string n) { return n; } } private static bool _registered; public static string DefaultDirectory { get { try { return Path.Combine(Paths.PluginPath, "UIManager_StyleKit"); } catch { return Path.Combine(Application.dataPath, "../UIManager_StyleKit"); } } } public static string Dump(string filter = null, string directory = null) { //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) directory = directory ?? DefaultDirectory; string text = Path.Combine(directory, "Sprites"); Directory.CreateDirectory(text); GameAssets.Index(force: true); DumpManifest dumpManifest = new DumpManifest { generated = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), unityVersion = Application.unityVersion }; int num = 0; int num2 = 0; HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (Sprite item in GameAssets.AllSprites.ToList()) { if ((Object)(object)item == (Object)null) { continue; } string name = ((Object)item).name; if (!string.IsNullOrEmpty(filter) && name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) < 0) { continue; } string text2 = Sanitize(name); if (!hashSet.Add(text2)) { continue; } try { Texture2D val = Extract(item); if ((Object)(object)val == (Object)null) { num2++; continue; } string text3 = text2 + ".png"; File.WriteAllBytes(Path.Combine(text, text3), ImageConversion.EncodeToPNG(val)); Object.DestroyImmediate((Object)(object)val); List sprites = dumpManifest.sprites; SpriteRecord spriteRecord = new SpriteRecord { name = name, file = text3, texture = (((Object)(object)item.texture != (Object)null) ? ((Object)item.texture).name : string.Empty) }; Rect rect = item.rect; spriteRecord.width = Mathf.RoundToInt(((Rect)(ref rect)).width); rect = item.rect; spriteRecord.height = Mathf.RoundToInt(((Rect)(ref rect)).height); spriteRecord.pixelsPerUnit = item.pixelsPerUnit; spriteRecord.border = new float[4] { item.border.x, item.border.y, item.border.z, item.border.w }; float[] array = new float[2]; rect = item.rect; float num3; if (!(((Rect)(ref rect)).width > 0f)) { num3 = 0.5f; } else { float x = item.pivot.x; rect = item.rect; num3 = x / ((Rect)(ref rect)).width; } array[0] = num3; rect = item.rect; float num4; if (!(((Rect)(ref rect)).height > 0f)) { num4 = 0.5f; } else { float y = item.pivot.y; rect = item.rect; num4 = y / ((Rect)(ref rect)).height; } array[1] = num4; spriteRecord.pivot = array; sprites.Add(spriteRecord); num++; } catch (Exception ex) { num2++; UILog.Debug("could not dump sprite '" + name + "': " + ex.Message); } } dumpManifest.fonts.AddRange(GameAssets.FontNames.OrderBy((string n) => n)); dumpManifest.tmpFonts.AddRange(GameAssets.TmpFontNames.OrderBy((string n) => n)); File.WriteAllText(Path.Combine(directory, "manifest.json"), JsonUtility.ToJson((object)dumpManifest, true)); File.WriteAllText(Path.Combine(directory, "README.txt"), Readme(dumpManifest)); string text4 = $"dumped {num} sprites to {directory}" + ((num2 > 0) ? $" ({num2} skipped)" : string.Empty); UILog.Info(text4); return text4; } private static Texture2D Extract(Sprite sprite) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown Texture2D texture = sprite.texture; if ((Object)(object)texture == (Object)null) { return null; } Rect val = sprite.textureRect; if (((Rect)(ref val)).width < 1f || ((Rect)(ref val)).height < 1f) { val = sprite.rect; } if (((Rect)(ref val)).width < 1f || ((Rect)(ref val)).height < 1f) { return null; } RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)1); RenderTexture active = RenderTexture.active; try { Graphics.Blit((Texture)(object)texture, temporary); RenderTexture.active = temporary; Texture2D val2 = new Texture2D((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height, (TextureFormat)4, false); val2.ReadPixels(new Rect(((Rect)(ref val)).x, ((Rect)(ref val)).y, ((Rect)(ref val)).width, ((Rect)(ref val)).height), 0, 0); val2.Apply(); return val2; } finally { RenderTexture.active = active; RenderTexture.ReleaseTemporary(temporary); } } private static string Sanitize(string name) { StringBuilder stringBuilder = new StringBuilder(name.Length); foreach (char c in name) { stringBuilder.Append((Array.IndexOf(Path.GetInvalidFileNameChars(), c) >= 0) ? '_' : c); } return stringBuilder.ToString(); } private static string Readme(DumpManifest manifest) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("UIManager style kit"); stringBuilder.AppendLine("==================="); stringBuilder.AppendLine(); stringBuilder.AppendLine("Generated " + manifest.generated + " from Valheim running Unity " + manifest.unityVersion + "."); stringBuilder.AppendLine($"{manifest.sprites.Count} sprites."); stringBuilder.AppendLine(); stringBuilder.AppendLine("How to use:"); stringBuilder.AppendLine(" 1. Copy this whole folder into your Unity project."); stringBuilder.AppendLine(" 2. The UIManagerStyleKit editor script reads manifest.json and applies the"); stringBuilder.AppendLine(" original 9-slice borders, pivots and pixels-per-unit to every PNG."); stringBuilder.AppendLine(" 3. Build your UI using these sprites. Keep the sprite ASSET names unchanged -"); stringBuilder.AppendLine(" that name is what Styler matches on at runtime. GameObject names are yours"); stringBuilder.AppendLine(" to prefix however you like."); stringBuilder.AppendLine(" 4. At runtime Styler.Apply swaps each one for the live game asset, so your UI"); stringBuilder.AppendLine(" picks up the real atlas, material and any art changes from game patches."); stringBuilder.AppendLine(); stringBuilder.AppendLine("Fonts available in game (use the same names on your Text components):"); foreach (string font in manifest.fonts) { stringBuilder.AppendLine(" " + font); } stringBuilder.AppendLine(); stringBuilder.AppendLine("TextMeshPro fonts:"); foreach (string tmpFont in manifest.tmpFonts) { stringBuilder.AppendLine(" " + tmpFont); } return stringBuilder.ToString(); } private static void Command(string name, string description, ConsoleEvent action) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (Terminal.commands != null && Terminal.commands.ContainsKey(name)) { UILog.Debug("console command '" + name + "' is already registered, leaving it alone"); } else { new ConsoleCommand(name, description, action, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } public static void RegisterConsoleCommands() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected O, but got Unknown if (_registered) { return; } _registered = true; object obj = <>c.<>9__8_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { string filter = ((args.Length > 1) ? args[1] : null); args.Context.AddString(Dump(filter)); }; <>c.<>9__8_0 = val; obj = (object)val; } Command("uim_dump", "[filter] - dump Valheim UI sprites to a style kit folder", (ConsoleEvent)obj); object obj2 = <>c.<>9__8_1; if (obj2 == null) { ConsoleEvent val2 = delegate(ConsoleEventArgs args) { if (args.Length < 2) { args.Context.AddString("usage: uim_find "); } else { List list = GameAssets.Search(args[1]).ToList(); args.Context.AddString((list.Count == 0) ? ("no sprite matches " + args[1]) : string.Join("\n", list.ToArray())); } }; <>c.<>9__8_1 = val2; obj2 = (object)val2; } Command("uim_find", " - list game sprites whose name contains term", (ConsoleEvent)obj2); object obj3 = <>c.<>9__8_2; if (obj3 == null) { ConsoleEvent val3 = delegate(ConsoleEventArgs args) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown if ((Object)(object)UIRoot.Front == (Object)null) { args.Context.AddString("the GUI is not up yet"); } else { bool flag = false; foreach (Transform item in UIRoot.Front) { Transform val5 = item; if (((Component)val5).gameObject.activeInHierarchy) { flag = true; string text = UILayout.Report(((Component)val5).gameObject); args.Context.AddString(text); UILog.Info(Environment.NewLine + text); } } if (!flag) { args.Context.AddString("no visible windows on the UIManager canvas"); } } }; <>c.<>9__8_2 = val3; obj3 = (object)val3; } Command("uim_overlap", "what your windows are covering, and how far to move", (ConsoleEvent)obj3); object obj4 = <>c.<>9__8_3; if (obj4 == null) { ConsoleEvent val4 = delegate(ConsoleEventArgs args) { args.Context.AddString("Font: " + string.Join(", ", GameAssets.FontNames.OrderBy((string n) => n).ToArray())); args.Context.AddString("TMP: " + string.Join(", ", GameAssets.TmpFontNames.OrderBy((string n) => n).ToArray())); }; <>c.<>9__8_3 = val4; obj4 = (object)val4; } Command("uim_fonts", "list the fonts the game has loaded", (ConsoleEvent)obj4); } } internal enum TextRole { Body, Title, Header, Label, Disabled } internal static class SpriteNames { public static string[] Window = new string[3] { "woodpanel_settings", "woodpanel_trophys", "woodpanel_password" }; public static string[] Panel = new string[4] { "panel_interior_bkg_128", "woodpanel_trophys", "InventoryBkg", "Background" }; public static string[] Button = new string[3] { "button", "button_small", "menu_button" }; public static string[] ButtonHighlight = new string[2] { "button_highlight", "button_fill" }; public static string[] ButtonDisabled = new string[2] { "button_disabled", "button" }; public static string[] Field = new string[2] { "text_field", "InputFieldBackground" }; public static string[] Checkbox = new string[1] { "checkbox" }; public static string[] CheckboxMarker = new string[1] { "checkbox_marker" }; public static string[] Slot = new string[3] { "item_background_sunken", "item_background", "inventory_slot" }; public static string[] ScrollHandle = new string[3] { "scrollbar_handle", "UISprite", "button" }; public static string[] ScrollTrack = new string[3] { "scrollbar_bkg", "Background", "UISprite" }; public static string[] Divider = new string[2] { "line_bkg", "UISprite" }; } internal static class FontNames { public static string[] Body = new string[2] { "AveriaSerifLibre-Regular", "Averia Serif Libre" }; public static string[] Bold = new string[1] { "AveriaSerifLibre-Bold" }; public static string[] Norse = new string[2] { "Norse", "Norsebold" }; public static string[] NorseBold = new string[2] { "Norsebold", "Norse" }; public static string[] TmpBody = new string[2] { "Valheim-AveriaSansLibre", "AveriaSerifLibre-Regular SDF" }; public static string[] TmpTitle = new string[2] { "Valheim-Norse", "Norsebold SDF" }; } internal static class GameColors { public static Color Orange = new Color(1f, 0.631f, 0.235f, 1f); public static Color Yellow = new Color(1f, 0.889f, 0f, 1f); public static Color Beige = new Color(0.8529f, 0.725f, 0.5331f, 1f); public static Color Muted = new Color(0.639f, 0.596f, 0.518f, 1f); public static Color Disabled = new Color(0.42f, 0.4f, 0.36f, 1f); public static Color Danger = new Color(0.85f, 0.27f, 0.22f, 1f); public static ColorBlock ButtonColors; static GameColors() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) ColorBlock buttonColors = default(ColorBlock); ((ColorBlock)(ref buttonColors)).normalColor = new Color(0.824f, 0.824f, 0.824f, 1f); ((ColorBlock)(ref buttonColors)).highlightedColor = new Color(1.3f, 1.3f, 1.3f, 1f); ((ColorBlock)(ref buttonColors)).pressedColor = new Color(0.537f, 0.556f, 0.556f, 1f); ((ColorBlock)(ref buttonColors)).selectedColor = new Color(0.824f, 0.824f, 0.824f, 1f); ((ColorBlock)(ref buttonColors)).disabledColor = new Color(0.566f, 0.566f, 0.566f, 0.502f); ((ColorBlock)(ref buttonColors)).colorMultiplier = 1f; ((ColorBlock)(ref buttonColors)).fadeDuration = 0.1f; ButtonColors = buttonColors; } } internal static class Skin { private static bool _loggedScrollbar; public static float PixelsPerUnit { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) Scene activeScene = SceneManager.GetActiveScene(); if (!(((Scene)(ref activeScene)).name == "start")) { return 1f; } return 2f; } } public static void Highlight(Image image, Color? color = null) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)image == (Object)null)) { ((Graphic)image).color = (Color)(((??)color) ?? GameColors.Yellow); ((Graphic)image).material = null; } } public static void Window(Image image) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)image == (Object)null)) { Sprite val = GameAssets.FirstSprite(SpriteNames.Window); if (!((Object)(object)val == (Object)null)) { image.sprite = val; image.type = (Type)1; ((Graphic)image).color = Color.white; ((Graphic)image).material = null; } } } public static void Panel(Image image) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)image == (Object)null)) { Sprite val = GameAssets.FirstSprite(SpriteNames.Panel); if (!((Object)(object)val == (Object)null)) { image.sprite = val; image.type = (Type)1; ((Graphic)image).color = Color.white; } } } public static void Slot(Image image) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)image == (Object)null)) { Sprite val = GameAssets.FirstSprite(SpriteNames.Slot); if (!((Object)(object)val == (Object)null)) { image.sprite = val; image.type = (Type)1; ((Graphic)image).color = Color.white; } } } public static void Button(Button button, int fontSize = 0, bool withSfx = true) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)button == (Object)null) { return; } Graphic targetGraphic = ((Selectable)button).targetGraphic; Image val = (Image)(((object)((targetGraphic is Image) ? targetGraphic : null)) ?? ((object)((Component)button).GetComponent())); Sprite val2 = GameAssets.FirstSprite(SpriteNames.Button); if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null) { val.sprite = val2; val.type = (Type)1; val.pixelsPerUnitMultiplier = PixelsPerUnit; ((Graphic)val).color = Color.white; ((Selectable)button).targetGraphic = (Graphic)(object)val; } ((Selectable)button).colors = GameColors.ButtonColors; Sprite val3 = GameAssets.FirstSprite(SpriteNames.ButtonHighlight); if ((Object)(object)val3 != (Object)null) { ((Selectable)button).transition = (Transition)2; SpriteState spriteState = ((Selectable)button).spriteState; ((SpriteState)(ref spriteState)).highlightedSprite = val3; ((SpriteState)(ref spriteState)).pressedSprite = val3; ((SpriteState)(ref spriteState)).selectedSprite = val3; Sprite val4 = GameAssets.FirstSprite(SpriteNames.ButtonDisabled); if ((Object)(object)val4 != (Object)null) { ((SpriteState)(ref spriteState)).disabledSprite = val4; } ((Selectable)button).spriteState = spriteState; } Text[] componentsInChildren = ((Component)button).GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { Text(componentsInChildren[i], TextRole.Label, fontSize); } TMP_Text[] componentsInChildren2 = ((Component)button).GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren2.Length; i++) { Text(componentsInChildren2[i], TextRole.Label, fontSize); } if (withSfx) { Sfx(button); } } public static void Sfx(Button button) { if (!((Object)(object)button == (Object)null) && !((Object)(object)((Component)button).GetComponent() != (Object)null)) { ButtonSfx val = UIRoot.FindSfxTemplate(); if (!((Object)(object)val == (Object)null)) { ButtonSfx obj = ((Component)button).gameObject.AddComponent(); obj.m_sfxPrefab = val.m_sfxPrefab; obj.m_selectSfxPrefab = val.m_selectSfxPrefab; } } } public static void Text(Text text, TextRole role = TextRole.Body, int fontSize = 0, bool outline = true) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)text == (Object)null)) { Font val = ((role == TextRole.Title || role == TextRole.Header) ? (GameAssets.FirstFont(FontNames.NorseBold) ?? GameAssets.FirstFont(FontNames.Bold)) : (GameAssets.FirstFont(FontNames.Body) ?? GameAssets.FirstFont(FontNames.Bold))); if ((Object)(object)val != (Object)null) { text.font = val; } ((Graphic)text).color = ColorFor(role); if (fontSize > 0) { text.fontSize = fontSize; } if (outline) { Outline(((Component)text).gameObject); } } } public static bool Font(TMP_Text text, TextRole role = TextRole.Body) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)text == (Object)null) { return false; } TMP_FontAsset val = ((role == TextRole.Title || role == TextRole.Header) ? VanillaUI.TitleTmpFont : VanillaUI.PrimaryTmpFont); val = val ?? GameAssets.FirstTmpFont((role == TextRole.Title) ? FontNames.TmpTitle : FontNames.TmpBody); if ((Object)(object)val == (Object)null) { return false; } text.fontStyle = (FontStyles)(text.fontStyle & -69); if ((Object)(object)val == (Object)(object)text.font) { return false; } text.font = val; if ((Object)(object)((TMP_Asset)val).material != (Object)null) { text.fontSharedMaterial = ((TMP_Asset)val).material; } return true; } public static bool Font(Text text, TextRole role = TextRole.Body) { if ((Object)(object)text == (Object)null) { return false; } Font val = VanillaUI.PrimaryFont ?? ((role == TextRole.Title || role == TextRole.Header) ? GameAssets.FirstFont(FontNames.NorseBold) : GameAssets.FirstFont(FontNames.Body)); if ((Object)(object)val == (Object)null || (Object)(object)val == (Object)(object)text.font) { return false; } text.font = val; return true; } public static void Text(TMP_Text text, TextRole role = TextRole.Body, int fontSize = 0) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)text == (Object)null)) { Font(text, role); ((Graphic)text).color = ColorFor(role); if (fontSize > 0) { text.fontSize = fontSize; } } } public static Color ColorFor(TextRole role) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) return (Color)(role switch { TextRole.Title => GameColors.Orange, TextRole.Header => GameColors.Yellow, TextRole.Label => GameColors.Beige, TextRole.Disabled => GameColors.Disabled, _ => GameColors.Beige, }); } public static void Outline(GameObject target, Color? color = null) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)target == (Object)null)) { Outline val = target.GetComponent(); if ((Object)(object)val == (Object)null) { val = target.AddComponent(); } ((Shadow)val).effectColor = (Color)(((??)color) ?? Color.black); ((Shadow)val).effectDistance = new Vector2(1f, -1f); } } public static void InputField(InputField field, int fontSize = 0) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)field == (Object)null)) { Image component = ((Component)field).GetComponent(); Sprite val = GameAssets.FirstSprite(SpriteNames.Field); if ((Object)(object)component != (Object)null && (Object)(object)val != (Object)null) { component.sprite = val; component.type = (Type)1; ((Graphic)component).color = Color.white; } if ((Object)(object)field.textComponent != (Object)null) { Text(field.textComponent, TextRole.Body, fontSize); } Graphic placeholder = field.placeholder; Text val2 = (Text)(object)((placeholder is Text) ? placeholder : null); if (val2 != null) { Text(val2, TextRole.Disabled, fontSize); } } } public static void Toggle(Toggle toggle) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)toggle == (Object)null) { return; } Graphic targetGraphic = ((Selectable)toggle).targetGraphic; Image val = (Image)(object)((targetGraphic is Image) ? targetGraphic : null); Sprite val2 = GameAssets.FirstSprite(SpriteNames.Checkbox); if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null) { val.sprite = val2; val.type = (Type)0; ((Graphic)val).color = Color.white; } Graphic graphic = toggle.graphic; Image val3 = (Image)(object)((graphic is Image) ? graphic : null); if (val3 != null) { Sprite val4 = GameAssets.FirstSprite(SpriteNames.CheckboxMarker); if ((Object)(object)val4 != (Object)null) { val3.sprite = val4; val3.type = (Type)0; ((Graphic)val3).color = Color.white; } } Text[] componentsInChildren = ((Component)toggle).GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { Text(componentsInChildren[i], TextRole.Label); } } public static void Scrollbar(Scrollbar scrollbar) { //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Invalid comparison between Unknown and I4 //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)scrollbar == (Object)null) { return; } Scrollbar scrollbarTemplate = VanillaUI.ScrollbarTemplate; if ((Object)(object)scrollbarTemplate == (Object)null) { ScrollbarByName(scrollbar); return; } Image val = HandleImage(scrollbarTemplate); Image val2 = TrackImage(scrollbarTemplate, val); Image val3 = HandleImage(scrollbar); Image val4 = TrackImage(scrollbar, val3); if (!_loggedScrollbar) { _loggedScrollbar = true; UILog.Info("scrollbar copied from " + UIExtensions.PathOf(((Component)scrollbarTemplate).transform) + " (track '" + (((Object)(object)val2 != (Object)null) ? SpriteName(val2) : "none") + "', handle '" + (((Object)(object)val != (Object)null) ? SpriteName(val) : "none") + "')"); } if ((Object)(object)val4 != (Object)null) { if ((Object)(object)val2 != (Object)null) { CopyImage(val2, val4); ((Behaviour)val4).enabled = ((Behaviour)val2).enabled; } else { ((Behaviour)val4).enabled = false; } } if ((Object)(object)val3 != (Object)null && (Object)(object)val != (Object)null) { CopyImage(val, val3); } ((Selectable)scrollbar).colors = ((Selectable)scrollbarTemplate).colors; ((Selectable)scrollbar).transition = ((Selectable)scrollbarTemplate).transition; ((Selectable)scrollbar).spriteState = ((Selectable)scrollbarTemplate).spriteState; if ((Object)(object)((Selectable)scrollbar).targetGraphic != (Object)null) { CanvasRenderer canvasRenderer = ((Selectable)scrollbar).targetGraphic.canvasRenderer; Color color; if ((int)((Selectable)scrollbar).transition != 1) { color = Color.white; } else { ColorBlock colors = ((Selectable)scrollbar).colors; color = ((ColorBlock)(ref colors)).normalColor; } canvasRenderer.SetColor(color); } ((Behaviour)scrollbar).enabled = false; ((Behaviour)scrollbar).enabled = true; } private static string SpriteName(Image image) { if (!((Object)(object)image.sprite != (Object)null)) { return "no sprite"; } return ((Object)image.sprite).name; } private static Image HandleImage(Scrollbar scrollbar) { if ((Object)(object)scrollbar.handleRect != (Object)null) { Image component = ((Component)scrollbar.handleRect).GetComponent(); if ((Object)(object)component != (Object)null) { return component; } } Graphic targetGraphic = ((Selectable)scrollbar).targetGraphic; return (Image)(object)((targetGraphic is Image) ? targetGraphic : null); } private static Image TrackImage(Scrollbar scrollbar, Image handle) { Image component = ((Component)scrollbar).GetComponent(); if ((Object)(object)component != (Object)null && (Object)(object)component != (Object)(object)handle) { return component; } Image[] componentsInChildren = ((Component)scrollbar).GetComponentsInChildren(true); foreach (Image val in componentsInChildren) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)handle) && (!((Object)(object)handle != (Object)null) || !((Component)val).transform.IsChildOf(((Component)handle).transform)) && (!((Object)(object)scrollbar.handleRect != (Object)null) || !((Component)val).transform.IsChildOf((Transform)(object)scrollbar.handleRect))) { return val; } } return null; } private static void ScrollbarByName(Scrollbar scrollbar) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) Image val = HandleImage(scrollbar); Image val2 = TrackImage(scrollbar, val); if ((Object)(object)val2 != (Object)null && VanillaUI.TryGetSprite(SpriteNames.ScrollTrack[0], out var sprite)) { val2.sprite = sprite; val2.type = (Type)1; ((Graphic)val2).color = new Color(0f, 0f, 0f, 0.5f); } if ((Object)(object)val != (Object)null && VanillaUI.TryGetSprite(SpriteNames.ScrollHandle[0], out var sprite2)) { val.sprite = sprite2; val.type = (Type)1; ((Graphic)val).color = GameColors.Muted; } if (!_loggedScrollbar) { _loggedScrollbar = true; UILog.Warning("no vanilla scrollbar found to copy; left the prefab's own art in place"); } } public static void ScrollRect(ScrollRect scroll, float fallbackSensitivity = 40f) { if ((Object)(object)scroll == (Object)null) { return; } ScrollRect scrollRectTemplate = VanillaUI.ScrollRectTemplate; if ((Object)(object)scrollRectTemplate == (Object)null) { if (scroll.scrollSensitivity < fallbackSensitivity) { scroll.scrollSensitivity = fallbackSensitivity; } } else { scroll.scrollSensitivity = scrollRectTemplate.scrollSensitivity; scroll.inertia = scrollRectTemplate.inertia; scroll.decelerationRate = scrollRectTemplate.decelerationRate; scroll.elasticity = scrollRectTemplate.elasticity; } } private static void CopyImage(Image from, Image to) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)from == (Object)null) && !((Object)(object)to == (Object)null)) { to.sprite = from.sprite; to.type = from.type; ((Graphic)to).color = ((Graphic)from).color; ((Graphic)to).material = ((Graphic)from).material; to.pixelsPerUnitMultiplier = from.pixelsPerUnitMultiplier; to.fillCenter = from.fillCenter; to.preserveAspect = from.preserveAspect; } } public static bool GameMaterial(Graphic graphic) { if ((Object)(object)graphic == (Object)null || graphic is TMP_Text) { return false; } Material uiMaterial = VanillaUI.UiMaterial; if ((Object)(object)uiMaterial == (Object)null || (Object)(object)graphic.material == (Object)(object)uiMaterial) { return false; } graphic.material = uiMaterial; return true; } public static bool Unlit(Graphic graphic) { if ((Object)(object)graphic == (Object)null || graphic is TMP_Text) { return false; } if ((Object)(object)graphic.material == (Object)null || (Object)(object)graphic.material == (Object)(object)Graphic.defaultGraphicMaterial) { return false; } graphic.material = null; return true; } public static void Slider(Slider slider) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)slider == (Object)null) { return; } Image componentInChildren = ((Component)slider).GetComponentInChildren(true); Sprite val = GameAssets.FirstSprite(SpriteNames.ScrollTrack); if ((Object)(object)componentInChildren != (Object)null && (Object)(object)val != (Object)null) { componentInChildren.sprite = val; componentInChildren.type = (Type)1; } if ((Object)(object)slider.handleRect != (Object)null) { Image component = ((Component)slider.handleRect).GetComponent(); Sprite val2 = GameAssets.FirstSprite(SpriteNames.ScrollHandle); if ((Object)(object)component != (Object)null && (Object)(object)val2 != (Object)null) { component.sprite = val2; ((Graphic)component).color = GameColors.Beige; } } } } internal static class Styler { public static StyleReport Apply(GameObject root, StyleOptions options = null) { StyleReport styleReport = new StyleReport(); if ((Object)(object)root == (Object)null) { return styleReport; } options = options ?? StyleOptions.Default; VanillaUI.Harvest(); GameAssets.Index(); if (options.RebindAssets || options.FixBrokenShaders || options.ApplyGameMaterial) { Rebind(root, options, styleReport); } if (options.RebindAssets) { Scrollbar[] componentsInChildren = root.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { Skin.Scrollbar(componentsInChildren[i]); } } if (options.MatchGameScrolling) { ScrollRect[] componentsInChildren2 = root.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren2.Length; i++) { Skin.ScrollRect(componentsInChildren2[i], options.FallbackScrollSensitivity); } } if (options.StyleByComponent) { StyleByComponent(root, options, styleReport); } ApplyRules(root, options, styleReport); UILog.Debug($"styled '{((Object)root).name}': {styleReport}"); if (UILog.Verbose && styleReport.UnresolvedSprites.Count > 0) { UILog.Debug("no game sprite named: " + string.Join(", ", styleReport.UnresolvedSprites.ToArray())); } return styleReport; } public static int Lit(GameObject root, params string[] paths) { return Set(root, paths, lit: true); } public static int Unlit(GameObject root, params string[] paths) { return Set(root, paths, lit: false); } private static int Set(GameObject root, string[] paths, bool lit) { if ((Object)(object)root == (Object)null) { return 0; } int num = 0; foreach (GameObject item in Targets(root, paths)) { Graphic[] components = item.GetComponents(); foreach (Graphic graphic in components) { if (lit ? Skin.GameMaterial(graphic) : Skin.Unlit(graphic)) { num++; } } } return num; } private static IEnumerable Targets(GameObject root, string[] paths) { if (paths == null || paths.Length == 0) { yield return root; yield break; } foreach (string text in paths) { GameObject val = UIExtensions.Find(root, text) ?? root.FindDeep(text); if ((Object)(object)val == (Object)null) { UILog.Warning("could not find '" + text + "' under '" + ((Object)root).name + "' to light"); } else { yield return val; } } } public static void ApplyTo(GameObject root, string path, ElementType element, StyleOptions options = null) { GameObject val = UIExtensions.Find(root, path); if ((Object)(object)val == (Object)null) { UILog.Warning("could not find '" + path + "' under '" + (((Object)(object)root != (Object)null) ? ((Object)root).name : "null") + "'"); } else { ApplyElement(val, element, options ?? StyleOptions.Default, new StyleReport()); } } private static void Rebind(GameObject root, StyleOptions options, StyleReport report) { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) Graphic[] componentsInChildren = root.GetComponentsInChildren(true); foreach (Graphic val in componentsInChildren) { if (options.FixBrokenShaders) { FixMaterial(val, report); } if (options.ApplyGameMaterial && Skin.GameMaterial(val)) { report.MaterialsApplied++; } if (!options.RebindAssets) { continue; } Image val2 = (Image)(object)((val is Image) ? val : null); if (val2 != null) { RebindSprite(val2, options, report); continue; } Text val3 = (Text)(object)((val is Text) ? val : null); if (val3 != null) { RebindFont(val3, options, report); continue; } TMP_Text val4 = (TMP_Text)(object)((val is TMP_Text) ? val : null); if (val4 != null) { RebindTmpFont(val4, options, report); } } if (!options.RebindAssets) { return; } Selectable[] componentsInChildren2 = root.GetComponentsInChildren(true); foreach (Selectable val5 in componentsInChildren2) { SpriteState spriteState = val5.spriteState; bool flag = false; Sprite sprite = ((SpriteState)(ref spriteState)).highlightedSprite; if (RebindSprite(ref sprite, report)) { ((SpriteState)(ref spriteState)).highlightedSprite = sprite; flag = true; } Sprite sprite2 = ((SpriteState)(ref spriteState)).pressedSprite; if (RebindSprite(ref sprite2, report)) { ((SpriteState)(ref spriteState)).pressedSprite = sprite2; flag = true; } Sprite sprite3 = ((SpriteState)(ref spriteState)).selectedSprite; if (RebindSprite(ref sprite3, report)) { ((SpriteState)(ref spriteState)).selectedSprite = sprite3; flag = true; } Sprite sprite4 = ((SpriteState)(ref spriteState)).disabledSprite; if (RebindSprite(ref sprite4, report)) { ((SpriteState)(ref spriteState)).disabledSprite = sprite4; flag = true; } if (flag) { val5.spriteState = spriteState; } } } private static void RebindSprite(Image image, StyleOptions options, StyleReport report) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 Sprite sprite = image.sprite; if ((Object)(object)sprite == (Object)null) { return; } if (!GameAssets.TryGetSprite(((Object)sprite).name, out var sprite2)) { if (!report.UnresolvedSprites.Contains(((Object)sprite).name)) { report.UnresolvedSprites.Add(((Object)sprite).name); } return; } if (options.MatchMenuPixelDensity && (int)image.type == 1) { image.pixelsPerUnitMultiplier = Skin.PixelsPerUnit; } if (!((Object)(object)sprite2 == (Object)(object)sprite)) { image.sprite = sprite2; report.SpritesRebound++; } } private static bool RebindSprite(ref Sprite sprite, StyleReport report) { if ((Object)(object)sprite == (Object)null) { return false; } if (!GameAssets.TryGetSprite(((Object)sprite).name, out var sprite2) || (Object)(object)sprite2 == (Object)(object)sprite) { return false; } sprite = sprite2; report.SpritesRebound++; return true; } private static void RebindFont(Text text, StyleOptions options, StyleReport report) { if ((Object)(object)text.font == (Object)null) { return; } Font val = VanillaUI.Font(((Object)text.font).name); if ((Object)(object)val == (Object)null) { if (!report.UnresolvedFonts.Contains(((Object)text.font).name)) { report.UnresolvedFonts.Add(((Object)text.font).name); } if (options.FallbackToGameFonts && Skin.Font(text, IsTitleFont(((Object)text.font).name) ? TextRole.Title : TextRole.Body)) { report.FontsRebound++; } } else if (!((Object)(object)val == (Object)(object)text.font)) { text.font = val; report.FontsRebound++; } } private static void RebindTmpFont(TMP_Text text, StyleOptions options, StyleReport report) { //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)text.font == (Object)null) { return; } TMP_FontAsset val = VanillaUI.TmpFont(((Object)text.font).name); if ((Object)(object)val == (Object)null) { if (!report.UnresolvedFonts.Contains(((Object)text.font).name)) { report.UnresolvedFonts.Add(((Object)text.font).name); } if (options.FallbackToGameFonts && Skin.Font(text, IsTitleFont(((Object)text.font).name) ? TextRole.Title : TextRole.Body)) { report.FontsRebound++; } } else if (!((Object)(object)val == (Object)(object)text.font)) { text.font = val; if ((Object)(object)((TMP_Asset)val).material != (Object)null) { text.fontSharedMaterial = ((TMP_Asset)val).material; } text.fontStyle = (FontStyles)(text.fontStyle & -69); report.FontsRebound++; } } private static bool IsTitleFont(string name) { if (!string.IsNullOrEmpty(name)) { return name.IndexOf("norse", StringComparison.OrdinalIgnoreCase) >= 0; } return false; } private static void FixMaterial(Graphic graphic, StyleReport report) { Material material = graphic.material; if (!((Object)(object)material == (Object)null) && !((Object)(object)material == (Object)(object)Graphic.defaultGraphicMaterial) && (!((Object)(object)material.shader != (Object)null) || !(((Object)material.shader).name != "Hidden/InternalErrorShader"))) { graphic.material = null; report.ShadersFixed++; } } private static void StyleByComponent(GameObject root, StyleOptions options, StyleReport report) { Button[] componentsInChildren = root.GetComponentsInChildren